@aiquants/spreadsheet 0.16.1 → 0.17.1

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.
@@ -49,11 +49,11 @@
49
49
 
50
50
  import { resolveVirtualScrollLocale, type ScrollBarTapCircleOptions, VIRTUAL_SCROLL_LABEL_KEYS, type VirtualGridHandle, type VirtualGridRange, type VirtualScrollLabels } from "@aiquants/virtualscroll"
51
51
  import type { ProfilerOnRenderCallback } from "react"
52
- import { forwardRef, type ReactNode, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"
52
+ import { type CSSProperties, forwardRef, type ReactNode, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"
53
53
  import type { ClipChannel } from "./clipboard/clipPayload.ts"
54
54
  import type { PasteOptions } from "./clipboard/pasteSpecial.ts"
55
55
  import { type ClipInfo, type PasteOutcome, type PasteSheet, useClipboard } from "./clipboard/useClipboard.ts"
56
- import { type BorderPreset, type CommandRunner, useCommands } from "./commands/useCommands.ts"
56
+ import { type BorderPreset, type CommandRunner, type KeyboardCellRect, useCommands } from "./commands/useCommands.ts"
57
57
  import { type SinkSnapshot, useCellEditor } from "./editor/useCellEditor.ts"
58
58
  import type { RenderCellContext } from "./grid/CellView.tsx"
59
59
  import { GridBody } from "./grid/GridBody.tsx"
@@ -85,7 +85,7 @@ import { clampSelectionToGrid, reduceActiveCycle, reduceSelectionExtend, reduceS
85
85
  import { useAutoScroller } from "./selection/useAutoScroller.ts"
86
86
  import { type PointDragOwner, usePointDrag } from "./selection/usePointDrag.ts"
87
87
  import { useSelectionEngine } from "./selection/useSelectionEngine.ts"
88
- import { clampSpreadsheetZoom, SPREADSHEET_DEFAULT_COLUMN_WIDTH_PX, SPREADSHEET_MAX_OPERATION_CELLS, stepSpreadsheetZoom } from "./view.ts"
88
+ import { clampSpreadsheetZoom, SPREADSHEET_DEFAULT_COLUMN_WIDTH_PX, SPREADSHEET_MAX_OPERATION_CELLS, SPREADSHEET_SCROLLBAR_SIZE_PX, stepSpreadsheetZoom } from "./view.ts"
89
89
 
90
90
  export type { SelectionState } from "./selection/selectionState.ts"
91
91
 
@@ -103,12 +103,51 @@ export type { SelectionState } from "./selection/selectionState.ts"
103
103
  */
104
104
  export type ScrollToCellOptions = { alignY?: "top" | "bottom" | "center"; alignX?: "start" | "end" | "center"; offsetX?: number; offsetY?: number }
105
105
 
106
+ /**
107
+ * The size of a grid's content in CSS px of the page (v0.17): the column-letter and row-number bands (0 when `headings`
108
+ * is false), every column and row at its current size, and the two scroll bars the grid always reserves, all scaled by
109
+ * the zoom — the box a host gives the grid to show every column and row without scrolling.
110
+ * グリッドの中身の大きさ (ページの CSS px。v0.17)。列の記号と行の番号の帯 (`headings` が false なら 0)、今の大きさの全部の列と行、
111
+ * グリッドがいつも取る 2 本のスクロールバーを、どれも倍率で伸び縮みさせたもの。ホストがスクロールなしで全部の列と行を見せる箱の大きさ。
112
+ */
113
+ export type SpreadsheetContentSize = {
114
+ /** The width in CSS px. 幅 (CSS px)。 */
115
+ readonly width: number
116
+ /** The height in CSS px. 高さ (CSS px)。 */
117
+ readonly height: number
118
+ }
119
+
120
+ /**
121
+ * The content size of a grid that draws nothing (no rows or no columns: no cells, bands or scroll bars).
122
+ * 何も描かないグリッド (行か列が無い。セルも帯もスクロールバーも無い) の中身の大きさ。
123
+ */
124
+ const EMPTY_CONTENT_SIZE: SpreadsheetContentSize = Object.freeze({ width: 0, height: 0 })
125
+
126
+ /** The `overflow` values that clip a box's content (a scroll container or a clipping box). 箱の中身を切り抜く `overflow` の値 (スクロールの容器か切り抜きの箱)。 */
127
+ const CLIPPING_OVERFLOWS: ReadonlySet<string> = new Set(["hidden", "clip", "scroll", "auto", "overlay"])
128
+
106
129
  /** Imperative surface (§6.9-8). / 命令 API (§6.9-8)。 */
107
130
  export type SpreadsheetHandle = {
108
131
  /** Row-height pair seam (§6.9-8). / 行高変更の対シーム。 */
109
132
  resizeRow: (row: number, heightPx: number) => void
110
133
  /** Column-width resize (§6.9-8). / 列幅変更。 */
111
134
  resizeColumn: (col: number, widthPx: number) => void
135
+ /**
136
+ * Fits each listed column to the widest text of ALL its rows (header rows included; v0.17), as Alt+Shift+= fits the
137
+ * active column over the rows in view: the same painted fonts, the 9 px padding and the 10,000 px bound, measured with
138
+ * the cells' base font. A hidden column keeps its width and so does an empty one. Refused through
139
+ * onOperationRejected("resize", cells, "limit") when the cells to measure exceed `maxOperationCells`. Works whatever
140
+ * `enableResizeUI` and `headings` say (an imperative path, like resizeColumn).
141
+ * 名指した列を、その列の**全部の行** (見出しの行も) で最も広い文字に合わせる (v0.17)。Alt+Shift+= が表示中の行で active 列を
142
+ * 合わせるのと同じ塗りの書体・余白 9 px・上限 10,000 px で、セルの基本の書体で測る。隠した列と空の列は幅を保つ。測るセルが
143
+ * `maxOperationCells` を超えると onOperationRejected("resize", セル, "limit") で拒む。`enableResizeUI` と `headings` に依らず
144
+ * 働く (resizeColumn と同じ命令の経路)。
145
+ *
146
+ * @param columns - The columns to fit (repeats count once). 合わせる列 (重複は 1 回)。
147
+ * @returns True when the fit ran (a hidden or empty column changes nothing); false when refused or when the grid cannot measure (`renderCell` is set, or the grid is not mounted). 走ったら true (隠した列・空の列は何も変えない)。拒まれたとき・測れないとき (`renderCell` がある、または未装着) は false。
148
+ * @throws {RangeError} When a column is not an integer between 0 and the column count − 1. 列が 0〜列数 − 1 の整数でない場合。
149
+ */
150
+ autoFitColumns: (columns: readonly number[]) => boolean
112
151
  /**
113
152
  * Programmatic viewport jump to a cell (delegates to the engine's scrollToCell — the
114
153
  * floor-and-pin jump API). Selection is unchanged; the deep grid stays reachable at any
@@ -448,6 +487,31 @@ export type SpreadsheetProps = {
448
487
  * 復元手段を失う (命令 API のみ)。
449
488
  */
450
489
  enableResizeUI?: boolean
490
+ /**
491
+ * v0.17 — Shows the column letters, the row numbers and the corner (Excel's "headings"; not `headerRows`), true by
492
+ * default. False draws none of the three and collapses their grid tracks to 0, so the cells start at the grid's
493
+ * top-left corner; the gestures that live only on them go with them (header presses, the corner's select-all, the
494
+ * resize strips and unhide markers), and their keyboard twins stay (Ctrl+Space, Shift+Space, Ctrl+A, Alt+Shift+Arrow,
495
+ * Alt+Shift+=). The bands are `aria-hidden`, so assistive technology meets the same grid. The root carries
496
+ * `data-aqsp-headings-hidden` while they are hidden. LIVE prop.
497
+ * v0.17 — 列の記号・行の番号・角 (Excel の「見出し」。`headerRows` とは別) を見せるか (既定 true)。false は 3 つを描かず、
498
+ * その格子の帯を 0 にしてセルを根の左上から始める。それらの上にだけある操作 (見出しの押下・角の全選択・境の帯と再表示の印) は
499
+ * 無くなり、キーの双子 (Ctrl+Space・Shift+Space・Ctrl+A・Alt+Shift+矢印・Alt+Shift+=) は残る。帯は `aria-hidden` なので、
500
+ * 支援技術から見えるグリッドは変わらない。隠している間、根は `data-aqsp-headings-hidden` を持つ。
501
+ */
502
+ headings?: boolean
503
+ /**
504
+ * v0.17 — Receives the size of the grid's content (`SpreadsheetContentSize`) after the first layout and again after
505
+ * every change of it: a track's size (a resize, an autofit, a hide or unhide, the imperative resizeRow / resizeColumn),
506
+ * the row or column count, the default sizes, the zoom or `headings`. An unchanged size is not repeated. A grid with no
507
+ * rows or no columns draws nothing and reports 0 × 0; a grid without a layout box (under a `display: none` ancestor)
508
+ * reports once it has one. A host uses it to size the grid's box to its content.
509
+ * v0.17 — グリッドの中身の大きさ (`SpreadsheetContentSize`) を、最初の配置の後と、それが変わるたびに受け取る (トラックの
510
+ * 大きさ — 境の操作・autofit・隠す・再表示・命令の resizeRow / resizeColumn —、行や列の数、既定の大きさ、倍率、`headings`)。
511
+ * 同じ大きさは繰り返さない。行か列の無いグリッドは何も描かないので 0 × 0、配置の箱の無いグリッド (display: none の祖先の中)
512
+ * は箱を得てから知らせる。ホストはこれでグリッドの箱を中身に合わせる。
513
+ */
514
+ onContentSizeChange?: (size: SpreadsheetContentSize) => void
451
515
  /**
452
516
  * AT announcement text for the active cell; omit for silence (no built-in strings). `text`
453
517
  * is the RAW canonical getCellText; `displayText` is the value-format display string (the
@@ -837,6 +901,8 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
837
901
  maxOperationCells = SPREADSHEET_MAX_OPERATION_CELLS,
838
902
  enableFillHandle = true,
839
903
  enableResizeUI = true,
904
+ headings = true,
905
+ onContentSizeChange,
840
906
  formatCellAnnouncement,
841
907
  formatSelectionAnnouncement,
842
908
  formatCommandAnnouncement,
@@ -1064,6 +1130,9 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
1064
1130
  }
1065
1131
  }, [requestZoom, zoomGestureEnabled])
1066
1132
  const bodyRef = useRef<HTMLDivElement | null>(null)
1133
+ const bodyStackRef = useRef<HTMLDivElement | null>(null)
1134
+ const zoomBoxRef = useRef<HTMLDivElement | null>(null)
1135
+ const revealRef = useRef<HTMLDivElement | null>(null)
1067
1136
  const handleRef = useRef<VirtualGridHandle | null>(null)
1068
1137
  const sinkRef = useRef<HTMLTextAreaElement | null>(null)
1069
1138
  const rowTrackRef = useRef<HTMLDivElement | null>(null)
@@ -1347,10 +1416,205 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
1347
1416
  ensureDepsRef.current = { rowAxis, colAxis }
1348
1417
  ensureCellVisibleRef.current = createEnsureCellVisible({ handleRef, rowAxis, colAxis })
1349
1418
  }
1350
- const ensureCellVisible = useCallback((cell: CellCoord) => {
1351
- ensureCellVisibleRef.current?.(cell)
1419
+ /**
1420
+ * A cell's rect in visual px relative to the body pane, read now through the three-way forward map (v0.9 §4.9 census
1421
+ * #11 — the keyboard-origin cellRect recipe, the onCellContextMenu twin): the one judgment site of this file, shared by
1422
+ * the keyboard cellRect and the page reveal.
1423
+ * セルの本体ペイン基準の視覚 px 矩形 (3 分岐順写像の判断時読み — v0.9 §4.9 census #11 の keyboard 起点 cellRect のレシピ、
1424
+ * onCellContextMenu と同式)。このファイル唯一の判断点で、keyboard の cellRect とページの追従が共有する。
1425
+ *
1426
+ * @param cell - The cell. セル。
1427
+ * @returns The rect in visual px. 視覚 px の矩形。
1428
+ */
1429
+ const cellRectOf = useCallback(
1430
+ (cell: CellCoord): KeyboardCellRect => {
1431
+ const handle = handleRef.current
1432
+ const position = handle === null ? { x: 0, y: 0 } : handle.getScrollPosition()
1433
+ // 帯件数と extent も同じ判断で読む (v0.9 計画 §4.9、census #11 — AxisForwardCtx はこの場で
1434
+ // インライン構築、§2.1 規則 1)。detached ハンドルは件数 0 / extent 0 の縮退 (末尾分岐不活性 = v0.8 恒等)
1435
+ const frozen = handle === null ? { rows: 0, cols: 0, trailingRows: 0, trailingCols: 0 } : handle.getFrozenSize()
1436
+ const viewport = handle === null ? { width: 0, height: 0 } : handle.getViewportSize()
1437
+ // 両軸とも番兵クランプ (detached の {-1, -1} を座標へ流さない)、ズーム境界で視覚 px へ
1438
+ const z = zoomRef.current
1439
+ return {
1440
+ // 行 / 列とも凍結パーティション 3 分岐順写像 (末尾は extent アンカー — v0.9 §2.1)。×zoom は写像後 (契約不変)
1441
+ top: rowToViewportY(rowAxis, cell.row, { scroll: Math.max(0, position.y), frozenCount: frozen.rows, trailingCount: frozen.trailingRows, extent: viewport.height }) * z,
1442
+ left: colToViewportX(colAxis, cell.col, { scroll: Math.max(0, position.x), frozenCount: frozen.cols, trailingCount: frozen.trailingCols, extent: viewport.width }) * z,
1443
+ width: colAxis.sizeOf(cell.col) * z,
1444
+ height: rowAxis.sizeOf(cell.row) * z,
1445
+ }
1446
+ },
1447
+ [rowAxis, colAxis],
1448
+ )
1449
+
1450
+ /**
1451
+ * Brings a cell the grid has just landed in its own viewport into view in the scroll containers outside the grid (a
1452
+ * host's box, the page), by the least scroll (block and inline "nearest", honouring their scroll-padding): a grid
1453
+ * taller or wider than its scroll container would otherwise keep the active cell off-screen, since the grid sees it
1454
+ * inside its own viewport (WCAG 2.4.11 / 2.4.12). The marker sits under the root, outside every container inside the
1455
+ * grid, and is clipped to the root's box, so only containers outside the grid move.
1456
+ * グリッドが自分の表示域の中へ着地させたセルを、グリッドの外のスクロールの容器 (ホストの箱・ページ) の中でも最小の量で見せる
1457
+ * 処理 (block・inline とも nearest、容器の scroll-padding に従う)。スクロールの容器より高い・広いグリッドでは、グリッドは自分の
1458
+ * 表示域の中にセルを見ているため、選んだセルが画面の外に残る (WCAG 2.4.11・2.4.12)。印は根の直下でグリッドの中のどの容器の
1459
+ * 外にも置き、根の箱に切り詰めるので、動くのはグリッドの外の容器だけ。
1460
+ *
1461
+ * @param cell - The cell, already in the grid's viewport. グリッドの表示域に着地済みのセル。
1462
+ */
1463
+ const revealCellInPage = useCallback(
1464
+ (cell: CellCoord): void => {
1465
+ const marker = revealRef.current
1466
+ const root = rootRef.current
1467
+ const stack = bodyStackRef.current
1468
+ if (marker === null || root === null || stack === null || handleRef.current === null) {
1469
+ return
1470
+ }
1471
+ const z = zoomRef.current
1472
+ const rect = cellRectOf(cell)
1473
+ // 本体ペインの原点は帯の分だけ根の左上から離れる (論理 px の offset を倍率で視覚 px へ)
1474
+ const top = stack.offsetTop * z + rect.top
1475
+ const left = stack.offsetLeft * z + rect.left
1476
+ // 根は overflow: hidden のスクロールの容器。印が根の箱からはみ出すと scrollIntoView が根自身を動かすので、根の箱に切り詰める
1477
+ const clippedTop = Math.max(0, top)
1478
+ const clippedLeft = Math.max(0, left)
1479
+ const clippedBottom = Math.min(root.clientHeight, top + rect.height)
1480
+ const clippedRight = Math.min(root.clientWidth, left + rect.width)
1481
+ if (clippedBottom <= clippedTop || clippedRight <= clippedLeft) {
1482
+ return
1483
+ }
1484
+ marker.style.top = `${clippedTop}px`
1485
+ marker.style.left = `${clippedLeft}px`
1486
+ marker.style.width = `${clippedRight - clippedLeft}px`
1487
+ marker.style.height = `${clippedBottom - clippedTop}px`
1488
+ // 配置された箱を持たない印 (display: none の中のグリッド) には見せる位置が無い
1489
+ const box = marker.getBoundingClientRect()
1490
+ if (box.width === 0 && box.height === 0) {
1491
+ return
1492
+ }
1493
+ // キーの移動は打鍵ごとにその場で着地させる (ホストの scroll-behavior: smooth に任せると、打鍵の速さに描画が遅れる)
1494
+ marker.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "instant" })
1495
+ },
1496
+ [cellRectOf],
1497
+ )
1498
+
1499
+ const ensureCellVisible = useCallback(
1500
+ (cell: CellCoord) => {
1501
+ ensureCellVisibleRef.current?.(cell)
1502
+ revealCellInPage(cell)
1503
+ },
1504
+ [revealCellInPage],
1505
+ )
1506
+
1507
+ /**
1508
+ * The height a page move travels, in logical px (v0.17.1): the grid's own viewport, cut to the part of its body pane
1509
+ * that the scroll containers outside the grid and the window show. A grid taller than its page (a box that shows
1510
+ * every row) would otherwise page from any row to its last, while the page shows a screenful of it. -1 while the
1511
+ * viewport is unmeasured; the whole viewport while no part of the body shows (the grid scrolled out of the page).
1512
+ * ページ移動が進む高さ (論理 px。v0.17.1)。グリッド自身の表示域を、グリッドの外のスクロールの容器と窓が見せる本体ペインの部分で
1513
+ * 切り詰めたもの。ページより高いグリッド (全部の行を見せる箱) では、そうしないと、ページが 1 画面しか見せないのにどの行からでも
1514
+ * 最後の行へ移る。表示域が未計測なら -1、本体がどこも見えない (ページの外へスクロールした) 間は表示域そのもの。
1515
+ *
1516
+ * @returns The travel in logical px, or -1. 論理 px の移動量、または -1。
1517
+ */
1518
+ const pageExtent = useCallback((): number => {
1519
+ const handle = handleRef.current
1520
+ const viewport = handle === null ? -1 : handle.getViewportSize().height
1521
+ const body = bodyRef.current
1522
+ const root = rootRef.current
1523
+ if (viewport <= 0 || body === null || root === null) {
1524
+ return viewport
1525
+ }
1526
+ const rect = body.getBoundingClientRect()
1527
+ if (rect.height <= 0 || body.offsetHeight <= 0) {
1528
+ return viewport
1529
+ }
1530
+ let top = rect.top
1531
+ let bottom = rect.bottom
1532
+ // グリッドの外で縦の overflow が切り抜く祖先 (スクロールの容器・切り抜きの箱) は、どれも本体を切り抜く。祖先の変形や
1533
+ // CSS の zoom で画面の大きさが配置の大きさと違うため、内側の高さは画面と配置の比で写す
1534
+ for (let ancestor = root.parentElement; ancestor !== null; ancestor = ancestor.parentElement) {
1535
+ if (!CLIPPING_OVERFLOWS.has(getComputedStyle(ancestor).overflowY)) {
1536
+ continue
1537
+ }
1538
+ const clip = ancestor.getBoundingClientRect()
1539
+ const scale = ancestor.offsetHeight > 0 ? clip.height / ancestor.offsetHeight : 1
1540
+ top = Math.max(top, clip.top + ancestor.clientTop * scale)
1541
+ bottom = Math.min(bottom, clip.top + (ancestor.clientTop + ancestor.clientHeight) * scale)
1542
+ }
1543
+ top = Math.max(top, 0)
1544
+ bottom = Math.min(bottom, root.ownerDocument.documentElement.clientHeight)
1545
+ // 画面の px を本体の論理 px へ (グリッドの倍率と祖先の伸び縮みの両方を含む比)
1546
+ const shown = (bottom - top) * (body.offsetHeight / rect.height)
1547
+ return shown > 0 ? Math.min(viewport, shown) : viewport
1352
1548
  }, [])
1353
1549
 
1550
+ // ---- 中身の大きさの知らせ (v0.17) ----
1551
+ const onContentSizeChangeRef = useRef(onContentSizeChange)
1552
+ onContentSizeChangeRef.current = onContentSizeChange
1553
+ const reportedContentSizeRef = useRef<SpreadsheetContentSize | null>(null)
1554
+ /**
1555
+ * Reports the content size to `onContentSizeChange` when it differs from the last one reported: the bands' tracks (the
1556
+ * zoom wrapper's inner size less the body pane's, so a host's band-size variables and `headings` count as laid out, on
1557
+ * either side of the body in a right-to-left grid), every track, and the two scroll bars the grid always reserves, all
1558
+ * inside the zoom wrapper and so scaled by the zoom. A grid with no rows or no columns draws nothing and reports 0 × 0;
1559
+ * a grid without a layout box (under a `display: none` ancestor) does not report until it has one.
1560
+ * 中身の大きさを、前に知らせたものと違うときだけ `onContentSizeChange` へ知らせる処理。帯の格子の帯 (ズームの包みの内側の
1561
+ * 大きさから本体ペインの大きさを引いたもの。ホストの帯の寸法の変数と `headings` が配置どおりに入り、右から左のグリッドでも
1562
+ * 帯が本体のどちら側にあっても数える)、全部のトラック、グリッドがいつも取る 2 本のスクロールバーで、どれもズームの包みの中に
1563
+ * あるので倍率で伸び縮みする。行か列の無いグリッドは何も描かないので 0 × 0、配置の箱の無いグリッド (display: none の祖先の中)
1564
+ * は箱を得るまで知らせない。
1565
+ */
1566
+ const reportContentSize = useCallback((): void => {
1567
+ const listener = onContentSizeChangeRef.current
1568
+ if (listener === undefined) {
1569
+ return
1570
+ }
1571
+ const stack = bodyStackRef.current
1572
+ const zoomBox = zoomBoxRef.current
1573
+ let size: SpreadsheetContentSize
1574
+ if (stack === null || zoomBox === null) {
1575
+ // 行か列の無いグリッドは本体を描かない (セルも帯もスクロールバーも無い) ため、中身は大きさを持たない
1576
+ size = EMPTY_CONTENT_SIZE
1577
+ } else if (stack.getClientRects().length === 0) {
1578
+ // 配置の箱の無いグリッド (display: none の祖先の中) では帯の大きさが 0 に読まれる。箱を得た時の大きさの変化で知らせ直す
1579
+ return
1580
+ } else {
1581
+ // 帯の大きさは包みと本体の差で読む (右から左のページでは帯が本体の右にあり、本体の左の位置は帯を数えない)
1582
+ const z = zoomRef.current
1583
+ size = {
1584
+ width: (zoomBox.clientWidth - stack.offsetWidth + colAxis.totalSize() + SPREADSHEET_SCROLLBAR_SIZE_PX) * z,
1585
+ height: (zoomBox.clientHeight - stack.offsetHeight + rowAxis.totalSize() + SPREADSHEET_SCROLLBAR_SIZE_PX) * z,
1586
+ }
1587
+ }
1588
+ const last = reportedContentSizeRef.current
1589
+ if (last !== null && last.width === size.width && last.height === size.height) {
1590
+ return
1591
+ }
1592
+ reportedContentSizeRef.current = size
1593
+ listener(size)
1594
+ }, [rowAxis, colAxis])
1595
+ // 描画のたびに測る (倍率・headings・行と列の数・既定の大きさの変化はどれも再描画を伴う)。知らせる先が外れたら次に付いた先へ
1596
+ // 今の大きさを改めて知らせ、同じ関数でない新しい知らせ先 (描画ごとに作るアロー関数) には値が変わるまで繰り返さない (同じ値の
1597
+ // 再送が知らせ先の状態更新と再描画を無限に回すため)
1598
+ useLayoutEffect(() => {
1599
+ if (onContentSizeChange === undefined) {
1600
+ reportedContentSizeRef.current = null
1601
+ return
1602
+ }
1603
+ reportContentSize()
1604
+ })
1605
+ // 配置の箱を得た時 (display: none の祖先が外れた時) と、帯の寸法の変数の変化は描き直しを伴わないため、本体の大きさの変化で
1606
+ // 知らせ直す (同じ大きさは上の処理が繰り返さない)
1607
+ const reportsContentSize = onContentSizeChange !== undefined
1608
+ useEffect(() => {
1609
+ const stack = bodyStackRef.current
1610
+ if (!reportsContentSize || stack === null) {
1611
+ return
1612
+ }
1613
+ const observer = new ResizeObserver(() => reportContentSize())
1614
+ observer.observe(stack)
1615
+ return () => observer.disconnect()
1616
+ }, [reportsContentSize, reportContentSize, isEmpty])
1617
+
1354
1618
  // ---- 読み上げ (live region — §6.9-9) ----
1355
1619
  const announceTimerRef = useRef<number | null>(null)
1356
1620
  const announceRafRef = useRef<number | null>(null)
@@ -1755,6 +2019,8 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
1755
2019
  // 同期 repaint はエンジン再レンダー前の stale getFrozenSize — 分割線可視は
1756
2020
  // post-commit heal が commit 済み値で整合させる (§2.7 — スクロール介在なし)
1757
2021
  scheduleDividerHeal()
2022
+ // 寸法の変更は再描画を伴わない命令の経路なので、描画の後の知らせを待たずにここで知らせる
2023
+ reportContentSize()
1758
2024
  return
1759
2025
  }
1760
2026
  for (const entry of entries) {
@@ -1768,8 +2034,9 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
1768
2034
  repaintOverlay()
1769
2035
  // 行側も同文 (H_F / H_T の分割線可視は commit 済み値で heal — §2.7)
1770
2036
  scheduleDividerHeal()
2037
+ reportContentSize()
1771
2038
  },
1772
- [rowAxis, colAxis, viewStore, repaintColHeaders, repaintHeaders, repaintOverlay, scheduleDividerHeal],
2039
+ [rowAxis, colAxis, viewStore, repaintColHeaders, repaintHeaders, repaintOverlay, scheduleDividerHeal, reportContentSize],
1773
2040
  )
