@jsudc/react 0.4.0 → 0.5.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.
Files changed (105) hide show
  1. package/README.md +615 -11
  2. package/dist/actions/RowActionsMenu.d.ts +45 -0
  3. package/dist/actions/RowActionsMenu.js +161 -0
  4. package/dist/actions/RowActionsMenu.js.map +1 -0
  5. package/dist/actions/bulk.d.ts +81 -0
  6. package/dist/actions/bulk.js +54 -0
  7. package/dist/actions/bulk.js.map +1 -0
  8. package/dist/actions/row.d.ts +50 -0
  9. package/dist/actions/row.js +34 -0
  10. package/dist/actions/row.js.map +1 -0
  11. package/dist/actions/useRowActionRunner.d.ts +26 -0
  12. package/dist/actions/useRowActionRunner.js +198 -0
  13. package/dist/actions/useRowActionRunner.js.map +1 -0
  14. package/dist/calendar/CalendarRenderer.js +4 -3
  15. package/dist/calendar/CalendarRenderer.js.map +1 -1
  16. package/dist/cards/CardRenderer.d.ts +6 -0
  17. package/dist/cards/CardRenderer.js +45 -9
  18. package/dist/cards/CardRenderer.js.map +1 -1
  19. package/dist/chart/ChartRenderer.js +6 -4
  20. package/dist/chart/ChartRenderer.js.map +1 -1
  21. package/dist/chart/ChartWindowControl.js +1 -1
  22. package/dist/data-view/BulkBar.d.ts +36 -0
  23. package/dist/data-view/BulkBar.js +239 -0
  24. package/dist/data-view/BulkBar.js.map +1 -0
  25. package/dist/data-view/FilePreview.js +1 -1
  26. package/dist/data-view/FilterBuilder.js +1 -1
  27. package/dist/data-view/FilterChips.js +1 -1
  28. package/dist/data-view/LiveIndicator.d.ts +10 -0
  29. package/dist/data-view/LiveIndicator.js +33 -0
  30. package/dist/data-view/LiveIndicator.js.map +1 -0
  31. package/dist/data-view/UdcDataView.d.ts +28 -1
  32. package/dist/data-view/UdcDataView.js +76 -9
  33. package/dist/data-view/UdcDataView.js.map +1 -1
  34. package/dist/headless.d.ts +6 -0
  35. package/dist/headless.js +9 -2
  36. package/dist/i18n/translations.js +144 -0
  37. package/dist/i18n/translations.js.map +1 -1
  38. package/dist/index.d.ts +10 -2
  39. package/dist/index.js +13 -4
  40. package/dist/kanban/KanbanCard.js +1 -1
  41. package/dist/kanban/KanbanRenderer.js +5 -4
  42. package/dist/kanban/KanbanRenderer.js.map +1 -1
  43. package/dist/lookup/batch.js +1 -1
  44. package/dist/lookup/options.js +4 -1
  45. package/dist/lookup/options.js.map +1 -1
  46. package/dist/lookup/useUdcLookup.js +9 -3
  47. package/dist/lookup/useUdcLookup.js.map +1 -1
  48. package/dist/map/MapRenderer.js +3 -2
  49. package/dist/map/MapRenderer.js.map +1 -1
  50. package/dist/renderers/types.d.ts +32 -1
  51. package/dist/renderers/types.js.map +1 -1
  52. package/dist/rows/useRowActivation.d.ts +17 -0
  53. package/dist/rows/useRowActivation.js +37 -5
  54. package/dist/rows/useRowActivation.js.map +1 -1
  55. package/dist/rows/useRowSelection.d.ts +92 -0
  56. package/dist/rows/useRowSelection.js +156 -0
  57. package/dist/rows/useRowSelection.js.map +1 -0
  58. package/dist/schema-editor/DeleteFieldDialog.js +1 -1
  59. package/dist/schema-editor/FieldFormDialog.js +1 -1
  60. package/dist/styles.css +1 -1
  61. package/dist/styles.scoped.css +1 -1
  62. package/dist/table/CellEditor.js +1 -1
  63. package/dist/table/Pager.d.ts +10 -2
  64. package/dist/table/Pager.js +26 -20
  65. package/dist/table/Pager.js.map +1 -1
  66. package/dist/table/SelectCheckbox.d.ts +15 -0
  67. package/dist/table/SelectCheckbox.js +37 -0
  68. package/dist/table/SelectCheckbox.js.map +1 -0
  69. package/dist/table/TableRenderer.d.ts +13 -0
  70. package/dist/table/TableRenderer.js +284 -125
  71. package/dist/table/TableRenderer.js.map +1 -1
  72. package/dist/table/cells.js +1 -1
  73. package/dist/table/index.d.ts +1 -0
  74. package/dist/table/states.js +1 -1
  75. package/dist/table/useRowWindow.d.ts +82 -0
  76. package/dist/table/useRowWindow.js +182 -0
  77. package/dist/table/useRowWindow.js.map +1 -0
  78. package/dist/table.js.map +1 -1
  79. package/dist/tree/TreeRenderer.d.ts +2 -0
  80. package/dist/tree/TreeRenderer.js +15 -9
  81. package/dist/tree/TreeRenderer.js.map +1 -1
  82. package/dist/udc/changeFeed.d.ts +107 -0
  83. package/dist/udc/changeFeed.js +281 -0
  84. package/dist/udc/changeFeed.js.map +1 -0
  85. package/dist/udc/changes.d.ts +40 -0
  86. package/dist/udc/changes.js +85 -0
  87. package/dist/udc/changes.js.map +1 -0
  88. package/dist/udc/client.js +5 -2
  89. package/dist/udc/client.js.map +1 -1
  90. package/dist/udc/hooks.d.ts +93 -20
  91. package/dist/udc/hooks.js +115 -11
  92. package/dist/udc/hooks.js.map +1 -1
  93. package/dist/udc/keys.d.ts +2 -0
  94. package/dist/udc/keys.js.map +1 -1
  95. package/dist/udc/listCache.d.ts +11 -0
  96. package/dist/udc/listCache.js +38 -0
  97. package/dist/udc/listCache.js.map +1 -0
  98. package/dist/udc/provider.d.ts +34 -2
  99. package/dist/udc/provider.js +28 -2
  100. package/dist/udc/provider.js.map +1 -1
  101. package/dist/udc/unauthenticated.d.ts +4 -0
  102. package/dist/udc/unauthenticated.js +17 -0
  103. package/dist/udc/unauthenticated.js.map +1 -0
  104. package/dist/ui-kit/types.d.ts +14 -0
  105. package/package.json +3 -3
@@ -54,14 +54,21 @@ function useRowActivation(options) {
54
54
  };
55
55
  const paging = useRef(options);
56
56
  paging.current = options;
57
+ /** A windowed list: the row the keys moved to before it was mounted; focused when it attaches. */
58
+ const revealRef = useRef(null);
57
59
  const elements = useRef(/* @__PURE__ */ new Map());
58
60
  const refs = useRef(/* @__PURE__ */ new Map());
