/** * The formats capability: display number-format codes attached to cells, * independent of the cell value lifecycle. Opt-in; `new Workbook()` includes it * by default. */ import { pack } from '../addr' import type { WorkbookCapability, WorkbookInternal } from '../capability' import type { Ref } from '../types' declare module '../capability' { interface WorkbookPlugins { formatsCapability: WorkbookCapability } interface Workbook_FeatureMap { formatsCapability: Workbook_Formats } } /** The method surface the formats capability contributes to a {@link Workbook}. */ export interface Workbook_Formats { /** * Attach a display number-format code (e.g. `"0.00%"`, `"yyyy-mm-dd"`) to a * cell. Purely descriptive — the engine ignores it; adapters render with it * via `formatValue`. Independent of the cell's value, so it survives input * edits. Pass `undefined` to clear. */ setFormat: (ref: Ref, code: string | undefined) => void /** The display number-format code for a cell, if any. */ getFormat: (ref: Ref) => string | undefined } export const formatsCapability: WorkbookCapability = { construct(internal: WorkbookInternal): void { const api = internal as unknown as WorkbookInternal & Workbook_Formats api.setFormat = function setFormat( ref: Ref, code: string | undefined, ): void { const key = pack(ref.row, ref.col) if (code === undefined) { const map = internal.formats.get(ref.sheet) if (!map?.has(key)) return // nothing to clear → no change, no notification map.delete(key) } else { let map = internal.formats.get(ref.sheet) if (!map) internal.formats.set(ref.sheet, (map = new Map())) if (map.get(key) === code) return // unchanged → no notification map.set(key, code) } // A format is display-affecting state. Bump revision and notify the // cell's region so subscribed views (e.g. useCell's `display`) re-render. internal.baseAtoms.revision.set((r) => r + 1) internal.notifyRegions(new Map([[ref.sheet, new Set([key])]])) } api.getFormat = function getFormat(ref: Ref): string | undefined { return internal.formats.get(ref.sheet)?.get(pack(ref.row, ref.col)) } }, }