|
|
|
import { WebApp } from '@grammyjs/web-app'; |
|
import { BehaviorSubject, Observable } from 'rxjs'; |
|
|
|
import { isTwa } from '../../common/is-twa.js'; |
|
|
|
|
|
/** |
|
* {@link https://core.telegram.org/bots/webapps#mainbutton | MainButton} |
|
*/ |
|
export interface TwaMainButtonState { |
|
text: string; |
|
color: string; |
|
textColor: string; |
|
isActive: boolean; |
|
isVisible: boolean; |
|
isProgressVisible: boolean; |
|
} |
|
|
|
|
|
const defaultState: TwaMainButtonState = { |
|
text: 'CONTINUE', |
|
color: (WebApp.themeParams.button_color ?? '#5AC8FB'), |
|
textColor: (WebApp.themeParams.button_text_color ?? '#FFF'), |
|
isActive: true, |
|
isVisible: false, |
|
isProgressVisible: false, |
|
}; |
|
|
|
|
|
export interface TwaMainButtonServiceOptions { |
|
initialState?: Partial<TwaMainButtonState>; |
|
} |
|
|
|
|
|
/** |
|
* Controls the state of the TWA main button. |
|
*/ |
|
export class TwaMainButtonService { |
|
|
|
#state$: BehaviorSubject<TwaMainButtonState>; |
|
|
|
|
|
constructor(options?: TwaMainButtonServiceOptions) { |
|
|
|
this.#state$ = new BehaviorSubject({ |
|
...defaultState, |
|
...(options?.initialState ?? {}) |
|
}); |
|
|
|
} |
|
|
|
|
|
updateButtonState( |
|
stateUpdate: Partial<TwaMainButtonState> |
|
|
|
): void { |
|
|
|
const currentState = this.#state$.value; |
|
|
|
const newState: TwaMainButtonState = { |
|
...currentState, |
|
...stateUpdate, |
|
}; |
|
|
|
this.#state$.next(newState); |
|
|
|
if (isTwa()) { |
|
this.#updateNativeButtonState( |
|
currentState, |
|
newState |
|
); |
|
} |
|
|
|
} |
|
|
|
getState(): Observable<TwaMainButtonState> { |
|
|
|
return this.#state$.asObservable(); |
|
|
|
} |
|
|
|
getStateSnapshot(): TwaMainButtonState { |
|
|
|
return this.#state$.value; |
|
|
|
} |
|
|
|
|
|
#updateNativeButtonState( |
|
currentState: TwaMainButtonState, |
|
newState: TwaMainButtonState, |
|
|
|
): void { |
|
|
|
if ( |
|
currentState.isProgressVisible !== |
|
newState.isProgressVisible |
|
) { |
|
if (newState.isProgressVisible) { |
|
WebApp.MainButton.showProgress(); |
|
|
|
} else { |
|
WebApp.MainButton.hideProgress(); |
|
|
|
} |
|
|
|
} |
|
|
|
WebApp.MainButton.setParams({ |
|
text: newState.text, |
|
color: newState.color, |
|
text_color: newState.textColor, |
|
is_active: newState.isActive, |
|
is_visible: newState.isVisible, |
|
}); |
|
|
|
} |
|
|
|
} |