// A chart's state: which series its legend hides, and which item is // active (hovered, or reached with the arrow keys), whose tooltip shows. // Every change is an action through the reducer. // // Lifted unchanged from saison's report charts (server/ts-src/elements/chart/ // state.ts, also in toboggan and times), the first piece of the library's // chart core. It lives in this package until a second chart needs it: a // package's types must stand alone (scripts/declarations.ts). export interface ChartState { hidden: ReadonlySet; active: number | null; } export type Step = "next" | "prev" | "first" | "last"; export type ChartAction = | { type: "toggle"; key: string } | { type: "activate"; index: number | null } | { type: "step"; by: Step; count: number }; export const initialChartState: ChartState = { hidden: new Set(), active: null }; export function chartReducer(state: ChartState, action: ChartAction): ChartState { switch (action.type) { case "toggle": { const hidden = new Set(state.hidden); if (!hidden.delete(action.key)) hidden.add(action.key); return { ...state, hidden }; } case "activate": return state.active === action.index ? state : { ...state, active: action.index }; case "step": { const { count, by } = action; if (count <= 0) return state; const last = count - 1; const at = state.active; const active = by === "first" ? 0 : by === "last" ? last : at === null ? (by === "next" ? 0 : last) : by === "next" ? Math.min(last, at + 1) : Math.max(0, at - 1); return { ...state, active }; } } }