@rowsncolumns/rnc-engine 1.10.7 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  // Lightweight dependency-graph NODE classes (data holders — NOT the JS calculator) used to shape the
2
2
  // real `getPrecedents`/`getDependents` results, which the engine now backs with actual graph data.
3
3
  import { CellNode, CellRangeNode, isCellCoordinate, isCellNode, makeKey, } from "@rowsncolumns/dag";
4
- import { DEFAULT_ACTIVE_CELL, DEFAULT_ARRAY, DEFAULT_COLUMN_WIDTH, DEFAULT_ROW_HEIGHT, isLinkedPictureSpec, defaultSpreadsheetTheme, getBandedCells, getInitialActiveSheetId, ICON_SET_COLORS, ICON_SET_GLYPHS, useFocusEmbedOrChart, useFonts, useGetSheetDimensions, useSetTableAutoExpansion, useSetCalculatedColumnFill, } from "@rowsncolumns/spreadsheet";
4
+ import { DEFAULT_ACTIVE_CELL, DEFAULT_ARRAY, DEFAULT_COLUMN_WIDTH, DEFAULT_ROW_HEIGHT, isLinkedPictureSpec, defaultSpreadsheetTheme, getBandedCells, getInitialActiveSheetId, ICON_SET_COLORS, ICON_SET_GLYPHS, useFocusEmbedOrChart, useFonts, useGetSheetDimensions, useSetTableAutoExpansion, useSetCalculatedColumnFill, useTableAutoExpansionValue, useCalculatedColumnFillValue, useSetFillOptions, useSetFlashFillOptions, useSetInsertOptions, } from "@rowsncolumns/spreadsheet";
5
5
  import { applyAdvancedFilterPlan, applySubtotalPlan, CellXfsRegistry, collectPaintMerges, generateDataFromClipboard, getBandedCellFormat, layerBandedFormat, paintSourceForActiveCell, pickFormula, pickValue, planAdvancedFilter, planSubtotals, resolvePasteSpecialOptions, SharedStringRegistry, spreadMergeAnchorFormats, tilePaintMerges, transpose, useOnCopy, previewTableStyle, useOnTraceDependentsPrecedents, useShowError, CIRCULAR_REFERENCE_WARNING_TITLE, planConsolidate, clearOutlineCalls, outlineStyleTargets, outlineSummaryAt, planAutoOutline, FLASH_FILL_NO_PATTERN_MESSAGE, FLASH_FILL_NO_PATTERN_TITLE, CircularReferenceTracker, formatCircularReferenceWarning, getDefaultCellFormat, } from "@rowsncolumns/spreadsheet-state";
6
6
  import { getFormulaLocale, normalizeExternalUrl, resolveDefaultHorizontalAlignment, uuidString, } from "@rowsncolumns/utils";
7
7
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -16,6 +16,7 @@ import { applyPasteSpecialToTiles, clipboardCellToPasteCell, clipboardFormats, c
16
16
  import { pastedMerges } from "./paste-merges";
17
17
  import { replayPasteEvent, snapshotClipboard } from "./paste-reapply";
18
18
  import { tileClipboardToSelection } from "./paste-tiling";
19
+ import { NO_STALE_CELLS } from "./stale-cells";
19
20
  import { windowRectReader } from "./rect-reader";
20
21
  import { flashFillTargetAt, planFlashFillInWindow, planFlashFillSuggestion, } from "./flash-fill";
21
22
  /** The width a column at no stored width takes (the grid's default, as `onCopy` reads it). */
@@ -441,6 +442,192 @@ function parseInternalLocation(location) {
441
442
  },
442
443
  };
443
444
  }
