Files
TelegramMemeVault/miniapp/src/lib/telegram.js
T

80 lines
3.0 KiB
JavaScript
Raw Normal View History

2026-10-07 02:17:30 +04:00
/** Обёртка над Telegram WebApp SDK */
const tg = window.Telegram?.WebApp
export const webApp = tg
/** initData для обмена на JWT */
export const initData = tg?.initData ?? ''
/** Закрыть Mini App */
export const close = () => tg?.close()
/**
* query_id присутствует когда Mini App открыта из меню «Приложить».
* Используется для answerWebAppQuery: позволяет отправить контент в чат одним тапом.
*/
export const getQueryId = () => tg?.initDataUnsafe?.query_id ?? null
export const isAttachmentMode = () => !!getQueryId()
2026-10-09 02:07:18 +04:00
/**
* Имя чата/собеседника, в который будет отправлено медиа.
* - Личный чат → receiver.first_name (+ last_name если есть)
* - Группа/канал → chat.title
* Возвращает null, если информации нет.
*/
export function getChatName() {
const d = tg?.initDataUnsafe
if (!d) return null
if (d.receiver) {
const name = [d.receiver.first_name, d.receiver.last_name].filter(Boolean).join(' ')
return name || d.receiver.username || null
}
if (d.chat) return d.chat.title ?? null
return null
}
/**
* Тип чата, в который будет отправлено медиа.
* - 'private' → личный чат (есть receiver)
* - 'group' → группа
* - 'supergroup' → супергруппа
* - 'channel' → канал
* - null → неизвестно
*/
export function getChatType() {
const d = tg?.initDataUnsafe
if (!d) return null
if (d.receiver) return 'private'
if (d.chat?.type) return d.chat.type // 'group' | 'supergroup' | 'channel'
return null
}
/**
* Показать нативный алерт Telegram.
* Если WebApp не поддерживает метод (версия < 6.1) или контекст — обычный браузер,
* падаем на стандартный window.alert.
*/
2026-10-07 02:17:30 +04:00
export const showAlert = (msg) => {
2026-10-09 02:07:18 +04:00
if (tg?.showAlert) {
try { tg.showAlert(msg) } catch { alert(msg) }
} else {
alert(msg)
}
2026-10-07 02:17:30 +04:00
}
/** Применить тему Telegram к CSS-переменным */
export function applyTheme() {
if (!tg) return
tg.expand()
tg.ready()
const colors = tg.themeParams
const root = document.documentElement.style
if (colors.bg_color) root.setProperty('--tg-bg', colors.bg_color)
if (colors.text_color) root.setProperty('--tg-text', colors.text_color)
if (colors.hint_color) root.setProperty('--tg-hint', colors.hint_color)
if (colors.link_color) root.setProperty('--tg-link', colors.link_color)
if (colors.button_color) root.setProperty('--tg-button', colors.button_color)
if (colors.button_text_color) root.setProperty('--tg-btn-text', colors.button_text_color)
if (colors.secondary_bg_color) root.setProperty('--tg-secondary-bg', colors.secondary_bg_color)
}