nakama/frontend/src/utils/telegram.js

122 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Утилиты для работы с Telegram Web App
let tg = null
export const initTelegramApp = () => {
if (typeof window !== 'undefined' && window.Telegram?.WebApp) {
tg = window.Telegram.WebApp
tg.ready()
tg.expand()
// Установить цвета темы
tg.setHeaderColor('#F2F3F5')
tg.setBackgroundColor('#F2F3F5')
return tg
}
return null
}
export const getTelegramApp = () => {
return tg || window.Telegram?.WebApp
}
export const getTelegramUser = () => {
const app = getTelegramApp()
return app?.initDataUnsafe?.user || null
}
export const getTelegramInitData = () => {
const app = getTelegramApp()
return app?.initData || ''
}
export const showAlert = (message) => {
const app = getTelegramApp()
if (app) {
app.showAlert(message)
} else {
alert(message)
}
}
export const showConfirm = (message) => {
const app = getTelegramApp()
return new Promise((resolve) => {
if (app) {
app.showConfirm(message, resolve)
} else {
resolve(confirm(message))
}
})
}
export const showPopup = (params) => {
const app = getTelegramApp()
return new Promise((resolve) => {
if (app) {
app.showPopup(params, resolve)
} else {
alert(params.message)
resolve()
}
})
}
export const openTelegramLink = (url) => {
const app = getTelegramApp()
if (app) {
app.openTelegramLink(url)
} else {
window.open(url, '_blank')
}
}
export const openLink = (url) => {
const app = getTelegramApp()
if (app) {
app.openLink(url)
} else {
window.open(url, '_blank')
}
}
export const hapticFeedback = (type = 'light') => {
const app = getTelegramApp()
if (app?.HapticFeedback) {
switch (type) {
case 'light':
app.HapticFeedback.impactOccurred('light')
break
case 'medium':
app.HapticFeedback.impactOccurred('medium')
break
case 'heavy':
app.HapticFeedback.impactOccurred('heavy')
break
case 'success':
app.HapticFeedback.notificationOccurred('success')
break
case 'warning':
app.HapticFeedback.notificationOccurred('warning')
break
case 'error':
app.HapticFeedback.notificationOccurred('error')
break
default:
app.HapticFeedback.impactOccurred('light')
}
}
}
export const isDevelopment = () => {
return !window.Telegram?.WebApp?.initDataUnsafe?.user
}
// Проверка, открыто ли приложение в стороннем клиенте (Aurogram и т.д.)
export const isThirdPartyClient = () => {
return typeof window !== 'undefined' && !window.Telegram?.WebApp
}