@aiquants/spreadsheet 0.20.1 → 0.20.2

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.
@@ -23,6 +23,8 @@
23
23
  * ants kept, no scroll jump, before seeding) and G16 live-re-checks the session cell at
24
24
  * `finishEdit` commit time (after the unchanged short-circuit, before `validateCommit`);
25
25
  * both fire the required `rejectReadOnly` funnel, and an undeclared capability is byte-identical.
26
+ * The session opens only in `startEdit` and closes only in `finishEdit`'s `closeSession`, so the host's
27
+ * `onEditSessionChange` (the `onSessionChange` param) hears every open and every close from those two points.
26
28
  *
27
29
  * セル編集セッション状態機械 (§6.7.1)。idle / editing(edit) / editing(replace) のセッション
28
30
  * 状態・composition 追跡・グリッド外 focusout commit・suppressFocusoutCommit を所有する。
@@ -41,7 +43,8 @@
41
43
  * v0.10 読み取り専用セル (計画 §6.3): G1 は全 6 入口の単一漏斗 `startEdit` で編集モード進入を
42
44
  * 拒否し (sink-null bail と `discardClip` の間 — アンツ保持・スクロール不跳び・シード前)、G16 は
43
45
  * `finishEdit` の確定時にセッションセルを生再検査する (無変更短絡の後・`validateCommit` の前)。
44
- * どちらも必須 `rejectReadOnly` 漏斗へ発火し、能力未宣言は従来挙動とバイト同一。
46
+ * どちらも必須 `rejectReadOnly` 漏斗へ発火し、能力未宣言は従来挙動とバイト同一。セッションが開くのは `startEdit`、閉じるのは
47
+ * `finishEdit` の `closeSession` だけなので、利用側の `onEditSessionChange` (`onSessionChange` 引数) は全ての開閉をこの 2 点から聞く。
45
48
  */
46
49
 
47
50
  import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from "react"
