// The store is the tiny bridge between the pure reducer and the renderer/DOM shell. It owns the // current state and notifies subscribers once per dispatch; render modules update only the // entities they saw change (DESIGN 7.2), so no module may assume a frame-by-frame redraw. import type { ReducerEvent, RootState } from './reducer.ts' import { initialState, reduce } from './reducer.ts' export type Listener = (state: RootState, event: ReducerEvent) => void export class Store { #state: RootState #listeners = new Set() constructor(state: RootState = initialState()) { this.#state = state } get state(): RootState { return this.#state } dispatch(event: ReducerEvent): RootState { const next = reduce(this.#state, event) this.#state = next for (const listener of this.#listeners) listener(next, event) return next } subscribe(listener: Listener): () => void { this.#listeners.add(listener) return () => { this.#listeners.delete(listener) } } }