use-telegram
Version:
A TypeScript package for easy integration with Telegram WebApp API
48 lines • 1.96 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useEffect, useRef } from "react";
export const TelegramWebContext = createContext({
show: () => { },
updateMainButton: () => { },
hide: () => { },
});
export const useTelegramWeb = () => {
const context = useContext(TelegramWebContext);
if (!context) {
throw new Error("useTelegramWeb must be used within a TelegramWebProvider");
}
return context;
};
export const TelegramWebContextProvider = ({ children, theme }) => {
const mainButtonCallbackRef = useRef(() => { });
const webApp = useRef(window.Telegram.WebApp);
const MainButton = useRef(webApp.current.MainButton);
useEffect(() => {
if (theme) {
Object.entries(theme).forEach(([key, value]) => {
webApp.current.themeParams[key.replace(/-/g, '_')] = value;
});
}
}, [theme]);
const applyOptions = useCallback((options) => {
options.text && (MainButton.current.setText(options.text));
options.color && (MainButton.current.color = options.color);
options.hasShineEffect && (MainButton.current.hasShineEffect = options.hasShineEffect);
}, []);
const updateMainButton = useCallback((options, onClick) => {
applyOptions(options);
// reset callback
MainButton.current.offClick(mainButtonCallbackRef.current);
if (onClick) {
mainButtonCallbackRef.current = onClick.bind(null, MainButton.current);
MainButton.current.onClick(mainButtonCallbackRef.current);
}
}, []);
const show = useCallback(() => {
MainButton.current.show();
}, []);
const hide = useCallback(() => {
MainButton.current.hide();
}, []);
return (_jsx(TelegramWebContext.Provider, { value: { show, hide, updateMainButton }, children: children }));
};
//# sourceMappingURL=TelegramWebContext.js.map