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
This commit is contained in:
Sped0n
2023-10-29 22:12:31 +08:00
parent 047ec5c630
commit 6e4213054c

View File

@@ -1,5 +1,5 @@
import { increment, decrement } from './utils'
import { updateIndexText, updateThresholdText } from './nav' import { updateIndexText, updateThresholdText } from './nav'
import { Watchable, decrement, increment } from './utils'
const thresholds = [ const thresholds = [
{ threshold: 20, trailLength: 20 }, { threshold: 20, trailLength: 20 },
@@ -18,43 +18,46 @@ const defaultState = {
export type State = typeof defaultState export type State = typeof defaultState
let state = defaultState export const state = new Watchable<State>(defaultState)
export function getState(): State {
// return a copy of state
return Object.create(
Object.getPrototypeOf(state),
Object.getOwnPropertyDescriptors(state)
)
}
export function initState(length: number): void { 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 { export function setIndex(index: number): void {
state.index = index const s = state.get()
updateIndexText() s.index = index
state.set(s)
} }
export function incIndex(): void { export function incIndex(): void {
state.index = increment(state.index, state.length) const s = state.get()
updateIndexText() s.index = increment(s.index, s.length)
state.set(s)
} }
export function decIndex(): void { export function decIndex(): void {
state.index = decrement(state.index, state.length) const s = state.get()
updateIndexText() s.index = decrement(s.index, s.length)
state.set(s)
} }
export function incThreshold(): void { export function incThreshold(): void {
state = updateThreshold(state, 1) let s = state.get()
updateThresholdText() s = updateThreshold(s, 1)
state.set(s)
} }
export function decThreshold(): void { export function decThreshold(): void {
state = updateThreshold(state, -1) let s = state.get()
updateThresholdText() s = updateThreshold(s, 1)
state.set(s)
} }
// helper // helper