|
| 1 | +import type { Bridge } from '../Bridge' |
| 2 | +import type { UnsubscribeFn } from '../internal/EventBus' |
| 3 | +import type { StoredState } from '../SessionStorage' |
| 4 | +import type { Theme } from './Theme' |
| 5 | +import { Effect, Store } from '@tanstack/store' |
| 6 | + |
| 7 | +export interface MainButton { |
| 8 | + stateStore: Store<State> |
| 9 | + onClick: (listener: () => void) => UnsubscribeFn |
| 10 | + offClick: (listener: any) => void |
| 11 | +} |
| 12 | + |
| 13 | +export interface State { |
| 14 | + text: string |
| 15 | + visible: boolean |
| 16 | + loading: boolean |
| 17 | + active: boolean |
| 18 | + shining: boolean |
| 19 | + bgColor: string | null |
| 20 | + textColor: string | null |
| 21 | +} |
| 22 | + |
| 23 | +const INITIAL_STATE: State = { |
| 24 | + text: 'Continue', |
| 25 | + visible: false, |
| 26 | + active: true, |
| 27 | + shining: false, |
| 28 | + loading: false, |
| 29 | + bgColor: null, |
| 30 | + textColor: null, |
| 31 | +} |
| 32 | + |
| 33 | +export const init = (options: { |
| 34 | + bridge: Bridge |
| 35 | + theme: Theme |
| 36 | + storedState: StoredState<State> |
| 37 | +}): MainButton => { |
| 38 | + const { bridge, theme, storedState } = options |
| 39 | + const stateStore = new Store<State>(storedState.load() ?? INITIAL_STATE) |
| 40 | + stateStore.subscribe(({ currentVal }) => { |
| 41 | + storedState.save(currentVal) |
| 42 | + }) |
| 43 | + const effect = new Effect({ |
| 44 | + fn: () => { |
| 45 | + const state = stateStore.state |
| 46 | + const palette = theme.paletteStore.state |
| 47 | + bridge.emit('web_app_setup_main_button', { |
| 48 | + text: state.text, |
| 49 | + is_visible: state.visible, |
| 50 | + is_active: state.active, |
| 51 | + is_progress_visible: state.loading, |
| 52 | + has_shine_effect: state.shining, |
| 53 | + color: state.bgColor ?? palette.button_color ?? '#2481cc', |
| 54 | + text_color: state.textColor ?? palette.button_text_color ?? '#ffffff', |
| 55 | + }) |
| 56 | + }, |
| 57 | + deps: [stateStore, theme.paletteStore], |
| 58 | + }) |
| 59 | + effect.mount() |
| 60 | + return { |
| 61 | + stateStore, |
| 62 | + onClick: (listener) => { |
| 63 | + return bridge.on('main_button_pressed', listener) |
| 64 | + }, |
| 65 | + offClick: (listener) => { |
| 66 | + bridge.off('main_button_pressed', listener) |
| 67 | + }, |
| 68 | + } |
| 69 | +} |
0 commit comments