/** * Transaction helpers: turning input strings into cells, and inverting patches * for undo/redo. The full recalc pipeline (dirty set -> topo -> evaluate) is * layered on in M3; M1 handles only literal coercion. */ import type { Cell, CellValue, Patch } from './types' /** * Coerce a raw literal input string into a {@link CellValue}. * * A leading apostrophe forces text (`"'123"` -> the string `"123"`) — this is * both Excel behavior and the seam the formula-injection guard uses later. */ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/ const MS_PER_DAY = 86_400_000 /** Days between the Excel epoch (1899-12-30) and the Unix epoch. */ const EXCEL_EPOCH_OFFSET = 25_569 export function coerceLiteral(input: string): CellValue { if (input === '') return null if (input[0] === "'") return input.slice(1) const upper = input.toUpperCase() if (upper === 'TRUE') return true if (upper === 'FALSE') return false // ISO date (`2020-01-01`) -> Excel date serial, so dates are computable and // decomposable (DATE/YEAR/MONTH/DAY). Display as a date is the format layer's // job. An out-of-range date (`2020-13-45`) falls through to text. if (ISO_DATE.test(input)) { const ms = Date.parse(input + 'T00:00:00Z') if (!Number.isNaN(ms)) return ms / MS_PER_DAY + EXCEL_EPOCH_OFFSET } // Numeric: reject the empty string and things like " " or "1 2" that Number // would coerce too eagerly. if (input.trim() !== '') { const n = Number(input) if (!Number.isNaN(n) && Number.isFinite(n)) return n } return input } /** Whether an input string is a formula (parsed by the engine, not coerced). */ export function isFormula(input: string): boolean { return input.length > 1 && input[0] === '=' } /** * Build a {@link Cell} from an input string. Formula cells get `kind:'formula'` * and a provisional `null` value; the evaluator fills `ast`/`value` during * recalc (M3). Literal cells are coerced immediately. */ export function makeCell(input: string): Cell { if (isFormula(input)) { return { input, kind: 'formula', value: null } } return { input, kind: 'literal', value: coerceLiteral(input) } } /** * Invert a command's patches for undo: swap before/after on each and reverse * order, so applying the result restores the prior inputs exactly. */ export function invertPatches(patches: Array): Array { const out: Array = [] for (let i = patches.length - 1; i >= 0; i--) { const p = patches[i]! out.push({ sheet: p.sheet, key: p.key, before: p.after, after: p.before }) } return out }