@xeplr/ui-table 1.0.7 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,10 +34,10 @@ The changeset is exactly what [`@xeplr/base-apis`](https://www.npmjs.com/package
34
34
  ## Install
35
35
 
36
36
  ```sh
37
- npm i @xeplr/ui-table @tanstack/react-table
37
+ npm i @xeplr/ui-table @tanstack/react-table react-router-dom
38
38
  ```
39
39
 
40
- Peers: `react` 18 or 19, `@tanstack/react-table` 8. Filter panels use `createPortal` from `react-dom`.
40
+ Peers: `react` 18 or 19, `@tanstack/react-table` 8, `react-router-dom` 6 or 7 (the URL state below comes from [`@xeplr/ui-utils`](https://www.npmjs.com/package/@xeplr/ui-utils)' `useUrlState`, which imports it; without a router above the table, everything stays in memory). Filter panels use `createPortal` from `react-dom`.
41
41
 
42
42
  The package ships its `src/` as ES modules with JSX and imports its own stylesheet (`xeplr-table.css`), so it needs a bundler that compiles both — Vite does.
43
43
 
@@ -63,8 +63,10 @@ The package ships its `src/` as ES modules with JSX and imports its own styleshe
63
63
  | `headerStyle` | — | `({ columnKey, isGroupHeader, depth }) => style` |
64
64
  | `cellZoom` | `false` | double-click a cell to show it enlarged. Ignored when the schema has children shown as `'popup'`, where double-click opens the record |
65
65
  | `columnSizing` | fill | `'content'` sizes columns to their text |
66
+ | `columnWindowing` | `'auto'` | wide tables draw only the columns in view — see Column windowing. `'on'` / `'off'` force it |
66
67
  | `columnText`, `sizingSampleRows` (200), `minColumnWidth` (40), `maxColumnWidth` (420), `columnWidths`, `sizingKey`, `onColumnSizing` | | content sizing — see below |
67
68
  | `className` | — | added to the container |
69
+ | `urlKey` | — | prefix for the query keys that keep the open record and modal in the URL — see below. Omit it and they stay in memory |
68
70
 
69
71
  Toolbar slots receive `{ rowCount, totalCount, selectedCount, resetFilters, resetSorting, enableFiltering }` — `rowCount` after filtering, `totalCount` before.
70
72
 
@@ -134,6 +136,26 @@ Children (a schema with level 1): in `'popup'` mode, double-click or view opens
134
136
 
135
137
  Without `onCommit` there are no checkboxes, toolbar edit buttons or built-in row actions.
136
138
 
139
+ ### Where you are lives in the URL: `urlKey`
140
+
141
+ The record detail popup and the view / edit / add / copy modal are places a person navigates to, so with `urlKey` they are written to the URL's query and a refresh or a shared link lands on them again:
142
+
143
+ | key | holds | example |
144
+ |---|---|---|
145
+ | `<urlKey>Row` | the id of the row open in the detail popup | `?ordersRow=17` |
146
+ | `<urlKey>Edit` | the modal: mode, then the record — for a child record, the root id and the path to it first | `?ordersEdit=edit:17`, `?ordersEdit=add`, `?ordersEdit=view:17/employees/e6` |
147
+
148
+ ```jsx
149
+ <XeplrTable urlKey="orders" data={orders} schema={schema} onCommit={save} />
150
+ ```
151
+
152
+ - **The key is the host's, never a default.** One page can render several tables, and the host app has its own keys, so the table only writes the URL when given a prefix — give each table on a page its own. **Without `urlKey` both stay in memory**, behaving as before.
153
+ - **Ids, not rows.** The URL holds the row's id (`_tempId` for an unsaved row), and the row is looked up in the current rows on every render, so a link opened before the data has loaded lands once it arrives — and a row that is gone opens nothing. Rows need an `id` for this, as for editing. An unsaved row's `_tempId` does not survive a refresh, because the staged changes do not.
154
+ - **The form being typed is not in the URL.** Reopening a record starts from the row again.
155
+ - **Opening or closing** adds a history entry, so Back closes the popup or modal; switching an open modal (View → Edit) replaces it.
156
+ - Needs a router above the table (`react-router-dom`). The rule is in `src/tableUrlState.js` (`tableUrlKeys`, `encodeModal`, `decodeModal`, `resolvePlace`).
157
+ - `useActionsController({ …, urlKey })` takes the same option when you build your own table around the controller.
158
+
137
159
  ### The changeset
138
160
 
139
161
  Sparse, nested by child `key`:
@@ -210,6 +232,18 @@ Numeric strings compare as numbers. A host `cellStyle` prop result is merged ove
210
232
 
211
233
  Each renderer is `(config) => (ctx) => node`. The `renderers` object is the registry the table reads, so `renderers.myType = (config) => (ctx) => …` adds one.
212
234
 
235
+ ## Column windowing
236
+
237
+ Rows are paged; columns are not. So a wide table (a pivot of a date by day over a year: 1,095 columns) built every cell of the page at once, and that froze the browser. With `columnWindowing: 'auto'` (the default), a table with **more than 60 leaf columns** draws only:
238
+ - the columns in view, plus 6 on each side
239
+ - one spacer cell at each edge, holding the width of the rest
240
+
241
+ The scrollbar, the scroll position and the layout are the full table's. Scrolling sideways redraws the window, once per frame. A grouped header (a date over its measures) is cut to the part in view.
242
+
243
+ - **Widths:** the measured ones under `columnSizing: 'content'` (pinned `columnWidths` included); otherwise 140px, or `minColumnWidth` if larger. A windowed table is always fixed-layout at exactly those widths.
244
+ - **Rule:** the arithmetic is in `src/columnWindow.js` (`columnWindow`, `windowHeaders`, `shouldWindowColumns`), pure and tested on its own.
245
+ - **Limitation:** columns off screen are not in the DOM, so the browser's find-in-page does not see them.
246
+
213
247
  ## Content sizing
214
248
 
215
249
  `columnSizing="content"` measures each column's text (canvas, at the table's font) over the first `sizingSampleRows` rows of `data` — not the current page, so columns do not jump when paging.
@@ -252,7 +286,7 @@ There is no margin property: a `<td>` ignores margin.
252
286
  npm test
253
287
  ```
254
288
 
255
- Plain Node, no browser: changeset building, conditional-style parsing, style-layer resolution, column-width allocation, and the staging logic behind `useActionsController`. A Vite demo lives in `demo/`.
289
+ Plain Node, no browser: changeset building, conditional-style parsing, style-layer resolution, column-width allocation, the staging logic behind `useActionsController`, and the URL state: the key format (`test/tableUrlState.test.js`) and the controller reading its places back from a real `MemoryRouter`, and every opener, close and save played through in memory, rendered with `react-dom/server` (`test/actionsUrlState.test.js`). A Vite demo lives in `demo/`.
256
290
 
257
291
  ## License
258
292
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/ui-table",
3
- "version": "1.0.7",
3
+ "version": "1.1.0",
4
4
  "description": "Controlled TanStack Table wrapper with auto-detected column types and smart filters",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -26,8 +26,12 @@
26
26
  "publishConfig": {
27
27
  "access": "public"
28
28
  },
29
+ "dependencies": {
30
+ "@xeplr/ui-utils": "^1.1.2"
31
+ },
29
32
  "peerDependencies": {
30
33
  "react": "^18.0.0 || ^19.0.0",
31
- "@tanstack/react-table": "^8.0.0"
34
+ "@tanstack/react-table": "^8.0.0",
35
+ "react-router-dom": "^6.0.0 || ^7.0.0"
32
36
  }
33
37
  }
@@ -3,6 +3,7 @@ import { flexRender } from '@tanstack/react-table';
3
3
  import useTableController from './useTableController.js';
4
4
  import useActionsController from './useActionsController.js';
5
5
  import useColumnWidths from './useColumnWidths.js';
6
+ import { shouldWindowColumns, columnWindow, windowHeaders, DEFAULT_WINDOW_COLUMN_WIDTH } from './columnWindow.js';
6
7
  import CellZoom from './CellZoom.jsx';
7
8
  import { TYPES } from './detectTypes.js';
8
9
  import StringFilter from './filters/StringFilter.jsx';
@@ -68,6 +69,12 @@ var CHILD_DISPLAY = { POPUP: 'popup', INNER: 'inner' };
68
69
  * the container, as a table always has. 'content' instead sizes each column
69
70
  * to its text at the current font, and leaves any width it doesn't need
70
71
  * blank rather than stretching to fill. See columnWidths.js for the rule.
72
+ * @param {string} [props.columnWindowing] - 'auto' (default): a table
73
+ * with more than 60 columns draws only the ones in view, plus a margin, and
74
+ * holds the rest of the width in a spacer each side — a 1,000-column pivot
75
+ * costs what a 30-column one does. 'on' always, 'off' never. Widths are the
76
+ * measured ones under 'content' sizing (and `columnWidths`), otherwise 140px
77
+ * (or `minColumnWidth`, if larger). See columnWindow.js.
71
78
  * @param {Function} [props.columnText] - (row, column) => string.
72
79
  * Only used by 'content' sizing, and only worth passing if cells are
73
80
  * formatted: measuring 36260.8 when the screen shows ₹36,260.80 sizes the
@@ -125,6 +132,10 @@ var CHILD_DISPLAY = { POPUP: 'popup', INNER: 'inner' };
125
132
  * longer belongs to. Resolved by the host from the same vocabulary
126
133
  * (tableStyles.js); this component only applies what it's handed.
127
134
  * @param {string} [props.className] - Additional CSS class
135
+ * @param {string} [props.urlKey] - Prefix for the query keys
136
+ * that keep the open record detail (`<urlKey>Row`) and record modal
137
+ * (`<urlKey>Edit`) in the URL, so a refresh or shared link reopens them.
138
+ * Omit it and they stay in memory. Give each table on a page its own.
128
139
  * @param {Function} [props.onCommit] - async (changeSet[]) => void
129
140
  * @param {Array<{key: string, label: string, icon?: any, onClick: (row) => void,
130
141
  * visible?: (row) => boolean, disabled?: (row) => boolean, variant?: string}>} [props.rowActions]
@@ -146,7 +157,8 @@ export default function XeplrTable(props) {
146
157
  var actions = useActionsController({
147
158
  onCommit: props.onCommit,
148
159
  schema: schema,
149
- data: props.data
160
+ data: props.data,
161
+ urlKey: props.urlKey
150
162
  });
151
163
 
152
164
  var { table, detectedTypes, resetFilters, resetSorting } = useTableController({
@@ -228,6 +240,63 @@ export default function XeplrTable(props) {
228
240
  });
229
241
  var sizing = widths.sizing;
230
242
 
243
+ // ── Column windowing (columnWindow.js) ──
244
+ // Rows are paged; columns were all drawn, and a pivot by day over a year
245
+ // (1,095 columns × 100 rows) froze the page. Above the threshold only the
246
+ // columns in view are drawn. Hooks run unconditionally; the work is skipped
247
+ // when the table is narrow.
248
+ var leafColumns = table.getVisibleLeafColumns();
249
+ var windowing = shouldWindowColumns(leafColumns.length, props.columnWindowing);
250
+ var fallbackWidth = Math.max(DEFAULT_WINDOW_COLUMN_WIDTH, props.minColumnWidth || 0);
251
+ var leafWidths = windowing
252
+ ? leafColumns.map(function(c, i) {
253
+ var measured = sizing && sizing.widths ? sizing.widths[i] : null;
254
+ return measured > 0 ? measured : fallbackWidth;
255
+ })
256
+ : null;
257
+ var [scrollView, setScrollView] = useState({ left: 0, width: 0 });
258
+ useLayoutEffect(function() {
259
+ if (!windowing) return undefined;
260
+ var el = widths.scrollRef.current;
261
+ if (!el) return undefined;
262
+ var frame = 0;
263
+ function read() {
264
+ frame = 0;
265
+ var next = { left: el.scrollLeft, width: el.clientWidth };
266
+ setScrollView(function(prev) { return prev.left === next.left && prev.width === next.width ? prev : next; });
267
+ }
268
+ // One read per frame however fast the scroll events come.
269
+ function onScroll() { if (!frame) frame = requestAnimationFrame(read); }
270
+ read();
271
+ el.addEventListener('scroll', onScroll, { passive: true });
272
+ var observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(onScroll);
273
+ if (observer) observer.observe(el);
274
+ return function() {
275
+ el.removeEventListener('scroll', onScroll);
276
+ if (observer) observer.disconnect();
277
+ if (frame) cancelAnimationFrame(frame);
278
+ };
279
+ }, [windowing, widths.scrollRef]);
280
+ var extraLeading = (showExpandCol ? ((sizing && sizing.extraWidths.expand) || 36) : 0) +
281
+ (actions.hasDelete ? ((sizing && sizing.extraWidths.checkbox) || 40) : 0);
282
+ var extraTrailing = hasRowActions ? ((sizing && sizing.extraWidths.actions) || 80) : 0;
283
+ var win = windowing
284
+ ? columnWindow({ widths: leafWidths, scrollLeft: scrollView.left, viewportWidth: scrollView.width, leadingWidth: extraLeading })
285
+ : null;
286
+ var windowedTableWidth = windowing
287
+ ? extraLeading + extraTrailing + leafWidths.reduce(function(sum, w) { return sum + w; }, 0)
288
+ : 0;
289
+ // Each header row cut to the window — or the row as it is.
290
+ function headersOf(headerGroup) {
291
+ return win
292
+ ? windowHeaders(headerGroup.headers, win.start, win.end)
293
+ : headerGroup.headers.map(function(h) { return { header: h, colSpan: h.colSpan }; });
294
+ }
295
+ function cellsOf(row) {
296
+ var cells = row.getVisibleCells();
297
+ return win ? cells.slice(win.start, win.end) : cells;
298
+ }
299
+
231
300
  // PER-COLUMN CLASS, resolved by leaf index — the same index `columnWidths`
232
301
  // uses, so a host that pins column 3 highlights column 3 without a second
233
302
  // way of naming it. Header and body share one answer: a selected column is
@@ -258,7 +327,9 @@ export default function XeplrTable(props) {
258
327
  enableFiltering: enableFiltering
259
328
  };
260
329
 
261
- var totalColumns = headerGroups[0]?.headers.length || 1;
330
+ var totalColumns = win
331
+ ? (win.end - win.start) + (win.before > 0 ? 1 : 0) + (win.after > 0 ? 1 : 0) || 1
332
+ : headerGroups[0]?.headers.length || 1;
262
333
  if (showExpandCol) totalColumns++;
263
334
  if (actions.hasDelete) totalColumns++;
264
335
  if (hasRowActions) totalColumns++;
@@ -359,10 +430,22 @@ export default function XeplrTable(props) {
359
430
  table edge instead of being stretched across empty space. */}
360
431
  <table
361
432
  ref={widths.tableRef}
362
- className={'xeplr-table' + (sizing ? ' xeplr-table-sized' : '') + (props.cellStyle ? ' xeplr-table-styled' : '')}
363
- style={sizing ? { width: sizing.tableWidth + 'px' } : undefined}
433
+ className={'xeplr-table' + (sizing || win ? ' xeplr-table-sized' : '') + (win ? ' xeplr-table-windowed' : '') + (props.cellStyle ? ' xeplr-table-styled' : '')}
434
+ style={win ? { width: windowedTableWidth + 'px' } : (sizing ? { width: sizing.tableWidth + 'px' } : undefined)}
364
435
  >
365
- {sizing && (
436
+ {win ? (
437
+ <colgroup>
438
+ {showExpandCol && <col style={{ width: ((sizing && sizing.extraWidths.expand) || 36) + 'px' }} />}
439
+ {actions.hasDelete && <col style={{ width: ((sizing && sizing.extraWidths.checkbox) || 40) + 'px' }} />}
440
+ {win.before > 0 && <col style={{ width: win.before + 'px' }} />}
441
+ {leafWidths.slice(win.start, win.end).map(function(width, i) {
442
+ var leaf = leafColumns[win.start + i];
443
+ return <col key={leaf ? leaf.id : win.start + i} style={{ width: width + 'px' }} />;
444
+ })}
445
+ {win.after > 0 && <col style={{ width: win.after + 'px' }} />}
446
+ {hasRowActions && <col style={{ width: extraTrailing + 'px' }} />}
447
+ </colgroup>
448
+ ) : sizing && (
366
449
  <colgroup>
367
450
  {showExpandCol && <col style={{ width: (sizing.extraWidths.expand || 36) + 'px' }} />}
368
451
  {actions.hasDelete && <col style={{ width: (sizing.extraWidths.checkbox || 40) + 'px' }} />}
@@ -391,7 +474,9 @@ export default function XeplrTable(props) {
391
474
  onChange={function() { actions.toggleSelectAll(visibleIds); }} />
392
475
  </th>
393
476
  )}
394
- {headerGroup.headers.map(function(header) {
477
+ {win && win.before > 0 && <th className="xeplr-table-th xeplr-table-col-spacer" aria-hidden="true" style={{ top: stickyTop }} />}
478
+ {headersOf(headerGroup).map(function(item) {
479
+ var header = item.header;
395
480
  var canSort = header.column.getCanSort();
396
481
  var sorted = header.column.getIsSorted();
397
482
  var dataType = header.column.columnDef.meta?.dataType || TYPES.STRING;
@@ -430,7 +515,7 @@ export default function XeplrTable(props) {
430
515
  // before. It only widens for a GROUP header (a pivoted
431
516
  // date spanning the measures under it), which is what
432
517
  // TanStack computed it for.
433
- <th key={header.id} colSpan={header.colSpan} className={thClass}
518
+ <th key={header.id} colSpan={item.colSpan} className={thClass}
434
519
  // The host's header style sits UNDER `top`, so a
435
520
  // sticky header stays stuck whatever it is styled with.
436
521
  style={Object.assign(
@@ -462,6 +547,7 @@ export default function XeplrTable(props) {
462
547
  </th>
463
548
  );
464
549
  })}
550
+ {win && win.after > 0 && <th className="xeplr-table-th xeplr-table-col-spacer" aria-hidden="true" style={{ top: stickyTop }} />}
465
551
  {hasRowActions && (
466
552
  <th className="xeplr-table-th xeplr-table-th-actions" style={{ top: stickyTop }}>
467
553
  <div className="xeplr-table-header-cell">
@@ -518,7 +604,8 @@ export default function XeplrTable(props) {
518
604
  onChange={function() { actions.toggleSelect(rowId); }} />
519
605
  </td>
520
606
  )}
521
- {row.getVisibleCells().map(function(cell) {
607
+ {win && win.before > 0 && <td className="xeplr-table-td xeplr-table-col-spacer" aria-hidden="true" />}
608
+ {cellsOf(row).map(function(cell) {
522
609
  var meta = cell.column.columnDef.meta;
523
610
  var cellStyleDef = meta?.cellStyle;
524
611
  var condStyle = cellStyleDef
@@ -568,6 +655,7 @@ export default function XeplrTable(props) {
568
655
  </td>
569
656
  );
570
657
  })}
658
+ {win && win.after > 0 && <td className="xeplr-table-td xeplr-table-col-spacer" aria-hidden="true" />}
571
659
  {hasRowActions && (
572
660
  <td className="xeplr-table-td xeplr-table-td-actions">
573
661
  <ActionsCell row={original} hasSave={actions.hasSave} hasDelete={actions.hasDelete}
@@ -0,0 +1,97 @@
1
+ // COLUMN WINDOWING — which columns of a wide table are worth drawing.
2
+ //
3
+ // Rows are already bounded: the table pages them. Columns were not: a pivot
4
+ // of a date by day over a year is 1,095 columns, and 100 rows of it is over a
5
+ // hundred thousand cells, built all at once, which froze the page. Only the
6
+ // columns in view (plus a margin) are drawn; one spacer cell on each side
7
+ // holds the width of everything left out, so the scrollbar, the scroll
8
+ // position and the layout are exactly what the full table would have.
9
+ //
10
+ // Pure functions — no React, no DOM — so the arithmetic is tested on its own.
11
+
12
+ /** Above this many leaf columns windowing switches on (with `columnWindowing: 'auto'`). */
13
+ export var COLUMN_WINDOW_THRESHOLD = 60;
14
+
15
+ /** Width of a column the table has not measured (no content sizing). */
16
+ export var DEFAULT_WINDOW_COLUMN_WIDTH = 140;
17
+
18
+ /** Columns drawn beyond each edge of the view, so a scroll never shows a blank. */
19
+ export var COLUMN_WINDOW_OVERSCAN = 6;
20
+
21
+ /**
22
+ * Whether a table with `leafCount` columns draws only its visible ones.
23
+ * @param {number} leafCount
24
+ * @param {'auto'|'on'|'off'} [mode='auto']
25
+ */
26
+ export function shouldWindowColumns(leafCount, mode) {
27
+ if (mode === 'off') return false;
28
+ if (mode === 'on') return leafCount > 0;
29
+ return leafCount > COLUMN_WINDOW_THRESHOLD;
30
+ }
31
+
32
+ /**
33
+ * The run of columns to draw.
34
+ *
35
+ * @param {object} o
36
+ * @param {number[]} o.widths - every leaf column's width, in order (px)
37
+ * @param {number} o.scrollLeft - the scroll port's scrollLeft
38
+ * @param {number} o.viewportWidth - the scroll port's clientWidth
39
+ * @param {number} [o.leadingWidth=0] - fixed columns before the data ones (expand, checkbox)
40
+ * @param {number} [o.overscan] - columns past each edge
41
+ * @returns {{ start: number, end: number, before: number, after: number }}
42
+ * `end` is exclusive; `before`/`after` are the widths the spacers hold.
43
+ */
44
+ export function columnWindow(o) {
45
+ var widths = o.widths || [];
46
+ var n = widths.length;
47
+ if (!n) return { start: 0, end: 0, before: 0, after: 0 };
48
+ var overscan = o.overscan === undefined ? COLUMN_WINDOW_OVERSCAN : o.overscan;
49
+ // Before the first measure there is no viewport yet: draw a screenful at
50
+ // the left rather than nothing.
51
+ var viewport = o.viewportWidth > 0 ? o.viewportWidth : 1600;
52
+ var left = Math.max(0, (o.scrollLeft || 0) - (o.leadingWidth || 0));
53
+ var right = left + viewport;
54
+
55
+ var x = 0;
56
+ var first = n - 1;
57
+ var last = n - 1;
58
+ var foundFirst = false;
59
+ for (var i = 0; i < n; i++) {
60
+ var w = widths[i] || 0;
61
+ if (!foundFirst && x + w > left) { first = i; foundFirst = true; }
62
+ if (x >= right) { last = i - 1; break; }
63
+ x += w;
64
+ }
65
+ if (!foundFirst) first = n - 1;
66
+ if (last < first) last = first;
67
+
68
+ var start = Math.max(0, first - overscan);
69
+ var end = Math.min(n, last + 1 + overscan);
70
+ var before = 0;
71
+ var after = 0;
72
+ for (var b = 0; b < start; b++) before += widths[b] || 0;
73
+ for (var a = end; a < n; a++) after += widths[a] || 0;
74
+ return { start: start, end: end, before: before, after: after };
75
+ }
76
+
77
+ /**
78
+ * A header row cut to the window: each header that reaches into [start, end)
79
+ * with its colSpan reduced to the part inside. Headers of one row cover the
80
+ * leaf columns contiguously, in order (TanStack pads every row to full width),
81
+ * which is what lets the leaf range of each be found by adding up spans.
82
+ *
83
+ * @param {Array<{ colSpan: number }>} headers
84
+ * @returns {Array<{ header: object, colSpan: number }>}
85
+ */
86
+ export function windowHeaders(headers, start, end) {
87
+ var out = [];
88
+ var at = 0;
89
+ for (var i = 0; i < headers.length; i++) {
90
+ var span = headers[i].colSpan || 1;
91
+ var from = Math.max(at, start);
92
+ var to = Math.min(at + span, end);
93
+ if (to > from) out.push({ header: headers[i], colSpan: to - from });
94
+ at += span;
95
+ }
96
+ return out;
97
+ }
@@ -0,0 +1,127 @@
1
+ // WHERE YOU ARE IN A TABLE LIVES IN THE URL — the pure half, no React.
2
+ //
3
+ // The record detail popup and the view / edit / add / copy modal are places a
4
+ // person navigates to, so a refresh or a shared link must land on them again.
5
+ // The URL holds only what NAMES the place — the row's id, the mode, the
6
+ // nesting path — never the row object or a half-typed form: rows are looked
7
+ // up again once they have loaded.
8
+ //
9
+ // Keys come from the host (`urlKey`), because one page can render several
10
+ // tables and a host app has keys of its own. Without one the table keeps
11
+ // these in memory, exactly as before.
12
+
13
+ /**
14
+ * The query keys a table writes, derived from the host's `urlKey`.
15
+ * `null` when there is none: the state then stays in memory.
16
+ *
17
+ * tableUrlKeys('orders') → { row: 'ordersRow', edit: 'ordersEdit' }
18
+ */
19
+ export function tableUrlKeys(urlKey) {
20
+ if (!urlKey) return null;
21
+ return { row: urlKey + 'Row', edit: urlKey + 'Edit' };
22
+ }
23
+
24
+ /** A row's identity, as the table uses it everywhere: `_tempId`, else `id`. */
25
+ export function rowKey(row) {
26
+ if (!row) return null;
27
+ var k = row._tempId || row.id;
28
+ return k === undefined || k === null || k === '' ? null : k;
29
+ }
30
+
31
+ /**
32
+ * The row whose id is `key`, or null. Compared as strings, because a key read
33
+ * back from the URL is always a string while a row's id may be a number.
34
+ */
35
+ export function findRowByKey(rows, key) {
36
+ if (key === null || key === undefined || key === '' || !rows) return null;
37
+ var want = String(key);
38
+ for (var i = 0; i < rows.length; i++) {
39
+ var k = rowKey(rows[i]);
40
+ if (k !== null && String(k) === want) return rows[i];
41
+ }
42
+ return null;
43
+ }
44
+
45
+ var MODES = { view: true, edit: true, add: true, copy: true };
46
+
47
+ /**
48
+ * A modal place → one query value.
49
+ *
50
+ * { mode: 'edit', id: 5 } → 'edit:5'
51
+ * { mode: 'add' } → 'add'
52
+ * { mode: 'view', rootId: 3, path: ['employees'], id: 'e6' } → 'view:3/employees/e6'
53
+ * { mode: 'add', rootId: 3, path: ['employees'] } → 'add:3/employees'
54
+ *
55
+ * Every segment is URI-encoded, so an id holding '/' or ':' still splits back
56
+ * apart exactly. A nested path alternates field, id, field (odd length), which
57
+ * is what tells a nested place from a parent one when it is read back.
58
+ */
59
+ export function encodeModal(place) {
60
+ if (!place || !MODES[place.mode]) return null;
61
+ var segs = [];
62
+ if (place.path && place.path.length) {
63
+ segs.push(place.rootId);
64
+ for (var i = 0; i < place.path.length; i++) segs.push(place.path[i]);
65
+ }
66
+ if (place.mode !== 'add') {
67
+ if (place.id === undefined || place.id === null || place.id === '') return null;
68
+ segs.push(place.id);
69
+ }
70
+ if (segs.length === 0) return place.mode;
71
+ return place.mode + ':' + segs.map(function(s) { return encodeURIComponent(String(s)); }).join('/');
72
+ }
73
+
74
+ /** The query value back to a modal place, or null when it is not one. */
75
+ export function decodeModal(value) {
76
+ if (!value || typeof value !== 'string') return null;
77
+ var colon = value.indexOf(':');
78
+ var mode = colon === -1 ? value : value.slice(0, colon);
79
+ if (!MODES[mode]) return null;
80
+ var segs = colon === -1 ? [] : value.slice(colon + 1).split('/').map(safeDecode);
81
+ if (segs.some(function(s) { return s === null || s === ''; })) return null;
82
+
83
+ var id = null;
84
+ if (mode !== 'add') {
85
+ if (segs.length === 0) return null;
86
+ id = segs.pop();
87
+ }
88
+ if (segs.length === 0) return { mode: mode, id: id, rootId: null, path: null };
89
+ // rootId + a path of odd length (field, id, field, …)
90
+ if (segs.length < 2 || (segs.length - 1) % 2 !== 1) return null;
91
+ return { mode: mode, id: id, rootId: segs[0], path: segs.slice(1) };
92
+ }
93
+
94
+ function safeDecode(s) {
95
+ try { return decodeURIComponent(s); } catch (e) { return null; }
96
+ }
97
+
98
+ /**
99
+ * A place in context terms the modal already uses: the root's REAL id (the
100
+ * URL holds a string; the queue matches on the row's own value) and a path
101
+ * whose id segments are the real ids too. Null while the rows it names have
102
+ * not loaded, or once they are gone.
103
+ *
104
+ * Returns { root, rows, context } where `rows` is the array the record lives
105
+ * in (the table's rows for a parent place).
106
+ */
107
+ export function resolvePlace(rows, place) {
108
+ if (!place) return null;
109
+ if (!place.path) return { rows: rows || [], context: { level: 'parent' } };
110
+ var root = findRowByKey(rows, place.rootId);
111
+ if (!root) return null;
112
+ var realPath = [];
113
+ var current = root;
114
+ for (var i = 0; i < place.path.length; i++) {
115
+ if (i % 2 === 0) {
116
+ realPath.push(place.path[i]);
117
+ current = current ? current[place.path[i]] : null;
118
+ } else {
119
+ var hit = Array.isArray(current) ? findRowByKey(current, place.path[i]) : null;
120
+ if (!hit) return null;
121
+ realPath.push(rowKey(hit));
122
+ current = hit;
123
+ }
124
+ }
125
+ if (!Array.isArray(current)) current = [];
126
+ return { rows: current, context: { level: 'nested', rootId: rowKey(root), path: realPath } };
127
+ }
@@ -1,5 +1,7 @@
1
1
  import { useState, useCallback, useMemo, useRef } from 'react';
2
+ import { useUrlState } from '@xeplr/ui-utils/src/url/useUrlState.js';
2
3
  import { buildChangeSet } from './buildChangeSet.js';
4
+ import { tableUrlKeys, rowKey, findRowByKey, encodeModal, decodeModal, resolvePlace } from './tableUrlState.js';
3
5
 
4
6
  /**
5
7
  * Controller for table CRUD actions with transactional queue.
@@ -13,6 +15,11 @@ import { buildChangeSet } from './buildChangeSet.js';
13
15
  * @param {Function} [options.onCommit] - async (changeSet[]) => void
14
16
  * @param {object} options.schema - { 0: { key, columns }, 1: { key, columns }, ... }
15
17
  * @param {Array} options.data - Original data
18
+ * @param {string} [options.urlKey] - Prefix for the query keys that hold
19
+ * the open record detail (`<urlKey>Row`) and modal (`<urlKey>Edit`), so a
20
+ * refresh or a shared link reopens them. Without it they stay in memory —
21
+ * a page can render several tables, and only the host knows which keys are
22
+ * free (see tableUrlState.js).
16
23
  */
17
24
  export default function useActionsController(options) {
18
25
  var onCommit = options.onCommit || null;
@@ -133,74 +140,116 @@ export default function useActionsController(options) {
133
140
  });
134
141
  }, []);
135
142
 
143
+ // ── Where you are: in the URL when the host names the keys ──
144
+ // The detail popup and the modal are places; the query holds the row's id
145
+ // and the modal's mode + path, and both are resolved against the rows on
146
+ // every render — so a link opened before the rows arrive lands once they
147
+ // do. Without `urlKey` the same values live in memory (inUrl: false).
148
+ var urlKeys = tableUrlKeys(options.urlKey);
149
+ var inUrl = !!urlKeys;
150
+
136
151
  // ── Detail popup (for childDisplay === 'popup') ──
137
- var [detailRow, setDetailRow] = useState(null);
152
+ var [detailKey, setDetailKey] = useUrlState(inUrl ? urlKeys.row : 'row', { inUrl: inUrl });
153
+ var detailRow = useMemo(function() {
154
+ return findRowByKey(stagedData, detailKey);
155
+ }, [stagedData, detailKey]);
138
156
 
139
157
  var openDetail = useCallback(function(row) {
140
- setDetailRow(row);
141
- }, []);
158
+ setDetailKey(rowKey(row));
159
+ }, [setDetailKey]);
142
160
 
143
161
  var closeDetail = useCallback(function() {
144
- setDetailRow(null);
145
- }, []);
162
+ setDetailKey(null);
163
+ }, [setDetailKey]);
146
164
 
147
165
  // ── Modal ──
148
- // context: { level, schemaLevel, rootId?, path? }
149
- var [modal, setModal] = useState({ mode: null, record: null, context: null });
166
+ // context: { level, rootId?, path? }
167
+ // The URL names WHICH record in WHICH mode; the form being typed is a
168
+ // draft kept here, tied to the value it was started under, and dropped
169
+ // whenever a modal is opened or closed.
170
+ var [modalValue, setModalValue] = useUrlState(inUrl ? urlKeys.edit : 'edit', { inUrl: inUrl });
171
+ var [draft, setDraft] = useState({ value: null, record: null });
172
+
173
+ var opened = useMemo(function() {
174
+ var place = decodeModal(modalValue);
175
+ var where = resolvePlace(stagedData, place);
176
+ if (!where) return null;
177
+ var record;
178
+ if (place.mode === 'add') {
179
+ var level = where.context.path ? (where.context.path.length + 1) / 2 : 0;
180
+ record = buildEmptyRecord(schema, level, level === 0 ? data : where.rows);
181
+ } else {
182
+ var hit = findRowByKey(where.rows, place.id);
183
+ if (!hit) return null;
184
+ record = Object.assign({}, hit);
185
+ if (place.mode === 'copy') {
186
+ record.id = '';
187
+ delete record._tempId;
188
+ }
189
+ }
190
+ return { mode: place.mode === 'copy' ? 'add' : place.mode, record: record, context: where.context };
191
+ }, [modalValue, stagedData, schema, data]);
192
+
193
+ var hasDraft = !!opened && draft.value === modalValue && !!draft.record;
194
+ var modal = opened
195
+ ? { mode: opened.mode, record: hasDraft ? draft.record : opened.record, context: opened.context }
196
+ : { mode: null, record: null, context: null };
197
+
198
+ // Opening pushes a history entry, so Back closes it; switching an open
199
+ // modal (View → Edit) replaces the entry instead.
200
+ var openModal = useCallback(function(place) {
201
+ setDraft({ value: null, record: null });
202
+ setModalValue(encodeModal(place), { replace: !!modalValue });
203
+ }, [setModalValue, modalValue]);
150
204
 
151
205
  var openView = useCallback(function(row) {
152
- setModal({ mode: 'view', record: Object.assign({}, row), context: { level: 'parent' } });
153
- }, []);
206
+ openModal({ mode: 'view', id: rowKey(row) });
207
+ }, [openModal]);
154
208
 
155
209
  var openEdit = useCallback(function(row) {
156
- setModal({ mode: 'edit', record: Object.assign({}, row), context: { level: 'parent' } });
157
- }, []);
210
+ openModal({ mode: 'edit', id: rowKey(row) });
211
+ }, [openModal]);
158
212
 
159
213
  var openCopy = useCallback(function(row) {
160
- var copy = Object.assign({}, row);
161
- copy.id = '';
162
- delete copy._tempId;
163
- setModal({ mode: 'add', record: copy, context: { level: 'parent' } });
164
- }, []);
214
+ openModal({ mode: 'copy', id: rowKey(row) });
215
+ }, [openModal]);
165
216
 
166
217
  var openAdd = useCallback(function() {
167
- var empty = buildEmptyRecord(schema, 0, data);
168
- setModal({ mode: 'add', record: empty, context: { level: 'parent' } });
169
- }, [schema, data]);
218
+ openModal({ mode: 'add' });
219
+ }, [openModal]);
170
220
 
171
221
  // Nested modal openers
172
222
  var openNestedView = useCallback(function(rootId, path, row) {
173
- setModal({ mode: 'view', record: Object.assign({}, row), context: { level: 'nested', rootId: rootId, path: path } });
174
- }, []);
223
+ openModal({ mode: 'view', rootId: rootId, path: path, id: rowKey(row) });
224
+ }, [openModal]);
175
225
 
176
226
  var openNestedEdit = useCallback(function(rootId, path, row) {
177
- setModal({ mode: 'edit', record: Object.assign({}, row), context: { level: 'nested', rootId: rootId, path: path } });
178
- }, []);
227
+ openModal({ mode: 'edit', rootId: rootId, path: path, id: rowKey(row) });
228
+ }, [openModal]);
179
229
 
180
230
  var openNestedCopy = useCallback(function(rootId, path, row) {
181
- var copy = Object.assign({}, row);
182
- copy.id = '';
183
- delete copy._tempId;
184
- setModal({ mode: 'add', record: copy, context: { level: 'nested', rootId: rootId, path: path } });
185
- }, []);
231
+ openModal({ mode: 'copy', rootId: rootId, path: path, id: rowKey(row) });
232
+ }, [openModal]);
186
233
 
187
- var openNestedAdd = useCallback(function(rootId, path, schemaLevel) {
188
- var empty = buildEmptyRecord(schema, schemaLevel, findNestedArray(stagedData, rootId, path));
189
- setModal({ mode: 'add', record: empty, context: { level: 'nested', rootId: rootId, path: path } });
190
- }, [schema, stagedData]);
234
+ var openNestedAdd = useCallback(function(rootId, path) {
235
+ openModal({ mode: 'add', rootId: rootId, path: path });
236
+ }, [openModal]);
191
237
 
192
238
  var closeModal = useCallback(function() {
193
- setModal({ mode: null, record: null, context: null });
194
- }, []);
239
+ setDraft({ value: null, record: null });
240
+ setModalValue(null);
241
+ }, [setModalValue]);
195
242
 
243
+ var openRecord = opened ? opened.record : null;
196
244
  var updateField = useCallback(function(field, value) {
197
- setModal(function(prev) {
198
- if (!prev.record) return prev;
199
- var updated = Object.assign({}, prev.record);
245
+ setDraft(function(prev) {
246
+ var base = prev.value === modalValue && prev.record ? prev.record : openRecord;
247
+ if (!base) return prev;
248
+ var updated = Object.assign({}, base);
200
249
  updated[field] = value;
201
- return { mode: prev.mode, record: updated, context: prev.context };
250
+ return { value: modalValue, record: updated };
202
251
  });
203
- }, []);
252
+ }, [modalValue, openRecord]);
204
253
 
205
254
  // ── Queue: save ──
206
255
  var handleSave = useCallback(function() {
@@ -438,16 +487,3 @@ function buildEmptyRecord(schema, schemaLevel, existingRecords) {
438
487
  empty.id = '';
439
488
  return empty;
440
489
  }
441
-
442
- /**
443
- * Find the nested array for a given rootId and path in stagedData.
444
- */
445
- function findNestedArray(stagedData, rootId, path) {
446
- for (var i = 0; i < stagedData.length; i++) {
447
- var rid = stagedData[i]._tempId || stagedData[i].id;
448
- if (rid === rootId) {
449
- return navigatePath(stagedData[i], path) || [];
450
- }
451
- }
452
- return [];
453
- }
@@ -1057,3 +1057,14 @@
1057
1057
  cursor: pointer;
1058
1058
  user-select: none;
1059
1059
  }
1060
+
1061
+ /* ── Column windowing (columnWindow.js) ──
1062
+ The spacers hold the width of the columns not drawn, so the scrollbar and
1063
+ the layout are the full table's. They must hold width and nothing else. */
1064
+ .xeplr-table-col-spacer,
1065
+ .xeplr-table-th.xeplr-table-col-spacer,
1066
+ .xeplr-table-td.xeplr-table-col-spacer {
1067
+ padding: 0;
1068
+ border-left: none;
1069
+ border-right: none;
1070
+ }