/** * Workbook → Store facades. A cell or region is exposed as a **real** * `@tanstack/store` computed atom (`ReadonlyAtom`) — not a `{ state, subscribe }` * lookalike — so it composes with other atoms and the framework store hooks * (`useSelector`, `useStore`). The atom tracks the workbook's `revision` atom, * so it recomputes on every commit (coarser than `subscribeRegion`, which stays * the per-region perf primitive — these facades are the interop layer). * * Read views are genuinely read-only: the returned `ReadonlyAtom` has no `set`, * so the type tells the truth. Writes go through {@link writeCells}, which maps * to one `applyPatches` transaction. Atoms are **materialised lazily and cached * by key** (one computed atom per cell/region is affordable; one per 10⁶ cells * is not — the cache coalesces repeat requests). */ import { createAtom } from '@tanstack/store' import { pack } from './addr' import type { ReadonlyAtom } from '@tanstack/store' import type { CellValue, Rect, Ref, SheetId } from './types' import type { Workbook } from './workbook' interface WorkbookFacades { cells: Map> ranges: Map>>> } // Per-workbook facade cache — lazy materialisation, keyed by node identity. const CACHE = new WeakMap() function facadesFor(wb: Workbook): WorkbookFacades { let f = CACHE.get(wb) if (!f) CACHE.set(wb, (f = { cells: new Map(), ranges: new Map() })) return f } const cellKey = (ref: Ref) => `${ref.sheet} ${pack(ref.row, ref.col)}` const rectKey = (sheet: SheetId, r: Rect) => `${sheet} ${r.r0} ${r.c0} ${r.r1} ${r.c1}` /** Coerce a store-written value to the input string a cell stores. */ function toInput(value: CellValue): string { if (value === null) return '' if (typeof value === 'number' || typeof value === 'boolean') return String(value) if (typeof value === 'object') return '' // errors/pending aren't writable inputs return value // keep a leading '=' as a formula; otherwise literal text } /** * A read-only computed atom over one cell's value. Recomputes when the workbook * commits; composes with `Derived`/`useStore`/`useSelector`. The same atom is * returned for repeated calls on the same (workbook, cell), so subscriptions * coalesce. */ export function cellValueFacade( wb: Workbook, ref: Ref, ): ReadonlyAtom { const cache = facadesFor(wb).cells const key = cellKey(ref) let atom = cache.get(key) if (!atom) { atom = createAtom((): CellValue => { wb.atoms.revision.get() // track revision → recompute on every commit return wb.getCell(ref)?.value ?? null }) cache.set(key, atom) } return atom } /** * A read-only computed atom over a rectangular region as a dense 2D value grid, * aligned with `subscribeRegion`'s shape. Cached by rect. */ export function rangeFacade( wb: Workbook, sheet: SheetId, rect: Rect, ): ReadonlyAtom>> { const cache = facadesFor(wb).ranges const key = rectKey(sheet, rect) let atom = cache.get(key) if (!atom) { atom = createAtom((): Array> => { wb.atoms.revision.get() const grid: Array> = [] for (let r = rect.r0; r <= rect.r1; r++) { const row: Array = [] for (let c = rect.c0; c <= rect.c1; c++) { row.push(wb.getCell({ sheet, row: r, col: c })?.value ?? null) } grid.push(row) } return grid }) cache.set(key, atom) } return atom } /** * Apply several cell writes as one `applyPatches` transaction ("Store `batch()` * maps to one `applyPatches`"): one recalc, one set of region notifications, * instead of N. This is the write path — the read facades are genuinely * read-only. */ export function writeCells( wb: Workbook, edits: Array<{ ref: Ref; value: CellValue }>, ): void { const patches = edits.flatMap((e) => wb.setInput(e.ref, toInput(e.value))) wb.applyPatches(patches) }