@aiquants/spreadsheet 0.20.1 → 0.20.3

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.
@@ -15,7 +15,14 @@
15
15
  * Ctrl / Meta primary press (no Shift) consults the pointer link-opening capability
16
16
  * (`openHyperlinkAt`) before the append / subtract semantics — a consumed press freezes the
17
17
  * selection and mutes the derived dblclick. All are capability params: absent = the v0.7
18
- * press path byte-for-byte.
18
+ * press path byte-for-byte. v0.20.3 (`sortFilter`): a press on a sort header cell (the
19
+ * `isSortHeaderCell` capability) that completes as a click — a primary mouse press without
20
+ * modifiers that passed the commit gate and wrote the selection, released on the same cell before
21
+ * moving `HEADER_TAP_SLOP_PX` — or as a tap of a finger or a pen — released on the same cell before
22
+ * moving that far, discarded by `pointercancel` and by the next press — calls `onHeaderSortPress`
23
+ * once; the touch / pen press on such a cell only has its default prevented (the tap's compatibility
24
+ * mouse press would move the focus onto the frozen band's row box) and still passes through to the
25
+ * scroll machinery.
19
26
  *
20
27
  * セル選択の pointer ステートマシン (§6.4.3)。body 単一リスナー・mouse 限定・contextmenu 配送・
21
28
  * rAF 合流ドラッグ矩形・押下 1 回 setState。選択済みセルへの Ctrl+押下は減算モード (§3.2) —
@@ -29,7 +36,11 @@
29
36
  * バー帯押下は不活性 (consume + focusSink、commit なし)。v0.8 D-53 (分冊 08 §11): Ctrl / Meta
30
37
  * 主ボタン押下 (Shift なし) は append / 減算判定より先にリンク開通能力 (`openHyperlinkAt`) へ諮り、
31
38
  * 消費された押下は選択凍結 + 派生 dblclick 不活性。いずれも能力 param: 不在 = v0.7 の
32
- * 押下経路と byte 同一。
39
+ * 押下経路と byte 同一。v0.20.3 (`sortFilter`): 並べ替えの見出しのマス (`isSortHeaderCell` 能力) の押下が
40
+ * クリック (修飾キー無しの主ボタンのマウスの押下で、確定の関門を通って選択を書き、`HEADER_TAP_SLOP_PX`
41
+ * 動く前に同じマスで離した) か、指とペンの叩き (その距離を動く前に同じマスで離した。`pointercancel` と次の押下で
42
+ * 捨てる) で終わったら `onHeaderSortPress` を 1 回呼ぶ。そのマスの指とペンの押下は既定を止めるだけで (叩きの互換のマウスの押下が焦点を
43
+ * 止めた帯の行の箱へ移すため)、今どおりスクロールの機械へ渡す。
33
44
  */
34
45
 
35
46
  import type { VirtualGridHandle } from "@aiquants/virtualscroll"
@@ -40,6 +51,38 @@ import { viewportXToCol, viewportYToRow } from "../model/frozenPartition.ts"
40
51
  import { reduceSelectionExtend, reduceSelectionPress, reduceSelectionSubtract, type SelectionState } from "./selectionState.ts"
41
52
  import { type AutoScroller, SCROLLER_ARM_THRESHOLD } from "./useAutoScroller.ts"
42
53
 
54
+ /**
55
+ * The movement (visual px, the larger of the two axes) at which a press on a sort header cell stops being a click or a tap.
56
+ * It equals the distance at which `@aiquants/virtualscroll`'s ScrollPane starts a pointer drag (its private
57
+ * `DRAG_ACTIVATION_THRESHOLD`, compared the same way in client px): a gesture the scrolling pane would take as a drag is
58
+ * never a sorting tap, and the frozen header band — outside the scrolling pane — reads the same gesture the same way.
59
+ * 並べ替えの見出しのマスの押下がクリックや叩きでなくなる動き (見た目の px、2 つの軸の大きい方)。`@aiquants/virtualscroll` の
60
+ * ScrollPane がポインタのなぞりを始める距離 (公開されない `DRAG_ACTIVATION_THRESHOLD`。同じく client px で比べる) と同じ値 —
61
+ * スクロールのペインがなぞりと取る動きは並べ替えの叩きにならず、ペインの外にある止めた見出しの帯も同じ動きを同じに読む。
62
+ */
63
+ export const HEADER_TAP_SLOP_PX = 6
64
+
65
+ /**
66
+ * Whether a pointer moved `HEADER_TAP_SLOP_PX` or more from where it was pressed (the larger axis, client px — the
67
+ * ScrollPane's drag test).
68
+ * ポインタが押した点から `HEADER_TAP_SLOP_PX` 以上動いたか (大きい方の軸、client px — ScrollPane のなぞりの判定と同じ)。
69
+ *
70
+ * @param origin - The press point. 押した点。
71
+ * @param point - The current point. 今の点。
72
+ * @returns True when the movement reaches the slop. 動きが閾に届けば true。
73
+ */
74
+ const movedPastTapSlop = (origin: { readonly clientX: number; readonly clientY: number }, point: { readonly clientX: number; readonly clientY: number }): boolean => Math.max(Math.abs(point.clientX - origin.clientX), Math.abs(point.clientY - origin.clientY)) >= HEADER_TAP_SLOP_PX
75
+
76
+ /**
77
+ * Whether a hit-tested cell (null = unmeasurable) is the given cell.
78
+ * ヒットテストしたマス (null = 測れない) が与えたマスか。
79
+ *
80
+ * @param hit - The hit-tested cell or null. ヒットテストしたマスか null。
81
+ * @param cell - The cell to compare with. 比べるマス。
82
+ * @returns True for the same cell. 同じマスなら true。
83
+ */
84
+ const hitsCell = (hit: CellCoord | null, cell: CellCoord): boolean => hit !== null && coordEquals(hit, cell)
85
+
43
86
  /**
44
87
  * Click-point caret resolution for the dblclick edit entry (ED-1 §6). Feature detection (NOT
45
88
  * a value fallback): caretPositionFromPoint first, caretRangeFromPoint second. Adoption needs
@@ -199,6 +242,20 @@ type UseSelectionEngineParams = {
199
242
  * ホスト) = append / 減算の押下経路と byte 同一。
200
243
  */
201
244
  openHyperlinkAt?: (cell: CellCoord) => boolean
245
+ /**
246
+ * v0.20.3 capability (`sortFilter`): whether a cell is a sort header cell (the last header row, a keyed column that
247
+ * sorts). Undefined = no header press is ever recorded (the press path byte-for-byte, no extra layout read).
248
+ * v0.20.3 能力 (`sortFilter`): マスが並べ替えの見出しのマス (見出しの最後の行で、鍵を持ち並べ替えできる列) か。undefined なら
249
+ * 見出しの押下を一切記録しない (押下経路は byte 同一で、レイアウトの読みも足さない)。
250
+ */
251
+ isSortHeaderCell?: (cell: CellCoord) => boolean
252
+ /**
253
+ * v0.20.3 capability: called once with the column and the pointer type when a press on a sort header cell completes as a
254
+ * click (mouse) or a tap (touch / pen). The root runs its state-change funnel (commit gate first) from here.
255
+ * v0.20.3 能力: 並べ替えの見出しのマスの押下がクリック (マウス) か叩き (指・ペン) で終わった時に、列とポインタの種類で 1 回呼ぶ。
256
+ * root はここから状態を変える手順 (確定の関門が先) を走らせる。
257
+ */
258
+ onHeaderSortPress?: (col: number, pointerType: string) => void
202
259
  }
