@rowsncolumns/rnc-engine 1.5.2 → 1.7.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.
@@ -2,19 +2,40 @@
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
4
  import { DEFAULT_ACTIVE_CELL, DEFAULT_ARRAY, defaultSpreadsheetTheme, getBandedCells, getInitialActiveSheetId, ICON_SET_COLORS, ICON_SET_GLYPHS, useFocusEmbedOrChart, useFonts, useGetSheetDimensions, useSetTableAutoExpansion, useSetCalculatedColumnFill, } from "@rowsncolumns/spreadsheet";
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, CircularReferenceTracker, formatCircularReferenceWarning, getDefaultCellFormat, } from "@rowsncolumns/spreadsheet-state";
6
- import { getFormulaLocale, normalizeExternalUrl, resolveDefaultHorizontalAlignment, } from "@rowsncolumns/utils";
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
+ import { getFormulaLocale, normalizeExternalUrl, resolveDefaultHorizontalAlignment, uuidString, } from "@rowsncolumns/utils";
7
7
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8
8
  import { createCommandHandlers, rejectionDialog, } from "./command-handlers";
9
+ import { ENGINE_DEFAULT_LOCALE, isForeignDisplayLocale, localizeDisplayValue, localizeEnteredNumber, } from "./display-locale";
9
10
  import { emptyRenderState, foldCommit, foldCommitStructuralOnly, foldWindow, foldWindows, frozenBandRanges, reconcileSheets, } from "./fold";
10
11
  import { RncEngine, } from "./index";
11
12
  import { cellKey, parseCellKey } from "./keys";
12
13
  import { fallbackSheetAfterDelete } from "./sheet-fallback";
13
14
  import { rescopeRulesAfterMove } from "./move-rescope";
14
- import { applyPasteSpecialToTiles, clipboardCellToPasteCell, isSkippedPasteCell, } from "./paste-special";
15
+ import { applyPasteSpecialToTiles, clipboardCellToPasteCell, clipboardFormats, columnWidthCopies, isSkippedPasteCell, noteCopies, pasteLinkCells, reattachClipboardFormats, validationCopies, withoutBorders, } from "./paste-special";
15
16
  import { pastedMerges } from "./paste-merges";
17
+ import { replayPasteEvent, snapshotClipboard } from "./paste-reapply";
16
18
  import { tileClipboardToSelection } from "./paste-tiling";
17
19
  import { windowRectReader } from "./rect-reader";
20
+ import { flashFillTargetAt, planFlashFillInWindow, planFlashFillSuggestion, } from "./flash-fill";
21
+ /** The width a column at no stored width takes (the grid's default, as `onCopy` reads it). */
22
+ const DEFAULT_PASTE_COLUMN_WIDTH = 100;
23
+ const EMPTY_ALLOW_EDIT_RANGES = [];
24
+ /** The selection the active cell sits in. */
25
+ const activeRange = (activeCell, selections) => selections?.find((s) => s.range &&
26
+ activeCell.rowIndex >= s.range.startRowIndex &&
27
+ activeCell.rowIndex <= s.range.endRowIndex &&
28
+ activeCell.columnIndex >= s.range.startColumnIndex &&
29
+ activeCell.columnIndex <= s.range.endColumnIndex)?.range;
30
+ const isSingleCell = (range) => !range ||
31
+ (range.startRowIndex === range.endRowIndex &&
32
+ range.startColumnIndex === range.endColumnIndex);
33
+ const indexRun = (start, end) => {
34
+ const out = [];
35
+ for (let i = start; i <= end; i++)
36
+ out.push(i);
37
+ return out;
38
+ };
18
39
  /** Minimum extra rows/columns to read on EACH side of the visible range so a small scroll reveals
19
40
  * already-loaded cells (no flash) before the next `readWindow`. The buffer actually used scales with
20
41
  * the viewport (see {@link windowBuffer}) and is never smaller than this. The window size stays
@@ -278,6 +299,24 @@ function withDocumentTheme(document, host) {
278
299
  };
279
300
  }
280
301
  /** Seed for the parsed facets before the first commit (stable reference). */
302
+ /**
303
+ * The sheet a workbook opens on: the one the document names (the imported file's active tab, Excel's
304
+ * `<workbookView activeTab>`) when it is still a visible sheet, else the first visible titled sheet.
305
+ */
306
+ export const getOpeningSheetId = (sheets, documentActiveSheetId) => {
307
+ const named = sheets.find((sheet) => sheet.sheetId === documentActiveSheetId && !sheet.hidden);
308
+ return named?.sheetId ?? getInitialActiveSheetId(sheets);
309
+ };
310
+ /** `documentFacets.activeSheetId` from the raw facets JSON (`null` when unreadable). */
311
+ const documentActiveSheetId = (facetsJson) => {
312
+ try {
313
+ const id = JSON.parse(facetsJson).activeSheetId;
314
+ return typeof id === "number" ? id : null;
315
+ }
316
+ catch {
317
+ return null;
318
+ }
319
+ };
281
320
  const EMPTY_FACETS = {
282
321
  conditionalFormats: [],
283
322
  dataValidations: [],
@@ -514,6 +553,15 @@ export function useEngineCore(options) {
514
553
  customAutofillListsRef.current = options.customAutofillLists;
515
554
  const autoExpandTablesRef = useRef(options.autoExpandTables);
516
555
  autoExpandTablesRef.current = options.autoExpandTables;
556
+ // The person's Regional Format vs the locale the document formats in (`locale`, else en-US).
557
+ const documentLocale = options.locale ?? ENGINE_DEFAULT_LOCALE;
558
+ const displayLocale = isForeignDisplayLocale(options.displayLocale, documentLocale)
559
+ ? options.displayLocale
560
+ : undefined;
561
+ const entryLocaleRef = useRef({
562
+ document: documentLocale,
563
+ });
564
+ entryLocaleRef.current = { display: displayLocale, document: documentLocale };
517
565
  const autoCalculatedColumnsRef = useRef(options.autoCalculatedColumns);
518
566
  autoCalculatedColumnsRef.current = options.autoCalculatedColumns;
519
567
  // Excel's AutoCorrect smart tag after a table auto-expanded — armed from the commit's
@@ -777,7 +825,7 @@ export function useEngineCore(options) {
777
825
  engineSheets.some((s) => !seedSheetIdsRef.current.has(s.sheetId))) {
778
826
  activeSheetRederivedRef.current = true;
779
827
  if (!userPickedSheetRef.current) {
780
- const derivedId = getInitialActiveSheetId(engineSheets) ?? engineSheets[0].sheetId;
828
+ const derivedId = getOpeningSheetId(engineSheets, documentActiveSheetId(engine.documentFacetsJson())) ?? engineSheets[0].sheetId;
781
829
  // Move through `activateSheetView`, never a bare `setActiveSheetId`: the tab strip
782
830
  // reads `activeSheetId` while the windowed grid paints `windowRef`'s sheet, and a
783
831
  // bare set moved only the former — after a peer (agent) created the first non-seed
@@ -863,8 +911,17 @@ export function useEngineCore(options) {
863
911
  });
864
912
  }
865
913
  });
