UNPKG

tg-mini-app-binder

Version:

A modular and extendable wrapper for the Telegram Mini App API to simplify interactions between your web app and the Telegram client.

72 lines (63 loc) 2.59 kB
/** * @class UIModule * @description Manages UI elements like the MainButton, BackButton, and HapticFeedback. */ export default class UIModule { /** * @param {object} tg - The Telegram WebApp object. */ constructor(tg) { this.tg = tg; this.mainButton = this.tg.MainButton; this.backButton = this.tg.BackButton; this.hapticFeedback = this.tg.HapticFeedback; } /** * Configures and shows the MainButton to request the user's phone number. * Listens for the mainButtonClicked event to handle the response. * @param {object} options - Configuration for the button. * @param {string} options.text - The text to display on the button (e.g., "Share Phone Number"). * @param {Function} options.onSuccess - Callback fired with `true` when the request is sent. * @param {Function} options.onFailure - Callback fired if the user denies the request or an error occurs. */ requestContact({ text = "Share Contact", onSuccess, onFailure }) { // A flag to ensure we only handle the callback once. let handled = false; const contactRequestedCallback = (accessGranted) => { if (handled) return; handled = true; if (accessGranted) { if(onSuccess) onSuccess(true); } else { if(onFailure) onFailure(false); } // Clean up this.mainButton.setText("Done"); setTimeout(() => this.mainButton.hide(), 1500); this.tg.offEvent('contact_requested', contactRequestedCallback); }; this.mainButton.setText(text); this.mainButton.show(); // This is a special event triggered after requestContact result this.tg.onEvent('contact_requested', contactRequestedCallback); this.mainButton.onClick(() => { if (!handled) { this.tg.requestContact(); } }); } /** * Triggers a haptic feedback impact. * @param {'light' | 'medium' | 'heavy' | 'rigid' | 'soft'} style - The impact style. */ impactOccurred(style = 'medium') { this.hapticFeedback.impactOccurred(style); } /** * Triggers a haptic feedback notification. * @param {'error' | 'success' | 'warning'} type - The notification type. */ notificationOccurred(type = 'success') { this.hapticFeedback.notificationOccurred(type); } }