1774
2041
 
1775
2042
  /** Pointer contextmenu relay to onCellContextMenu (§6.4.3-4 sole channel). / pointer 起点の横流し。 */
@@ -1864,9 +2131,10 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
1864
2131
  })
1865
2132
 
1866
2133
  // ---- ヘッダー選択 (§6.8 — 列 / 行の転置共通機械) ----
2134
+ // 帯の上の機械は帯があるときだけ結線する (headings を切り替えると依存が変わり、新しい帯の要素へ結線し直す)
1867
2135
  const colHeaderMachine = useHeaderSelection({
1868
2136
  zoomRef,
1869
- enabled: !isEmpty,
2137
+ enabled: !isEmpty && headings,
1870
2138
  axis: "col",
1871
2139
  headerRef: colHeaderRef,
1872
2140
  mainAxis: colAxis,
@@ -1885,7 +2153,7 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
1885
2153
  })
1886
2154
  const rowHeaderMachine = useHeaderSelection({
1887
2155
  zoomRef,
1888
- enabled: !isEmpty,
2156
+ enabled: !isEmpty && headings,
1889
2157
  axis: "row",
1890
2158
  headerRef: rowHeaderRef,
1891
2159
  mainAxis: rowAxis,
@@ -1906,9 +2174,10 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
1906
2174
  // ---- リサイズ / unhide 機械 (§7 PT-1) + fill 機械 (§8 PT-2) ----
1907
2175
  const headerResizeMachine = useHeaderResize({
1908
2176
  zoomRef,
1909
- enabled: !isEmpty && enableResizeUI,
2177
+ enabled: !isEmpty && enableResizeUI && headings,
1910
2178
  colBandRef: colHeaderRef,
1911
2179
  rowBandRef: rowHeaderRef,
2180
+ fontSourceRef: bodyRef,
1912
2181
  colAxis,
1913
2182
  rowAxis,
1914
2183
  viewStore,
@@ -2144,26 +2413,12 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
2144
2413
 
2145
2414
  // ---- コマンド実行 (v0.8 §4.1.13 / ADR-17) ----
2146
2415
  /** The active cell's viewport rect in visual px via the three-way forward map (v0.9 §4.9 census #11 — the keyboard-origin cellRect recipe, onCellContextMenu twin) for onPasteSpecialRequest. / active セルの視覚 px 矩形 — 3 分岐順写像 (v0.9 §4.9 census #11。keyboard 起点 cellRect のレシピ、onCellContextMenu と同式)。 */
2147
- const keyboardCellRect = useCallback(() => {
2416
+ const keyboardCellRect = useCallback((): KeyboardCellRect => {
2148
2417
  const active = selectionRef.current.active
2149
2418
  // 画面外座標へメニューを出さない (§6.6.1) — 可視化してからハンドルの同期読み (§7-4)
2150
2419
  ensureCellVisible(active)
2151
- const handle = handleRef.current
2152
- const position = handle === null ? { x: 0, y: 0 } : handle.getScrollPosition()
2153
- // 帯件数と extent も同じ判断で読む (v0.9 計画 §4.9、census #11 — AxisForwardCtx はこの場で
2154
- // インライン構築、§2.1 規則 1)。detached ハンドルは件数 0 / extent 0 の縮退 (末尾分岐不活性 = v0.8 恒等)
2155
- const frozen = handle === null ? { rows: 0, cols: 0, trailingRows: 0, trailingCols: 0 } : handle.getFrozenSize()
2156
- const viewport = handle === null ? { width: 0, height: 0 } : handle.getViewportSize()
2157
- // 両軸とも番兵クランプ (detached の {-1, -1} を座標へ流さない)、ズーム境界で視覚 px へ
2158
- const z = zoomRef.current
2159
- return {
2160
- // 行 / 列とも凍結パーティション 3 分岐順写像 (末尾は extent アンカー — v0.9 §2.1)。×zoom は写像後 (契約不変)
2161
- top: rowToViewportY(rowAxis, active.row, { scroll: Math.max(0, position.y), frozenCount: frozen.rows, trailingCount: frozen.trailingRows, extent: viewport.height }) * z,
2162
- left: colToViewportX(colAxis, active.col, { scroll: Math.max(0, position.x), frozenCount: frozen.cols, trailingCount: frozen.trailingCols, extent: viewport.width }) * z,
2163
- width: colAxis.sizeOf(active.col) * z,
2164
- height: rowAxis.sizeOf(active.row) * z,
2165
- }
2166
- }, [rowAxis, colAxis, ensureCellVisible])
2420
+ return cellRectOf(active)
2421
+ }, [ensureCellVisible, cellRectOf])
2167
2422
  const commands = useCommands({
2168
2423
  adapter,
2169
2424
  // キーボードの寸法の変更は帯のリサイズ UI と同じ可否 (enableResizeUI が false なら利用者は寸法を変えない)
@@ -2229,6 +2484,7 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
2229
2484
  setSelection,
2230
2485
  moveActive,
2231
2486
  ensureCellVisible,
2487
+ pageExtent,
2232
2488
  isEditing,
2233
2489
  requestCommit,
2234
2490
  startEdit,
@@ -2725,6 +2981,7 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
2725
2981
  repaintOverlay()
2726
2982
  // 分割線可視は commit 済み getFrozenSize の post-commit heal で整合 (§2.7)
2727
2983
  scheduleDividerHeal()
2984
+ reportContentSize()
2728
2985
  },
2729
2986
  resizeColumn: (col: number, widthPx: number) => {
2730
2987
  // 対呼び出し (§3.8): colAxis (SSOT) を先に更新し、グリッドの幅木へ通知する。
@@ -2739,6 +2996,15 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
2739
2996
  repaintOverlay()
2740
2997
  // 分割線可視は commit 済み getFrozenSize の post-commit heal で整合 (§2.7)
2741
2998
  scheduleDividerHeal()
2999
+ reportContentSize()
3000
+ },
3001
+ autoFitColumns: (columns: readonly number[]) => {
3002
+ for (const col of columns) {
3003
+ if (!Number.isInteger(col) || col < 0 || col >= colAxis.count) {
3004
+ throw new RangeError(`[spreadsheet] autoFitColumns: each column must be a whole number from 0 to ${colAxis.count - 1} (got ${String(col)})`)
3005
+ }
3006
+ }
3007
+ return headerResizeMachine.autofitColumnsInAllRows(columns)
2742
3008
  },
2743
3009
  scrollToCell: (cell: CellCoord, options?: ScrollToCellOptions) => {
2744
3010
  // エンジンのセル狙いジャンプへ素通し (§7-4 の真実。選択は変えない — 純 viewport 移動)。
@@ -2773,7 +3039,7 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
2773
3039
  openPopoverRef.current(kind)
2774
3040
  },
2775
3041
  }),
2776
- [rowAxis, colAxis, viewStore, repaintColHeaders, repaintHeaders, repaintOverlay, scheduleDividerHeal, focusSink, isEditing, rearmSink, adapter, paintedFormatOf, startEdit, requireCommands],
3042
+ [rowAxis, colAxis, viewStore, repaintColHeaders, repaintHeaders, repaintOverlay, scheduleDividerHeal, reportContentSize, headerResizeMachine, focusSink, isEditing, rearmSink, adapter, paintedFormatOf, startEdit, requireCommands],
2777
3043
  )
2778
3044
 
2779
3045
  // ---- 空グリッド分岐 (§6.9-1: フックの後・結線の前) ----
@@ -2791,75 +3057,84 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
2791
3057
  return (
2792
3058
  // biome-ignore lint/a11y/useSemanticElements: fieldset はフォーム意味論であり不適。role="group" は Escape 脱出の着地点に現在地名を与えるための選択 (§6.9-7 / §10-4)
2793
3059
  // biome-ignore lint/a11y/noNoninteractiveTabindex: tabIndex=0 は WCAG 2.1.2 の脱出着地点 + グリッド再進入口 (§10-4) — 意図的な tab stop
2794
- <div ref={rootRef} className={className ? `aqsp-root ${className}` : "aqsp-root"} role="group" {...rootName} tabIndex={0} onFocus={onRootFocus} onBlur={onRootBlur} data-aqsp-root="" data-testid={testId}>
3060
+ <div ref={rootRef} className={className ? `aqsp-root ${className}` : "aqsp-root"} role="group" {...rootName} tabIndex={0} onFocus={onRootFocus} onBlur={onRootBlur} data-aqsp-root="" data-aqsp-headings-hidden={headings ? undefined : ""} data-testid={testId}>
2795
3061
  {/* ズームラッパー (v0.3): 視覚は transform スケール、内側レイアウトは 100%/z の論理 px —
2796
3062
  virtualscroll の実測 (ResizeObserver / clientHeight) は論理値のまま。z=1 は無スタイル
2797
3063
  (v0.2 と byte 同一の DOM 幾何 — 既存全ゲートの不変性) */}
2798
- <div className="aqsp-zoom" data-aqsp-zoom={zoomValue} onPointerDown={onZoomPointerDown} style={zoomValue === 1 ? undefined : { width: `${100 / zoomValue}%`, height: `${100 / zoomValue}%`, transform: `scale(${zoomValue})` }}>
2799
- <div
2800
- className="aqsp-corner"
2801
- aria-hidden="true"
2802
- data-aqsp-corner=""
2803
- onPointerDown={(event) => {
2804
- // mouse 限定 (§6.4.1 の表ヘッダー「mouse のみ」— エンジン / ヘッダー機械と同一ゲート)
2805
- if (event.pointerType !== "mouse") {
2806
- return
2807
- }
2808
- // 非主ボタンも既定のフォーカス移動だけは止める (全押下面共通 — R2 是正)
2809
- event.preventDefault()
2810
- if (event.button !== 0) {
2811
- return
2812
- }
2813
- // 参照ポインティング中 (v0.8 §4.2.13): コーナー押下は consume + シンクへ焦点 (全選択も確定もしない)
2814
- if (isPointing()) {
2815
- focusSink()
2816
- return
2817
- }
2818
- // 編集中の requestCommit ゲート (§6.8-3 — コーナーもフォーカス不動で focusout 不発)
2819
- if (isEditing() && !requestCommit()) {
2820
- focusSink()
2821
- return
2822
- }
2823
- focusSink()
2824
- // コーナーの全セル選択は単一構築 state の setSelection 1 回 (過渡状態なし)。active = A1
2825
- setSelection({
2826
- ranges: [makeRange({ row: 0, col: 0 }, { row: adapter.rowCount - 1, col: adapter.colCount - 1 })],
2827
- anchor: { row: 0, col: 0 },
2828
- active: { row: 0, col: 0 },
2829
- })
2830
- }}
2831
- />
2832
- <ColumnHeader
2833
- viewStore={viewStore}
2834
- colAxis={colAxis}
2835
- frozenCols={frozenColumns}
2836
- frozenTrailingCols={frozenTrailingColumns}
2837
- handleRef={handleRef}
2838
- bandRef={colHeaderRef}
2839
- colTrackRef={colTrackRef}
2840
- windowOriginXRef={windowOriginXRef}
2841
- repaintColHeaders={repaintColHeaders}
2842
- selectionRanges={selection.ranges}
2843
- enableResizeUI={enableResizeUI}
2844
- dividerLeadingRef={dividerXLeadingRef}
2845
- dividerTrailingRef={dividerXTrailingRef}
2846
- />
2847
- <RowHeader
2848
- viewStore={viewStore}
2849
- rowAxis={rowAxis}
2850
- handleRef={handleRef}
2851
- bandRef={rowHeaderRef}
2852
- selectionRanges={selection.ranges}
2853
- rowTrackRef={rowTrackRef}
2854
- windowOriginYRef={windowOriginYRef}
2855
- repaintHeaders={repaintHeaders}
2856
- enableResizeUI={enableResizeUI}
2857
- frozenRows={frozenRows}
2858
- frozenTrailingRows={frozenTrailingRows}
2859
- dividerLeadingRef={dividerYLeadingRef}
2860
- dividerTrailingRef={dividerYTrailingRef}
2861
- />
2862
- <div className="aqsp-body-stack" data-aqsp-body-stack="">
3064
+ <div
3065
+ ref={zoomBoxRef}
3066
+ className="aqsp-zoom"
3067
+ data-aqsp-zoom={zoomValue}
3068
+ onPointerDown={onZoomPointerDown}
3069
+ style={zoomValue === 1 ? undefined : ({ width: `${100 / zoomValue}%`, height: `${100 / zoomValue}%`, transform: `scale(${zoomValue})`, "--_aqsp-zoom": String(zoomValue) } as CSSProperties)}>
3070
+ {headings ? (
3071
+ <>
3072
+ <div
3073
+ className="aqsp-corner"
3074
+ aria-hidden="true"
3075
+ data-aqsp-corner=""
3076
+ onPointerDown={(event) => {
3077
+ // mouse 限定 (§6.4.1 の表ヘッダー「mouse のみ」— エンジン / ヘッダー機械と同一ゲート)
3078
+ if (event.pointerType !== "mouse") {
3079
+ return
3080
+ }
3081
+ // 非主ボタンも既定のフォーカス移動だけは止める (全押下面共通 — R2 是正)
3082
+ event.preventDefault()
3083
+ if (event.button !== 0) {
3084
+ return
3085
+ }
3086
+ // 参照ポインティング中 (v0.8 §4.2.13): コーナー押下は consume + シンクへ焦点 (全選択も確定もしない)
3087
+ if (isPointing()) {
3088
+ focusSink()
3089
+ return
3090
+ }
3091
+ // 編集中の requestCommit ゲート (§6.8-3 — コーナーもフォーカス不動で focusout 不発)
3092
+ if (isEditing() && !requestCommit()) {
3093
+ focusSink()
3094
+ return
3095
+ }
3096
+ focusSink()
3097
+ // コーナーの全セル選択は単一構築 state の setSelection 1 回 (過渡状態なし)。active = A1
3098
+ setSelection({
3099
+ ranges: [makeRange({ row: 0, col: 0 }, { row: adapter.rowCount - 1, col: adapter.colCount - 1 })],
3100
+ anchor: { row: 0, col: 0 },
3101
+ active: { row: 0, col: 0 },
3102
+ })
3103
+ }}
3104
+ />
3105
+ <ColumnHeader
3106
+ viewStore={viewStore}
3107
+ colAxis={colAxis}
3108
+ frozenCols={frozenColumns}
3109
+ frozenTrailingCols={frozenTrailingColumns}
3110
+ handleRef={handleRef}
3111
+ bandRef={colHeaderRef}
3112
+ colTrackRef={colTrackRef}
3113
+ windowOriginXRef={windowOriginXRef}
3114
+ repaintColHeaders={repaintColHeaders}
3115
+ selectionRanges={selection.ranges}
3116
+ enableResizeUI={enableResizeUI}
3117
+ dividerLeadingRef={dividerXLeadingRef}
3118
+ dividerTrailingRef={dividerXTrailingRef}
3119
+ />
3120
+ <RowHeader
3121
+ viewStore={viewStore}
3122
+ rowAxis={rowAxis}
3123
+ handleRef={handleRef}
3124
+ bandRef={rowHeaderRef}
3125
+ selectionRanges={selection.ranges}
3126
+ rowTrackRef={rowTrackRef}
3127
+ windowOriginYRef={windowOriginYRef}
3128
+ repaintHeaders={repaintHeaders}
3129
+ enableResizeUI={enableResizeUI}
3130
+ frozenRows={frozenRows}
3131
+ frozenTrailingRows={frozenTrailingRows}
3132
+ dividerLeadingRef={dividerYLeadingRef}
3133
+ dividerTrailingRef={dividerYTrailingRef}
3134
+ />
3135
+ </>
3136
+ ) : null}
3137
+ <div ref={bodyStackRef} className="aqsp-body-stack" data-aqsp-body-stack="">
2863
3138
  <GridBody
2864
3139
  adapter={adapter}
2865
3140
  rowAxis={rowAxis}
@@ -2934,6 +3209,8 @@ export const Spreadsheet = forwardRef<SpreadsheetHandle, SpreadsheetProps & Spre
2934
3209
  </div>
2935
3210
  {hasAnnouncement ? <div ref={liveRegionRef} className="aqsp-live-region" aria-live="polite" data-aqsp-live-region="" /> : null}
2936
3211
  </div>
3212
+ {/* キーの移動で選んだセルをページの中で見せる印 (位置は revealCellInPage が書く)。ズームの包みの外の根の直下に置き、グリッドの中の容器を動かさない */}
3213
+ <div ref={revealRef} className="aqsp-reveal" aria-hidden="true" data-aqsp-reveal="" />
2937
3214
  </div>
2938
3215
  )
2939
3216
  })