@@ -52,8 +55,19 @@ import { type CellEdit, type EditRejection, isReadOnlyCell, type ReadOnlyRejecti
52
55
  import type { ValidationVerdict } from "../model/dataValidation.ts"
53
56
  import { cycleAnchorAt, findReferenceAt, formatRangeReference, isPointingPrefix, type PointingTarget, type ReferenceAxis } from "../model/formulaRefs.ts"
54
57
 
55
- /** Editing mode (§6.7.1 state diagram). / 編集モード。 */
56
- export type EditingMode = "edit" | "replace"
58
+ /**
59
+ * The open in-place edit session (§6.7.1): the cell it writes to, captured when it opened, and how it opened — `"edit"`
60
+ * (F2, a double-click, `startEdit("edit")`: the cell's text with the caret in it) or `"replace"` (a printable key, an IME
61
+ * composition, `startEdit("replace")`: an empty editor). Reported by `onEditSessionChange` and read by the handle's
62
+ * `getEditSession`; the grid replaces the object, never mutates it.
63
+ * 開いているその場の入力のセッション (§6.7.1): 開いた時に捉えた書き込み先のマスと、開き方 — `"edit"` (F2・ダブルクリック・
64
+ * `startEdit("edit")`。マスの字にキャレット) か `"replace"` (印字キー・IME の変換・`startEdit("replace")`。空の入力欄)。
65
+ * `onEditSessionChange` が知らせ、handle の `getEditSession` が読む。グリッドは物を差し替え、書き換えない。
66
+ */
67
+ export type EditSession = { readonly cell: CellCoord; readonly mode: "edit" | "replace" }
68
+
69
+ /** Editing mode (§6.7.1 state diagram) — the session's own `mode`. / 編集モード (セッションの `mode` そのもの)。 */
70
+ export type EditingMode = EditSession["mode"]
57
71
 
58
72
  /** Sink snapshot for the reference-drag Escape restore (value + caret range before the drag). / 参照ドラッグの Escape 復元用シンク断面 (ドラッグ前の value とキャレット区間)。 */
59
73
  export type SinkSnapshot = { value: string; selectionStart: number; selectionEnd: number }
@@ -151,6 +165,16 @@ type UseCellEditorParams = {
151
165
  * keep / discard 経路。undefined = 検証なし (v0.7 恒等)。
152
166
  */
153
167
  validateCommit?: (cell: CellCoord, text: string) => ValidationVerdict
168
+ /**
169
+ * The host's `onEditSessionChange`, read when called (a re-render with another function takes effect at the next
170
+ * open or close): the new session right after it opens, `null` right after it closes — after `applyEdits` returned
171
+ * for a commit, before the key that committed moves the active cell. A refused commit that keeps the session open
172
+ * closes nothing and calls nothing. Undefined = no notice.
173
+ * 利用側の `onEditSessionChange` (呼ぶ時に読む — 別の関数での再描画は次の開閉から効く): 開いた直後に新しいセッション、閉じた直後に
174
+ * `null` — 確定なら `applyEdits` が戻った後、確定したキーがアクティブなマスを動かす前。入力を続ける断りは何も閉じず何も呼ばない。
175
+ * undefined = 知らせない。
176
+ */
177
+ onSessionChange?: (session: EditSession | null) => void
154
178
  }
155
179
 
156
180
  /** Seams consumed by the keymap and the pointer machines. / キーマップ / ポインタ機械が消費するシーム。 */
@@ -182,6 +206,8 @@ export type CellEditor = PointingSeams & {
182
206
  getSessionText: () => string | null
183
207
  /** The session's cell, or null when idle — the count-shrink clamp cancels a session whose cell left the grid. / セッションのセル (idle は null) — 行数 / 列数縮小の畳込みが、グリッドから消えたセルのセッションを取り消す判定に使う。 */
184
208
  getSessionCell: () => CellCoord | null
209
+ /** The open session — the same object `onSessionChange` reported — or null when idle (the handle's `getEditSession`). / 開いているセッション (`onSessionChange` が知らせた物と同じ物)、idle は null (handle の `getEditSession`)。 */
210
+ getSession: () => EditSession | null
185
211
  /** Recomputes and re-applies the edit paint after an editing-column format toggle, then repaints the overlay. / 編集列の書式トグル後に塗りを再計算・再適用し overlay を再描画。 */
186
212
  refreshPaint: () => void
187
213
  /** React state mirror for the overlay's editing prop (§6.7.2-4). / overlay の editing prop 用ミラー。 */
@@ -224,7 +250,7 @@ export const useCellEditor = (params: UseCellEditorParams): CellEditor => {
224
250
  paramsRef.current = params
225
251
 
226
252
  /** In-flight session (null = idle); commit writes to the cell captured at start. / 飛行中セッション。commit は開始時に捕捉したセルへ書く。 */
227
- const sessionRef = useRef<{ cell: CellCoord; mode: EditingMode } | null>(null)
253
+ const sessionRef = useRef<EditSession | null>(null)
228
254
  const [editing, setEditing] = useState(false)
229
255
  const isComposingRef = useRef(false)
230
256
  const suppressFocusoutCommitRef = useRef(false)
@@ -348,6 +374,7 @@ export const useCellEditor = (params: UseCellEditorParams): CellEditor => {
348
374
  sink.removeAttribute(POINTING_ATTRIBUTE)
349
375
  }
350
376
  setEditing(false)
377
+ p.onSessionChange?.(null)
351
378
  }
352
379
  if (options.commit) {
353
380
  const sink = p.sinkRef.current
@@ -464,8 +491,10 @@ export const useCellEditor = (params: UseCellEditorParams): CellEditor => {
464
491
  // 非武装のため述語は構造的に不成立で、ヒント属性は前セッションの closeSession が除去済み
465
492
  pointingArmedRef.current = false
466
493
  pointingAnchorRef.current = null
467
- sessionRef.current = { cell: active, mode }
494
+ const session: EditSession = { cell: active, mode }
495
+ sessionRef.current = session
468
496
  setEditing(true)
497
+ p.onSessionChange?.(session)
469
498
  },
470
499
  [applyPaint],
471
500
  )
@@ -659,6 +688,8 @@ export const useCellEditor = (params: UseCellEditorParams): CellEditor => {
659
688
 
660
689
  const getSessionCell = useCallback((): CellCoord | null => (sessionRef.current === null ? null : sessionRef.current.cell), [])
661
690
 
691
+ const getSession = useCallback((): EditSession | null => sessionRef.current, [])
692
+
662
693
  const refreshPaint = useCallback((): void => {
663
694
  const p = paramsRef.current
664
695
  const session = sessionRef.current
@@ -754,9 +785,10 @@ export const useCellEditor = (params: UseCellEditorParams): CellEditor => {
754
785
  insertAtCaret,
755
786
  getSessionText,
756
787
  getSessionCell,
788
+ getSession,
757
789
  refreshPaint,
758
790
  editing,
759
791
  }),
760
- [requestCommit, cancelEdit, startEdit, getPointing, togglePointingArm, getReferenceCursor, insertReference, captureSink, restoreSink, cycleAnchorAtCaret, insertAtCaret, getSessionText, getSessionCell, refreshPaint, editing],
792
+ [requestCommit, cancelEdit, startEdit, getPointing, togglePointingArm, getReferenceCursor, insertReference, captureSink, restoreSink, cycleAnchorAtCaret, insertAtCaret, getSessionText, getSessionCell, getSession, refreshPaint, editing],
761
793
  )
762
794
  }
package/src/index.ts CHANGED
@@ -49,6 +49,7 @@ export { estimatePasteCellCount, expandPaste } from "./clipboard/tiling.ts"
49
49
  export { iterateTsvPrefixRows, iterateTsvRows, measureTsv, parseTsv, serializeClipboardTsv, serializeTsv } from "./clipboard/tsv.ts"
50
50
  export type { ClipInfo, PasteOutcome } from "./clipboard/useClipboard.ts"
51
51
  export type { BorderPreset } from "./commands/useCommands.ts"
52
+ export type { EditSession } from "./editor/useCellEditor.ts"
52
53
  // renderCell の ctx 型 — prop が公開面にある以上、その引数型も名指しできなければならない
53
54
  // (未公開だと consumer は Parameters<...> 抽出を強いられる)。型のみの追加で非破壊
54
55
  export type { RenderCellContext } from "./grid/CellView.tsx"
@@ -122,5 +123,16 @@ export { NoteTip, type NoteTipProps } from "./popover/NoteTip.tsx"
122
123
  // PopoverContext.anchorRect の型 (層座標系の矩形) — 配置エンジン placePopover 本体は非公開のまま
123
124
  export type { PopoverRect } from "./popover/placement.ts"
124
125
  export type { CommentPopoverContext, LinkPopoverContext, ListPopoverContext, MessagePopoverContext, NotePopoverContext, NoteTipContext, PopoverContext, PopoverKind, PopoverOverrides } from "./popover/usePopovers.ts"
125
- export { DEFAULT_CUSTOM_COLORS, type ScrollToCellOptions, Spreadsheet, type SpreadsheetContentSize, type SpreadsheetHandle, type SpreadsheetProps, type SpreadsheetScrollBarControls } from "./Spreadsheet.tsx"
126
+ export {
127
+ type CommitEditOutcome,
128
+ DEFAULT_CUSTOM_COLORS,
129
+ type ScrollToCellOptions,
130
+ type SelectionChangeReason,
131
+ type SetSelectionOptions,
132
+ Spreadsheet,
133
+ type SpreadsheetContentSize,
134
+ type SpreadsheetHandle,
135
+ type SpreadsheetProps,
136
+ type SpreadsheetScrollBarControls,
137
+ } from "./Spreadsheet.tsx"
126
138
  export type { SelectionState } from "./selection/selectionState.ts"
@@ -37,7 +37,12 @@
37
37
  * in a text field (`isConsumedWhileEditing` — no Alt, a function key or Ctrl with a character
38
38
  * key) the editing column consumes it after every row, so the browser's own shortcut (bookmark,
39
39
  * reload, search box) never fires; the session is left untouched and `onCommandBlockedWhileEditing`
40
- * reports the command and chord.
40
+ * reports the command and chord. The composition guard drops every IME keydown except one: the
41
+ * editing column's `fillSelection` chord (read from `event.code`, rebinding included) pressed while
42
+ * the composition is open is remembered and runs once in the task after `compositionend` when the
43
+ * committed text is not empty and the session is still open, and one arriving right after the
44
+ * composition ended (Safari's order, the 50 ms window) runs at once — so Ctrl+Enter fills with the
45
+ * confirmed text on the first press.
41
46
  *
42
47
  * シンク keydown 上のキーマップ実装 (§6.6.1 の契約表 — idle 列。編集列は Phase 3 の編集
43
48
  * セッションへ委譲)。v0.2 で findDataEdge ナビゲーション + ディスパッチ前 fail-fast 検証 (§2)・
@@ -68,7 +73,10 @@
68
73
  * fillRight の Ctrl+R・insertLink の Ctrl+K …) は編集中に走らず、入力欄に何も打たないチョード
69
74
  * (`isConsumedWhileEditing` — Alt なしで機能キーか Ctrl + 文字キー) なら編集列が全ての行の後で消費する
70
75
  * — ブラウザの既定 (ブックマーク・再読込・検索欄) は発火しない。セッションには触らず、
71
- * `onCommandBlockedWhileEditing` がコマンドとチョードを報告する。
76
+ * `onCommandBlockedWhileEditing` がコマンドとチョードを報告する。変換ガードは IME の keydown を全て捨てるが、
77
+ * 1 つだけ例外がある: 変換の途中に押した編集列の `fillSelection` のチョード (`event.code` で読む。付け替えも
78
+ * 含む) は覚え、`compositionend` の次のタスクで、確定した字が空でなく入力がまだ開いていれば 1 回走らせる。変換が
79
+ * 終わった直後に届いたもの (Safari の順・50 ms の窓) はその場で走らせる — Ctrl+Enter は確定した字で 1 回で埋める。
72
80
  */
73
81
 
74
82
  import type { VirtualGridHandle } from "@aiquants/virtualscroll"
@@ -234,6 +242,11 @@ const isSelectionDestroyingNav = (event: KeyboardEvent): boolean => {
234
242
  export const useGridKeyboard = (params: UseGridKeyboardParams): void => {
235
243
  const compositionEndedAtRef = useRef<number | null>(null)
236
244
  const clearTimerRef = useRef<number | null>(null)
245
+ // 変換の途中かどうかはこのフック自身の compositionstart / compositionend で持つ — エディタの変換の印とは聞き手の順が決まらない
246
+ const composingRef = useRef(false)
247
+ // 変換中に押された fillSelection のチョード (冒頭のガードが捨てる keydown) の覚えと、確定の後に走らせるタイマー
248
+ const pendingFillRef = useRef(false)
249
+ const fillTimerRef = useRef<number | null>(null)
237
250
  // ctrl+alt 印字形状の遅延開始保留 (v0.3.3): 直前 keydown が ctrl+alt 同時の 1 文字キーの
238
251
  // ときだけ true。実文字の到着 (input) で消費、次の keydown / keyup / blur で失効する一発
239
252
  // フラグ。現実の通過者は文字を生まないリテラル和音 (Ctrl+Alt+X 等 — 空置換セッション破壊の
@@ -397,6 +410,65 @@ export const useGridKeyboard = (params: UseGridKeyboardParams): void => {
397
410
  p.moveActive({ mode: "cycle", direction: cycleDirection })
398
411
  }
399
412
 
413
+ /**
414
+ * The command dispatch when a composition-guarded keydown is the editing column's `fillSelection` chord (the
415
+ * chord is read from `event.code`, so an IME keydown whose `key` is `"Process"` resolves too, and so does a
416
+ * rebound chord); null otherwise — idle, the command unavailable, or another chord.
417
+ * 変換ガードが捨てる keydown が編集列の `fillSelection` のチョードなら、そのコマンドの配り口 (チョードは `event.code` で読むので、
418
+ * `key` が `"Process"` の IME の keydown も、付け替えたチョードも解決する)。それ以外 (idle・使えない・別のチョード) は null。
419
+ *
420
+ * @param event - The keydown the composition guard dropped. 変換ガードが捨てた keydown。
421
+ * @returns The dispatch to run `fillSelection` through, or null. `fillSelection` を走らせる配り口、または null。
422
+ */
423
+ const compositionFillDispatch = (event: KeyboardEvent): CommandDispatch | null => {
424
+ const p = paramsRef.current
425
+ const commands = p.commands
426
+ if (commands === undefined || !p.isEditing()) {
427
+ return null
428
+ }
429
+ const binding = resolveBinding(commands.table, event)
430
+ return binding !== null && binding.command === "fillSelection" && commands.isAvailable("fillSelection") ? commands : null
431
+ }
432
+
433
+ /**
434
+ * Runs the `fillSelection` remembered during a composition, after the composition committed — only while the
435
+ * session is still open and the command still available.
436
+ * 変換中に覚えた `fillSelection` を、変換の確定の後に走らせる — 入力がまだ開いていて、コマンドがまだ使えるときだけ。
437
+ */
438
+ const runCompositionFill = (): void => {
439
+ fillTimerRef.current = null
440
+ const p = paramsRef.current
441
+ const commands = p.commands
442
+ // 確定の前に入力が閉じた (焦点の離脱の確定など) — 入力の無い fillSelection はアクティブなマスを写す別の動きになる
443
+ if (commands === undefined || !p.isEditing() || !commands.isAvailable("fillSelection")) {
444
+ return
445
+ }
446
+ commands.execute("fillSelection")
447
+ }
448
+
449
+ /**
450
+ * Handles a keydown the composition guard drops. While the composition is open, a `fillSelection` chord is
451
+ * remembered for the commit and any other key forgets it (the IME took that key for itself). Right after the
452
+ * composition ended — Safari fires `compositionend` before the confirming keydown, and the 50 ms window drops a
453
+ * chord pressed just after a confirmation — the chord runs at once. Every other dropped keydown stays dropped.
454
+ * 変換ガードが捨てる keydown の扱い。変換の途中なら、`fillSelection` のチョードは確定まで覚え、ほかのキーは覚えを捨てる (IME が
455
+ * そのキーを使った)。変換が終わった直後 — Safari は確定のキーより先に `compositionend` を出し、50 ms の窓は確定の直後に押した
456
+ * チョードを捨てる — なら、その場で走らせる。ほかの捨てた keydown は捨てたまま。
457
+ *
458
+ * @param event - The keydown the composition guard dropped. 変換ガードが捨てた keydown。
459
+ */
460
+ const takeCompositionKeydown = (event: KeyboardEvent): void => {
461
+ const fill = compositionFillDispatch(event)
462
+ if (composingRef.current) {
463
+ pendingFillRef.current = fill !== null
464
+ return
465
+ }
466
+ if (fill !== null && compositionEndedAtRef.current !== null) {
467
+ event.preventDefault()
468
+ fill.execute("fillSelection")
469
+ }
470
+ }
471
+
400
472
  /** Manual newline insertion at the caret (editing Alt+Enter — most browsers insert nothing natively). / キャレット位置へ改行を挿入 (編集列 Alt+Enter)。 */
401
473
  const insertNewlineAtCaret = (): void => {
402
474
  const sink = sinkRef.current
@@ -441,8 +513,10 @@ export const useGridKeyboard = (params: UseGridKeyboardParams): void => {
441
513
  // 新しい打鍵は AltGr 保留を無条件に失効させる (保留を再設定するのは末尾の AltGr 分岐のみ)
442
514
  altGrPendingRef.current = false
443
515
  // 冒頭ガード (§6.6.2-1): 変換中 / keyCode 229 / compositionend 直後 50 ms 窓の Enter・Escape —
444
- // 判定は compositionGuard.ts の単一真実源 (ポップオーバーの keydown も同じ関数を通す)
516
+ // 判定は compositionGuard.ts の単一真実源 (ポップオーバーの keydown も同じ関数を通す)。捨てる keydown のうち
517
+ // fillSelection のチョードだけは、確定した字で 1 回で埋める (変換中の Ctrl+Enter が 2 回押しにならない)
445
518
  if (isCompositionKeydown(event, compositionEndedAtRef.current)) {
519
+ takeCompositionKeydown(event)
446
520
  return
447
521
  }
448
522
  const ctrl = event.ctrlKey || event.metaKey
@@ -911,6 +985,8 @@ export const useGridKeyboard = (params: UseGridKeyboardParams): void => {
911
985
 
912
986
  const onCompositionStart = () => {
913
987
  const p = paramsRef.current
988
+ composingRef.current = true
989
+ pendingFillRef.current = false
914
990
  if (!p.isEditing()) {
915
991
  // IME トリガー: value = "" の設定 1 点で replace モード開始 (§6.6.2-5)
916
992
  p.startEdit("replace")
@@ -918,6 +994,7 @@ export const useGridKeyboard = (params: UseGridKeyboardParams): void => {
918
994
  }
919
995
 
920
996
  const onCompositionEnd = (event: CompositionEvent) => {
997
+ composingRef.current = false
921
998
  compositionEndedAtRef.current = event.timeStamp
922
999
  if (clearTimerRef.current !== null) {
923
1000
  window.clearTimeout(clearTimerRef.current)
@@ -927,6 +1004,20 @@ export const useGridKeyboard = (params: UseGridKeyboardParams): void => {
927
1004
  compositionEndedAtRef.current = null
928
1005
  clearTimerRef.current = null
929
1006
  }, COMPOSITION_CLEAR_MS)
1007
+ if (!pendingFillRef.current) {
1008
+ return
1009
+ }
1010
+ pendingFillRef.current = false
1011
+ // 取り消された変換 (確定した字が空) の後に埋めると、置き換えで始まった入力の空の字で選んだマスを全て消す
1012
+ if (event.data === "") {
1013
+ return
1014
+ }
1015
+ if (fillTimerRef.current !== null) {
1016
+ window.clearTimeout(fillTimerRef.current)
1017
+ }
1018
+ // compositionend の聞き手はほかにもあり (エディタの変換の印)、Firefox は compositionend の後に input を出す —
1019
+ // 全てが済んだ次のタスクで入力の字を読む
1020
+ fillTimerRef.current = window.setTimeout(runCompositionFill, 0)
930
1021
  }
931
1022
 
932
1023
  const onInput = () => {
@@ -1002,6 +1093,13 @@ export const useGridKeyboard = (params: UseGridKeyboardParams): void => {
1002
1093
  if (clearTimerRef.current !== null) {
1003
1094
  window.clearTimeout(clearTimerRef.current)
1004
1095
  }
1096
+ // 再結線 / アンマウントを跨いで、覚えた埋めを古い結線の上で走らせない
1097
+ if (fillTimerRef.current !== null) {
1098
+ window.clearTimeout(fillTimerRef.current)
1099
+ fillTimerRef.current = null
1100
+ }
1101
+ composingRef.current = false
1102
+ pendingFillRef.current = false
1005
1103
  // 再結線 / アンマウントを跨いで矩形を残さない (writer リレーはノード不在なら no-op)
1006
1104
  clearPointFrame()
1007
1105
  }
@@ -65,6 +65,76 @@ export const clampSelectionToGrid = (state: SelectionState, rowCount: number, co
65
65
  }
66
66
  }
67
67
 
68
+ /**
69
+ * The fields of one object a host handed over, or a RangeError naming it when it is not an object (a JS host can pass
70
+ * anything).
71
+ * 利用側が渡した 1 つの物のフィールド。物でなければ、それを名指す RangeError (JS の利用側は何でも渡せる)。
72
+ *
73
+ * @param value - The value to read. 読む値。
74
+ * @param label - The name the error uses. 誤りの文が使う名。
75
+ * @returns The value's fields, each still unchecked. 値のフィールド (どれもまだ検めていない)。
76
+ * @throws {RangeError} When `value` is not a non-null object. `value` が null でない物でないとき。
77
+ */
78
+ const placedFieldsOf = (value: unknown, label: string): Readonly<Record<string, unknown>> => {
79
+ if (typeof value !== "object" || value === null) {
80
+ throw new RangeError(`[spreadsheet] setSelection: the ${label} must be an object (got ${String(value)})`)
81
+ }
82
+ return value as Readonly<Record<string, unknown>>
83
+ }
84
+
85
+ /**
86
+ * Validates a selection a host places through `SpreadsheetHandle.setSelection` against a grid of `rowCount` ×
87
+ * `colCount` and returns a copy the root owns (the host may go on mutating its own object; the grid's state must not
88
+ * follow it). The shape is the reducers' invariant: at least one range, every bound of a range a whole number inside
89
+ * the grid with each start at most its end, the anchor inside the tail range and the active cell inside some range.
90
+ * Hidden tracks are not checked — a placement may land on a hidden row or column, as the count-shrink clamp and the
91
+ * sheet switch's A1 can.
92
+ * 利用側が `SpreadsheetHandle.setSelection` で置く選択を `rowCount` × `colCount` のグリッドに照らして検め、root が持つ写しを
93
+ * 返す (利用側が自分の物を書き換え続けても、グリッドの状態は追わない)。形は reducer の不変条件: レンジは 1 つ以上、レンジの各境は
94
+ * グリッドの中の整数で始まりが終わり以下、anchor は末尾のレンジの中、active はどれかのレンジの中。隠したトラックは検めない (縮小の
95
+ * 畳みやシート切替の A1 と同じく、隠した行・列の上にも置ける)。
96
+ *
97
+ * @param selection - The selection the host places. 利用側が置く選択。
98
+ * @param rowCount - The grid's row count. グリッドの行数。
99
+ * @param colCount - The grid's column count. グリッドの列数。
100
+ * @returns A structurally equal copy that shares no object with `selection`. `selection` と物を共有しない、構造の等しい写し。
101
+ * @throws {RangeError} When the selection breaks one of the rules above (a grid without rows or columns has no cell, so
102
+ * every placement throws). 上の決まりのどれかを破るとき (行か列の無いグリッドにはマスが無いので、どの選択も投げる)。
103
+ */
104
+ export const placedSelectionOf = (selection: SelectionState, rowCount: number, colCount: number): SelectionState => {
105
+ const fields = placedFieldsOf(selection, "selection")
106
+ const rangeList = fields.ranges
107
+ if (!Array.isArray(rangeList) || rangeList.length === 0) {
108
+ throw new RangeError("[spreadsheet] setSelection: the selection must have at least one range")
109
+ }
110
+ const grid = `${rowCount} x ${colCount} grid`
111
+ const within = (value: unknown, count: number): value is number => typeof value === "number" && Number.isInteger(value) && value >= 0 && value < count
112
+ const cellOf = (value: unknown, label: string): CellCoord => {
113
+ const { row, col } = placedFieldsOf(value, label)
114
+ if (!(within(row, rowCount) && within(col, colCount))) {
115
+ throw new RangeError(`[spreadsheet] setSelection: the ${label} {row: ${String(row)}, col: ${String(col)}} is not a cell of the ${grid}`)
116
+ }
117
+ return { row, col }
118
+ }
119
+ const ranges = rangeList.map((value: unknown, index: number): CellRange => {
120
+ const { startRow, startCol, endRow, endCol } = placedFieldsOf(value, `range ${index}`)
121
+ if (!(within(startRow, rowCount) && within(endRow, rowCount) && within(startCol, colCount) && within(endCol, colCount) && startRow <= endRow && startCol <= endCol)) {
122
+ throw new RangeError(`[spreadsheet] setSelection: range ${index} {startRow: ${String(startRow)}, startCol: ${String(startCol)}, endRow: ${String(endRow)}, endCol: ${String(endCol)}} is not a range of the ${grid} with each start at most its end`)
123
+ }
124
+ return { startRow, startCol, endRow, endCol }
125
+ })
126
+ const anchor = cellOf(fields.anchor, "anchor")
127
+ const active = cellOf(fields.active, "active cell")
128
+ // reducer の不変条件: 伸ばす操作は末尾のレンジの anchor を起点にし、Tab / Enter の巡回は active の属するレンジから始まる
129
+ if (!rangeContains(ranges[ranges.length - 1], anchor)) {
130
+ throw new RangeError(`[spreadsheet] setSelection: the anchor {row: ${anchor.row}, col: ${anchor.col}} must lie in the last range`)
131
+ }
132
+ if (!ranges.some((range) => rangeContains(range, active))) {
133
+ throw new RangeError(`[spreadsheet] setSelection: the active cell {row: ${active.row}, col: ${active.col}} must lie in one of the ranges`)
134
+ }
135
+ return { ranges, anchor, active }
136
+ }
137
+
68
138
  /** Replaces the tail range, preserving identity when unchanged. / 現在レンジのみ置換 (等価なら入力を返す)。 */
69
139
  const replaceCurrentRange = (state: SelectionState, next: CellRange): SelectionState => {
70
140
  // identity 保存契約 (冒頭): 無変化なら新オブジェクトを作らない — §6.9-1 の Object.is bail の根拠