203
260
 
204
261
  /** Producer side of the Escape split (§6.6.2). / Escape 分担の生産側。 */
@@ -272,6 +329,22 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
272
329
  * (押下は選択ジェスチャではない)。`subtractModeRef` と同じく配送される主ボタン押下ごとに掃除。
273
330
  */
274
331
  const lastPressOpenedLinkRef = useRef(false)
332
+ /**
333
+ * The mouse press on a sort header cell that may still complete as a sorting click (v0.20.3): set only after the press
334
+ * passed the commit gate and wrote the selection, cleared by every primary mouse press, by a movement of
335
+ * `HEADER_TAP_SLOP_PX` and by `cleanupDrag` (abort, capture loss, chorded release, sheet switch).
336
+ * 並べ替えのクリックで終わり得る、並べ替えの見出しのマスのマウスの押下 (v0.20.3)。押下が確定の関門を通って選択を書いた後にだけ置き、
337
+ * 主ボタンのマウスの押下・`HEADER_TAP_SLOP_PX` の動き・`cleanupDrag` (中断・捕捉の喪失・chord の解放・シート切替) で捨てる。
338
+ */
339
+ const headerPressRef = useRef<{ readonly cell: CellCoord; readonly clientX: number; readonly clientY: number } | null>(null)
340
+ /**
341
+ * The touch / pen press on a sort header cell that may still complete as a sorting tap (v0.20.3), owned by its pointer
342
+ * id: cleared by the next press of any pointer, by that pointer's `pointercancel`, and by a movement of
343
+ * `HEADER_TAP_SLOP_PX`.
344
+ * 並べ替えの叩きで終わり得る、並べ替えの見出しのマスの指・ペンの押下 (v0.20.3)。持ち主はその pointerId。どのポインタでも次の押下・
345
+ * そのポインタの `pointercancel`・`HEADER_TAP_SLOP_PX` の動きで捨てる。
346
+ */
347
+ const headerTapRef = useRef<{ readonly pointerId: number; readonly pointerType: string; readonly cell: CellCoord; readonly clientX: number; readonly clientY: number } | null>(null)
275
348
 
276
349
  /** Hit test with the freshness hierarchy (§6.4.3-3) over the press-cached body rect — the shared mapping. / 鮮度序列準拠のヒットテスト (押下時計測の body rect 上) — 共有写像。 */
