From 6e4213054c614bfccc1d048579c1c8b0caea1968 Mon Sep 17 00:00:00 2001 From: Sped0n Date: Sun, 29 Oct 2023 22:12:31 +0800 Subject: [PATCH] refactor(state.ts): refactor state management to use a Watchable class for improved reactivity and encapsulation fix(state.ts): fix bug in decThreshold function where the wrong value was being passed to updateThreshold function --- assets/ts/state.ts | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/assets/ts/state.ts b/assets/ts/state.ts index 4aebfe9..482f215 100644 --- a/assets/ts/state.ts +++ b/assets/ts/state.ts @@ -1,5 +1,5 @@ -import { increment, decrement } from './utils' import { updateIndexText, updateThresholdText } from './nav' +import { Watchable, decrement, increment } from './utils' const thresholds = [ { threshold: 20, trailLength: 20 }, @@ -18,43 +18,46 @@ const defaultState = { export type State = typeof defaultState -let state = defaultState - -export function getState(): State { - // return a copy of state - return Object.create( - Object.getPrototypeOf(state), - Object.getOwnPropertyDescriptors(state) - ) -} +export const state = new Watchable(defaultState) export function initState(length: number): void { - state.length = length + const s = state.get() + s.length = length + state.set(s) + state.addWatcher(() => { + updateIndexText() + updateThresholdText() + }) } export function setIndex(index: number): void { - state.index = index - updateIndexText() + const s = state.get() + s.index = index + state.set(s) } export function incIndex(): void { - state.index = increment(state.index, state.length) - updateIndexText() + const s = state.get() + s.index = increment(s.index, s.length) + state.set(s) } export function decIndex(): void { - state.index = decrement(state.index, state.length) - updateIndexText() + const s = state.get() + s.index = decrement(s.index, s.length) + state.set(s) } export function incThreshold(): void { - state = updateThreshold(state, 1) - updateThresholdText() + let s = state.get() + s = updateThreshold(s, 1) + state.set(s) } export function decThreshold(): void { - state = updateThreshold(state, -1) - updateThresholdText() + let s = state.get() + s = updateThreshold(s, 1) + state.set(s) } // helper