59
61
  const refFor = (id) => {
60
62
  let cb = refs.current.get(id);
61
63
  if (!cb) {
62
64
  cb = (el) => {
63
- if (el) elements.current.set(id, el);
64
- else elements.current.delete(id);
65
+ if (el) {
66
+ elements.current.set(id, el);
67
+ if (revealRef.current === id) {
68
+ revealRef.current = null;
69
+ el.focus({ preventScroll: true });
70
+ }
71
+ } else elements.current.delete(id);
65
72
  };
66
73
  refs.current.set(id, cb);
67
74
  }
@@ -73,7 +80,17 @@ function useRowActivation(options) {
73
80
  const pendingRef = useRef(null);
74
81
  const focusRow = useCallback((id) => {
75
82
  const el = elements.current.get(id);
76
- if (!el) return;
83
+ if (!el) {
84
+ const reveal = paging.current.reveal;
85
+ const list = latest.current.rows;
86
+ const i = list.findIndex((r) => idOf(r) === id);
87
+ if (reveal && i >= 0) {
88
+ revealRef.current = id;
89
+ reveal(list[i], i);
90
+ }
91
+ return;
92
+ }
93
+ revealRef.current = null;
77
94
  el.focus({ preventScroll: true });
78
95
  if (typeof el.scrollIntoView === "function") el.scrollIntoView({ block: "nearest" });
79
96
  }, []);
@@ -146,11 +163,24 @@ function useRowActivation(options) {
146
163
  if (activeRowId === null) return;
147
164
  const el = elements.current.get(activeRowId);
148
165
  if (el && typeof el.scrollIntoView === "function") el.scrollIntoView({ block: "nearest" });
166
+ else if (!el && paging.current.reveal) {
167
+ const list = latest.current.rows;
168
+ const i = list.findIndex((r) => idOf(r) === activeRowId);
169
+ if (i >= 0) paging.current.reveal(list[i], i);
170
+ }
149
171
  }, [activeRowId]);
150
172
  const onKeyDown = (e, row) => {
151
- if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
173
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
152
174
  if (!within(e.currentTarget, e.target)) return;
153
175
  if (ownsKeys(e.target)) return;
176
+ const toggleSelect = paging.current.onToggleSelect;
177
+ if (e.key === " " && toggleSelect) {
178
+ if (closestOf(e.target, "a,button") !== null && e.target !== e.currentTarget) return;
179
+ e.preventDefault();
180
+ toggleSelect(row, e.shiftKey);
181
+ return;
182
+ }
183
+ if (e.shiftKey) return;
154
184
  const id = idOf(row);
155
185
  switch (e.key) {
156
186
  case "ArrowDown":
@@ -193,10 +223,12 @@ function useRowActivation(options) {
193
223
  const rowProps = (row) => {
194
224
  if (!enabled) return {};
195
225
  const id = idOf(row);
226
+ const isSelected = paging.current.isSelected;
196
227
  return {
197
228
  ref: refFor(id),
198
229
  tabIndex: id === tabStopId ? 0 : -1,
199
- "aria-selected": id === activeRowId,
230
+ "aria-selected": isSelected ? isSelected(id) : id === activeRowId,
231
+ ...isSelected ? { "aria-current": id === activeRowId ? "true" : void 0 } : {},
200
232
  "data-active": id === activeRowId ? "true" : void 0,
201
233
  onKeyDown: (e) => onKeyDown(e, row),
202
234
  onFocus: (e) => {
@@ -1 +1 @@
1
- {"version":3,"file":"useRowActivation.js","names":[],"sources":["../../src/rows/useRowActivation.ts"],"sourcesContent":["// Row activation and keyboard movement over a list of rows: the active row, a roving tab\n// stop, ArrowUp / ArrowDown / j / k / Home / End / Enter, and a click that activates. The\n// table and the cards use it; a host renderer gets the same behaviour from\n// `@jsudc/react/headless`. No JSX.\nimport type { Row } from \"@jsudc/core\";\nimport {\n type FocusEvent,\n type KeyboardEvent,\n type MouseEvent,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\n\n/**\n * The activation props of `UdcDataView` and of `RendererProps`. All optional;\n * with none of them a list behaves as before 0.4.0 (no tab stop on the rows,\n * no keys, no active row).\n */\nexport interface RowActivationProps {\n /** A row was activated: Enter on it, or a plain click (no modifier, the main button). */\n onRowActivate?: ((row: Row) => void) | undefined;\n /**\n * The row drawn as active (`aria-selected=\"true\"`, `data-active`, the\n * `--selected` background). Passed: controlled, the host moves it in\n * `onActiveRowChange`; `null` is \"none\". Left out: the list keeps it itself.\n */\n activeRowId?: string | null | undefined;\n /**\n * The active row changed by the user: moved by the keys (without Enter) or a\n * click on another row (before `onRowActivate`). Preview on move here.\n */\n onActiveRowChange?: ((row: Row | null) => void) | undefined;\n}\n\n/** Is activation on: any of the three props passed? */\nexport function rowActivationEnabled(p: RowActivationProps): boolean {\n return (\n p.onRowActivate !== undefined ||\n p.activeRowId !== undefined ||\n p.onActiveRowChange !== undefined\n );\n}\n\nexport interface UseRowActivationOptions extends RowActivationProps {\n /** The loaded rows, in the order they are drawn. */\n rows: readonly Row[];\n /** Infinite mode: moving past the last loaded row asks for the next page. */\n hasNextPage?: boolean | undefined;\n isFetchingNextPage?: boolean | undefined;\n fetchNextPage?: (() => unknown) | undefined;\n /** Override the default, `rowActivationEnabled(options)`. */\n enabled?: boolean | undefined;\n}\n\n/** What to spread on the element of one row (a `<tr>`, a card, an `<li>`). */\nexport interface RowActivationRowProps {\n ref: (el: HTMLElement | null) => void;\n /** One tab stop for the list: the active row, else the last focused one, else the first. */\n tabIndex: 0 | -1;\n \"aria-selected\": boolean;\n /** `\"true\"` on the active row: a stable hook for CSS (`.udc-row[data-active]`). */\n \"data-active\": \"true\" | undefined;\n onKeyDown: (e: KeyboardEvent<HTMLElement>) => void;\n onFocus: (e: FocusEvent<HTMLElement>) => void;\n onBlur: (e: FocusEvent<HTMLElement>) => void;\n}\n\nexport interface RowActivation {\n /** Off: `rowProps` is `{}` and the handlers do nothing. */\n enabled: boolean;\n /** The active row's id when it is among `rows`, else `null`. */\n activeRowId: string | null;\n /** The row holding the list's tab stop. */\n tabStopId: string | null;\n /** The props of one row's element (`{}` when off). */\n rowProps: (row: Row) => RowActivationRowProps | Record<string, never>;\n /**\n * A click on the row: a plain click activates it (and focuses it, unless the\n * click went to a focusable cell). A modified or non-main-button click, or one\n * on a link, button, input or menu, is left alone. `true` when it activated.\n */\n handleClick: (e: MouseEvent<HTMLElement>, row: Row) => boolean;\n /** Activate `row` as Enter does: make it active, then `onRowActivate`. */\n activate: (row: Row) => void;\n /** Move the active row, as the keys do, and focus it. */\n move: (to: \"next\" | \"previous\" | \"first\" | \"last\") => void;\n}\n\n/** Elements whose keys belong to them: an input, a cell editor, a menu, a dialog, a list box. */\nconst OWNS_KEYS =\n 'input,textarea,select,[contenteditable=\"\"],[contenteditable=\"true\"],[role=\"menu\"],[role=\"menubar\"],[role=\"dialog\"],[role=\"alertdialog\"],[role=\"listbox\"],[role=\"combobox\"],[role=\"textbox\"],[data-cell-editor]';\n/** Where a click is the control's, not the row's. */\nconst OWNS_CLICK = `a,button,label,${OWNS_KEYS}`;\n\n// Duck-typed, so an element of another realm (an iframe) counts too.\nfunction closestOf(target: EventTarget | null, selector: string): Element | null {\n const el = target as Element | null;\n return el && typeof el.closest === \"function\" ? el.closest(selector) : null;\n}\n\n/** Is `target` inside `container` (a key or click from a portal bubbles through React too)? */\nfunction within(container: HTMLElement, target: EventTarget | null): boolean {\n const node = target as Node | null;\n return !!node && typeof node.nodeType === \"number\" && container.contains(node);\n}\n\n/** Does a key pressed on `target` belong to it rather than to the list? */\nexport function ownsKeys(target: EventTarget | null): boolean {\n if ((target as HTMLElement | null)?.isContentEditable === true) return true;\n return closestOf(target, OWNS_KEYS) !== null;\n}\n\nconst idOf = (r: Row) => r.__meta.id;\n\n/**\n * The active row of a list and the keys that move it. Spread `rowProps(row)`\n * on each row's element, call `handleClick` from its `onClick`, and give the\n * list `role=\"grid\"` (rows `role=\"row\"`) while `enabled`.\n */\nexport function useRowActivation(options: UseRowActivationOptions): RowActivation {\n const { rows, activeRowId: controlledId, onRowActivate, onActiveRowChange } = options;\n const enabled = options.enabled ?? rowActivationEnabled(options);\n const controlled = controlledId !== undefined;\n const [ownId, setOwnId] = useState<string | null>(null);\n const [focusId, setFocusId] = useState<string | null>(null);\n const rawId = controlled ? controlledId : ownId;\n const has = (id: string | null): id is string => id !== null && rows.some((r) => idOf(r) === id);\n const activeRowId = enabled && has(rawId) ? rawId : null;\n const tabStopId = !enabled\n ? null\n : (activeRowId ?? (has(focusId) ? focusId : null) ?? (rows[0] ? idOf(rows[0]) : null));\n\n // The latest values, for handlers that outlive a render.\n const latest = useRef({ rows, activeRowId, onRowActivate, onActiveRowChange, controlled });\n latest.current = { rows, activeRowId, onRowActivate, onActiveRowChange, controlled };\n const paging = useRef(options);\n paging.current = options;\n\n // One stable ref callback per row id, so React does not detach and reattach each render.\n const elements = useRef(new Map<string, HTMLElement>());\n const refs = useRef(new Map<string, (el: HTMLElement | null) => void>());\n const refFor = (id: string) => {\n let cb = refs.current.get(id);\n if (!cb) {\n cb = (el) => {\n if (el) elements.current.set(id, el);\n else elements.current.delete(id);\n };\n refs.current.set(id, cb);\n }\n return cb;\n };\n\n /** The row id that had focus while the list had it; kept across a refetch that unmounts rows. */\n const focusedRef = useRef<string | null>(null);\n /** Infinite mode: the last row when ArrowDown asked for the next page; moves past it on arrival. */\n const pendingRef = useRef<string | null>(null);\n\n const focusRow = useCallback((id: string) => {\n const el = elements.current.get(id);\n if (!el) return;\n el.focus({ preventScroll: true });\n if (typeof el.scrollIntoView === \"function\") el.scrollIntoView({ block: \"nearest\" });\n }, []);\n\n const changeActive = useCallback((row: Row) => {\n const now = latest.current;\n if (now.activeRowId === idOf(row)) return;\n if (!now.controlled) setOwnId(idOf(row));\n now.onActiveRowChange?.(row);\n }, []);\n\n const go = useCallback(\n (row: Row) => {\n setFocusId(idOf(row));\n focusedRef.current = idOf(row);\n changeActive(row);\n focusRow(idOf(row));\n },\n [changeActive, focusRow],\n );\n\n const activate = useCallback(\n (row: Row) => {\n changeActive(row);\n latest.current.onRowActivate?.(row);\n },\n [changeActive],\n );\n\n const step = useCallback(\n (from: string | null, to: \"next\" | \"previous\" | \"first\" | \"last\") => {\n const list = latest.current.rows;\n if (list.length === 0) return;\n if (to === \"first\") return go(list[0] as Row);\n const last = list.length - 1;\n if (to === \"last\") return go(list[last] as Row);\n const i = from === null ? -1 : list.findIndex((r) => idOf(r) === from);\n if (i < 0) return go(list[0] as Row);\n const next = to === \"next\" ? i + 1 : i - 1;\n if (next < 0) return;\n if (next > last) {\n const { hasNextPage, isFetchingNextPage, fetchNextPage } = paging.current;\n if (hasNextPage && fetchNextPage) {\n pendingRef.current = idOf(list[last] as Row);\n if (!isFetchingNextPage) fetchNextPage();\n }\n return;\n }\n go(list[next] as Row);\n },\n [go],\n );\n\n const move = useCallback(\n (to: \"next\" | \"previous\" | \"first\" | \"last\") => {\n const now = latest.current;\n step(now.activeRowId ?? focusedRef.current, to);\n },\n [step],\n );\n\n // A page arrived after ArrowDown on the last row: continue onto its first row.\n useEffect(() => {\n const pending = pendingRef.current;\n if (!enabled || pending === null) return;\n const i = rows.findIndex((r) => idOf(r) === pending);\n const next = i >= 0 ? rows[i + 1] : undefined;\n if (next) {\n pendingRef.current = null;\n go(next);\n } else if (i < 0 || (!options.isFetchingNextPage && !options.hasNextPage)) {\n pendingRef.current = null;\n }\n }, [enabled, rows, go, options.isFetchingNextPage, options.hasNextPage]);\n\n // Rows unmounted under the focus (a refetch drawing skeletons, a sort): give it back by id.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `rows` is the trigger, not an input\n useLayoutEffect(() => {\n const id = focusedRef.current;\n if (!enabled || id === null) return;\n const el = elements.current.get(id);\n if (!el) return;\n const active = typeof document === \"undefined\" ? null : document.activeElement;\n if (active === el) return;\n if (active === null || active === document.body) el.focus({ preventScroll: true });\n }, [enabled, rows]);\n\n // The active row set from outside (the host opened a message) is scrolled into view.\n useEffect(() => {\n if (activeRowId === null) return;\n const el = elements.current.get(activeRowId);\n if (el && typeof el.scrollIntoView === \"function\") el.scrollIntoView({ block: \"nearest\" });\n }, [activeRowId]);\n\n const onKeyDown = (e: KeyboardEvent<HTMLElement>, row: Row) => {\n if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;\n // A key from a portalled menu or dialog bubbles through React to here: not the list's.\n if (!within(e.currentTarget, e.target)) return;\n if (ownsKeys(e.target)) return;\n const id = idOf(row);\n switch (e.key) {\n case \"ArrowDown\":\n case \"j\":\n step(id, \"next\");\n break;\n case \"ArrowUp\":\n case \"k\":\n step(id, \"previous\");\n break;\n case \"Home\":\n step(id, \"first\");\n break;\n case \"End\":\n step(id, \"last\");\n break;\n case \"Enter\":\n // Enter on a link or a button in the row is that control's.\n if (closestOf(e.target, \"a,button\") !== null && e.target !== e.currentTarget) return;\n activate(row);\n break;\n default:\n return;\n }\n e.preventDefault();\n };\n\n const handleClick = (e: MouseEvent<HTMLElement>, row: Row): boolean => {\n if (!enabled || e.defaultPrevented) return false;\n if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return false;\n if (!within(e.currentTarget, e.target)) return false;\n if (closestOf(e.target, OWNS_CLICK)) return false;\n const id = idOf(row);\n setFocusId(id);\n // A click in a focusable cell (an editable one) keeps the focus there.\n const focusable = closestOf(e.target, \"[tabindex]\");\n if (!focusable || focusable === e.currentTarget) {\n focusedRef.current = id;\n elements.current.get(id)?.focus({ preventScroll: true });\n }\n activate(row);\n return true;\n };\n\n const rowProps = (row: Row): RowActivationRowProps | Record<string, never> => {\n if (!enabled) return {};\n const id = idOf(row);\n return {\n ref: refFor(id),\n tabIndex: id === tabStopId ? 0 : -1,\n \"aria-selected\": id === activeRowId,\n \"data-active\": id === activeRowId ? \"true\" : undefined,\n onKeyDown: (e) => onKeyDown(e, row),\n onFocus: (e) => {\n if (e.target !== e.currentTarget) return;\n focusedRef.current = id;\n setFocusId(id);\n },\n onBlur: (e) => {\n // Focus left the list (not to another row or a cell of it): forget it.\n const list = e.currentTarget.parentElement;\n if (!list || !within(list, e.relatedTarget)) focusedRef.current = null;\n },\n };\n };\n\n return { enabled, activeRowId, tabStopId, rowProps, handleClick, activate, move };\n}\n"],"mappings":";;;AAsCA,SAAgB,qBAAqB,GAAgC;CACnE,OACE,EAAE,kBAAkB,KAAA,KACpB,EAAE,gBAAgB,KAAA,KAClB,EAAE,sBAAsB,KAAA;AAE5B;;AAgDA,IAAM,YACJ;;AAEF,IAAM,aAAa,kBAAkB;AAGrC,SAAS,UAAU,QAA4B,UAAkC;CAC/E,MAAM,KAAK;CACX,OAAO,MAAM,OAAO,GAAG,YAAY,aAAa,GAAG,QAAQ,QAAQ,IAAI;AACzE;;AAGA,SAAS,OAAO,WAAwB,QAAqC;CAC3E,MAAM,OAAO;CACb,OAAO,CAAC,CAAC,QAAQ,OAAO,KAAK,aAAa,YAAY,UAAU,SAAS,IAAI;AAC/E;;AAGA,SAAgB,SAA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AAE;GACd,UAAU,OAAO,YAAY,IAAI;GACjC,iBAAiB,OAAO;GACxB,eAAe,OAAO,cAAc,SAAS,KAAA;GAC7C,YAAY,MAAM,UAAU,GAAG,GAAG;GAClC,UAAU,MAAM;IACd,IAAI,EAAE,WAAW,EAAE,eAAe;IAClC,WAAW,UAAU;IACrB,WAAW,EAAE;GACf;GACA,SAAS,MAAM;IAEb,MAAM,OAAO,EAAE,cAAc;IAC7B,IAAI,CAAC,QAAQ,CAAC,OAAO,MAAM,EAAE,aAAa,GAAG,WAAW,UAAU;GACpE;EACF;CACF;CAEA,OAAO;EAAE;EAAS;EAAa;EAAW;EAAU;EAAa;EAAU;CAAK;AAClF"}
1
+ {"version":3,"file":"useRowActivation.js","names":[],"sources":["../../src/rows/useRowActivation.ts"],"sourcesContent":["// Row activation and keyboard movement over a list of rows: the active row, a roving tab\n// stop, ArrowUp / ArrowDown / j / k / Home / End / Enter, and a click that activates. The\n// table and the cards use it; a host renderer gets the same behaviour from\n// `@jsudc/react/headless`. No JSX.\nimport type { Row } from \"@jsudc/core\";\nimport {\n type FocusEvent,\n type KeyboardEvent,\n type MouseEvent,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\n\n/**\n * The activation props of `UdcDataView` and of `RendererProps`. All optional;\n * with none of them a list behaves as before 0.4.0 (no tab stop on the rows,\n * no keys, no active row).\n */\nexport interface RowActivationProps {\n /** A row was activated: Enter on it, or a plain click (no modifier, the main button). */\n onRowActivate?: ((row: Row) => void) | undefined;\n /**\n * The row drawn as active (`aria-selected=\"true\"`, `data-active`, the\n * `--selected` background). Passed: controlled, the host moves it in\n * `onActiveRowChange`; `null` is \"none\". Left out: the list keeps it itself.\n */\n activeRowId?: string | null | undefined;\n /**\n * The active row changed by the user: moved by the keys (without Enter) or a\n * click on another row (before `onRowActivate`). Preview on move here.\n */\n onActiveRowChange?: ((row: Row | null) => void) | undefined;\n}\n\n/** Is activation on: any of the three props passed? */\nexport function rowActivationEnabled(p: RowActivationProps): boolean {\n return (\n p.onRowActivate !== undefined ||\n p.activeRowId !== undefined ||\n p.onActiveRowChange !== undefined\n );\n}\n\nexport interface UseRowActivationOptions extends RowActivationProps {\n /** The loaded rows, in the order they are drawn. */\n rows: readonly Row[];\n /** Infinite mode: moving past the last loaded row asks for the next page. */\n hasNextPage?: boolean | undefined;\n isFetchingNextPage?: boolean | undefined;\n fetchNextPage?: (() => unknown) | undefined;\n /** Override the default, `rowActivationEnabled(options)`. */\n enabled?: boolean | undefined;\n /**\n * Multiselect is on (0.5.0): `aria-selected` then says whether the row is\n * selected (ARIA's multi-select grid), and the active row is the one holding\n * the focus, marked `aria-current=\"true\"` and `data-active`. Absent: as in\n * 0.4.0, `aria-selected` marks the active row.\n */\n isSelected?: ((id: string) => boolean) | undefined;\n /** Space on a row toggles its selection (Shift+Space: a range from the last toggled row). */\n onToggleSelect?: ((row: Row, range: boolean) => void) | undefined;\n /**\n * A windowed list (0.5.0; the table's long lists) mounts only some rows: when the keys move\n * to a row whose element is not mounted, this is called to scroll it in and mount it, and\n * the row takes the focus the moment its element attaches. Absent: every row is mounted.\n */\n reveal?: ((row: Row, index: number) => void) | undefined;\n}\n\n/** What to spread on the element of one row (a `<tr>`, a card, an `<li>`). */\nexport interface RowActivationRowProps {\n ref: (el: HTMLElement | null) => void;\n /** One tab stop for the list: the active row, else the last focused one, else the first. */\n tabIndex: 0 | -1;\n \"aria-selected\": boolean;\n /** With `isSelected` (multiselect): `\"true\"` on the active row, whose `aria-selected` is its selection. */\n \"aria-current\"?: \"true\" | undefined;\n /** `\"true\"` on the active row: a stable hook for CSS (`.udc-row[data-active]`). */\n \"data-active\": \"true\" | undefined;\n onKeyDown: (e: KeyboardEvent<HTMLElement>) => void;\n onFocus: (e: FocusEvent<HTMLElement>) => void;\n onBlur: (e: FocusEvent<HTMLElement>) => void;\n}\n\nexport interface RowActivation {\n /** Off: `rowProps` is `{}` and the handlers do nothing. */\n enabled: boolean;\n /** The active row's id when it is among `rows`, else `null`. */\n activeRowId: string | null;\n /** The row holding the list's tab stop. */\n tabStopId: string | null;\n /** The props of one row's element (`{}` when off). */\n rowProps: (row: Row) => RowActivationRowProps | Record<string, never>;\n /**\n * A click on the row: a plain click activates it (and focuses it, unless the\n * click went to a focusable cell). A modified or non-main-button click, or one\n * on a link, button, input or menu, is left alone. `true` when it activated.\n */\n handleClick: (e: MouseEvent<HTMLElement>, row: Row) => boolean;\n /** Activate `row` as Enter does: make it active, then `onRowActivate`. */\n activate: (row: Row) => void;\n /** Move the active row, as the keys do, and focus it. */\n move: (to: \"next\" | \"previous\" | \"first\" | \"last\") => void;\n}\n\n/** Elements whose keys belong to them: an input, a cell editor, a menu, a dialog, a list box. */\nconst OWNS_KEYS =\n 'input,textarea,select,[contenteditable=\"\"],[contenteditable=\"true\"],[role=\"menu\"],[role=\"menubar\"],[role=\"dialog\"],[role=\"alertdialog\"],[role=\"listbox\"],[role=\"combobox\"],[role=\"textbox\"],[data-cell-editor]';\n/** Where a click is the control's, not the row's. */\nconst OWNS_CLICK = `a,button,label,${OWNS_KEYS}`;\n\n// Duck-typed, so an element of another realm (an iframe) counts too.\nfunction closestOf(target: EventTarget | null, selector: string): Element | null {\n const el = target as Element | null;\n return el && typeof el.closest === \"function\" ? el.closest(selector) : null;\n}\n\n/** Is `target` inside `container` (a key or click from a portal bubbles through React too)? */\nfunction within(container: HTMLElement, target: EventTarget | null): boolean {\n const node = target as Node | null;\n return !!node && typeof node.nodeType === \"number\" && container.contains(node);\n}\n\n/** Does a key pressed on `target` belong to it rather than to the list? */\nexport function ownsKeys(target: EventTarget | null): boolean {\n if ((target as HTMLElement | null)?.isContentEditable === true) return true;\n return closestOf(target, OWNS_KEYS) !== null;\n}\n\nconst idOf = (r: Row) => r.__meta.id;\n\n/**\n * The active row of a list and the keys that move it. Spread `rowProps(row)`\n * on each row's element, call `handleClick` from its `onClick`, and give the\n * list `role=\"grid\"` (rows `role=\"row\"`) while `enabled`.\n */\nexport function useRowActivation(options: UseRowActivationOptions): RowActivation {\n const { rows, activeRowId: controlledId, onRowActivate, onActiveRowChange } = options;\n const enabled = options.enabled ?? rowActivationEnabled(options);\n const controlled = controlledId !== undefined;\n const [ownId, setOwnId] = useState<string | null>(null);\n const [focusId, setFocusId] = useState<string | null>(null);\n const rawId = controlled ? controlledId : ownId;\n const has = (id: string | null): id is string => id !== null && rows.some((r) => idOf(r) === id);\n const activeRowId = enabled && has(rawId) ? rawId : null;\n const tabStopId = !enabled\n ? null\n : (activeRowId ?? (has(focusId) ? focusId : null) ?? (rows[0] ? idOf(rows[0]) : null));\n\n // The latest values, for handlers that outlive a render.\n const latest = useRef({ rows, activeRowId, onRowActivate, onActiveRowChange, controlled });\n latest.current = { rows, activeRowId, onRowActivate, onActiveRowChange, controlled };\n const paging = useRef(options);\n paging.current = options;\n\n /** A windowed list: the row the keys moved to before it was mounted; focused when it attaches. */\n const revealRef = useRef<string | null>(null);\n // One stable ref callback per row id, so React does not detach and reattach each render.\n const elements = useRef(new Map<string, HTMLElement>());\n const refs = useRef(new Map<string, (el: HTMLElement | null) => void>());\n const refFor = (id: string) => {\n let cb = refs.current.get(id);\n if (!cb) {\n cb = (el) => {\n if (el) {\n elements.current.set(id, el);\n // A windowed list mounted the row the keys moved to: it takes the focus now.\n if (revealRef.current === id) {\n revealRef.current = null;\n el.focus({ preventScroll: true });\n }\n } else elements.current.delete(id);\n };\n refs.current.set(id, cb);\n }\n return cb;\n };\n\n /** The row id that had focus while the list had it; kept across a refetch that unmounts rows. */\n const focusedRef = useRef<string | null>(null);\n /** Infinite mode: the last row when ArrowDown asked for the next page; moves past it on arrival. */\n const pendingRef = useRef<string | null>(null);\n\n const focusRow = useCallback((id: string) => {\n const el = elements.current.get(id);\n if (!el) {\n const reveal = paging.current.reveal;\n const list = latest.current.rows;\n const i = list.findIndex((r) => idOf(r) === id);\n if (reveal && i >= 0) {\n revealRef.current = id;\n reveal(list[i] as Row, i);\n }\n return;\n }\n revealRef.current = null;\n el.focus({ preventScroll: true });\n if (typeof el.scrollIntoView === \"function\") el.scrollIntoView({ block: \"nearest\" });\n }, []);\n\n const changeActive = useCallback((row: Row) => {\n const now = latest.current;\n if (now.activeRowId === idOf(row)) return;\n if (!now.controlled) setOwnId(idOf(row));\n now.onActiveRowChange?.(row);\n }, []);\n\n const go = useCallback(\n (row: Row) => {\n setFocusId(idOf(row));\n focusedRef.current = idOf(row);\n changeActive(row);\n focusRow(idOf(row));\n },\n [changeActive, focusRow],\n );\n\n const activate = useCallback(\n (row: Row) => {\n changeActive(row);\n latest.current.onRowActivate?.(row);\n },\n [changeActive],\n );\n\n const step = useCallback(\n (from: string | null, to: \"next\" | \"previous\" | \"first\" | \"last\") => {\n const list = latest.current.rows;\n if (list.length === 0) return;\n if (to === \"first\") return go(list[0] as Row);\n const last = list.length - 1;\n if (to === \"last\") return go(list[last] as Row);\n const i = from === null ? -1 : list.findIndex((r) => idOf(r) === from);\n if (i < 0) return go(list[0] as Row);\n const next = to === \"next\" ? i + 1 : i - 1;\n if (next < 0) return;\n if (next > last) {\n const { hasNextPage, isFetchingNextPage, fetchNextPage } = paging.current;\n if (hasNextPage && fetchNextPage) {\n pendingRef.current = idOf(list[last] as Row);\n if (!isFetchingNextPage) fetchNextPage();\n }\n return;\n }\n go(list[next] as Row);\n },\n [go],\n );\n\n const move = useCallback(\n (to: \"next\" | \"previous\" | \"first\" | \"last\") => {\n const now = latest.current;\n step(now.activeRowId ?? focusedRef.current, to);\n },\n [step],\n );\n\n // A page arrived after ArrowDown on the last row: continue onto its first row.\n useEffect(() => {\n const pending = pendingRef.current;\n if (!enabled || pending === null) return;\n const i = rows.findIndex((r) => idOf(r) === pending);\n const next = i >= 0 ? rows[i + 1] : undefined;\n if (next) {\n pendingRef.current = null;\n go(next);\n } else if (i < 0 || (!options.isFetchingNextPage && !options.hasNextPage)) {\n pendingRef.current = null;\n }\n }, [enabled, rows, go, options.isFetchingNextPage, options.hasNextPage]);\n\n // Rows unmounted under the focus (a refetch drawing skeletons, a sort): give it back by id.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `rows` is the trigger, not an input\n useLayoutEffect(() => {\n const id = focusedRef.current;\n if (!enabled || id === null) return;\n const el = elements.current.get(id);\n if (!el) return;\n const active = typeof document === \"undefined\" ? null : document.activeElement;\n if (active === el) return;\n if (active === null || active === document.body) el.focus({ preventScroll: true });\n }, [enabled, rows]);\n\n // The active row set from outside (the host opened a message) is scrolled into view.\n useEffect(() => {\n if (activeRowId === null) return;\n const el = elements.current.get(activeRowId);\n if (el && typeof el.scrollIntoView === \"function\") el.scrollIntoView({ block: \"nearest\" });\n else if (!el && paging.current.reveal) {\n // A windowed list whose active row is not mounted: scroll it in (the focus stays put).\n const list = latest.current.rows;\n const i = list.findIndex((r) => idOf(r) === activeRowId);\n if (i >= 0) paging.current.reveal(list[i] as Row, i);\n }\n }, [activeRowId]);\n\n const onKeyDown = (e: KeyboardEvent<HTMLElement>, row: Row) => {\n if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;\n // A key from a portalled menu or dialog bubbles through React to here: not the list's.\n if (!within(e.currentTarget, e.target)) return;\n if (ownsKeys(e.target)) return;\n // Space toggles the row's selection when the list selects (0.5.0); unbound otherwise.\n const toggleSelect = paging.current.onToggleSelect;\n if (e.key === \" \" && toggleSelect) {\n if (closestOf(e.target, \"a,button\") !== null && e.target !== e.currentTarget) return;\n e.preventDefault();\n toggleSelect(row, e.shiftKey);\n return;\n }\n if (e.shiftKey) return;\n const id = idOf(row);\n switch (e.key) {\n case \"ArrowDown\":\n case \"j\":\n step(id, \"next\");\n break;\n case \"ArrowUp\":\n case \"k\":\n step(id, \"previous\");\n break;\n case \"Home\":\n step(id, \"first\");\n break;\n case \"End\":\n step(id, \"last\");\n break;\n case \"Enter\":\n // Enter on a link or a button in the row is that control's.\n if (closestOf(e.target, \"a,button\") !== null && e.target !== e.currentTarget) return;\n activate(row);\n break;\n default:\n return;\n }\n e.preventDefault();\n };\n\n const handleClick = (e: MouseEvent<HTMLElement>, row: Row): boolean => {\n if (!enabled || e.defaultPrevented) return false;\n if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return false;\n if (!within(e.currentTarget, e.target)) return false;\n if (closestOf(e.target, OWNS_CLICK)) return false;\n const id = idOf(row);\n setFocusId(id);\n // A click in a focusable cell (an editable one) keeps the focus there.\n const focusable = closestOf(e.target, \"[tabindex]\");\n if (!focusable || focusable === e.currentTarget) {\n focusedRef.current = id;\n elements.current.get(id)?.focus({ preventScroll: true });\n }\n activate(row);\n return true;\n };\n\n const rowProps = (row: Row): RowActivationRowProps | Record<string, never> => {\n if (!enabled) return {};\n const id = idOf(row);\n const isSelected = paging.current.isSelected;\n return {\n ref: refFor(id),\n tabIndex: id === tabStopId ? 0 : -1,\n \"aria-selected\": isSelected ? isSelected(id) : id === activeRowId,\n ...(isSelected ? { \"aria-current\": id === activeRowId ? \"true\" : undefined } : {}),\n \"data-active\": id === activeRowId ? \"true\" : undefined,\n onKeyDown: (e) => onKeyDown(e, row),\n onFocus: (e) => {\n if (e.target !== e.currentTarget) return;\n focusedRef.current = id;\n setFocusId(id);\n },\n onBlur: (e) => {\n // Focus left the list (not to another row or a cell of it): forget it.\n const list = e.currentTarget.parentElement;\n if (!list || !within(list, e.relatedTarget)) focusedRef.current = null;\n },\n };\n };\n\n return { enabled, activeRowId, tabStopId, rowProps, handleClick, activate, move };\n}\n"],"mappings":";;;AAsCA,SAAgB,qBAAqB,GAAgC;CACnE,OACE,EAAE,kBAAkB,KAAA,KACpB,EAAE,gBAAgB,KAAA,KAClB,EAAE,sBAAsB,KAAA;AAE5B;;AAiEA,IAAM,YACJ;;AAEF,IAAM,aAAa,kBAAkB;AAGrC,SAAS,UAAU,QAA4B,UAAkC;CAC/E,MAAM,KAAK;CACX,OAAO,MAAM,OAAO,GAAG,YAAY,aAAa,GAAG,QAAQ,QAAQ,IAAI;AACzE;;AAGA,SAAS,OAAO,WAAwB,QAAqC;CAC3E,MAAM,OA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,WAAW,EAAE;GACf;GACA,SAAS,MAAM;IAEb,MAAM,OAAO,EAAE,cAAc;IAC7B,IAAI,CAAC,QAAQ,CAAC,OAAO,MAAM,EAAE,aAAa,GAAG,WAAW,UAAU;GACpE;EACF;CACF;CAEA,OAAO;EAAE;EAAS;EAAa;EAAW;EAAU;EAAa;EAAU;CAAK;AAClF"}
@@ -0,0 +1,92 @@
1
+ import type { Row } from "@jsudc/core";
2
+ /**
3
+ * What is selected. `ids`: exactly these rows. `matching`: every row the
4
+ * list's filter matches, loaded or not, except `except`. `anchor` is the row a
5
+ * shift-range starts from (the last one toggled), `null` for none.
6
+ */
7
+ export type RowSelectionState = {
8
+ mode: "ids";
9
+ ids: ReadonlySet<string>;
10
+ anchor: string | null;
11
+ } | {
12
+ mode: "matching";
13
+ except: ReadonlySet<string>;
14
+ anchor: string | null;
15
+ };
16
+ /** Nothing selected. */
17
+ export declare const EMPTY_SELECTION: RowSelectionState;
18
+ /** Is the row `id` selected? */
19
+ export declare function selectionHas(s: RowSelectionState, id: string): boolean;
20
+ /** Nothing selected: no id in id mode (matching mode always counts as something). */
21
+ export declare function selectionIsEmpty(s: RowSelectionState): boolean;
22
+ /**
23
+ * How many rows are selected: the ids in id mode; in matching mode `total`
24
+ * minus the exceptions, or `null` when the list has no total (a source with
25
+ * `capabilities.total_count: false`).
26
+ */
27
+ export declare function selectionCount(s: RowSelectionState, total: number | null): number | null;
28
+ /** Flip one row; it becomes the anchor of the next range. */
29
+ export declare function toggleSelection(s: RowSelectionState, id: string): RowSelectionState;
30
+ /**
31
+ * Shift-click on `id`: every row from the anchor to `id`, in the order of
32
+ * `rows` (the rows as loaded), takes the state the anchor has. Without an
33
+ * anchor among `rows` it is a plain toggle. The anchor stays where it was, so
34
+ * a second shift-click re-ranges from the same row.
35
+ */
36
+ export declare function selectRange(s: RowSelectionState, rows: readonly Row[], id: string): RowSelectionState;
37
+ /** Every loaded row selected (`on`) or none of them. */
38
+ export declare function setPageSelection(s: RowSelectionState, rows: readonly Row[], on: boolean): RowSelectionState;
39
+ /** Every row that matches the list's filter, loaded or not. */
40
+ export declare function selectAllMatching(): RowSelectionState;
41
+ /** How much of the loaded rows is selected: `none`, `some` or `all` (no rows: `none`). */
42
+ export declare function pageSelectionState(s: RowSelectionState, rows: readonly Row[]): "none" | "some" | "all";
43
+ /**
44
+ * The live selection of one list: its state, what follows from it, and the
45
+ * operations. What `RendererProps.selection` carries.
46
+ */
47
+ export interface RowSelection {
48
+ /** `ids`: the rows in `ids`. `matching`: every row of the filter except `exceptIds`. */
49
+ mode: "ids" | "matching";
50
+ /** The selected ids (id mode; empty in matching mode). */
51
+ ids: readonly string[];
52
+ /** The ids taken out of an "all that match" selection (matching mode; empty in id mode). */
53
+ exceptIds: readonly string[];
54
+ /** How many rows are selected; `null` in matching mode when the list has no total. */
55
+ count: number | null;
56
+ /** Nothing is selected. */
57
+ isEmpty: boolean;
58
+ /**
59
+ * The selected rows the list has loaded, in id mode also those loaded
60
+ * earlier and no longer in the list (kept from when they were selected).
61
+ */
62
+ rows: readonly Row[];
63
+ /** How much of the loaded rows is selected, for a header checkbox. */
64
+ pageState: "none" | "some" | "all";
65
+ isSelected: (id: string) => boolean;
66
+ /** Flip one row; with `range` (shift-click) select from the last toggled row to this one. */
67
+ toggle: (id: string, opts?: {
68
+ range?: boolean;
69
+ }) => void;
70
+ /** Select (`true`) or clear (`false`) every loaded row. */
71
+ setPage: (on: boolean) => void;
72
+ /** Select every row that matches the filter, loaded or not. */
73
+ selectAllMatching: () => void;
74
+ /** Keep exactly these ids selected (id mode). */
75
+ setIds: (ids: readonly string[]) => void;
76
+ /** Select nothing. */
77
+ clear: () => void;
78
+ }
79
+ export interface UseRowSelectionOptions {
80
+ /** The loaded rows, in the order they are drawn: what a range and "the page" cover. */
81
+ rows: readonly Row[];
82
+ /** The list's total; `null` when the source does not count. */
83
+ total: number | null;
84
+ /**
85
+ * Changes when the selection no longer applies: the collection or the
86
+ * filter (search, chips, the filter tree, the host's filter). A sort, a
87
+ * refetch or another page loading keep the key, and the selection.
88
+ */
89
+ resetKey: string;
90
+ }
91
+ /** One list's selection, cleared whenever `resetKey` changes. */
92
+ export declare function useRowSelection({ rows, total, resetKey }: UseRowSelectionOptions): RowSelection;
@@ -0,0 +1,156 @@
1
+ import { useCallback, useMemo, useRef, useState } from "react";
2
+ // src/rows/useRowSelection.ts
3
+ /** Nothing selected. */
4
+ var EMPTY_SELECTION = Object.freeze({
5
+ mode: "ids",
6
+ ids: /* @__PURE__ */ new Set(),
7
+ anchor: null
8
+ });
9
+ var idOf = (r) => r.__meta.id;
10
+ /** Is the row `id` selected? */
11
+ function selectionHas(s, id) {
12
+ return s.mode === "ids" ? s.ids.has(id) : !s.except.has(id);
13
+ }
14
+ /** Nothing selected: no id in id mode (matching mode always counts as something). */
15
+ function selectionIsEmpty(s) {
16
+ return s.mode === "ids" && s.ids.size === 0;
17
+ }
18
+ /**
19
+ * How many rows are selected: the ids in id mode; in matching mode `total`
20
+ * minus the exceptions, or `null` when the list has no total (a source with
21
+ * `capabilities.total_count: false`).
22
+ */
23
+ function selectionCount(s, total) {
24
+ if (s.mode === "ids") return s.ids.size;
25
+ return total === null ? null : Math.max(0, total - s.except.size);
26
+ }
27
+ /** Set (`on`) or unset each of `ids`, keeping the mode. */
28
+ function setMany(s, ids, on, anchor) {
29
+ if (s.mode === "ids") {
30
+ const next = new Set(s.ids);
31
+ for (const id of ids) on ? next.add(id) : next.delete(id);
32
+ return {
33
+ mode: "ids",
34
+ ids: next,
35
+ anchor
36
+ };
37
+ }
38
+ const except = new Set(s.except);
39
+ for (const id of ids) on ? except.delete(id) : except.add(id);
40
+ return {
41
+ mode: "matching",
42
+ except,
43
+ anchor
44
+ };
45
+ }
46
+ /** Flip one row; it becomes the anchor of the next range. */
47
+ function toggleSelection(s, id) {
48
+ return setMany(s, [id], !selectionHas(s, id), id);
49
+ }
50
+ /**
51
+ * Shift-click on `id`: every row from the anchor to `id`, in the order of
52
+ * `rows` (the rows as loaded), takes the state the anchor has. Without an
53
+ * anchor among `rows` it is a plain toggle. The anchor stays where it was, so
54
+ * a second shift-click re-ranges from the same row.
55
+ */
56
+ function selectRange(s, rows, id) {
57
+ const from = s.anchor === null ? -1 : rows.findIndex((r) => idOf(r) === s.anchor);
58
+ const to = rows.findIndex((r) => idOf(r) === id);
59
+ if (from < 0 || to < 0) return toggleSelection(s, id);
60
+ const [lo, hi] = from <= to ? [from, to] : [to, from];
61
+ return setMany(s, rows.slice(lo, hi + 1).map(idOf), selectionHas(s, s.anchor), s.anchor);
62
+ }
63
+ /** Every loaded row selected (`on`) or none of them. */
64
+ function setPageSelection(s, rows, on) {
65
+ return setMany(s, rows.map(idOf), on, s.anchor);
66
+ }
67
+ /** Every row that matches the list's filter, loaded or not. */
68
+ function selectAllMatching() {
69
+ return {
70
+ mode: "matching",
71
+ except: /* @__PURE__ */ new Set(),
72
+ anchor: null
73
+ };
74
+ }
75
+ /** How much of the loaded rows is selected: `none`, `some` or `all` (no rows: `none`). */
76
+ function pageSelectionState(s, rows) {
77
+ let on = 0;
78
+ for (const r of rows) if (selectionHas(s, idOf(r))) on++;
79
+ if (on === 0) return "none";
80
+ return on === rows.length ? "all" : "some";
81
+ }
82
+ /** One list's selection, cleared whenever `resetKey` changes. */
83
+ function useRowSelection({ rows, total, resetKey }) {
84
+ const [held, setHeld] = useState({
85
+ key: resetKey,
86
+ state: EMPTY_SELECTION
87
+ });
88
+ const state = held.key === resetKey ? held.state : EMPTY_SELECTION;
89
+ const latest = useRef({
90
+ rows,
91
+ resetKey
92
+ });
93
+ latest.current = {
94
+ rows,
95
+ resetKey
96
+ };
97
+ const known = useRef(/* @__PURE__ */ new Map());
98
+ for (const r of rows) if (known.current.has(idOf(r))) known.current.set(idOf(r), r);
99
+ const update = useCallback((f) => {
100
+ const { rows: now, resetKey: key } = latest.current;
101
+ setHeld((h) => ({
102
+ key,
103
+ state: f(h.key === key ? h.state : EMPTY_SELECTION, now)
104
+ }));
105
+ }, []);
106
+ const toggle = useCallback((id, opts) => update((s, now) => opts?.range ? selectRange(s, now, id) : toggleSelection(s, id)), [update]);
107
+ const setPage = useCallback((on) => update((s, now) => setPageSelection(s, now, on)), [update]);
108
+ const selectAll = useCallback(() => update(() => selectAllMatching()), [update]);
109
+ const setIds = useCallback((ids) => update(() => ({
110
+ mode: "ids",
111
+ ids: new Set(ids),
112
+ anchor: null
113
+ })), [update]);
114
+ const clear = useCallback(() => update(() => EMPTY_SELECTION), [update]);
115
+ return useMemo(() => {
116
+ const byId = new Map(rows.map((r) => [idOf(r), r]));
117
+ let selectedRows;
118
+ if (state.mode === "ids") {
119
+ selectedRows = [];
120
+ for (const id of state.ids) {
121
+ const r = byId.get(id) ?? known.current.get(id);
122
+ if (r) selectedRows.push(r);
123
+ }
124
+ } else selectedRows = rows.filter((r) => !state.except.has(idOf(r)));
125
+ const keep = /* @__PURE__ */ new Map();
126
+ for (const r of selectedRows) keep.set(idOf(r), r);
127
+ known.current = keep;
128
+ return {
129
+ mode: state.mode,
130
+ ids: state.mode === "ids" ? [...state.ids] : [],
131
+ exceptIds: state.mode === "matching" ? [...state.except] : [],
132
+ count: selectionCount(state, total),
133
+ isEmpty: selectionIsEmpty(state),
134
+ rows: selectedRows,
135
+ pageState: pageSelectionState(state, rows),
136
+ isSelected: (id) => selectionHas(state, id),
137
+ toggle,
138
+ setPage,
139
+ selectAllMatching: selectAll,
140
+ setIds,
141
+ clear
142
+ };
143
+ }, [
144
+ state,
145
+ rows,
146
+ total,
147
+ toggle,
148
+ setPage,
149
+ selectAll,
150
+ setIds,
151
+ clear
152
+ ]);
153
+ }
154
+ export { EMPTY_SELECTION, pageSelectionState, selectAllMatching, selectRange, selectionCount, selectionHas, selectionIsEmpty, setPageSelection, toggleSelection, useRowSelection };
155
+
156
+ //# sourceMappingURL=useRowSelection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRowSelection.js","names":[],"sources":["../../src/rows/useRowSelection.ts"],"sourcesContent":["// Row selection over a list (0.5.0): a set of ids, or \"every row that matches this filter,\n// except these ids\". The model is plain data with pure operations (so a virtualised list,\n// which draws only some rows, ranges over the rows as loaded, not over the DOM), and\n// `useRowSelection` keeps one for a list, clearing it when the list's key (collection and\n// filter) changes. The data view uses it; a host renderer gets the same from\n// `@jsudc/react/headless` through `RendererProps.selection`. No JSX.\nimport type { Row } from \"@jsudc/core\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\n/**\n * What is selected. `ids`: exactly these rows. `matching`: every row the\n * list's filter matches, loaded or not, except `except`. `anchor` is the row a\n * shift-range starts from (the last one toggled), `null` for none.\n */\nexport type RowSelectionState =\n | { mode: \"ids\"; ids: ReadonlySet<string>; anchor: string | null }\n | { mode: \"matching\"; except: ReadonlySet<string>; anchor: string | null };\n\n/** Nothing selected. */\nexport const EMPTY_SELECTION: RowSelectionState = Object.freeze({\n mode: \"ids\",\n ids: new Set<string>(),\n anchor: null,\n}) as RowSelectionState;\n\nconst idOf = (r: Row) => r.__meta.id;\n\n/** Is the row `id` selected? */\nexport function selectionHas(s: RowSelectionState, id: string): boolean {\n return s.mode === \"ids\" ? s.ids.has(id) : !s.except.has(id);\n}\n\n/** Nothing selected: no id in id mode (matching mode always counts as something). */\nexport function selectionIsEmpty(s: RowSelectionState): boolean {\n return s.mode === \"ids\" && s.ids.size === 0;\n}\n\n/**\n * How many rows are selected: the ids in id mode; in matching mode `total`\n * minus the exceptions, or `null` when the list has no total (a source with\n * `capabilities.total_count: false`).\n */\nexport function selectionCount(s: RowSelectionState, total: number | null): number | null {\n if (s.mode === \"ids\") return s.ids.size;\n return total === null ? null : Math.max(0, total - s.except.size);\n}\n\n/** Set (`on`) or unset each of `ids`, keeping the mode. */\nfunction setMany(\n s: RowSelectionState,\n ids: readonly string[],\n on: boolean,\n anchor: string | null,\n): RowSelectionState {\n if (s.mode === \"ids\") {\n const next = new Set(s.ids);\n for (const id of ids) on ? next.add(id) : next.delete(id);\n return { mode: \"ids\", ids: next, anchor };\n }\n const except = new Set(s.except);\n for (const id of ids) on ? except.delete(id) : except.add(id);\n return { mode: \"matching\", except, anchor };\n}\n\n/** Flip one row; it becomes the anchor of the next range. */\nexport function toggleSelection(s: RowSelectionState, id: string): RowSelectionState {\n return setMany(s, [id], !selectionHas(s, id), id);\n}\n\n/**\n * Shift-click on `id`: every row from the anchor to `id`, in the order of\n * `rows` (the rows as loaded), takes the state the anchor has. Without an\n * anchor among `rows` it is a plain toggle. The anchor stays where it was, so\n * a second shift-click re-ranges from the same row.\n */\nexport function selectRange(\n s: RowSelectionState,\n rows: readonly Row[],\n id: string,\n): RowSelectionState {\n const from = s.anchor === null ? -1 : rows.findIndex((r) => idOf(r) === s.anchor);\n const to = rows.findIndex((r) => idOf(r) === id);\n if (from < 0 || to < 0) return toggleSelection(s, id);\n const [lo, hi] = from <= to ? [from, to] : [to, from];\n const ids = rows.slice(lo, hi + 1).map(idOf);\n return setMany(s, ids, selectionHas(s, s.anchor as string), s.anchor);\n}\n\n/** Every loaded row selected (`on`) or none of them. */\nexport function setPageSelection(\n s: RowSelectionState,\n rows: readonly Row[],\n on: boolean,\n): RowSelectionState {\n return setMany(s, rows.map(idOf), on, s.anchor);\n}\n\n/** Every row that matches the list's filter, loaded or not. */\nexport function selectAllMatching(): RowSelectionState {\n return { mode: \"matching\", except: new Set(), anchor: null };\n}\n\n/** How much of the loaded rows is selected: `none`, `some` or `all` (no rows: `none`). */\nexport function pageSelectionState(\n s: RowSelectionState,\n rows: readonly Row[],\n): \"none\" | \"some\" | \"all\" {\n let on = 0;\n for (const r of rows) if (selectionHas(s, idOf(r))) on++;\n if (on === 0) return \"none\";\n return on === rows.length ? \"all\" : \"some\";\n}\n\n/**\n * The live selection of one list: its state, what follows from it, and the\n * operations. What `RendererProps.selection` carries.\n */\nexport interface RowSelection {\n /** `ids`: the rows in `ids`. `matching`: every row of the filter except `exceptIds`. */\n mode: \"ids\" | \"matching\";\n /** The selected ids (id mode; empty in matching mode). */\n ids: readonly string[];\n /** The ids taken out of an \"all that match\" selection (matching mode; empty in id mode). */\n exceptIds: readonly string[];\n /** How many rows are selected; `null` in matching mode when the list has no total. */\n count: number | null;\n /** Nothing is selected. */\n isEmpty: boolean;\n /**\n * The selected rows the list has loaded, in id mode also those loaded\n * earlier and no longer in the list (kept from when they were selected).\n */\n rows: readonly Row[];\n /** How much of the loaded rows is selected, for a header checkbox. */\n pageState: \"none\" | \"some\" | \"all\";\n isSelected: (id: string) => boolean;\n /** Flip one row; with `range` (shift-click) select from the last toggled row to this one. */\n toggle: (id: string, opts?: { range?: boolean }) => void;\n /** Select (`true`) or clear (`false`) every loaded row. */\n setPage: (on: boolean) => void;\n /** Select every row that matches the filter, loaded or not. */\n selectAllMatching: () => void;\n /** Keep exactly these ids selected (id mode). */\n setIds: (ids: readonly string[]) => void;\n /** Select nothing. */\n clear: () => void;\n}\n\nexport interface UseRowSelectionOptions {\n /** The loaded rows, in the order they are drawn: what a range and \"the page\" cover. */\n rows: readonly Row[];\n /** The list's total; `null` when the source does not count. */\n total: number | null;\n /**\n * Changes when the selection no longer applies: the collection or the\n * filter (search, chips, the filter tree, the host's filter). A sort, a\n * refetch or another page loading keep the key, and the selection.\n */\n resetKey: string;\n}\n\n/** One list's selection, cleared whenever `resetKey` changes. */\nexport function useRowSelection({ rows, total, resetKey }: UseRowSelectionOptions): RowSelection {\n const [held, setHeld] = useState<{ key: string; state: RowSelectionState }>({\n key: resetKey,\n state: EMPTY_SELECTION,\n });\n // A new key reads as empty at once (no effect, no frame with a stale selection).\n const state = held.key === resetKey ? held.state : EMPTY_SELECTION;\n const latest = useRef({ rows, resetKey });\n latest.current = { rows, resetKey };\n // Rows selected while loaded, so `rows` still names them after a refetch drops them.\n const known = useRef(new Map<string, Row>());\n for (const r of rows) if (known.current.has(idOf(r))) known.current.set(idOf(r), r);\n\n const update = useCallback(\n (f: (s: RowSelectionState, rows: readonly Row[]) => RowSelectionState) => {\n const { rows: now, resetKey: key } = latest.current;\n setHeld((h) => ({ key, state: f(h.key === key ? h.state : EMPTY_SELECTION, now) }));\n },\n [],\n );\n\n const toggle = useCallback(\n (id: string, opts?: { range?: boolean }) =>\n update((s, now) => (opts?.range ? selectRange(s, now, id) : toggleSelection(s, id))),\n [update],\n );\n const setPage = useCallback(\n (on: boolean) => update((s, now) => setPageSelection(s, now, on)),\n [update],\n );\n const selectAll = useCallback(() => update(() => selectAllMatching()), [update]);\n const setIds = useCallback(\n (ids: readonly string[]) => update(() => ({ mode: \"ids\", ids: new Set(ids), anchor: null })),\n [update],\n );\n const clear = useCallback(() => update(() => EMPTY_SELECTION), [update]);\n\n return useMemo(() => {\n const byId = new Map(rows.map((r) => [idOf(r), r] as const));\n let selectedRows: Row[];\n if (state.mode === \"ids\") {\n selectedRows = [];\n for (const id of state.ids) {\n const r = byId.get(id) ?? known.current.get(id);\n if (r) selectedRows.push(r);\n }\n } else {\n selectedRows = rows.filter((r) => !state.except.has(idOf(r)));\n }\n // Remember what is selected now; forget what is not.\n const keep = new Map<string, Row>();\n for (const r of selectedRows) keep.set(idOf(r), r);\n known.current = keep;\n return {\n mode: state.mode,\n ids: state.mode === \"ids\" ? [...state.ids] : [],\n exceptIds: state.mode === \"matching\" ? [...state.except] : [],\n count: selectionCount(state, total),\n isEmpty: selectionIsEmpty(state),\n rows: selectedRows,\n pageState: pageSelectionState(state, rows),\n isSelected: (id: string) => selectionHas(state, id),\n toggle,\n setPage,\n selectAllMatching: selectAll,\n setIds,\n clear,\n };\n }, [state, rows, total, toggle, setPage, selectAll, setIds, clear]);\n}\n"],"mappings":";;;AAmBA,IAAa,kBAAqC,OAAO,OAAO;CAC9D,MAAM;CACN,qBAAK,IAAI,IAAY;CACrB,QAAQ;AACV,CAAC;AAED,IAAM,QAAQ,MAAW,EAAE,OAAO;;AAGlC,SAAgB,aAAa,GAAsB,IAAqB;CACtE,OAAO,EAAE,SAAS,QAAQ,EAAE,IAAI,IAAI,EAAE,IAAI,CAAC,EAAE,OAAO,IAAI,EAAE;AAC5D;;AAGA,SAA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M;EAAO;EAAQ;EAAS;EAAW;EAAQ;CAAK,CAAC;AACpE"}
@@ -1,9 +1,9 @@
1
1
  import { useI18n } from "../i18n/i18n.js";
2
2
  import { useUdcSchema } from "../udc/hooks.js";
3
3
  import { useUiKit } from "../ui-kit/context.js";
4
+ import { isUdcError } from "@jsudc/core";
4
5
  import { useState } from "react";
5
6
  import { AlertTriangle, Trash2 } from "lucide-react";
6
- import { isUdcError } from "@jsudc/core";
7
7
  import { jsx, jsxs } from "react/jsx-runtime";
8
8
  // src/schema-editor/DeleteFieldDialog.tsx
9
9
  /** Confirms a soft delete: the column goes, the data stays. */
@@ -4,9 +4,9 @@ import { useUdcSchema } from "../udc/hooks.js";
4
4
  import { useUiKit } from "../ui-kit/context.js";
5
5
  import { FORM_TYPES, draftFromDef, draftToFieldDef, emptyDraft, nameProblem, suggestName, typeControls, validateDraft } from "./fieldForm.js";
6
6
  import { TagInput } from "./TagInput.js";
7
+ import { isUdcError } from "@jsudc/core";
7
8
  import { useId, useState } from "react";
8
9
  import { AlertTriangle, Lock } from "lucide-react";
9
- import { isUdcError } from "@jsudc/core";
10
10
  import { jsx, jsxs } from "react/jsx-runtime";
11
11
  // src/schema-editor/FieldFormDialog.tsx
12
12
  /**