277
350
  const hitTest = useCallback((clientX: number, clientY: number): CellCoord | null => {
@@ -299,6 +372,7 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
299
372
  dragAnchorRowRef.current = null
300
373
  subtractModeRef.current = false
301
374
  subtractPressCellRef.current = null
375
+ headerPressRef.current = null
302
376
  if (dragRafRef.current !== null) {
303
377
  cancelAnimationFrame(dragRafRef.current)
304
378
  dragRafRef.current = null
@@ -355,8 +429,21 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
355
429
  */
356
430
  const isCellAreaTarget = (target: EventTarget | null): boolean => target instanceof Element && target.closest("[data-aqsp-cells]") !== null
357
431
 
432
+ /**
433
+ * Hit test over a FRESH body rect without touching the press-cached one (the touch / pen tap path runs concurrently
434
+ * with a mouse drag, whose cached rect must stay the drag's).
435
+ * その場で測った body の矩形でのヒットテスト。押下時に測った矩形には触れない (指とペンの叩きはマウスのドラッグと並んで流れ、
436
+ * ドラッグの矩形はドラッグの物のまま保つ)。
437
+ */
438
+ const hitTestNow = (clientX: number, clientY: number): CellCoord | null => {
439
+ const { handleRef, rowAxis, colAxis, zoomRef } = paramsRef.current
440
+ return hitTestCell(handleRef.current, body.getBoundingClientRect(), rowAxis, colAxis, zoomRef.current, clientX, clientY)
441
+ }
442
+
358
443
  const onPointerDown = (event: PointerEvent) => {
359
444
  const p = paramsRef.current
445
+ // 叩きの記録はどのポインタでも次の押下で捨てる (2 本目の指や続く押下が入ったジェスチャは叩きではない)
446
+ headerTapRef.current = null
360
447
  // 主ボタン mouse 押下は領域を問わず最上流で stale 減算フラグを掃除する (§3.2 の
361
448
  // 二重遮断の完全形 — 領域外 / 編集ゲート拒否 / hitTest null で中断される押下でも
362
449
  // 必ず走る。宙吊りジェスチャ (capture 失敗 + 領域外リリース) が残した旧フラグで
@@ -365,6 +452,7 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
365
452
  subtractModeRef.current = false
366
453
  subtractPressCellRef.current = null
367
454
  lastPressOpenedLinkRef.current = false
455
+ headerPressRef.current = null
368
456
  }
369
457
  lastPressInCellsRef.current = isCellAreaTarget(event.target)
370
458
  if (!lastPressInCellsRef.current) {
@@ -404,6 +492,17 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
404
492
  // (mouse ゲートより先 — touch 押下も記録してから弾く)
405
493
  lastPointerTypeRef.current = event.pointerType
406
494
  if (event.pointerType !== "mouse") {
495
+ // 指とペン (v0.20.3): 並べ替えの見出しのマスなら叩きの記録を置き、押下は今どおりスクロールの機械へ渡す。
496
+ // 矩形の読みは能力があるときだけ (渡さない表の押下はレイアウトを読まない)
497
+ if (p.isSortHeaderCell !== undefined) {
498
+ const cell = hitTestNow(event.clientX, event.clientY)
499
+ if (cell !== null && p.isSortHeaderCell(cell)) {
500
+ // 叩きの互換のマウスの押下は pointerup の後に届き、焦点を止めた帯の行の箱 (tabIndex −1) へ移す (実の Chromium で
501
+ // 確かめた) — 叩きの後に受け口へ戻した焦点を奪われないよう既定を止める。パンは touch-action が決めるので止まらない
502
+ event.preventDefault()
503
+ headerTapRef.current = { pointerId: event.pointerId, pointerType: event.pointerType, cell, clientX: event.clientX, clientY: event.clientY }
504
+ }
505
+ }
407
506
  return // タッチ / ペンは virtualscroll のドラッグスクロールへ
408
507
  }
409
508
  if (event.button !== 0) {
@@ -461,6 +560,11 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
461
560
  // 押下は reduceSelectionPress をその場で 1 回 setState (Excel は押下即座に選択が変わる)
462
561
  p.setSelection(reduceSelectionPress(before, cell, { extend, append }))
463
562
  }
563
+ // 並べ替えのクリックの候補 (v0.20.3): 関門を通って選択を書いた、修飾キー無しの押下だけ (Shift・Ctrl・Meta は範囲と
564
+ // 足し引きの操作、Alt は OS の操作に使われる)
565
+ if (!(extend || append || event.altKey) && p.isSortHeaderCell?.(cell) === true) {
566
+ headerPressRef.current = { cell, clientX: event.clientX, clientY: event.clientY }
567
+ }
464
568
  draggingRef.current = true
465
569
  // press 直後の repaint エッジ (§8.2 — フラグ成立後にハンドル可視条件を再評価させる)
466
570
  p.repaintOverlay()
@@ -510,6 +614,11 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
510
614
  return
511
615
  }
512
616
  pointerRef.current = { clientX: event.clientX, clientY: event.clientY }
617
+ // 閾まで動いた押下はなぞり — 同じマスへ戻って離しても並べ替えない (v0.20.3)
618
+ const press = headerPressRef.current
619
+ if (press !== null && movedPastTapSlop(press, event)) {
620
+ headerPressRef.current = null
621
+ }
513
622
  // 距離ゲートつき武装 (押下起動の廃止 + fill 機械の FILL_ARM_THRESHOLD 双子 — R5 是正):
514
623
  // 実クリックは押下〜解放間に 1〜3px のジッタや座標同値のキャプチャエコーを含むため、
515
624
  // 「move 1 発」では武装させない (右端ゾーンのクリックが +32px/frame のドレインに化ける
@@ -540,6 +649,11 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
540
649
  }
541
650
 
542
651
  const onPointerMove = (event: PointerEvent) => {
652
+ // 叩きの候補の指・ペンが閾まで動いたらなぞり (v0.20.3 — 指とペンはドラッグの機械に入らないので、ここで見る)
653
+ const tap = headerTapRef.current
654
+ if (tap !== null && event.pointerId === tap.pointerId && movedPastTapSlop(tap, event)) {
655
+ headerTapRef.current = null
656
+ }
543
657
  applyPointerMove(event)
544
658
  // chord 中の主ボタン解放 (R4 是正): 主ボタン保持中に 2 本目を押した状態で主ボタンを離すと、
545
659
  // その解放は pointerup でなく pointermove (buttons から主ビットが消える) で届き、最後の
@@ -552,13 +666,36 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
552
666
  }
553
667
 
554
668
  const onPointerUp = (event: PointerEvent) => {
669
+ // 指とペンの叩き (v0.20.3): 記録した pointerId の解放だけを見る — 閾まで動かず同じマスで離せば叩き
670
+ const tap = headerTapRef.current
671
+ if (tap !== null && event.pointerId === tap.pointerId) {
672
+ headerTapRef.current = null
673
+ if (!movedPastTapSlop(tap, event) && hitsCell(hitTestNow(event.clientX, event.clientY), tap.cell)) {
674
+ paramsRef.current.onHeaderSortPress?.(tap.cell.col, tap.pointerType)
675
+ }
676
+ }
555
677
  // 主ボタンのリリースのみ確定する (非主ボタンの up は同一 pointerId のため isOwnPointer を
556
678
  // 通過してしまう — ドラッグ中の右ボタンリリースでの早期確定と、宙吊りジェスチャを
557
679
  // 右クリックが旧フラグのまま確定する事故の両方を閉塞。Excel も左リリースのみ確定)
558
680
  if (event.button !== 0 || !(draggingRef.current && isOwnPointer(event))) {
559
681
  return
560
682
  }
683
+ // 並べ替えのクリック (v0.20.3): 判定は確定の前 (確定の cleanupDrag が記録を捨てる)、呼ぶのは確定の後 — 押下が
684
+ // 選んだ見出しのマスを確定してから、状態を変える手順へ渡す
685
+ const press = headerPressRef.current
686
+ const sorts = press !== null && !movedPastTapSlop(press, event) && hitsCell(hitTest(event.clientX, event.clientY), press.cell)
561
687
  confirmAt(event)
688
+ if (sorts) {
689
+ paramsRef.current.onHeaderSortPress?.(press.cell.col, event.pointerType)
690
+ }
691
+ }
692
+
693
+ const onPointerCancel = (event: PointerEvent) => {
694
+ // ブラウザがジェスチャ (パン・拡大) を取った指は叩きではない (v0.20.3)
695
+ const tap = headerTapRef.current
696
+ if (tap !== null && event.pointerId === tap.pointerId) {
697
+ headerTapRef.current = null
698
+ }
562
699
  }
563
700
 
564
701
  /** Confirms the in-flight gesture at the event position (primary release — pointerup or chorded move). / 飛行中ジェスチャの確定 (主ボタン解放 — pointerup または chord 中の move)。 */
@@ -677,6 +814,7 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
677
814
  body.addEventListener("pointerdown", onPointerDown)
678
815
  body.addEventListener("pointermove", onPointerMove)
679
816
  body.addEventListener("pointerup", onPointerUp)
817
+ body.addEventListener("pointercancel", onPointerCancel)
680
818
  body.addEventListener("lostpointercapture", onLostPointerCapture)
681
819
  body.addEventListener("contextmenu", onContextMenu)
682
820
  body.addEventListener("dblclick", onDblClick)
@@ -684,6 +822,7 @@ export const useSelectionEngine = (params: UseSelectionEngineParams): SelectionE
684
822
  body.removeEventListener("pointerdown", onPointerDown)
685
823
  body.removeEventListener("pointermove", onPointerMove)
686
824
  body.removeEventListener("pointerup", onPointerUp)
825
+ body.removeEventListener("pointercancel", onPointerCancel)
687
826
  body.removeEventListener("lostpointercapture", onLostPointerCapture)
688
827
  body.removeEventListener("contextmenu", onContextMenu)
689
828
  body.removeEventListener("dblclick", onDblClick)
@@ -0,0 +1,380 @@
1
+ /**
2
+ * @fileoverview The column menu of a sort / filter header cell (`sortFilter`): a non-modal `role="dialog"` drawn in the
3
+ * popover layer's frame and named after the column. Its sections follow the column's resolved options:
4
+ * 1. sort (a column that sorts): ascending / descending / clear — the current direction is `aria-pressed`, clear is
5
+ * disabled unless this column is the sorted one, and each applies at once;
6
+ * 2. match mode (a column offering both modes): two radios, starting at the column's filter mode, else its default mode;
7
+ * 3. exact match: a value search (NFKC, lower case, substring over the shown text), "select all" / "clear all" acting on
8
+ * the values the search matches, and the value list `getFilterValues` resolves — loaded once, the first time the
9
+ * section shows, with an `AbortSignal` that aborts when the menu closes (a late answer is dropped); while loading the
10
+ * list is `aria-busy` with `filterLoading`, a rejection or a malformed list shows `filterLoadFailed` (reopen the menu
11
+ * to retry), at most `LIST_POPOVER_MAX_OPTIONS` rows mount and one `listMore` row counts the rest, `listEmpty` when no
12
+ * value matches, and an empty label shows `filterBlank`; the first checks are the column's exact values, else every
13
+ * value;
14
+ * 4. fuzzy search: the query (starting at the column's fuzzy query), Enter applies;
15
+ * 5. apply (exact needs at least one checked listed value), clear this column's filter and clear all filters (each
16
+ * disabled when there is nothing to clear).
17
+ * Every action goes through `changeState` (the root's funnel: commit gate, closing, clip discard, one notification); a
18
+ * refused change keeps the menu open. Escape closes, and so does focus leaving the menu — focus returns to the grid's
19
+ * sink only when it moved inside the grid. The menu asks the layer to place its frame again when the mode or the load
20
+ * state changes its height. DOM hooks: `data-aqsp-popover="columnMenu"`, `data-aqsp-column-menu-action`,
21
+ * `data-aqsp-column-menu-mode`, `data-aqsp-column-menu-input="search" | "query"`, `data-aqsp-column-menu-values`,
22
+ * `data-aqsp-column-menu-value="<value>"`, `data-aqsp-column-menu-status="loading" | "failed" | "empty" | "more"`.
23
+ *
24
+ * 並べ替えと絞り込みの見出しのマスの列の品書き (`sortFilter`)。ポップオーバーの層のフレームに描くモーダルでない `role="dialog"` で、名前は
25
+ * 列から。節は列の解いた指定に従う: 1. 並べ替え (並べ替えできる列) — 昇順・降順・外す (今の向きは `aria-pressed`、外すはこの列で並べ替えて
26
+ * いなければ押せない。どれも押すとすぐ当てる)。2. 検索方法 (2 つの方法を持つ列) — ラジオ 2 つ。初めは列の絞り込みの方法、無ければ初めの方法。
27
+ * 3. 完全一致 — 値を探す欄 (NFKC・小文字・見せる字の部分一致)、探す語に当たる値だけに効く「すべて選ぶ」「すべて外す」、`getFilterValues` の値の
28
+ * 一覧 (節を初めて見せた時に 1 回読み、品書きを閉じると止まる `AbortSignal` を渡す。遅れた答えは捨てる)。読み込み中は一覧が `aria-busy` で
29
+ * `filterLoading`、拒みと形の誤りは `filterLoadFailed` (読み直すには開き直す)、描くのは `LIST_POPOVER_MAX_OPTIONS` 行までで残りは `listMore`
30
+ * の 1 行、当たる値が無ければ `listEmpty`、空の字は `filterBlank`。初めの印は列の完全一致の値、無ければ全ての値。4. あいまい検索 — 語の欄
31
+ * (初めは列のあいまい検索の語)、Enter で当てる。5. 当てる (完全一致は一覧の値に 1 つ以上の印が要る)・この列の絞り込みを外す・すべての
32
+ * 絞り込みを外す (外す物が無ければ押せない)。全ての操作は `changeState` (root の手順: 確定の関門・閉じる・写しの印を捨てる・1 回の知らせ) を
33
+ * 通り、断られたら開いたまま。Escape と品書きの外への焦点の移りで閉じ、焦点はグリッドの中へ移った時だけ受け口へ戻す。方法と読み込みの状態で
34
+ * 高さが変わると、層にフレームを置き直してもらう。
35
+ */
36
+
37
+ import { type FocusEvent, type KeyboardEvent, type ReactNode, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react"
38
+ import { resolveLabel, type SpreadsheetLabels } from "../model/labels.ts"
39
+ import { LIST_POPOVER_MAX_OPTIONS } from "../popover/ListPopover.tsx"
40
+ import {
41
+ filterValueMatches,
42
+ MATCH_MODES,
43
+ type ResolvedSortFilterColumn,
44
+ type SpreadsheetFilterValue,
45
+ type SpreadsheetMatchMode,
46
+ type SpreadsheetSortDirection,
47
+ type SpreadsheetSortFilter,
48
+ type SpreadsheetSortFilterState,
49
+ validateFilterValues,
50
+ withExactFilter,
51
+ withFuzzyFilter,
52
+ withoutFilter,
53
+ withoutFilters,
54
+ withSort,
55
+ } from "./sortFilterModel.ts"
56
+
57
+ export type ColumnMenuProps = {
58
+ /** The resolved column the menu acts on (it carries controls). / 品書きが扱う解いた列 (操作を持つ)。 */
59
+ column: ResolvedSortFilterColumn
60
+ /** The column name (the dialog's name). / 列の名 (dialog の名前)。 */
61
+ columnName: string
62
+ /** The host's current state. / 利用側の今の状態。 */
63
+ state: SpreadsheetSortFilterState
64
+ /** The host's value loader (present whenever a column offers exact matching). / 利用側の値の読み込み (完全一致を使える列があれば必ずある)。 */
65
+ getFilterValues: SpreadsheetSortFilter["getFilterValues"]
66
+ /** The root's state-change funnel; false = refused (the menu stays open). / root の状態を変える手順。false は断り (品書きは開いたまま)。 */
67
+ changeState: (next: SpreadsheetSortFilterState) => boolean
68
+ /** Closes the menu (`restoreFocus: false` keeps the focus where it moved). / 品書きを閉じる (`restoreFocus: false` なら焦点は移った先のまま)。 */
69
+ close: (options?: { restoreFocus: boolean }) => void
70
+ /** Whether a node is inside the grid (the blur rule's focus return). / ノードがグリッドの中か (blur の決まりの焦点の戻し)。 */
71
+ isInsideGrid: (node: Node) => boolean
72
+ /** Asks the layer to place the frame again (the content changed height). / 層にフレームを置き直してもらう (中身の高さが変わった)。 */
73
+ relayout: () => void
74
+ labels: SpreadsheetLabels
75
+ }
76
+
77
+ /** The load state of the exact-match value list. / 完全一致の値の一覧の読み込みの状態。 */
78
+ type ValueLoad = { readonly status: "idle" | "loading" | "failed" } | { readonly status: "loaded"; readonly values: readonly SpreadsheetFilterValue[] }
79
+
80
+ /** The control that takes the menu's initial focus (the first one in the menu). / 品書きの初めの焦点を受ける操作 (品書きの最初の物)。 */
81
+ type AutofocusTarget = "sort" | "mode" | "search" | "query"
82
+
83
+ /**
84
+ * The initial checks of the exact list: the column's exact filter values, else every listed value.
85
+ * 完全一致の一覧の初めの印。列の完全一致の絞り込みの値、無ければ一覧の全ての値。
86
+ *
87
+ * @param state - The state when the list arrived. 一覧が届いた時の状態。
88
+ * @param key - The column key. 列の鍵。
89
+ * @param values - The listed values. 一覧の値。
90
+ * @returns The checked values. 印のある値。
91
+ */
92
+ const initialChecks = (state: SpreadsheetSortFilterState, key: string, values: readonly SpreadsheetFilterValue[]): ReadonlySet<string> => {
93
+ const filter = Object.hasOwn(state.filters, key) ? state.filters[key] : undefined
94
+ return new Set(filter !== undefined && filter.mode === "exact" ? filter.values : values.map((entry) => entry.value))
95
+ }
96
+
97
+ /**
98
+ * Renders the column menu of one header cell.
99
+ * 見出しのマス 1 つの列の品書きを描く。
100
+ */
101
+ export const ColumnMenu = ({ column, columnName, state, getFilterValues, changeState, close, isInsideGrid, relayout, labels }: ColumnMenuProps): ReactNode => {
102
+ const key = column.key
103
+ const current = Object.hasOwn(state.filters, key) ? state.filters[key] : undefined
104
+ const sortedHere = state.sort !== null && state.sort.columnKey === key ? state.sort.direction : null
105
+ const [mode, setMode] = useState<SpreadsheetMatchMode>(() => (current === undefined ? column.defaultMatchMode : current.mode))
106
+ const [query, setQuery] = useState(() => (current !== undefined && current.mode === "fuzzy" ? current.query : ""))
107
+ const [search, setSearch] = useState("")
108
+ const [load, setLoad] = useState<ValueLoad>({ status: "idle" })
109
+ const [checked, setChecked] = useState<ReadonlySet<string>>(() => new Set())
110
+ const settlingRef = useRef(false)
111
+ // 読み込みの答えの印の初めは、答えが届いた時の状態から作る (開いた後に利用側が状態を替えても今の絞り込みに合わせる)
112
+ const stateRef = useRef(state)
113
+ stateRef.current = state
114
+ const radioName = useId()
115
+ const titleId = useId()
116
+ const exactShown = column.filterable && mode === "exact"
117
+ // 完全一致の節を初めて見せた時から読む (後で方法を替えても読み直さず、読みかけも止めない)
118
+ const valuesWanted = exactShown || load.status !== "idle"
119
+
120
+ // 利用側の値の読み込み (外部の非同期の処理) との同期: 品書きの命と同じ長さの AbortController で持ち、閉じたら止めて遅れた答えを捨てる
121
+ useEffect(() => {
122
+ if (!valuesWanted) {
123
+ return
124
+ }
125
+ // 完全一致を使える列があれば検めが読み込みの口を求めるので、無いのは届かない枝 — 黙って読み込み中に留めず失敗として示す
126
+ if (getFilterValues === undefined) {
127
+ setLoad({ status: "failed" })
128
+ return
129
+ }
130
+ const controller = new AbortController()
131
+ let answer: Promise<unknown>
132
+ try {
133
+ answer = Promise.resolve(getFilterValues(key, stateRef.current, controller.signal))
134
+ } catch {
135
+ // 同期に投げる読み込みも拒みと同じく失敗として示す (描画を落とさない)
136
+ setLoad({ status: "failed" })
137
+ return () => controller.abort()
138
+ }
139
+ setLoad({ status: "loading" })
140
+ answer.then(
141
+ (resolved) => {
142
+ if (controller.signal.aborted) {
143
+ return
144
+ }
145
+ let values: readonly SpreadsheetFilterValue[]
146
+ try {
147
+ values = validateFilterValues(resolved)
148
+ } catch {
149
+ setLoad({ status: "failed" })
150
+ return
151
+ }
152
+ setLoad({ status: "loaded", values })
153
+ setChecked(initialChecks(stateRef.current, key, values))
154
+ },
155
+ () => {
156
+ // 閉じた後の拒み (止めた signal の AbortError) は描く先が無い — 開いている間の拒みだけを失敗として示す
157
+ if (!controller.signal.aborted) {
158
+ setLoad({ status: "failed" })
159
+ }
160
+ },
161
+ )
162
+ return () => controller.abort()
163
+ // 読むのは 1 回 — 列と読み込みの口は品書きの命の間は替わらない (替われば root が品書きを閉じる)
164
+ }, [valuesWanted])
165
+
166
+ // 方法と読み込みの段で中身の高さが変わる — 層のフレームの置き場と高さの上限を測り直してもらう (初めの置き場は層が測る)。読む前と
167
+ // 読み込み中は同じ字を描くので同じ段
168
+ const loadPhase = load.status === "loaded" || load.status === "failed" ? load.status : "pending"
169
+ const laidOutRef = useRef(false)
170
+ useLayoutEffect(() => {
171
+ if (!laidOutRef.current) {
172
+ laidOutRef.current = true
173
+ return
174
+ }
175
+ relayout()
176
+ }, [mode, loadPhase])
177
+
178
+ const listed = load.status === "loaded" ? load.values : null
179
+ const shownOf = (entry: SpreadsheetFilterValue): string => (entry.label === "" ? resolveLabel(labels, "filterBlank") : entry.label)
180
+ const matching = useMemo(() => (listed === null ? [] : listed.filter((entry) => filterValueMatches(entry.label === "" ? resolveLabel(labels, "filterBlank") : entry.label, search))), [listed, search, labels])
181
+ // 描くのは上限まで — 一覧の残りは件数の 1 行で示し、探す欄で狭める (検証の一覧と同じ決まり)
182
+ const visible = matching.length > LIST_POPOVER_MAX_OPTIONS ? matching.slice(0, LIST_POPOVER_MAX_OPTIONS) : matching
183
+ const hidden = matching.length - visible.length
184
+ const checkedListed = listed === null ? 0 : listed.filter((entry) => checked.has(entry.value)).length
185
+
186
+ /** Runs an action that may close the menu, so the blur it causes is not read as focus leaving. / 品書きを閉じ得る操作を走らせる (その操作が起こす blur を焦点の離脱と読まない)。 */
187
+ const settle = (action: () => void): void => {
188
+ settlingRef.current = true
189
+ try {
190
+ action()
191
+ } finally {
192
+ settlingRef.current = false
193
+ }
194
+ }
195
+ const change = (next: SpreadsheetSortFilterState): void => settle(() => void changeState(next))
196
+ const sortBy = (direction: SpreadsheetSortDirection | null): void => change(withSort(state, key, direction))
197
+ const apply = (): void => {
198
+ if (mode === "fuzzy") {
199
+ change(withFuzzyFilter(state, key, query))
200
+ return
201
+ }
202
+ // 一覧が無い・印が無い当て方は押せない (ボタンが disabled — 押下以外の道からの呼び出しも何もしない)
203
+ if (listed === null || checkedListed === 0) {
204
+ return
205
+ }
206
+ change(
207
+ withExactFilter(
208
+ state,
209
+ key,
210
+ checked,
211
+ listed.map((entry) => entry.value),
212
+ ),
213
+ )
214
+ }
215
+ const checkMatching = (on: boolean): void => {
216
+ const next = new Set(checked)
217
+ for (const entry of matching) {
218
+ if (on) {
219
+ next.add(entry.value)
220
+ } else {
221
+ next.delete(entry.value)
222
+ }
223
+ }
224
+ setChecked(next)
225
+ }
226
+ const toggle = (value: string): void => {
227
+ const next = new Set(checked)
228
+ if (next.has(value)) {
229
+ next.delete(value)
230
+ } else {
231
+ next.add(value)
232
+ }
233
+ setChecked(next)
234
+ }
235
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
236
+ // 変換中の Escape / Enter は層が capture で捨てる — ここへ届くのは確定した操作だけ
237
+ if (event.key === "Escape") {
238
+ event.preventDefault()
239
+ settle(() => close())
240
+ }
241
+ }
242
+ const onBlur = (event: FocusEvent<HTMLDivElement>): void => {
243
+ const next = event.relatedTarget
244
+ if (settlingRef.current || (next instanceof Node && event.currentTarget.contains(next))) {
245
+ return
246
+ }
247
+ // 焦点がグリッドの中へ移った時だけ受け口へ戻す (表の外の欄へ移った焦点は奪わない)
248
+ settle(() => close({ restoreFocus: next instanceof Node && isInsideGrid(next) }))
249
+ }
250
+
251
+ const showModes = column.filterable && column.matchModes.length === 2
252
+ // 品書きは操作の列でだけ開く — 並べ替えできなければ絞り込める列
253
+ const autofocus: AutofocusTarget = column.sortable ? "sort" : showModes ? "mode" : mode === "exact" ? "search" : "query"
254
+ const autofocusProps = (target: AutofocusTarget) => (autofocus === target ? { "data-aqsp-popover-autofocus": "" } : {})
255
+ const filtered = Object.keys(state.filters).length > 0
256
+
257
+ return (
258
+ <div className="aqsp-popover-column-menu" data-aqsp-popover="columnMenu" role="dialog" aria-labelledby={titleId} onKeyDown={onKeyDown} onBlur={onBlur}>
259
+ <div className="aqsp-popover-title" id={titleId}>
260
+ {columnName.trim() === "" ? resolveLabel(labels, "columnMenu") : `${columnName} ${resolveLabel(labels, "columnMenu")}`}
261
+ </div>
262
+ {column.sortable ? (
263
+ <div className="aqsp-popover-section aqsp-popover-actions">
264
+ <button type="button" className="aqsp-popover-button" data-aqsp-column-menu-action="sortAsc" aria-pressed={sortedHere === "asc"} onClick={() => sortBy("asc")} {...autofocusProps("sort")}>
265
+ {resolveLabel(labels, "sortAscending")}
266
+ </button>
267
+ <button type="button" className="aqsp-popover-button" data-aqsp-column-menu-action="sortDesc" aria-pressed={sortedHere === "desc"} onClick={() => sortBy("desc")}>
268
+ {resolveLabel(labels, "sortDescending")}
269
+ </button>
270
+ <button type="button" className="aqsp-popover-button" data-aqsp-column-menu-action="sortClear" disabled={sortedHere === null} onClick={() => sortBy(null)}>
271
+ {resolveLabel(labels, "sortClear")}
272
+ </button>
273
+ </div>
274
+ ) : null}
275
+ {showModes ? (
276
+ <fieldset className="aqsp-popover-section aqsp-popover-fieldset">
277
+ <legend className="aqsp-popover-field-label">{resolveLabel(labels, "filterMatchMode")}</legend>
278
+ {MATCH_MODES.map((option) => (
279
+ <label key={option} className="aqsp-popover-radio">
280
+ <input
281
+ type="radio"
282
+ name={radioName}
283
+ value={option}
284
+ data-aqsp-column-menu-mode={option}
285
+ checked={mode === option}
286
+ onChange={() => setMode(option)}
287
+ // 初めの焦点は選んでいる方のラジオ (ラジオの組の焦点の作法)
288
+ {...(mode === option ? autofocusProps("mode") : {})}
289
+ />
290
+ {resolveLabel(labels, option === "exact" ? "filterModeExact" : "filterModeFuzzy")}
291
+ </label>
292
+ ))}
293
+ </fieldset>
294
+ ) : null}
295
+ {exactShown ? (
296
+ <div className="aqsp-popover-section">
297
+ <input
298
+ type="search"
299
+ className="aqsp-popover-input"
300
+ data-aqsp-column-menu-input="search"
301
+ aria-label={resolveLabel(labels, "filterSearchValues")}
302
+ placeholder={resolveLabel(labels, "filterSearchValues")}
303
+ value={search}
304
+ onChange={(event) => setSearch(event.currentTarget.value)}
305
+ {...autofocusProps("search")}
306
+ />
307
+ <div className="aqsp-popover-actions">
308
+ <button type="button" className="aqsp-popover-button" data-aqsp-column-menu-action="checkAll" disabled={matching.length === 0} onClick={() => checkMatching(true)}>
309
+ {resolveLabel(labels, "filterSelectAll")}
310
+ </button>
311
+ <button type="button" className="aqsp-popover-button" data-aqsp-column-menu-action="checkNone" disabled={matching.length === 0} onClick={() => checkMatching(false)}>
312
+ {resolveLabel(labels, "filterSelectNone")}
313
+ </button>
314
+ </div>
315
+ <fieldset className="aqsp-popover-values" data-aqsp-column-menu-values="" aria-label={resolveLabel(labels, "filterModeExact")} aria-busy={load.status === "loading" || load.status === "idle" ? "true" : undefined}>
316
+ {load.status === "failed" ? (
317
+ <div className="aqsp-popover-empty" data-aqsp-column-menu-status="failed" role="alert">
318
+ {resolveLabel(labels, "filterLoadFailed")}
319
+ </div>
320
+ ) : listed === null ? (
321
+ <div className="aqsp-popover-empty" data-aqsp-column-menu-status="loading">
322
+ {resolveLabel(labels, "filterLoading")}
323
+ </div>
324
+ ) : visible.length === 0 ? (
325
+ <div className="aqsp-popover-empty" data-aqsp-column-menu-status="empty">
326
+ {resolveLabel(labels, "listEmpty")}
327
+ </div>
328
+ ) : (
329
+ visible.map((entry) => (
330
+ <label key={entry.value} className="aqsp-popover-value">
331
+ <input type="checkbox" data-aqsp-column-menu-value={entry.value} checked={checked.has(entry.value)} onChange={() => toggle(entry.value)} />
332
+ <span className="aqsp-popover-value-text">{shownOf(entry)}</span>
333
+ <span className="aqsp-popover-value-count">{entry.count}</span>
334
+ </label>
335
+ ))
336
+ )}
337
+ {hidden > 0 ? (
338
+ <div className="aqsp-popover-empty" data-aqsp-column-menu-status="more">
339
+ {resolveLabel(labels, "listMore", hidden)}
340
+ </div>
341
+ ) : null}
342
+ </fieldset>
343
+ </div>
344
+ ) : null}
345
+ {column.filterable && mode === "fuzzy" ? (
346
+ <div className="aqsp-popover-section">
347
+ <input
348
+ type="search"
349
+ className="aqsp-popover-input"
350
+ data-aqsp-column-menu-input="query"
351
+ aria-label={resolveLabel(labels, "filterQuery")}
352
+ placeholder={resolveLabel(labels, "filterQuery")}
353
+ value={query}
354
+ onChange={(event) => setQuery(event.currentTarget.value)}
355
+ onKeyDown={(event) => {
356
+ if (event.key === "Enter") {
357
+ event.preventDefault()
358
+ apply()
359
+ }
360
+ }}
361
+ {...autofocusProps("query")}
362
+ />
363
+ </div>
364
+ ) : null}
365
+ {column.filterable ? (
366
+ <div className="aqsp-popover-actions">
367
+ <button type="button" className="aqsp-popover-button" data-aqsp-column-menu-action="apply" disabled={mode === "exact" && checkedListed === 0} onClick={apply}>
368
+ {resolveLabel(labels, "filterApply")}
369
+ </button>
370
+ <button type="button" className="aqsp-popover-button" data-aqsp-column-menu-action="clear" disabled={current === undefined} onClick={() => change(withoutFilter(state, key))}>
371
+ {resolveLabel(labels, "filterClearColumn")}
372
+ </button>
373
+ <button type="button" className="aqsp-popover-button" data-aqsp-column-menu-action="clearAll" disabled={!filtered} onClick={() => change(withoutFilters(state))}>
374
+ {resolveLabel(labels, "filterClearAll")}
375
+ </button>
376
+ </div>
377
+ ) : null}
378
+ </div>
379
+ )
380
+ }