445
+ /**
446
+ * Commands that are not a person's edit: the store records no undo entry for them — rnc-store's
447
+ * `records_no_history` (`rust/crates/rnc-store/src/lib.rs`) one for one, plus the recalculation and
448
+ * calculation-setting commands `SpreadsheetStore::apply_command` sends down their own paths before
449
+ * any history capture: a host's answer to a custom function, a host formula-text rewrite,
450
+ * protection, an Unlock Range, F9 / Shift+F9 / Ctrl+Alt+F9, Calculation Options, iterative
451
+ * calculation. (`change-batch` with `enableHistory: false` is the store's one conditional entry; see
452
+ * {@link commandIsEdit}.) `fill-options-undo.spec.tsx` reads the Rust source and fails when the two
453
+ * lists part.
454
+ */
455
+ export const NOT_EDIT_COMMANDS = new Set([
456
+ "set-effective-value",
457
+ "rewrite-formula-text",
458
+ "protect-sheet",
459
+ "unprotect-sheet",
460
+ "protect-workbook",
461
+ "unprotect-workbook",
462
+ "unlock-allow-edit-range",
463
+ "recalculate",
464
+ "set-iterative-calculation",
465
+ "set-calculation-mode",
466
+ "calculate-sheet",
467
+ "calculate-full",
468
+ ]);
469
+ /**
470
+ * Commands that only change what this person sees, never the document another reader opens: the
471
+ * sheet tab they look at and a conditional-format rule previewed while its dialog is open (the
472
+ * store sends the preview down its own path with no undo entry, and never persists it). Every other
473
+ * store command changes the document — outline collapse, note visibility, freeze panes and the
474
+ * sheet view flags ride `update-sheet` and are saved with the file.
475
+ */
476
+ export const VIEW_ONLY_COMMANDS = new Set([
477
+ "set-active-sheet",
478
+ "preview-conditional-format",
479
+ ]);
480
+ /**
481
+ * Whether a command, given the commit it produced, is a person's edit — what the AutoCorrect smart
482
+ * tags count as "the next edit": any command outside {@link NOT_EDIT_COMMANDS} and
483
+ * {@link VIEW_ONLY_COMMANDS} that the engine did not refuse. A batch is one when any member is, and
484
+ * a refusal of one member does not undo the others. Read off the command, never off what the
485
+ * commit happened to report: a table resize, a defined name, a rule or a sheet is an edit even
486
+ * though it streams no cell. A command that changes nothing still counts (it drops the tags, which
487
+ * Excel's next action would too); a real edit never slips through.
488
+ */
489
+ export const commandIsEdit = (command, commit) => {
490
+ if (command.command === "batch") {
491
+ return command.commands.some((member) => commandIsEdit(member));
492
+ }
493
+ if ((commit?.rejections?.length ?? 0) > 0) {
494
+ return false;
495
+ }
496
+ if (command.command === "change-batch") {
497
+ return (command.options
498
+ ?.enableHistory !== false);
499
+ }
500
+ return (!NOT_EDIT_COMMANDS.has(command.command) &&
501
+ !VIEW_ONLY_COMMANDS.has(command.command));
502
+ };
503
+ const inRange = (range, rowIndex, columnIndex) => rowIndex >= range.startRowIndex &&
504
+ rowIndex <= range.endRowIndex &&
505
+ columnIndex >= range.startColumnIndex &&
506
+ columnIndex <= range.endColumnIndex;
507
+ /**
508
+ * Every cell a calculated-column tag's action can write when chosen (rnc-store, `lib.rs`).
509
+ * "Undo Calculated Column" (`undo_calculated_column`) restores the `previous` cells and clears the
510
+ * column's recorded formula on the table entry. "Overwrite all cells in this column"
511
+ * (`calculated_column` → `fill_table_column_body`) writes every body row of the column of the
512
+ * table as it stands when chosen and records the formula on the table entry: its body range when
513
+ * armed, the table entry covering any change to it since. Neither removes a column, a row or the
514
+ * table, so no formula, rule, chart or slicer elsewhere loses what it refers to.
515
+ */
516
+ export const calcTagActionRegions = (tag) => {
517
+ if (tag.kind === "overwrite") {
518
+ return [
519
+ {
520
+ range: {
521
+ startRowIndex: tag.range.startRowIndex,
522
+ endRowIndex: tag.range.endRowIndex,
523
+ startColumnIndex: tag.columnIndex,
524
+ endColumnIndex: tag.columnIndex,
525
+ },
526
+ },
527
+ ];
528
+ }
529
+ if (tag.previous.length === 0)
530
+ return [];
531
+ const cells = tag.previous.map(({ rowIndex, columnIndex }) => ({
532
+ rowIndex,
533
+ columnIndex,
534
+ }));
535
+ return [
536
+ {
537
+ range: {
538
+ startRowIndex: Math.min(...cells.map((c) => c.rowIndex)),
539
+ endRowIndex: Math.max(...cells.map((c) => c.rowIndex)),
540
+ startColumnIndex: Math.min(...cells.map((c) => c.columnIndex)),
541
+ endColumnIndex: Math.max(...cells.map((c) => c.columnIndex)),
542
+ },
543
+ cells,
544
+ },
545
+ ];
546
+ };
547
+ /** The JSON of one table's facet entry (`""` when the workbook has no such table). */
548
+ const tableFacetJson = (tables, tableId) => {
549
+ const table = tables?.find((t) => t.id === tableId);
550
+ return table ? JSON.stringify(table) : "";
551
+ };
552
+ /** The most cells a tag's regions may hold, together, to be read back. */
553
+ export const TAG_CELLS_READ_CAP = 10_000;
554
+ /**
555
+ * A tag's action cells as the engine holds them (value or formula, and format) as one string to
556
+ * compare across a remote fold: one window read per region. `""` when the action writes no cell;
557
+ * `null` when the regions hold more than {@link TAG_CELLS_READ_CAP} cells, or the read fails
558
+ * (never compared: the tag drops on doubt).
559
+ */
560
+ export const readTagRegions = (engine, sheetId, regions) => {
561
+ let total = 0;
562
+ for (const { range } of regions) {
563
+ total +=
564
+ (range.endRowIndex - range.startRowIndex + 1) *
565
+ (range.endColumnIndex - range.startColumnIndex + 1);
566
+ }
567
+ if (total > TAG_CELLS_READ_CAP)
568
+ return null;
569
+ try {
570
+ return readRegions(engine, sheetId, regions);
571
+ }
572
+ catch {
573
+ return null;
574
+ }
575
+ };
576
+ const readRegions = (engine, sheetId, regions) => {
577
+ const byPosition = (x, y) => x.rowIndex - y.rowIndex || x.columnIndex - y.columnIndex;
578
+ return JSON.stringify(regions.map(({ range, cells }) => {
579
+ const keys = cells && new Set(cells.map((c) => `${c.rowIndex}:${c.columnIndex}`));
580
+ const kept = (entry) => !keys || keys.has(`${entry.rowIndex}:${entry.columnIndex}`);
581
+ const snap = engine.readWindow(sheetId, range.startRowIndex, range.startColumnIndex, range.endRowIndex, range.endColumnIndex);
582
+ return [
583
+ snap.cells.filter(kept).sort(byPosition),
584
+ snap.styles.filter(kept).sort(byPosition),
585
+ ];
586
+ }));
587
+ };
588
+ /** Remember a calculated-column tag just armed, with what its action writes as it stands now. */
589
+ const armCalcTag = (engine, record, tables) => {
590
+ const regions = calcTagActionRegions(record);
591
+ return {
592
+ record,
593
+ regions,
594
+ tableJson: tableFacetJson(tables, record.tableId),
595
+ cellsJson: readTagRegions(engine, record.sheetId, regions),
596
+ };
597
+ };
598
+ /**
599
+ * Whether a collaborator's commit (a remote sync fold) touches what a pending calculated-column
600
+ * tag's action would write, so the tag has to go: its table's facet entry changed (a resize, a
601
+ * rename, a column, the totals row, the table removed); rows, columns or merges moved on the tag's
602
+ * sheet (the regions no longer name the same cells); or the value, formula or format of a cell the
603
+ * action would write changed (a recalculation counts). Notes are not compared: no action writes
604
+ * one. Where the fold's per-cell report cannot say — it resynced the tag's sheet whole (the collab
605
+ * engine's `syncRemote` does, for every sheet, after any remote update), or a windowed render left
606
+ * cells out of it — `cellsChanged` reads the regions back and compares them with how they were when
607
+ * the tag was armed; it answers `true` whenever it cannot compare. The tag never stays on doubt.
608
+ */
609
+ export const remoteFoldTouchesTag = (commit, scope, tableChanged, cellsChanged) => {
610
+ if (tableChanged)
611
+ return true;
612
+ const { sheetId, regions } = scope;
613
+ const onSheet = (entry) => entry.sheetId === sheetId;
614
+ if (commit.rowChanges?.some(onSheet) ||
615
+ commit.columnChanges?.some(onSheet) ||
616
+ commit.merges?.some(onSheet)) {
617
+ return true;
618
+ }
619
+ if ((commit.omittedCells ?? 0) > 0 ||
620
+ commit.fullResyncSheets?.includes(sheetId)) {
621
+ return cellsChanged();
622
+ }
623
+ const touched = (entry) => entry.sheetId === sheetId &&
624
+ regions.some(({ range, cells }) => inRange(range, entry.rowIndex, entry.columnIndex) &&
625
+ (!cells ||
626
+ cells.some((c) => c.rowIndex === entry.rowIndex &&
627
+ c.columnIndex === entry.columnIndex)));
628
+ return ((commit.changes?.some(touched) ?? false) ||
629
+ (commit.styleChanges?.some(touched) ?? false));
630
+ };
444
631
  // `useEngineCore` is the engine-only surface (data / calc / commands / accessors) — NOT a standalone