866
- if (initial.current.initialDocument)
914
+ if (initial.current.initialDocument) {
867
915
  engine.load(initial.current.initialDocument);
916
+ // The loaded workbook opens on the sheet it names (an imported file's active tab).
917
+ const opening = getOpeningSheetId(engine.sheets(), documentActiveSheetId(engine.documentFacetsJson()));
918
+ if (opening != null &&
919
+ !userPickedSheetRef.current &&
920
+ opening !== viewRef.current.activeSheetId) {
921
+ viewRef.current = viewOfSheet(opening);
922
+ setActiveSheetId(opening);
923
+ }
924
+ }
868
925
  // Push the host's starting locale so the first render is already localized (re-derives + streams
869
926
  // every formatted cell). en-US is the engine default, so only a non-default locale needs this.
870
927
  if (initial.current.locale && initial.current.locale !== "en-US")
@@ -876,7 +933,7 @@ export function useEngineCore(options) {
876
933
  // first scroll event) and read the engine's extents. The load above already ran with `windowRef`
877
934
  // null (so its commit folded only structurally — no 1M-cell accumulation); we now read the window.
878
935
  if (windowedRef.current) {
879
- const firstSheet = initial.current.sheets[0]?.sheetId;
936
+ const firstSheet = viewRef.current.activeSheetId ?? initial.current.sheets[0]?.sheetId;
880
937
  if (firstSheet != null) {
881
938
  windowRef.current = {
882
939
  sheetId: firstSheet,
@@ -1291,7 +1348,11 @@ export function useEngineCore(options) {
1291
1348
  type: es.type,
1292
1349
  chartId: es.chartId,
1293
1350
  }));
1294
- const firstId = engineSheets[0]?.sheetId ?? viewRef.current.activeSheetId;
1351
+ // The import opens on the file's active tab (Excel's `<workbookView activeTab>`), else the first
1352
+ // visible sheet.
1353
+ const firstId = getOpeningSheetId(engineSheets, documentActiveSheetId(engine.documentFacetsJson())) ??
1354
+ engineSheets[0]?.sheetId ??
1355
+ viewRef.current.activeSheetId;
1295
1356
  windowRef.current = windowedRef.current
1296
1357
  ? {
1297
1358
  sheetId: firstId,
@@ -1348,7 +1409,7 @@ export function useEngineCore(options) {
1348
1409
  setHist({ canUndo: engine.canUndo(), canRedo: engine.canRedo() });
1349
1410
  // The document was REPLACED: the old workbook's per-sheet cursors are meaningless on the new one
1350
1411
  // (imported sheet ids typically collide with the old ids), and the view undo/redo stacks pair with
1351
- // engine history that no longer exists. Reset all of it; the import opens at the first sheet's A1.
1412
+ // engine history that no longer exists. Reset all of it; the import opens at its opening sheet's A1.
1352
1413
  activeCellBySheetIdRef.current = {};
1353
1414
  selectionsBySheetIdRef.current = {};
1354
1415
  setActiveCellBySheetId({});
@@ -1517,8 +1578,14 @@ export function useEngineCore(options) {
1517
1578
  if (cell?.ue?.sv === "'") {
1518
1579
  return "";
1519
1580
  }
1581
+ // The person's Regional Format: a number renders with the cell's own format in their locale.
1582
+ if (displayLocale && typeof cell?.ev?.nv === "number" && cell.ev.ev == null) {
1583
+ const localized = localizeDisplayValue(cell.ev.nv, getEffectiveFormat(sheetId, rowIndex, columnIndex)?.numberFormat, displayLocale, documentLocale);
1584
+ if (localized !== undefined)
1585
+ return localized;
1586
+ }
1520
1587
  return cell?.fv ?? undefined;
1521
- }, [getCellData]);
1588
+ }, [getCellData, getEffectiveFormat, displayLocale, documentLocale]);
1522
1589
  // The cell's effective value as a SCALAR (bool ?? number ?? string) — the shape `<CanvasGrid>` and
1523
1590
  // chart series want. Mirrors useSheetProperties' `getEffectiveValue`. Errors → undefined.
1524
1591
  const getEffectiveValue = useCallback((sheetId, rowIndex, columnIndex) => {
@@ -1557,7 +1624,9 @@ export function useEngineCore(options) {
1557
1624
  }
1558
1625
  return ev;
1559
1626
  }, [getCellData]);
1560
- const getUserEnteredValue = useCallback((sheetId, rowIndex, columnIndex) => {
1627
+ // The stored entry in the document's canonical spelling (`1.5`): what range readers hand
1628
+ // programmatic consumers.
1629
+ const getCanonicalUserEnteredValue = useCallback((sheetId, rowIndex, columnIndex) => {
1561
1630
  // Ignores holds: the editor and formula bar open on the real value.
1562
1631
  const ue = getUnheldCellData(sheetId, rowIndex, columnIndex)?.ue;
1563
1632
  if (!ue)
@@ -1570,6 +1639,16 @@ export function useEngineCore(options) {
1570
1639
  return ue.bv ? "TRUE" : "FALSE";
1571
1640
  return ue.sv ?? undefined;
1572
1641
  }, [getUnheldCellData]);
1642
+ // What the editor and formula bar open with: under a Regional Format a number literal shows with
1643
+ // its decimal mark (`1,5`), so committing it unchanged reads back as the same number.
1644
+ const getUserEnteredValue = useCallback((sheetId, rowIndex, columnIndex) => {
1645
+ const value = getCanonicalUserEnteredValue(sheetId, rowIndex, columnIndex);
1646
+ if (!displayLocale || value === undefined)
1647
+ return value;
1648
+ return getUnheldCellData(sheetId, rowIndex, columnIndex)?.ue?.nv != null
1649
+ ? localizeEnteredNumber(value, displayLocale)
1650
+ : value;
1651
+ }, [getCanonicalUserEnteredValue, getUnheldCellData, displayLocale]);
1573
1652
  const getHyperlink = useCallback((sheetId, rowIndex, columnIndex) => getCellData(sheetId, rowIndex, columnIndex)?.hyperlink, [getCellData]);
1574
1653
  // ── Additional cell accessors (mirror useSheetProperties / useSpreadsheetState, typed via SS) ──
1575
1654
  // Rich-text runs ride on the cell (`textFormatRuns`, emitted by the engine from the imported
@@ -1683,6 +1762,8 @@ export function useEngineCore(options) {
1683
1762
  endColumnIndex: right,
1684
1763
  };
1685
1764
  }, []);
1765
+ // Stable identity: reads through `engineRef`, so the grid's formula-bar effect never re-runs for it.
1766
+ const getArrayFormula = useCallback((sheetId, rowIndex, columnIndex) => engineRef.current?.arrayFormulaAt(sheetId, rowIndex, columnIndex), []);
1686
1767
  const getDataColumnCount = useCallback((sheetId) => {
1687
1768
  const rows = sheetData[String(sheetId)];
1688
1769
  let max = 0;
@@ -1801,10 +1882,10 @@ export function useEngineCore(options) {
1801
1882
  if ((skipRows && isHiddenRow(sheetId, r)) ||
1802
1883
  (skipCols && isHiddenColumn(sheetId, c)))
1803
1884
  continue;
1804
- out.push(getUserEnteredValue(sheetId, r, c));
1885
+ out.push(getCanonicalUserEnteredValue(sheetId, r, c));
1805
1886
  }
1806
1887
  return out;
1807
- }, [getUserEnteredValue, isHiddenRow, isHiddenColumn]);
1888
+ }, [getCanonicalUserEnteredValue, isHiddenRow, isHiddenColumn]);
1808
1889
  const getFormulasFromRange = useCallback((sheetRange, strategy) => {
1809
1890
  const { sheetId, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex, } = sheetRange;
1810
1891
  const { skipRows, skipCols } = hiddenStrategyAxes(strategy);
@@ -2188,6 +2269,7 @@ export function useEngineCore(options) {
2188
2269
  const handlers = useMemo(() => createCommandHandlers(onCommand, {
2189
2270
  getCustomAutofillLists: () => customAutofillListsRef.current,
2190
2271
  getAutoExpandTables: () => autoExpandTablesRef.current,
2272
+ getEntryLocale: () => entryLocaleRef.current,
2191
2273
  getAutoCalculatedColumns: () => autoCalculatedColumnsRef.current,
2192
2274
  getActiveCell: (sheetId) => viewRef.current.activeSheetId === sheetId
2193
2275
  ? viewRef.current.activeCell
@@ -2251,6 +2333,264 @@ export function useEngineCore(options) {
2251
2333
  });
2252
2334
  return plan;
2253
2335
  }, [handlers, readRect]);
2336
+ // Data ▸ Consolidate: each source range is read straight from the engine (any sheet — a
2337
+ // windowed host holds only the active sheet's viewport), the shared planner combines them, and
2338
+ // the result block is written at the destination in ONE `batchHistory` — one undo step.
2339
+ const onConsolidate = useCallback((sheetId, destination, options) => {
2340
+ const cells = new Map();
2341
+ for (const reference of options.references) {
2342
+ const { range } = reference;
2343
+ const snapshot = engineRef.current?.readWindow(reference.sheetId, range.startRowIndex, range.startColumnIndex, range.endRowIndex, range.endColumnIndex);
2344
+ const raw = windowRectReader(snapshot?.cells ?? [], "raw");
2345
+ const shown = windowRectReader(snapshot?.cells ?? [], "display");
2346
+ for (let r = range.startRowIndex; r <= range.endRowIndex; r++) {
2347
+ for (let c = range.startColumnIndex; c <= range.endColumnIndex; c++) {
2348
+ const value = raw.getValue(r, c);
2349
+ if (value === undefined)
2350
+ continue;
2351
+ cells.set(`${reference.sheetId}:${r}:${c}`, {
2352
+ value,
2353
+ text: String(shown.getValue(r, c) ?? ""),
2354
+ });
2355
+ }
2356
+ }
2357
+ }
2358
+ const plan = planConsolidate({ sheetId, ...destination }, options, {
2359
+ getValue: (s, r, c) => cells.get(`${s}:${r}:${c}`)?.value,
2360
+ getText: (s, r, c) => cells.get(`${s}:${r}:${c}`)?.text ?? "",
2361
+ getSheetName: (s) => stateSheetsRef.current.find((sheet) => sheet.sheetId === s)?.title,
2362
+ });
2363
+ if (!plan)
2364
+ return undefined;
2365
+ batchHistory(() => handlers.onChangeBatch(sheetId, plan.range, plan.values.map((row) => row.map((v) => (v === null ? "" : v)))));
2366
+ return plan;
2367
+ }, [batchHistory, handlers]);
2368
+ // Data ▸ Outline beyond Group / Ungroup. Every command reads the sheet's folded row/column
2369
+ // metadata and `outlinePr`, then issues ordinary group / ungroup / collapse / expand commands —
2370
+ // inside `batchHistory` where it issues several, so each is one undo step.
2371
+ const outlineOf = useCallback((sheetId) => {
2372
+ const sheet = sheetById.get(sheetId);
2373
+ return {
2374
+ rows: sheet?.rowMetadata,
2375
+ columns: sheet?.columnMetadata,
2376
+ summaryBelow: sheet?.outlinePr?.summaryBelow !== false,
2377
+ summaryRight: sheet?.outlinePr?.summaryRight !== false,
2378
+ };
2379
+ }, [sheetById]);
2380
+ /** Auto Outline: the selection, or the current region around a single cell (Excel). Replaces the
2381
+ * existing outline in that range with the groups its summary formulas imply. */
2382
+ const onAutoOutline = useCallback((sheetId, activeCell, selections) => {
2383
+ const selection = activeRange(activeCell, selections);
2384
+ const range = isSingleCell(selection)
2385
+ ? getDataRegion(sheetId, activeCell)
2386
+ : selection;
2387
+ if (!range)
2388
+ return undefined;
2389
+ const outline = outlineOf(sheetId);
2390
+ const plan = planAutoOutline(range, readRect(sheetId, range, "raw"), outline);
2391
+ if (!plan.rows.length && !plan.columns.length) {
2392
+ showError({
2393
+ title: "Auto Outline",
2394
+ message: "Cannot create an outline.",
2395
+ });
2396
+ return plan;
2397
+ }
2398
+ batchHistory(() => {
2399
+ if (plan.rows.length) {
2400
+ for (const indexes of clearOutlineCalls(outline.rows, {
2401
+ start: range.startRowIndex,
2402
+ end: range.endRowIndex,
2403
+ })) {
2404
+ handlers.onUngroupRows(sheetId, indexes);
2405
+ }
2406
+ }
2407
+ if (plan.columns.length) {
2408
+ for (const indexes of clearOutlineCalls(outline.columns, {
2409
+ start: range.startColumnIndex,
2410
+ end: range.endColumnIndex,
2411
+ })) {
2412
+ handlers.onUngroupColumns(sheetId, indexes);
2413
+ }
2414
+ }
2415
+ for (const span of plan.rows) {
2416
+ handlers.onGroupRows(sheetId, indexRun(span.start, span.end));
2417
+ }
2418
+ for (const span of plan.columns) {
2419
+ handlers.onGroupColumns(sheetId, indexRun(span.start, span.end));
2420
+ }
2421
+ });
2422
+ return plan;
2423
+ }, [batchHistory, getDataRegion, handlers, outlineOf, readRect, showError]);
2424
+ /** Clear Outline: ungroup every level — of the selected rows / columns, or of the whole sheet
2425
+ * from a single cell. Hidden detail is shown first so nothing stays hidden without a group. */
2426
+ const onClearOutline = useCallback((sheetId, activeCell, selections) => {
2427
+ const selection = activeRange(activeCell, selections);
2428
+ const whole = isSingleCell(selection);
2429
+ const outline = outlineOf(sheetId);
2430
+ const rowCalls = clearOutlineCalls(outline.rows, whole || !selection
2431
+ ? undefined
2432
+ : { start: selection.startRowIndex, end: selection.endRowIndex });
2433
+ const columnCalls = clearOutlineCalls(outline.columns, whole || !selection
2434
+ ? undefined
2435
+ : { start: selection.startColumnIndex, end: selection.endColumnIndex });
2436
+ if (!rowCalls.length && !columnCalls.length)
2437
+ return;
2438
+ batchHistory(() => {
2439
+ if (rowCalls.length)
2440
+ handlers.onSetOutlineDepth(sheetId, "row", 8);
2441
+ if (columnCalls.length)
2442
+ handlers.onSetOutlineDepth(sheetId, "column", 8);
2443
+ for (const indexes of rowCalls)
2444
+ handlers.onUngroupRows(sheetId, indexes);
2445
+ for (const indexes of columnCalls)
2446
+ handlers.onUngroupColumns(sheetId, indexes);
2447
+ });
2448
+ }, [batchHistory, handlers, outlineOf]);
2449
+ /** Show Detail / Hide Detail: expand / collapse the group around the active cell — its rows,
2450
+ * unless whole columns are selected or the row is in no group. */
2451
+ const toggleDetail = useCallback((sheetId, activeCell, selections, show) => {
2452
+ const outline = outlineOf(sheetId);
2453
+ const selection = activeRange(activeCell, selections);
2454
+ const wholeColumns = !!selection &&
2455
+ selection.startRowIndex <= 1 &&
2456
+ selection.endRowIndex >= getSheetRowCount(sheetId);
2457
+ const row = wholeColumns
2458
+ ? undefined
2459
+ : outlineSummaryAt(outline.rows, activeCell.rowIndex, outline.summaryBelow);
2460
+ if (row !== undefined) {
2461
+ if (show)
2462
+ handlers.onExpandRowGroup(sheetId, row);
2463
+ else
2464
+ handlers.onCollapseRowGroup(sheetId, row);
2465
+ return true;
2466
+ }
2467
+ const column = outlineSummaryAt(outline.columns, activeCell.columnIndex, outline.summaryRight);
2468
+ if (column === undefined)
2469
+ return false;
2470
+ if (show)
2471
+ handlers.onExpandColumnGroup(sheetId, column);
2472
+ else
2473
+ handlers.onCollapseColumnGroup(sheetId, column);
2474
+ return true;
2475
+ }, [getSheetRowCount, handlers, outlineOf]);
2476
+ const onShowDetail = useCallback((sheetId, activeCell, selections) => toggleDetail(sheetId, activeCell, selections, true), [toggleDetail]);
2477
+ const onHideDetail = useCallback((sheetId, activeCell, selections) => toggleDetail(sheetId, activeCell, selections, false), [toggleDetail]);
2478
+ /** Outline settings: summary rows below / columns right and "Automatic styles", stored on the
2479
+ * sheet's `outlinePr` (one `update-sheet`; round-trips through xlsx `<outlinePr>`). */
2480
+ const onUpdateOutlineSettings = useCallback((sheetId, settings) => onCommand({
2481
+ command: "update-sheet",
2482
+ sheetId,
2483
+ sheetSpec: { outlinePr: settings },
2484
+ }), [onCommand]);
2485
+ /** Outline settings ▸ Apply Styles: Excel's RowLevel_1 / ColLevel_1 (bold) and RowLevel_2 /
2486
+ * ColLevel_2 (italic) on the summary rows and columns, over the sheet's data — one undo step. */
2487
+ const onApplyOutlineStyles = useCallback((sheetId) => {
2488
+ const outline = outlineOf(sheetId);
2489
+ const rows = outlineStyleTargets(outline.rows, outline.summaryBelow);
2490
+ const columns = outlineStyleTargets(outline.columns, outline.summaryRight);
2491
+ const lastRow = Math.max(1, getDataRowCount(sheetId) ?? 1);
2492
+ const lastColumn = Math.max(1, getDataColumnCount(sheetId) ?? 1);
2493
+ const apply = (ranges, textFormat) => {
2494
+ if (!ranges.length)
2495
+ return;
2496
+ handlers.onChangeFormatting(sheetId, { rowIndex: ranges[0].startRowIndex, columnIndex: ranges[0].startColumnIndex }, ranges.map((range) => ({ range })), "textFormat", textFormat);
2497
+ };
2498
+ const rowRange = (r) => ({
2499
+ startRowIndex: r,
2500
+ endRowIndex: r,
2501
+ startColumnIndex: 1,
2502
+ endColumnIndex: lastColumn,
2503
+ });
2504
+ const columnRange = (c) => ({
2505
+ startRowIndex: 1,
2506
+ endRowIndex: lastRow,
2507
+ startColumnIndex: c,
2508
+ endColumnIndex: c,
2509
+ });
2510
+ batchHistory(() => {
2511
+ apply([...rows.bold.map(rowRange), ...columns.bold.map(columnRange)], { bold: true });
2512
+ apply([...rows.italic.map(rowRange), ...columns.italic.map(columnRange)], {
2513
+ italic: true,
2514
+ });
2515
+ });
2516
+ }, [batchHistory, getDataColumnCount, getDataRowCount, handlers, outlineOf]);
2517
+ // Data ▸ Flash Fill / Ctrl+E: learn the pattern from the column's examples over ONE engine window
2518
+ // read of the block, then write every filled run inside `batchHistory` — one undo step. When no
2519
+ // pattern explains the examples, Excel's "couldn't find a pattern" message, and nothing is written.
2520
+ const runFlashFill = useCallback((sheetId, target) => {
2521
+ const result = target
2522
+ ? planFlashFillInWindow(target, engineRef.current?.readWindow(sheetId, target.region.startRowIndex, target.region.startColumnIndex, target.region.endRowIndex, target.region.endColumnIndex))
2523
+ : { ok: false, reason: "no-examples" };
2524
+ if (!result.ok) {
2525
+ showError({
2526
+ title: FLASH_FILL_NO_PATTERN_TITLE,
2527
+ message: FLASH_FILL_NO_PATTERN_MESSAGE,
2528
+ });
2529
+ return result;
2530
+ }
2531
+ batchHistory(() => {
2532
+ for (const write of result.writes) {
2533
+ handlers.onChangeBatch(sheetId, write.range, write.values);
2534
+ }
2535
+ });
2536
+ return result;
2537
+ }, [batchHistory, handlers, showError]);
2538
+ const onFlashFill = useCallback((sheetId, activeCell, selections) => {
2539
+ const selection = selections?.find((s) => s.range &&
2540
+ activeCell.rowIndex >= s.range.startRowIndex &&
2541
+ activeCell.rowIndex <= s.range.endRowIndex &&
2542
+ activeCell.columnIndex >= s.range.startColumnIndex &&
2543
+ activeCell.columnIndex <= s.range.endColumnIndex)?.range;
2544
+ return runFlashFill(sheetId, flashFillTargetAt(activeCell, getDataRegion(sheetId, activeCell), selection));
2545
+ }, [getDataRegion, runFlashFill]);
2546
+ const onFlashFillSuggest = useCallback((sheetId, cell, text) => {
2547
+ const target = flashFillTargetAt(cell, getDataRegion(sheetId, cell), undefined);
2548
+ if (!target)
2549
+ return undefined;
2550
+ return planFlashFillSuggestion(target, engineRef.current?.readWindow(sheetId, target.region.startRowIndex, target.region.startColumnIndex, target.region.endRowIndex, target.region.endColumnIndex), { rowIndex: cell.rowIndex, text });
2551
+ }, [getDataRegion]);
2552
+ const onAcceptFlashFill = useCallback((sheetId, writes) => {
2553
+ if (!writes.length)
2554
+ return;
2555
+ batchHistory(() => {
2556
+ for (const write of writes) {
2557
+ handlers.onChangeBatch(sheetId, write.range, write.values);
2558
+ }
2559
+ });
2560
+ }, [batchHistory, handlers]);
2561
+ // The fill handle with Auto Fill Options ▸ Flash Fill: the dragged source rows are the examples
2562
+ // and the rest of the drag is filled from them, one column at a time. Every other fill type goes
2563
+ // to the engine's own fill.
2564
+ const onFill = useCallback(async (sheetId, activeCell, fillSelection, selections, fillableSelections, fillType, options) => {
2565
+ if ((fillType ?? options?.fillType) !== "FlashFill") {
2566
+ return handlers.onFill(sheetId, activeCell, fillSelection, selections, fillableSelections, fillType, options);
2567
+ }
2568
+ const source = selections[0]?.range;
2569
+ const fill = fillSelection.range;
2570
+ if (!source || !fill)
2571
+ return;
2572
+ const exampleRowIndexes = [];
2573
+ for (let r = source.startRowIndex; r <= source.endRowIndex; r++)
2574
+ exampleRowIndexes.push(r);
2575
+ const targetRowIndexes = [];
2576
+ for (let r = fill.startRowIndex; r <= fill.endRowIndex; r++) {
2577
+ if (r < source.startRowIndex || r > source.endRowIndex)
2578
+ targetRowIndexes.push(r);
2579
+ }
2580
+ batchHistory(() => {
2581
+ for (let c = fill.startColumnIndex; c <= fill.endColumnIndex; c++) {
2582
+ const region = getDataRegion(sheetId, { rowIndex: source.startRowIndex, columnIndex: c });
2583
+ const target = flashFillTargetAt({ rowIndex: source.startRowIndex, columnIndex: c }, region, undefined);
2584
+ if (!target)
2585
+ continue;
2586
+ target.region.startRowIndex = Math.min(target.region.startRowIndex, fill.startRowIndex);
2587
+ target.region.endRowIndex = Math.max(target.region.endRowIndex, fill.endRowIndex);
2588
+ target.exampleRowIndexes = exampleRowIndexes;
2589
+ target.targetRowIndexes = targetRowIndexes;
2590
+ runFlashFill(sheetId, target);
2591
+ }
2592
+ });
2593
+ }, [batchHistory, getDataRegion, handlers, runFlashFill]);
2254
2594
  // Grid-shaped handlers that need view state (the active sheet). Kept as STABLE useCallbacks here (not
2255
2595
  // in the pure factory) so `<CanvasGrid>` props don't churn every render — they read `viewRef.current`
2256
2596
  // (the live active sheet) instead of closing over `activeSheetId`, so identity never changes. The
@@ -2333,6 +2673,7 @@ export function useEngineCore(options) {
2333
2673
  showFirstColumn: t.showFirstColumn,
2334
2674
  showLastColumn: t.showLastColumn,
2335
2675
  totalRow: t.totalRow ?? false,
2676
+ headerRow: t.headerRow !== false,
2336
2677
  range: { ...t.range, sheetId },
2337
2678
  ...t.bandedRange,
2338
2679
  })),
@@ -2571,6 +2912,7 @@ export function useEngineCore(options) {
2571
2912
  paintFacetsRef.current = { bandedRanges: facets.bandedRanges, tables };
2572
2913
  const namedRanges = facets.namedRanges;
2573
2914
  const protectedRanges = facets.protectedRanges;
2915
+ const allowEditRanges = facets.allowEditRanges ?? EMPTY_ALLOW_EDIT_RANGES;
2574
2916
  const embeds = facets.embeds;
2575
2917
  const slicers = facets.slicers;
2576
2918
  // Citations (workbook-level collection; a cell links to one via `citationId`). The grid renders the
@@ -2680,7 +3022,79 @@ export function useEngineCore(options) {
2680
3022
  // cellXfs style-refs to an inline `CellFormat` on each parsed cell, which we forward per cell below;
2681
3023
  // the engine applies it via `set_style` (streams on `styleChanges`). Only a still-unresolved
2682
3024
  // `StyleReference` (no matching cellXfs entry) is skipped, since a bare ref can't cross to the engine.
2683
- const onPaste = useCallback(async (e, sourceSheetId, destinationSheetId, copiedSelections, pasteActiveCell, pasteSelections, _finalSelections, isCutOperation) => {
3025
+ const pasteInto = useCallback(async (e, sourceSheetId, destinationSheetId, copiedSelections, pasteActiveCell, pasteSelections, _finalSelections, isCutOperation) => {
3026
+ // Paste Special. The grid stashes the request under synthetic clipboard keys (same as
3027
+ // `useSpreadsheetState`; `resolvePasteSpecialOptions` reads both the legacy single mode and the
3028
+ // full options).
3029
+ const pasteSpecial = resolvePasteSpecialOptions(e?.clipboardData);
3030
+ // The copied range, kept for Paste Link, the notes / validation / column widths and the cut
3031
+ // source-clear below. A foreign clipboard (another app) has none.
3032
+ const from = copiedSelections?.[0]?.range;
3033
+ const pasteSource = from && sourceSheetId != null
3034
+ ? { sheetId: sourceSheetId, sheetName: getSheetName(sourceSheetId), range: from }
3035
+ : undefined;
3036
+ // Destination top-left = the paste selection's start (else the active cell).
3037
+ const to = pasteSelections?.[pasteSelections.length - 1]?.range;
3038
+ const target = to
3039
+ ? { rowIndex: to.startRowIndex, columnIndex: to.startColumnIndex }
3040
+ : pasteActiveCell;
3041
+ // Excel's Column widths / Keep Source Column Widths: each destination column takes the width
3042
+ // of the copied column it stands for (a source column at the sheet default takes that default).
3043
+ const copySourceColumnWidths = (source) => {
3044
+ const defaultWidth = state.sheets.find((s) => s.sheetId === source.sheetId)?.defaultColumnWidth ??
3045
+ DEFAULT_PASTE_COLUMN_WIDTH;
3046
+ for (const copy of columnWidthCopies(source.range, target.columnIndex)) {
3047
+ onCommand({
3048
+ command: "resize",
3049
+ sheetId: destinationSheetId,
3050
+ indexes: [copy.columnIndex],
3051
+ dimension: getColumnWidth(source.sheetId, copy.sourceColumnIndex) ?? defaultWidth,
3052
+ axis: "y",
3053
+ });
3054
+ }
3055
+ };
3056
+ // Paste Special → Comments and Notes / Validation / Column widths paste no cells: only the
3057
+ // copied range's notes, data-validation rules or column widths travel, in one undo step.
3058
+ // They need a copied range (Excel offers them only after a copy, never after a cut).
3059
+ if (pasteSpecial.notesOnly ||
3060
+ pasteSpecial.validationOnly ||
3061
+ pasteSpecial.columnWidths === "only") {
3062
+ if (!pasteSource || isCutOperation)
3063
+ return;
3064
+ batchHistory(() => {
3065
+ if (pasteSpecial.notesOnly) {
3066
+ const notes = noteCopies(pasteSource.range, target, (r, c) => getNote(pasteSource.sheetId, r, c), pasteSpecial.transpose);
3067
+ for (const { cell, note } of notes) {
3068
+ onCommand({
3069
+ command: "update-note",
3070
+ sheetId: destinationSheetId,
3071
+ activeCell: cell,
3072
+ note,
3073
+ });
3074
+ }
3075
+ }
3076
+ else if (pasteSpecial.validationOnly) {
3077
+ const rules = validationCopies(facets.dataValidations, pasteSource, destinationSheetId, target);
3078
+ for (const rule of rules) {
3079
+ onCommand({
3080
+ command: "create-data-validation",
3081
+ sheetId: destinationSheetId,
3082
+ range: rule.ranges[0],
3083
+ rule: { ...rule, id: uuidString() },
3084
+ });
3085
+ }
3086
+ }
3087
+ else {
3088
+ copySourceColumnWidths(pasteSource);
3089
+ }
3090
+ });
3091
+ return;
3092
+ }
3093
+ // Paste Link refers back to the copied cells, so it needs a copied range — Excel greys it out
3094
+ // after a cut.
3095
+ const pasteLink = Boolean(pasteSpecial.link);
3096
+ if (pasteLink && (!pasteSource || isCutOperation))
3097
+ return;
2684
3098
  // A cut is a MOVE: Excel keeps the moved formulas' text verbatim (`=B1*2` cut from A1 to A5
2685
3099
  // still reads `=B1*2`) and only repoints references INTO the moved block — the engine does
2686
3100
  // that remap (`repoint_formulas_into_moved_block`), so the clipboard parse must not
@@ -2692,7 +3106,7 @@ export function useEngineCore(options) {
2692
3106
  // Pasted image FILES arrive as floating pictures anchored at the active cell (Excel /
2693
3107
  // Google Sheets Ctrl+V of a picture) — the same lossless `create-embed` the Insert → Image
2694
3108
  // dialog emits, one undo entry for all of them, the first one selected like a new chart.
2695
- const pastedEmbeds = parsed?.embeds ?? [];
3109
+ const pastedEmbeds = pasteLink ? [] : parsed?.embeds ?? [];
2696
3110
  if (pastedEmbeds.length) {
2697
3111
  batchHistory(() => {
2698
3112
  for (const spec of pastedEmbeds) {
@@ -2701,35 +3115,42 @@ export function useEngineCore(options) {
2701
3115
  });
2702
3116
  focusEmbedOrChart(pastedEmbeds[0].embedId);
2703
3117
  }
2704
- let results = parsed?.results ?? [];
3118
+ // Paste Link: one reference formula per copied cell instead of the copied cells.
3119
+ let results = pasteLink && pasteSource
3120
+ ? pasteLinkCells(pasteSource, destinationSheetId)
3121
+ : parsed?.results ?? [];
2705
3122
  if (!results.length)
2706
3123
  return;
2707
3124
  // The clipboard's own size and merges, before Paste Special / tiling reshape `results`.
2708
3125
  const clipRows = results.length;
2709
3126
  const clipCols = Math.max(0, ...results.map((row) => row.length));
2710
3127
  const clipboardMerges = parsed?.merges ?? [];
2711
- // Paste Special. The grid stashes the request under synthetic clipboard keys (same as
2712
- // `useSpreadsheetState`; `resolvePasteSpecialOptions` reads both the legacy single mode and the
2713
- // full options). Transpose/Values/Formulas transform the parsed cells UI-side (the engine can't
2714
- // "resolve a formula to its value"); Formats rides a `format_only` flag the engine honors (apply
2715
- // each cell's format, leave destination values intact); Operation / Skip blanks need the
3128
+ // Transpose/Values/Formulas transform the parsed cells UI-side (the engine can't "resolve a
3129
+ // formula to its value"); Formats rides a `format_only` flag the engine honors (apply each
3130
+ // cell's format, leave destination values intact); Operation / Skip blanks need the
2716
3131
  // destination cells and are folded in after tiling (see `applyPasteSpecialToTiles`).
2717
- const pasteSpecial = resolvePasteSpecialOptions(e?.clipboardData);
2718
3132
  if (pasteSpecial.transpose) {
2719
3133
  results = transpose(results);
2720
3134
  }
3135
+ // Values & Number Formatting, Formulas & Number Formatting, Values & Source Formatting: the
3136
+ // source formats are read before the pick, which strips them.
3137
+ const keptFormats = pasteSpecial.numberFormats || pasteSpecial.sourceFormats
3138
+ ? clipboardFormats(results)
3139
+ : undefined;
2721
3140
  if (pasteSpecial.paste === "values") {
2722
3141
  results = pickValue(results, destinationSheetId, initial.current.locale);
2723
3142
  }
2724
3143
  else if (pasteSpecial.paste === "formulas") {
2725
3144
  results = pickFormula(results, destinationSheetId, initial.current.locale);
2726
3145
  }
3146
+ if (keptFormats) {
3147
+ results = reattachClipboardFormats(results, keptFormats, pasteSpecial.sourceFormats ? "sourceFormats" : "numberFormats");
3148
+ }
3149
+ // All except borders (Paste Options ▸ No Borders): the destination keeps its own borders.
3150
+ if (pasteSpecial.noBorders) {
3151
+ results = withoutBorders(results);
3152
+ }
2727
3153
  const formatOnly = pasteSpecial.paste === "formats";
2728
- // Destination top-left = the paste selection's start (else the active cell).
2729
- const to = pasteSelections?.[pasteSelections.length - 1]?.range;
2730
- const target = to
2731
- ? { rowIndex: to.startRowIndex, columnIndex: to.startColumnIndex }
2732
- : pasteActiveCell;
2733
3154
  // A paste selection larger than the clipboard tiles it (copy G1, select G2:G5, paste fills all
2734
3155
  // four), wrapping like `useOnPaste`. Tiling UI-side keeps the engine's `paste` a plain rectangle
2735
3156
  // and the whole paste ONE undo entry; the tiles' formulas are shifted here (see `paste-tiling`).
@@ -2739,8 +3160,6 @@ export function useEngineCore(options) {
2739
3160
  results = tileClipboardToSelection(results, to, pasteActiveCell, destinationSheetId, getSheetName(destinationSheetId), initial.current.locale);
2740
3161
  }
2741
3162
  const tiles = applyPasteSpecialToTiles(results, target, destinationSheetId, pasteSpecial, { getCellData, getUserEnteredFormat }, initial.current.locale);
2742
- // The copied range top-left, kept for the cut source-clear below.
2743
- const from = copiedSelections?.[0]?.range;
2744
3163
  const cutMove = isCutOperation && from && sourceSheetId != null;
2745
3164
  // COPY: `generateDataFromClipboard` has ALREADY re-anchored each relative formula ref to its
2746
3165
  // destination (its `moveFormula(sourceCell → destinationCell)` pass overwrites the cell's `fv`), so
@@ -2759,8 +3178,9 @@ export function useEngineCore(options) {
2759
3178
  // The clipboard rectangle is row-major from the copied range's top-left, so the note of the
2760
3179
  // tile's source cell is looked up by offset; tiled repeats (copy only) reuse the modular offset.
2761
3180
  const noteAt = (i, j) => {
2762
- // A transposed paste no longer maps tiles back to source cells by offset.
2763
- if (!from || sourceSheetId == null || pasteSpecial.transpose)
3181
+ // A transposed paste no longer maps tiles back to source cells by offset; a link carries
3182
+ // only the reference.
3183
+ if (!from || sourceSheetId == null || pasteSpecial.transpose || pasteLink)
2764
3184
  return undefined;
2765
3185
  const height = from.endRowIndex - from.startRowIndex + 1;
2766
3186
  const width = from.endColumnIndex - from.startColumnIndex + 1;
@@ -2790,10 +3210,11 @@ export function useEngineCore(options) {
2790
3210
  // and a cut moves its own merges in the engine (rowsncolumns/spreadsheet#1234).
2791
3211
  const merges = !isCutOperation &&
2792
3212
  !pasteSpecial.transpose &&
3213
+ !pasteLink &&
2793
3214
  (pasteSpecial.paste === "all" || formatOnly)
2794
3215
  ? pastedMerges(clipboardMerges, pasteActiveCell, target, clipRows, clipCols, tiles.length, Math.max(0, ...tiles.map((row) => row.length)))
2795
3216
  : [];
2796
- onCommand({
3217
+ const pasteCommand = {
2797
3218
  command: "paste",
2798
3219
  sheetId: destinationSheetId,
2799
3220
  target,
@@ -2810,20 +3231,113 @@ export function useEngineCore(options) {
2810
3231
  ...(autoCalculatedColumnsRef.current === false
2811
3232
  ? { autoCalculatedColumns: false }
2812
3233
  : {}),
2813
- });
3234
+ };
3235
+ // Keep Source Column Widths: the cells and the widths are one undo step. A transposed block
3236
+ // no longer lines its columns up with the copied ones, so it takes no widths.
3237
+ if (pasteSpecial.columnWidths === "also" && pasteSource && !pasteSpecial.transpose) {
3238
+ batchHistory(() => {
3239
+ onCommand(pasteCommand);
3240
+ copySourceColumnWidths(pasteSource);
3241
+ });
3242
+ }
3243
+ else {
3244
+ onCommand(pasteCommand);
3245
+ }
2814
3246
  }, [
2815
3247
  getSheetName,
2816
3248
  getCellData,
2817
3249
  getUserEnteredFormat,
2818
3250
  getNote,
3251
+ getColumnWidth,
2819
3252
  onCommand,
2820
3253
  batchHistory,
2821
3254
  focusEmbedOrChart,
2822
3255
  getSheetDimensions,
3256
+ facets,
3257
+ state.sheets,
2823
3258
  ]);
3259
+ // The last paste, kept for Excel's Paste Options button (`onReapplyPaste`): its clipboard, its
3260
+ // placement arguments and the undo depth right after it. A cut is a move and has no Paste Options.
3261
+ const lastPasteRef = useRef(null);
3262
+ const onPaste = useCallback(async (e, sourceSheetId, destinationSheetId, copiedSelections, pasteActiveCell, pasteSelections, finalSelections, isCutOperation) => {
3263
+ // Read the clipboard before the first await: a browser paste event's data is gone after it.
3264
+ const entries = isCutOperation ? null : snapshotClipboard(e?.clipboardData);
3265
+ const depthBefore = engineRef.current?.undoDepth() ?? 0;
3266
+ lastPasteRef.current = null;
3267
+ await pasteInto(e, sourceSheetId, destinationSheetId, copiedSelections, pasteActiveCell, pasteSelections, finalSelections, isCutOperation);
3268
+ const depth = engineRef.current?.undoDepth() ?? 0;
3269
+ if (entries && depth > depthBefore) {
3270
+ lastPasteRef.current = {
3271
+ entries,
3272
+ args: [
3273
+ sourceSheetId,
3274
+ destinationSheetId,
3275
+ copiedSelections,
3276
+ pasteActiveCell,
3277
+ pasteSelections,
3278
+ finalSelections,
3279
+ ],
3280
+ depth,
3281
+ };
3282
+ }
3283
+ }, [pasteInto]);
3284
+ // Paste Options: undo the last paste and paste its clipboard again as `options`, at the same place.
3285
+ // The undone paste only moves to the redo stack, and the new paste clears it, so the result is ONE
3286
+ // undo step. Refused (false) once anything else has been written since the paste.
3287
+ const onReapplyPaste = useCallback(async (options) => {
3288
+ const last = lastPasteRef.current;
3289
+ const engine = engineRef.current;
3290
+ if (!last || !engine || engine.undoDepth() !== last.depth) {
3291
+ lastPasteRef.current = null;
3292
+ return false;
3293
+ }
3294
+ // The pasted range stays selected, as after the paste (the undo alone would restore the
3295
+ // selection from before it).
3296
+ const view = viewRef.current;
3297
+ undo();
3298
+ await onPaste(replayPasteEvent(last.entries, options), ...last.args, false);
3299
+ if (view)
3300
+ applyView(view);
3301
+ return lastPasteRef.current !== null;
3302
+ }, [onPaste, undo, applyView]);
3303
+ // Insert-copy. Two commits, the insert first: the engine refuses a band that would tear a merge /
3304
+ // table / array or push data off the sheet, and a refused insert must not let the paste overwrite
3305
+ // the destination (a `batch` runs every member whatever the one before it refused).
3306
+ const onInsertCopiedCells = useCallback(async (e, sheetId, from, to, shift) => {
3307
+ const direction = shift ??
3308
+ (to.range.startRowIndex === from.range.startRowIndex ? "right" : "down");
3309
+ const target = {
3310
+ rowIndex: to.range.startRowIndex,
3311
+ columnIndex: to.range.startColumnIndex,
3312
+ };
3313
+ const commit = onCommand({
3314
+ command: direction === "down"
3315
+ ? "insert-cells-shift-down"
3316
+ : "insert-cells-shift-right",
3317
+ sheetId,
3318
+ activeCell: target,
3319
+ selections: [to],
3320
+ });
3321
+ if (!commit || commit.rejections?.length)
3322
+ return;
3323
+ // Opening the band slides a source that sits wholly in it; the paste reads the source's
3324
+ // notes from where they now are (the cells themselves already ride on the clipboard).
3325
+ await pasteInto(e, sheetId, sheetId, [{ ...from, range: rangeAfterInsertBand(from.range, to.range, direction) }], target, [to], [to], false);
3326
+ }, [onCommand, pasteInto]);
2824
3327
  return useMemo(() => ({
2825
3328
  ...state,
2826
3329
  ...handlers,
3330
+ onConsolidate,
3331
+ onAutoOutline,
3332
+ onClearOutline,
3333
+ onShowDetail,
3334
+ onHideDetail,
3335
+ onUpdateOutlineSettings,
3336
+ onApplyOutlineStyles,
3337
+ onFill,
3338
+ onFlashFill,
3339
+ onFlashFillSuggest,
3340
+ onAcceptFlashFill,
2827
3341
  onRemoveTable,
2828
3342
  ready,
2829
3343
  engine: engineRef.current,
@@ -2890,6 +3404,7 @@ export function useEngineCore(options) {
2890
3404
  getSheetColumnCount,
2891
3405
  getDataRowCount,
2892
3406
  getDataRegion,
3407
+ getArrayFormula,
2893
3408
  findAll,
2894
3409
  getSeriesValuesFromRange,
2895
3410
  getDomainValuesFromRange,
@@ -2929,6 +3444,7 @@ export function useEngineCore(options) {
2929
3444
  tables,
2930
3445
  namedRanges,
2931
3446
  protectedRanges,
3447
+ allowEditRanges,
2932
3448
  customTableStyles: facets.customTableStyles,
2933
3449
  embeds,
2934
3450
  slicers,
@@ -2988,10 +3504,23 @@ export function useEngineCore(options) {
2988
3504
  onDeleteDataValidationRules,
2989
3505
  onCopy,
2990
3506
  onPaste,
3507
+ onInsertCopiedCells,
3508
+ onReapplyPaste,
2991
3509
  }), [
2992
3510
  formulaLocale,
2993
3511
  state,
2994
3512
  handlers,
3513
+ onConsolidate,
3514
+ onAutoOutline,
3515
+ onClearOutline,
3516
+ onShowDetail,
3517
+ onHideDetail,
3518
+ onUpdateOutlineSettings,
3519
+ onApplyOutlineStyles,
3520
+ onFill,
3521
+ onFlashFill,
3522
+ onFlashFillSuggest,
3523
+ onAcceptFlashFill,
2995
3524
  onRemoveTable,
2996
3525
  ready,
2997
3526
  hist,
@@ -3051,6 +3580,7 @@ export function useEngineCore(options) {
3051
3580
  getSheetColumnCount,
3052
3581
  getDataRowCount,
3053
3582
  getDataRegion,
3583
+ getArrayFormula,
3054
3584
  findAll,
3055
3585
  getSeriesValuesFromRange,
3056
3586
  getDomainValuesFromRange,
@@ -3074,6 +3604,7 @@ export function useEngineCore(options) {
3074
3604
  tables,
3075
3605
  namedRanges,
3076
3606
  protectedRanges,
3607
+ allowEditRanges,
3077
3608
  facets.customTableStyles,
3078
3609
  embeds,
3079
3610
  slicers,
@@ -3102,5 +3633,33 @@ export function useEngineCore(options) {
3102
3633
  onClearHistory,
3103
3634
  onCopy,
3104
3635
  onPaste,
3636
+ onInsertCopiedCells,
3637
+ onReapplyPaste,
3105
3638
  ]);
3106
3639
  }
3640
+ /** Where `range` sits once cells open at `band` and shift `direction` (a range wholly in the band's
3641
+ * lanes, at or past its first line, slides by the band's size; anything else stays put). */
3642
+ export const rangeAfterInsertBand = (range, band, direction) => {
3643
+ if (direction === "down") {
3644
+ const inLanes = range.startColumnIndex >= band.startColumnIndex &&
3645
+ range.endColumnIndex <= band.endColumnIndex;
3646
+ if (!inLanes || range.startRowIndex < band.startRowIndex)
3647
+ return range;
3648
+ const size = band.endRowIndex - band.startRowIndex + 1;
3649
+ return {
3650
+ ...range,
3651
+ startRowIndex: range.startRowIndex + size,
3652
+ endRowIndex: range.endRowIndex + size,
3653
+ };
3654
+ }
3655
+ const inLanes = range.startRowIndex >= band.startRowIndex &&
3656
+ range.endRowIndex <= band.endRowIndex;
3657
+ if (!inLanes || range.startColumnIndex < band.startColumnIndex)
3658
+ return range;
3659
+ const size = band.endColumnIndex - band.startColumnIndex + 1;
3660
+ return {
3661
+ ...range,
3662
+ startColumnIndex: range.startColumnIndex + size,
3663
+ endColumnIndex: range.endColumnIndex + size,
3664
+ };
3665
+ };