445
632
  // drop-in for `useSpreadsheetState`. The chrome (dialogs + host intents) lives in `useSpreadsheetUI`;
446
633
  // the drop-in parity lock is asserted on their composition, `useSpreadsheetEngine`.
@@ -556,6 +743,13 @@ export function useEngineCore(options) {
556
743
  // every commit bumps the tick so the pictures redraw — only while the workbook has one.
557
744
  const hasLinkedPicturesRef = useRef(false);
558
745
  const [linkedPictureTick, setLinkedPictureTick] = useState(0);
746
+ // Format Stale Values: the active sheet's formula cells Manual calculation left out of date (pass
747
+ // to CanvasGrid's `staleCells` when the host's setting is on). Read from the engine only after a
748
+ // commit that says a calculation is pending; a commit that does not clears it. In an automatic mode
749
+ // no commit says so: nothing is read, allocated or set, and it stays `NO_STALE_CELLS`.
750
+ const [staleCells, setStaleCells] = useState(NO_STALE_CELLS);
751
+ const staleCellsRef = useRef(NO_STALE_CELLS);
752
+ const calculationPendingRef = useRef(false);
559
753
  const customAutofillListsRef = useRef(options.customAutofillLists);
560
754
  customAutofillListsRef.current = options.customAutofillLists;
561
755
  const autoExpandTablesRef = useRef(options.autoExpandTables);
@@ -578,6 +772,36 @@ export function useEngineCore(options) {
578
772
  // Excel's AutoCorrect smart tag after a formula typed into a table column — armed from the
579
773
  // commit's `calculatedColumnFill` record; `CanvasGrid` renders it.
580
774
  const setCalculatedColumnFill = useSetCalculatedColumnFill();
775
+ // Every smart tag (Auto Fill Options, Insert Options, AutoCorrect Options, Flash Fill Options,
776
+ // the calculated-column tag) acts on the edit it belongs to: an undo or redo, by any route
777
+ // (keyboard, toolbar, menu), takes them away so a choice cannot act on an undone edit.
778
+ const setFillOptions = useSetFillOptions();
779
+ const setInsertOptions = useSetInsertOptions();
780
+ const setFlashFillOptions = useSetFlashFillOptions();
781
+ // The calculated-column tag this hook armed and has not dropped, with what its action writes and
782
+ // its table's facet entry when it was armed — what a collaborator's commit is checked against.
783
+ // A tag cleared or replaced elsewhere (`CanvasGrid`'s sheet-switch and left-the-table checks, a
784
+ // host's setter) no longer matches the atom, and the remote check forgets it without a read.
785
+ // The tag atoms are mirrored in refs (set synchronously when this hook arms one).
786
+ const pendingCalcTagRef = useRef(null);
787
+ const tableTagRef = useRef(null);
788
+ tableTagRef.current = useTableAutoExpansionValue();
789
+ const calcTagRef = useRef(null);
790
+ calcTagRef.current = useCalculatedColumnFillValue();
791
+ const dropSmartTags = useCallback(() => {
792
+ setFillOptions(null);
793
+ setInsertOptions(null);
794
+ setTableAutoExpansion(null);
795
+ setCalculatedColumnFill(null);
796
+ setFlashFillOptions(null);
797
+ pendingCalcTagRef.current = null;
798
+ }, [
799
+ setFillOptions,
800
+ setInsertOptions,
801
+ setTableAutoExpansion,
802
+ setCalculatedColumnFill,
803
+ setFlashFillOptions,
804
+ ]);
581
805
  // One windowed read = the buffered window + the sheet's frozen bands + the sheet's active cell
582
806
  // (pinned so the formula bar's active-cell read survives scrolling it out of the window — see
583
807
  // `readWindowWithFrozenBands`). Frozen counts come from the host's getter when provided (see
@@ -620,6 +844,15 @@ export function useEngineCore(options) {
620
844
  // falling back to the first seed (seeds may omit `title`, which that helper filters out) — then 1.
621
845
  const [activeSheetId, setActiveSheetId] = useState(() => getInitialActiveSheetId(options.sheets) ?? options.sheets[0]?.sheetId ?? 1);
622
846
  const [activeCellBySheetId, setActiveCellBySheetId] = useState({});
847
+ // Format Stale Values follows the active sheet, while a calculation is pending only.
848
+ useEffect(() => {
849
+ const engine = engineRef.current;
850
+ if (!calculationPendingRef.current || !engine)
851
+ return;
852
+ const next = engine.staleFormulaCells(activeSheetId);
853
+ staleCellsRef.current = next;
854
+ setStaleCells(next);
855
+ }, [activeSheetId]);
623
856
  const [selectionsBySheetId, setSelectionsBySheetId] = useState({});
624
857
  const activeCellBySheetIdRef = useRef(activeCellBySheetId);
625
858
  const selectionsBySheetIdRef = useRef(selectionsBySheetId);
@@ -770,9 +1003,22 @@ export function useEngineCore(options) {
770
1003
  const snaps = readWindowedSnapshots(engine, w);
771
1004
  setState((prev) => foldWindows(prev, snaps));
772
1005
  };
773
- unsubscribe = engine.onChanges((commit) => {
1006
+ unsubscribe = engine.onChanges((commit, origin) => {
774
1007
  if (hasLinkedPicturesRef.current)
775
1008
  setLinkedPictureTick((t) => t + 1);
1009
+ if (commit.calculationPending) {
1010
+ calculationPendingRef.current = true;
1011
+ const next = engine.staleFormulaCells(viewRef.current.activeSheetId);
1012
+ if (next !== staleCellsRef.current) {
1013
+ staleCellsRef.current = next;
1014
+ setStaleCells(next);
1015
+ }
1016
+ }
1017
+ else if (calculationPendingRef.current) {
1018
+ calculationPendingRef.current = false;
1019
+ staleCellsRef.current = NO_STALE_CELLS;
1020
+ setStaleCells(NO_STALE_CELLS);
1021
+ }
776
1022
  // Before anything folds: what the grid drew when this commit began is what a `holdCells`
777
1023
  // right after it copies. Then release holds whose sheet this commit moved.
778
1024
  const drawn = drawnRef.current;
@@ -789,13 +1035,15 @@ export function useEngineCore(options) {
789
1035
  // be derived from the command. `reconcileSheets` preserves each surviving sheet's
790
1036
  // dimension/merge metadata and returns the SAME array when nothing changed (no churn).
791
1037
  const engineSheets = engine.sheets();
1038
+ // Read only for a sheet whose background version changed (see `reconcileSheets`).
1039
+ const readBackground = (sheetId) => engine.sheetBackgroundImageUrl(sheetId);
792
1040
  if (windowedRef.current) {
793
1041
  // Windowed: do NOT accumulate the commit's cell changes (that's the 1M-row blowup). Fold only
794
1042
  // the structural channels (dimensions / merges), then re-read the CURRENT window so in-view
795
1043
  // edits + recomputed dependents update. Out-of-view changes need no folding.
796
1044
  setState((prev) => {
797
1045
  const folded = foldCommitStructuralOnly(prev, commit);
798
- const sheets = reconcileSheets(folded.sheets, engineSheets);
1046
+ const sheets = reconcileSheets(folded.sheets, engineSheets, readBackground);
799
1047
  return sheets === folded.sheets ? folded : { ...folded, sheets };
800
1048
  });
801
1049
  refreshWindow();
@@ -804,7 +1052,7 @@ export function useEngineCore(options) {
804
1052
  else {
805
1053
  setState((prev) => {
806
1054
  const folded = foldCommit(prev, commit);
807
- const sheets = reconcileSheets(folded.sheets, engineSheets);
1055
+ const sheets = reconcileSheets(folded.sheets, engineSheets, readBackground);
808
1056
  return sheets === folded.sheets ? folded : { ...folded, sheets };
809
1057
  });
810
1058
  }
@@ -850,6 +1098,34 @@ export function useEngineCore(options) {
850
1098
  const nextFacets = engine.documentFacetsJson();
851
1099
  setFacetsJson((prev) => (prev === nextFacets ? prev : nextFacets));
852
1100
  setHist({ canUndo: engine.canUndo(), canRedo: engine.canRedo() });
1101
+ // A collaborator's commit arrives with no command, so `onCommand`'s next-edit rule never
1102
+ // sees it. The table-expansion tag goes on ANY remote update: its undo resizes the table
1103
+ // back, which can break what a collaborator built on the grown table anywhere (a formula
1104
+ // naming its new column turns into #REF!, a slicer on it loses its column), so no
1105
+ // comparison could prove it safe. A calculated-column tag goes when the fold touched what
1106
+ // its action writes (`remoteFoldTouchesTag`). A new document drops every tag. With no tag
1107
+ // pending this costs two ref reads.
1108
+ if (origin === "load") {
1109
+ dropSmartTags();
1110
+ }
1111
+ else if (origin === "remote") {
1112
+ if (tableTagRef.current) {
1113
+ setTableAutoExpansion(null);
1114
+ }
1115
+ const pending = pendingCalcTagRef.current;
1116
+ if (pending && pending.record !== calcTagRef.current) {
1117
+ pendingCalcTagRef.current = null;
1118
+ }
1119
+ else if (pending) {
1120
+ const facets = JSON.parse(nextFacets);
1121
+ if (remoteFoldTouchesTag(commit, { sheetId: pending.record.sheetId, regions: pending.regions }, tableFacetJson(facets.tables, pending.record.tableId) !==
1122
+ pending.tableJson, () => pending.cellsJson === null ||
1123
+ readTagRegions(engine, pending.record.sheetId, pending.regions) !== pending.cellsJson)) {
1124
+ setCalculatedColumnFill(null);
1125
+ pendingCalcTagRef.current = null;
1126
+ }
1127
+ }
1128
+ }
853
1129
  // Resolve host custom-function requests: run the registered JS impl with the engine's RESOLVED
854
1130
  // args + the calling cell, then push the result (incl. `structuredValue`) back via
855
1131
  // `set-effective-value`. Everything is deferred to a microtask, so we never re-enter the engine
@@ -1129,11 +1405,27 @@ export function useEngineCore(options) {
1129
1405
  // A value-writing command grew a table over the written cells: arm the AutoCorrect smart tag
1130
1406
  // with the engine's record of the growth (rowsncolumns/spreadsheet#668 T-12) — "Undo Table
1131
1407
  // AutoExpansion" resizes back and clears the cells the growth wrote (`writes`, T-89).
1408
+ // The AutoCorrect tags belong to the edit that armed them: the next edit drops them. An edit
1409
+ // is read off the command (`commandIsEdit`), never off the undo stack's depth, which stops
1410
+ // growing at the store's history cap and stays flat when a store groups quick edits into one
1411
+ // entry. A collaborator's update drops them in the `onChanges` remote branch; arming the
1412
+ // calculated-column tag remembers what its action writes as it stands now, to compare there.
1413
+ const isEdit = commandIsEdit(command, commit);
1132
1414
  if (commit.tableAutoExpansion) {
1133
1415
  setTableAutoExpansion(commit.tableAutoExpansion);
1416
+ tableTagRef.current = commit.tableAutoExpansion;
1417
+ }
1418
+ else if (isEdit) {
1419
+ setTableAutoExpansion(null);
1134
1420
  }
1135
1421
  if (commit.calculatedColumnFill) {
1136
1422
  setCalculatedColumnFill(commit.calculatedColumnFill);
1423
+ calcTagRef.current = commit.calculatedColumnFill;
1424
+ pendingCalcTagRef.current = armCalcTag(engine, commit.calculatedColumnFill, engine.documentFacets().tables);
1425
+ }
1426
+ else if (isEdit) {
1427
+ setCalculatedColumnFill(null);
1428
+ pendingCalcTagRef.current = null;
1137
1429
  }
1138
1430
  // A refusal wrote nothing — show the user Excel's dialog text through the same channel the
1139
1431
  // legacy engine's hooks use (`useShowError`), once: `createCommandHandlers` skips the
@@ -1270,10 +1562,17 @@ export function useEngineCore(options) {
1270
1562
  // Chart selection after an undo/redo step (Excel: the chart an undo brings back, or a redo
1271
1563
  // re-creates / re-positions, ends up selected; one whose step removed it is deselected). The
1272
1564
  // engine's chart deltas are the signal — same as the legacy history's `selectedEmbedOrChart`.
1273
- const restoreChartSelection = useCallback((commit) => {
1565
+ // After an undo or redo: select a chart the step brought back or moved (Excel shows where the
1566
+ // object went); a chart whose look merely changed (a theme, a style, a title) keeps the selection
1567
+ // as it was. A removed chart is deselected. `before` is the charts as drawn before the step.
1568
+ const restoreChartSelection = useCallback((commit, before) => {
1274
1569
  for (const change of commit.chartChanges) {
1275
1570
  if (change.chart) {
1276
- focusEmbedOrChart(change.chartId);
1571
+ const previous = before.get(change.chartId);
1572
+ const placed = !previous ||
1573
+ JSON.stringify(previous.position) !== JSON.stringify(change.chart.position);
1574
+ if (placed)
1575
+ focusEmbedOrChart(change.chartId);
1277
1576
  }
1278
1577
  else {
1279
1578
  focusEmbedOrChart((prev) => prev === change.chartId ? undefined : prev);
@@ -1290,7 +1589,9 @@ export function useEngineCore(options) {
1290
1589
  return;
1291
1590
  // An undo rewrites cells no command range names: show them all.
1292
1591
  releaseCells();
1592
+ dropSmartTags();
1293
1593
  const prevDepth = engine.undoDepth();
1594
+ const chartsBefore = drawnRef.current.state.charts;
1294
1595
  const commit = engine.undo();
1295
1596
  if (engine.undoDepth() < prevDepth) {
1296
1597
  const restore = viewUndo.current.pop();
@@ -1300,14 +1601,16 @@ export function useEngineCore(options) {
1300
1601
  }
1301
1602
  }
1302
1603
  lastUndoDepth.current = engine.undoDepth();
1303
- restoreChartSelection(commit);
1304
- }, [applyView, restoreChartSelection, releaseCells]);
1604
+ restoreChartSelection(commit, chartsBefore);
1605
+ }, [applyView, restoreChartSelection, releaseCells, dropSmartTags]);
1305
1606
  const redo = useCallback(() => {
1306
1607
  const engine = engineRef.current;
1307
1608
  if (!engine)
1308
1609
  return;
1309
1610
  releaseCells();
1611
+ dropSmartTags();
1310
1612
  const prevRedoDepth = engine.redoDepth();
1613
+ const chartsBefore = drawnRef.current.state.charts;
1311
1614
  const commit = engine.redo();
1312
1615
  if (engine.redoDepth() < prevRedoDepth) {
1313
1616
  const restore = viewRedo.current.pop();
@@ -1317,8 +1620,8 @@ export function useEngineCore(options) {
1317
1620
  }
1318
1621
  }
1319
1622
  lastUndoDepth.current = engine.undoDepth();
1320
- restoreChartSelection(commit);
1321
- }, [applyView, restoreChartSelection, releaseCells]);
1623
+ restoreChartSelection(commit, chartsBefore);
1624
+ }, [applyView, restoreChartSelection, releaseCells, dropSmartTags]);
1322
1625
  const load = useCallback((document) => {
1323
1626
  releaseCells();
1324
1627
  engineRef.current?.load(document);
@@ -1341,7 +1644,9 @@ export function useEngineCore(options) {
1341
1644
  const commit = engine.importXlsx(bytes);
1342
1645
  if (!commit)
1343
1646
  return false;
1344
- // A replaced document holds nothing from the old one.
1647
+ // A replaced document holds nothing from the old one: no smart tag acts on it (the import
1648
+ // notifies no subscriber, so the `load` branch that drops them never runs).
1649
+ dropSmartTags();
1345
1650
  if (heldCellsRef.current) {
1346
1651
  heldCellsRef.current = null;
1347
1652
  setHeldCells(null);
@@ -1381,6 +1686,7 @@ export function useEngineCore(options) {
1381
1686
  commit !== null &&
1382
1687
  Array.isArray(commit.changes);
1383
1688
  const extents = engine.sheetExtents?.() ?? [];
1689
+ const readBackground = (sheetId) => engine.sheetBackgroundImageUrl(sheetId);
1384
1690
  setState(() => {
1385
1691
  let next = emptyRenderState(seedSheets);
1386
1692
  if (windowedRef.current) {
@@ -1409,7 +1715,7 @@ export function useEngineCore(options) {
1409
1715
  }
1410
1716
  }
1411
1717
  }
1412
- const sheets = reconcileSheets(next.sheets, engineSheets);
1718
+ const sheets = reconcileSheets(next.sheets, engineSheets, readBackground);
1413
1719
  return sheets === next.sheets ? next : { ...next, sheets };
1414
1720
  });
1415
1721
  // Re-read the engine's authoritative facets / extents / history after the replace.
@@ -1434,7 +1740,7 @@ export function useEngineCore(options) {
1434
1740
  };
1435
1741
  setActiveSheetId(firstId);
1436
1742
  return true;
1437
- }, []);
1743
+ }, [dropSmartTags]);
1438
1744
  // WINDOWED reads. Wire to CanvasGrid's `onViewPortChange`: read the visible range (+ a buffer) from
1439
1745
  // the engine and replace the in-JS window (evicting cells outside it, so memory stays O(viewport)).
1440
1746
  // A no-op in the default mode (every cell is already folded). Reads the active sheet from `viewRef`
@@ -1555,6 +1861,15 @@ export function useEngineCore(options) {
1555
1861
  }
1556
1862
  : getUnheldEffectiveFormat, [heldCells, getUnheldEffectiveFormat]);
1557
1863
  const getNote = useCallback((sheetId, rowIndex, columnIndex) => notes.get(cellKey(sheetId, rowIndex, columnIndex)), [notes]);
1864
+ const localizeNumber = useCallback((value, numberFormat) => {
1865
+ if (!displayLocale && !shortDateFormat)
1866
+ return undefined;
1867
+ if (!displayLocale &&
1868
+ !isBuiltInShortDatePattern(numberFormat?.pattern, documentLocale)) {
1869
+ return undefined;
1870
+ }
1871
+ return localizeDisplayValue(value, numberFormat ?? undefined, displayLocale ?? documentLocale, documentLocale, shortDateFormat);
1872
+ }, [displayLocale, documentLocale, shortDateFormat]);
1558
1873
  const getFormattedValue = useCallback((sheetId, rowIndex, columnIndex) => {
1559
1874
  const cell = getCellData(sheetId, rowIndex, columnIndex);
1560
1875
  // A host-call cell awaiting its answer displays the loading placeholder, not the engine's
@@ -1593,15 +1908,12 @@ export function useEngineCore(options) {
1593
1908
  if ((displayLocale || shortDateFormat) &&
1594
1909
  typeof cell?.ev?.nv === "number" &&
1595
1910
  cell.ev.ev == null) {
1596
- const numberFormat = getEffectiveFormat(sheetId, rowIndex, columnIndex)?.numberFormat;
1597
- if (displayLocale || isBuiltInShortDatePattern(numberFormat?.pattern, documentLocale)) {
1598
- const localized = localizeDisplayValue(cell.ev.nv, numberFormat, displayLocale ?? documentLocale, documentLocale, shortDateFormat);
1599
- if (localized !== undefined)
1600
- return localized;
1601
- }
1911
+ const localized = localizeNumber(cell.ev.nv, getEffectiveFormat(sheetId, rowIndex, columnIndex)?.numberFormat);
1912
+ if (localized !== undefined)
1913
+ return localized;
1602
1914
  }
1603
1915
  return cell?.fv ?? undefined;
1604
- }, [getCellData, getEffectiveFormat, displayLocale, documentLocale, shortDateFormat]);
1916
+ }, [getCellData, getEffectiveFormat, displayLocale, shortDateFormat, localizeNumber]);
1605
1917
  // The cell's effective value as a SCALAR (bool ?? number ?? string) — the shape `<CanvasGrid>` and
1606
1918
  // chart series want. Mirrors useSheetProperties' `getEffectiveValue`. Errors → undefined.
1607
1919
  const getEffectiveValue = useCallback((sheetId, rowIndex, columnIndex) => {
@@ -3484,6 +3796,7 @@ export function useEngineCore(options) {
3484
3796
  theme,
3485
3797
  getCellData,
3486
3798
  getFormattedValue,
3799
+ localizeNumber,
3487
3800
  getLinkedPictureSource,
3488
3801
  getUserEnteredValue,
3489
3802
  getEffectiveValue,
@@ -3611,6 +3924,7 @@ export function useEngineCore(options) {
3611
3924
  onPaste,
3612
3925
  onInsertCopiedCells,
3613
3926
  onReapplyPaste,
3927
+ staleCells,
3614
3928
  }), [
3615
3929
  formulaLocale,
3616
3930
  state,
@@ -3667,6 +3981,7 @@ export function useEngineCore(options) {
3667
3981
  theme,
3668
3982
  getCellData,
3669
3983
  getFormattedValue,
3984
+ localizeNumber,
3670
3985
  getLinkedPictureSource,
3671
3986
  getUserEnteredValue,
3672
3987
  getEffectiveValue,
@@ -3743,6 +4058,7 @@ export function useEngineCore(options) {
3743
4058
  onPaste,
3744
4059
  onInsertCopiedCells,
3745
4060
  onReapplyPaste,
4061
+ staleCells,
3746
4062
  ]);
3747
4063
  }
3748
4064
  /** Where `range` sits once cells open at `band` and shift `direction` (a range wholly in the band's