@human-kit/ui 1.0.0 → 1.1.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.
@@ -9,7 +9,7 @@
9
9
  The table barrel exports the prop types of each public Table part.
10
10
 
11
11
  These are `TableRootProps`, `TableColumnProps`, `TableHeaderProps`, `TableBodyProps`,
12
- `TableFooterProps`, `TableRowProps`, `TableColumnHeaderCellProps`, `TableSortTriggerProps`,
12
+ `TableFooterProps`, `TableRowProps`, `TableSectionRowProps`, `TableColumnHeaderCellProps`, `TableSortTriggerProps`,
13
13
  `TableColumnResizerProps`, `TableCellProps`, `TableEmptyStateProps`, `TableCheckboxProps`,
14
14
  and `TableCheckboxIndicatorProps`.
15
15
 
@@ -82,6 +82,7 @@ and `TableCheckboxIndicatorProps`.
82
82
  - `Table.EmptyState`
83
83
  - `Table.Footer`
84
84
  - `Table.Row`
85
+ - `Table.SectionRow`
85
86
  - `Table.ColumnHeaderCell`
86
87
  - `Table.SortTrigger`
87
88
  - `Table.ColumnResizer`
@@ -124,9 +125,68 @@ and `TableCheckboxIndicatorProps`.
124
125
  - In body rows, pressing `ArrowLeft` before the first cell or `ArrowRight` after the last cell moves focus to the row itself. Repeating that same horizontal arrow loops back into the opposite edge cell of the same row.
125
126
  - `Table.Checkbox` is the supported interactive control inside table cells for explicit row selection in v1.
126
127
 
128
+ ## Grouped lists
129
+
130
+ Use `Table.SectionRow` to show a list in groups. A section row is a full-width header row between the body rows. It has one cell, and that cell covers all the visible columns, also the selection column.
131
+
132
+ Put the groups and their rows in one `items` array. In the `children` snippet of `Table.Body`, render a `Table.SectionRow` for each group item and a `Table.Row` for each other item. To close a group, remove its rows from `items`.
133
+
134
+ ```svelte
135
+ <script lang="ts">
136
+ type Item =
137
+ | { id: string; kind: 'group'; label: string; count: number }
138
+ | { id: string; kind: 'user'; email: string };
139
+
140
+ let collapsed = $state(new Set<string>());
141
+
142
+ const items = $derived(
143
+ groups.flatMap((group): Item[] => [
144
+ { id: `group-${group.name}`, kind: 'group', label: group.name, count: group.users.length },
145
+ ...(collapsed.has(group.name)
146
+ ? []
147
+ : group.users.map((user): Item => ({ id: user.id, kind: 'user', email: user.email })))
148
+ ])
149
+ );
150
+
151
+ function toggle(name: string) {
152
+ const next = new Set(collapsed);
153
+ if (next.has(name)) next.delete(name);
154
+ else next.add(name);
155
+ collapsed = next;
156
+ }
157
+ </script>
158
+
159
+ <Table.Body {items} isSectionItem={(item) => item.kind === 'group'}>
160
+ {#snippet children(item)}
161
+ {#if item.kind === 'group'}
162
+ <Table.SectionRow
163
+ id={item.id}
164
+ aria-expanded={!collapsed.has(item.label)}
165
+ onAction={() => toggle(item.label)}
166
+ >
167
+ <ChevronIcon />
168
+ {item.label}
169
+ <span>{item.count}</span>
170
+ </Table.SectionRow>
171
+ {:else}
172
+ <Table.Row id={item.id}>
173
+ <Table.Cell>{item.email}</Table.Cell>
174
+ </Table.Row>
175
+ {/if}
176
+ {/snippet}
177
+ </Table.Body>
178
+ ```
179
+
180
+ - A section row is a row for the keyboard. `ArrowUp` and `ArrowDown` move into it and out of it. Under `keyboardNavigation="grid"` its single cell takes the focus, and `Home`, `End`, `ArrowLeft` and `ArrowRight` keep the focus on that cell. Under `keyboardNavigation="row"` the row takes the focus, as other rows do.
181
+ - A section row is not a data row. It has no checkbox, and it is not in the selection. Select-all, the range selection with `Shift`, and the header checkbox do not include it.
182
+ - A click, `Enter` or `Space` calls `onAction` of the section row. The table does not call `onRowAction` for a section row.
183
+ - A mounted section row tells the table that it is a section row. With a virtualizer, also set `isSectionItem` on `Table.Body`, because the table does not know the section rows that are not mounted.
184
+ - With a virtualizer, set `sectionRowHeight` when a section row has a different height from `rowHeight`. This also needs `isSectionItem`. Give the rows the same heights in CSS.
185
+ - The cell is not sticky. In a table with pinned columns, add `sticky left-0` (or a similar class) to the content of the section row to keep it in view.
186
+
127
187
  ## Composition contract
128
188
 
129
- - DOM-rendering parts: `Table.Root`, `Table.Header`, `Table.Body`, `Table.Footer`, `Table.Row`, `Table.Cell`, `Table.InteractiveCell`, `Table.ColumnHeaderCell`, `Table.ColumnResizer`, `Table.Checkbox`, `Table.CheckboxIndicator`, and `Table.EmptyState` all render DOM.
189
+ - DOM-rendering parts: `Table.Root`, `Table.Header`, `Table.Body`, `Table.Footer`, `Table.Row`, `Table.SectionRow`, `Table.Cell`, `Table.InteractiveCell`, `Table.ColumnHeaderCell`, `Table.ColumnResizer`, `Table.Checkbox`, `Table.CheckboxIndicator`, and `Table.EmptyState` all render DOM.
130
190
  - Metadata-only part: `Table.Column` does not render its own element. It only registers the public column input for the surrounding header composition.
131
191
  - Sorting: `Table.SortTrigger` is the public opt-in for sortable columns. Rendering it inside `Table.ColumnHeaderCell` makes the owning `Table.Column` sortable and toggles `Table.Root.sortDescriptor`.
132
192
  - `Table.SortTrigger.children` can consume a `sortDirection` render state so the trigger button can expose stateful labels or visuals without reading the root descriptor directly.
@@ -9,6 +9,7 @@
9
9
  let {
10
10
  items,
11
11
  virtualizer,
12
+ isSectionItem,
12
13
  children,
13
14
  empty,
14
15
  class: className = '',
@@ -31,6 +32,17 @@
31
32
  };
32
33
  });
33
34
 
35
+ $effect(() => {
36
+ table.setSectionRowKeys(
37
+ isSectionItem && items
38
+ ? items.filter((item) => isSectionItem(item)).map((item) => item.id)
39
+ : undefined
40
+ );
41
+ return () => {
42
+ table.setSectionRowKeys(undefined);
43
+ };
44
+ });
45
+
34
46
  const itemList = $derived(items ?? []);
35
47
  const isItemsMode = $derived(items !== undefined);
36
48
  const virtualizerEnabled = $derived(Boolean(virtualizer && itemList.length > 0));
@@ -77,6 +89,39 @@
77
89
  return 18;
78
90
  });
79
91
 
92
+ /**
93
+ * Top offset of each item (and, last, the total height) when section rows
94
+ * have a height of their own. `undefined` keeps the uniform path, where the
95
+ * offsets are plain multiples of `rowHeight`.
96
+ */
97
+ const rowOffsets = $derived.by(() => {
98
+ if (!virtualizer || !virtualizerEnabled || !isSectionItem) return undefined;
99
+ const { rowHeight, sectionRowHeight } = virtualizer;
100
+ if (sectionRowHeight === undefined || sectionRowHeight === rowHeight) return undefined;
101
+
102
+ const offsets = new Float64Array(itemList.length + 1);
103
+ for (let index = 0; index < itemList.length; index += 1) {
104
+ const height = isSectionItem(itemList[index]) ? sectionRowHeight : rowHeight;
105
+ offsets[index + 1] = offsets[index] + height;
106
+ }
107
+ return offsets;
108
+ });
109
+
110
+ /** Index of the item whose box contains `offset` (the last one past the end). */
111
+ function findItemIndexAt(offsets: Float64Array, offset: number) {
112
+ let low = 0;
113
+ let high = offsets.length - 2;
114
+ while (low < high) {
115
+ const middle = Math.ceil((low + high) / 2);
116
+ if (offsets[middle] <= offset) {
117
+ low = middle;
118
+ } else {
119
+ high = middle - 1;
120
+ }
121
+ }
122
+ return low;
123
+ }
124
+
80
125
  // Plain (non-reactive) memo of the last window, used only to keep the derived
81
126
  // value's identity stable across recomputations that produce the same window.
82
127
  let lastVisibleRange:
@@ -94,8 +139,14 @@
94
139
 
95
140
  const rowHeight = virtualizer.rowHeight;
96
141
  const rowCount = itemList.length;
97
- const startIndex = Math.min(rowCount - 1, Math.floor(Math.max(0, scrollTop) / rowHeight));
98
- const endIndex = Math.min(rowCount - 1, startIndex + visibleCount - 1);
142
+ const offsets = rowOffsets;
143
+ const viewportTop = Math.max(0, scrollTop);
144
+ const startIndex = offsets
145
+ ? findItemIndexAt(offsets, viewportTop)
146
+ : Math.min(rowCount - 1, Math.floor(viewportTop / rowHeight));
147
+ const endIndex = offsets
148
+ ? findItemIndexAt(offsets, viewportTop + effectiveViewportHeight)
149
+ : Math.min(rowCount - 1, startIndex + visibleCount - 1);
99
150
 
100
151
  // Snap the window edges to a block boundary so scrolling *within* a block
101
152
  // leaves the rendered set identical.
@@ -130,8 +181,10 @@
130
181
  const from = Math.max(0, Math.floor(rawFrom / block) * block);
131
182
  const to = Math.max(from, Math.min(rowCount - 1, Math.ceil((rawTo + 1) / block) * block - 1));
132
183
 
133
- const topSpacerHeight = from * rowHeight;
134
- const bottomSpacerHeight = Math.max(0, (rowCount - to - 1) * rowHeight);
184
+ const topSpacerHeight = offsets ? offsets[from] : from * rowHeight;
185
+ const bottomSpacerHeight = offsets
186
+ ? Math.max(0, offsets[rowCount] - offsets[to + 1])
187
+ : Math.max(0, (rowCount - to - 1) * rowHeight);
135
188
 
136
189
  // Return the *same object* when nothing about the window changed. Scrolling
137
190
  // within a block recomputes this on every scroll event, and a fresh object
@@ -40,6 +40,15 @@
40
40
  // its width outwards; the physical shift direction depends on the layout
41
41
  // direction, resolved once the element mounts.
42
42
  const handleRtl = $derived(element ? isRightToLeft() : false);
43
+ // A column pinned to the inline end is held by that edge: it is the table's, or the next
44
+ // pinned column's, which paints over it — half the handle was covered and the drag found
45
+ // nothing there. Its free edge is the inline start, so the handle moves there and the drag
46
+ // reads mirrored: pulling it towards the start widens the column.
47
+ const atInlineStart = $derived(column.pin === 'right');
48
+ // Centred on the edge it sits on: half inside the column, half over its neighbour.
49
+ const handleTransform = $derived(
50
+ atInlineStart !== handleRtl ? 'translateX(-50%)' : 'translateX(50%)'
51
+ );
43
52
 
44
53
  let isFocused = $state(false);
45
54
  let isFocusVisible = $state(false);
@@ -336,7 +345,7 @@
336
345
 
337
346
  const pointerDelta = latestClientX - previousClientX;
338
347
  previousClientX = latestClientX;
339
- const widthDelta = isRTL ? -pointerDelta : pointerDelta;
348
+ const widthDelta = isRTL !== atInlineStart ? -pointerDelta : pointerDelta;
340
349
  dragWidth = clampWidth(dragWidth + widthDelta);
341
350
  const nextWidth = dragWidth;
342
351
  updateWidth(nextWidth);
@@ -531,7 +540,7 @@
531
540
  event.stopPropagation();
532
541
 
533
542
  const delta = event.shiftKey ? shiftStep : step;
534
- const direction = isRightToLeft() ? -1 : 1;
543
+ const direction = isRightToLeft() !== atInlineStart ? -1 : 1;
535
544
  const baseWidth = getResolvedWidth();
536
545
 
537
546
  switch (event.key) {
@@ -595,12 +604,13 @@
595
604
  data-resizing={isResizing ? 'true' : undefined}
596
605
  data-resizable={isResizable ? 'true' : undefined}
597
606
  data-table-column-resizer="true"
598
- data-resizable-direction="right"
607
+ data-resizable-direction={atInlineStart ? 'left' : 'right'}
599
608
  style:position="absolute"
600
609
  style:z-index="2"
601
610
  style:top="0"
602
- style:inset-inline-end="0"
603
- style:transform={handleRtl ? 'translateX(-50%)' : 'translateX(50%)'}
611
+ style:inset-inline-start={atInlineStart ? '0' : undefined}
612
+ style:inset-inline-end={atInlineStart ? undefined : '0'}
613
+ style:transform={handleTransform}
604
614
  style:width="0.75rem"
605
615
  style:height="100%"
606
616
  style:display="flex"
@@ -1,5 +1,5 @@
1
1
  export * as Table from './index.parts.js';
2
- export type { CellContext, CellProps, CellRenderer, ColumnDef, Row, RowData, TableBodyProps, TableBodyVirtualizer, TableCellProps, TableCheckboxIndicatorProps, TableCheckboxProps, TableColumnHeaderCellProps, TableColumnProps, TableColumnResizerProps, TableSortTriggerRenderState, TableSortTriggerProps, TableInteractiveCellProps, TableEmptyStateProps, TableFooterProps, TableHeaderProps, TableRowProps, TableRootProps } from './types.js';
2
+ export type { CellContext, CellProps, CellRenderer, ColumnDef, Row, RowData, TableBodyProps, TableBodyVirtualizer, TableCellProps, TableCheckboxIndicatorProps, TableCheckboxProps, TableColumnHeaderCellProps, TableColumnProps, TableColumnResizerProps, TableSortTriggerRenderState, TableSortTriggerProps, TableInteractiveCellProps, TableEmptyStateProps, TableFooterProps, TableHeaderProps, TableRowProps, TableRootProps, TableSectionRowProps } from './types.js';
3
3
  export { default as TableRoot } from './root/table-root.svelte';
4
4
  export { default as TableColumn } from './column/table-column.svelte';
5
5
  export { default as TableHeader } from './header/table-header.svelte';
@@ -7,6 +7,7 @@ export { default as TableBody } from './body/table-body.svelte';
7
7
  export { default as TableEmptyState } from './empty-state/table-empty-state.svelte';
8
8
  export { default as TableFooter } from './footer/table-footer.svelte';
9
9
  export { default as TableRow } from './row/table-row.svelte';
10
+ export { default as TableSectionRow } from './section-row/table-section-row.svelte';
10
11
  export { default as TableColumnHeaderCell } from './column-header-cell/table-column-header-cell.svelte';
11
12
  export { default as TableSortTrigger } from './sort-trigger/table-sort-trigger.svelte';
12
13
  export { default as TableColumnResizer } from './column-resizer/table-column-resizer.svelte';
@@ -6,6 +6,7 @@ export { default as TableBody } from './body/table-body.svelte';
6
6
  export { default as TableEmptyState } from './empty-state/table-empty-state.svelte';
7
7
  export { default as TableFooter } from './footer/table-footer.svelte';
8
8
  export { default as TableRow } from './row/table-row.svelte';
9
+ export { default as TableSectionRow } from './section-row/table-section-row.svelte';
9
10
  export { default as TableColumnHeaderCell } from './column-header-cell/table-column-header-cell.svelte';
10
11
  export { default as TableSortTrigger } from './sort-trigger/table-sort-trigger.svelte';
11
12
  export { default as TableColumnResizer } from './column-resizer/table-column-resizer.svelte';
@@ -5,6 +5,7 @@ export { default as Body } from './body/table-body.svelte';
5
5
  export { default as EmptyState } from './empty-state/table-empty-state.svelte';
6
6
  export { default as Footer } from './footer/table-footer.svelte';
7
7
  export { default as Row } from './row/table-row.svelte';
8
+ export { default as SectionRow } from './section-row/table-section-row.svelte';
8
9
  export { default as ColumnHeaderCell } from './column-header-cell/table-column-header-cell.svelte';
9
10
  export { default as SortTrigger } from './sort-trigger/table-sort-trigger.svelte';
10
11
  export { default as ColumnResizer } from './column-resizer/table-column-resizer.svelte';
@@ -5,6 +5,7 @@ export { default as Body } from './body/table-body.svelte';
5
5
  export { default as EmptyState } from './empty-state/table-empty-state.svelte';
6
6
  export { default as Footer } from './footer/table-footer.svelte';
7
7
  export { default as Row } from './row/table-row.svelte';
8
+ export { default as SectionRow } from './section-row/table-section-row.svelte';
8
9
  export { default as ColumnHeaderCell } from './column-header-cell/table-column-header-cell.svelte';
9
10
  export { default as SortTrigger } from './sort-trigger/table-sort-trigger.svelte';
10
11
  export { default as ColumnResizer } from './column-resizer/table-column-resizer.svelte';
@@ -85,6 +85,11 @@ type TableRowRegistration = {
85
85
  section: TableSectionKind;
86
86
  id?: TableSelectionKey;
87
87
  disabled: boolean;
88
+ /**
89
+ * Marks a `Table.SectionRow`: a full-width group header that takes part in
90
+ * focus navigation but never in selection or in `onRowAction`.
91
+ */
92
+ isSection?: boolean;
88
93
  element?: HTMLTableRowElement;
89
94
  };
90
95
  type TableCellRegistration = {
@@ -95,6 +100,12 @@ type TableCellRegistration = {
95
100
  columnToken?: string;
96
101
  element?: HTMLElement;
97
102
  focusDelegate?: () => HTMLElement | undefined;
103
+ /**
104
+ * The single cell of a `Table.SectionRow`. It spans every column, so it
105
+ * belongs to no column: it sits at the first visible column for navigation
106
+ * and never takes part in column measurement or column hiding.
107
+ */
108
+ spansRow?: boolean;
98
109
  };
99
110
  export type CreateTableContextOptions = {
100
111
  selectionMode?: TableSelectionMode;
@@ -191,6 +202,13 @@ export type TableContext = {
191
202
  registerRow: (row: TableRowRegistration) => void;
192
203
  unregisterRow: (token: string) => void;
193
204
  setLogicalBodyRows: (ids?: Iterable<TableSelectionKey>) => void;
205
+ /**
206
+ * Declares which logical body rows are section rows. `Table.Body` calls it
207
+ * from `isSectionItem`, so section rows a virtualizer has not mounted are
208
+ * still kept out of select-all and range selection.
209
+ */
210
+ setSectionRowKeys: (ids?: Iterable<TableSelectionKey>) => void;
211
+ isSectionRowKey: (id: TableSelectionKey | undefined) => boolean;
194
212
  markBodyRowsInitialized: () => void;
195
213
  getHeaderRowCount: () => number;
196
214
  getBodyRowCount: () => number;
@@ -86,6 +86,11 @@ export function createTableContext(options = {}) {
86
86
  let selectableBodyRowCount = 0;
87
87
  let logicalBodyRowIds = null;
88
88
  let logicalBodyRowIndexCache = null;
89
+ // Section row keys come from two places: the section rows that registered
90
+ // (kept after they unmount, so a virtualizer scrolling them away does not
91
+ // make them selectable again) and the keys `Table.Body` declares up front.
92
+ const registeredSectionRowKeys = new SvelteSet();
93
+ const declaredSectionRowKeys = new SvelteSet();
89
94
  const cells = new SvelteMap();
90
95
  const cellOrderSet = new SvelteSet();
91
96
  // Cell keys grouped by row, so dropping a row does not have to scan every
@@ -480,6 +485,7 @@ export function createTableContext(options = {}) {
480
485
  left.section === right.section &&
481
486
  left.id === right.id &&
482
487
  left.disabled === right.disabled &&
488
+ left.isSection === right.isSection &&
483
489
  left.element === right.element);
484
490
  }
485
491
  function sameCellRegistration(left, right) {
@@ -489,7 +495,8 @@ export function createTableContext(options = {}) {
489
495
  left.columnIndex === right.columnIndex &&
490
496
  left.columnToken === right.columnToken &&
491
497
  left.element === right.element &&
492
- left.focusDelegate === right.focusDelegate);
498
+ left.focusDelegate === right.focusDelegate &&
499
+ left.spansRow === right.spansRow);
493
500
  }
494
501
  function resolveCellTargetByKey(key) {
495
502
  return key ? (cells.get(key) ?? null) : null;
@@ -981,6 +988,8 @@ export function createTableContext(options = {}) {
981
988
  notifyWidth();
982
989
  }
983
990
  function getCellColumn(cell) {
991
+ if (cell.spansRow)
992
+ return undefined;
984
993
  if (cell.section === 'header' && cell.columnToken) {
985
994
  return columns.get(cell.columnToken);
986
995
  }
@@ -1220,18 +1229,23 @@ export function createTableContext(options = {}) {
1220
1229
  bodyRowOrderSet.delete(row.token);
1221
1230
  }
1222
1231
  const previousSelectableBodyRow = isSelectableBodyRow(existing);
1232
+ const sectionKeysChanged = syncRegisteredSectionRowKey(row);
1223
1233
  rows.set(row.token, row);
1224
1234
  if (targetOrder && targetOrderSet && !targetOrderSet.has(row.token)) {
1225
1235
  targetOrder.push(row.token);
1226
1236
  targetOrderSet.add(row.token);
1227
1237
  }
1228
1238
  const nextSelectableBodyRow = isSelectableBodyRow(row);
1229
- if (previousSelectableBodyRow !== nextSelectableBodyRow) {
1239
+ if (sectionKeysChanged) {
1240
+ recomputeSelectableBodyRowCount();
1241
+ }
1242
+ else if (previousSelectableBodyRow !== nextSelectableBodyRow) {
1230
1243
  selectableBodyRowCount += nextSelectableBodyRow ? 1 : -1;
1231
1244
  }
1232
- if ((selectedKeys.size > 0 &&
1233
- logicalBodyRowIds === null &&
1234
- (existing?.section === 'body' || row.section === 'body')) ||
1245
+ if (sectionKeysChanged ||
1246
+ (selectedKeys.size > 0 &&
1247
+ logicalBodyRowIds === null &&
1248
+ (existing?.section === 'body' || row.section === 'body')) ||
1235
1249
  (bodyRowsInitialized &&
1236
1250
  (previousSelectableBodyRowCount === 0) !== (selectableBodyRowCount === 0))) {
1237
1251
  notifySelection();
@@ -1262,9 +1276,57 @@ export function createTableContext(options = {}) {
1262
1276
  return;
1263
1277
  logicalBodyRowIds = nextIds;
1264
1278
  logicalBodyRowIndexCache = null;
1279
+ pruneRegisteredSectionRowKeys();
1265
1280
  notifyLayout();
1266
1281
  notifySelection();
1267
1282
  }
1283
+ /**
1284
+ * Records a section row's key, or forgets it when a regular row now owns
1285
+ * that key. Returns whether the set of section keys changed.
1286
+ */
1287
+ function syncRegisteredSectionRowKey(row) {
1288
+ if (row.section !== 'body' || row.id === undefined)
1289
+ return false;
1290
+ if (row.isSection) {
1291
+ if (registeredSectionRowKeys.has(row.id))
1292
+ return false;
1293
+ registeredSectionRowKeys.add(row.id);
1294
+ return true;
1295
+ }
1296
+ return registeredSectionRowKeys.delete(row.id);
1297
+ }
1298
+ // A registered section key outlives its row, so that an unmounted
1299
+ // (virtualized) section stays out of the selection. Once the key leaves the
1300
+ // logical rows altogether it no longer names a section of this table.
1301
+ function pruneRegisteredSectionRowKeys() {
1302
+ if (registeredSectionRowKeys.size === 0 || logicalBodyRowIds === null)
1303
+ return;
1304
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity -- a throwaway lookup, not state.
1305
+ const logicalKeys = new Set(logicalBodyRowIds);
1306
+ for (const key of [...registeredSectionRowKeys]) {
1307
+ if (!logicalKeys.has(key))
1308
+ registeredSectionRowKeys.delete(key);
1309
+ }
1310
+ }
1311
+ function setSectionRowKeys(ids) {
1312
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity -- a throwaway comparison, not state.
1313
+ const next = new Set(ids ?? []);
1314
+ if (hasSameSelection(declaredSectionRowKeys, next))
1315
+ return;
1316
+ declaredSectionRowKeys.clear();
1317
+ for (const key of next) {
1318
+ declaredSectionRowKeys.add(key);
1319
+ }
1320
+ recomputeSelectableBodyRowCount();
1321
+ invalidateLayoutCaches();
1322
+ notifyLayout();
1323
+ notifySelection();
1324
+ }
1325
+ function isSectionRowKey(id) {
1326
+ if (id === undefined)
1327
+ return false;
1328
+ return declaredSectionRowKeys.has(id) || registeredSectionRowKeys.has(id);
1329
+ }
1268
1330
  function unregisterRow(token) {
1269
1331
  defaultFocusKeyCache = undefined;
1270
1332
  const row = rows.get(token);
@@ -1273,6 +1335,11 @@ export function createTableContext(options = {}) {
1273
1335
  if (isSelectableBodyRow(row)) {
1274
1336
  selectableBodyRowCount = Math.max(0, selectableBodyRowCount - 1);
1275
1337
  }
1338
+ // Without logical rows nothing else can tell the key apart, so a manual
1339
+ // section row that unmounts takes its key with it.
1340
+ if (row?.isSection && row.id !== undefined && logicalBodyRowIds === null) {
1341
+ registeredSectionRowKeys.delete(row.id);
1342
+ }
1276
1343
  if (focusedRowTarget?.rowToken === token) {
1277
1344
  focusedRowTarget = null;
1278
1345
  }
@@ -1400,13 +1467,19 @@ export function createTableContext(options = {}) {
1400
1467
  }
1401
1468
  return rowIds;
1402
1469
  }
1403
- function isRowSelectionDisabled(id, localDisabled = false) {
1470
+ function isRowKeyDisabled(id, localDisabled = false) {
1404
1471
  if (localDisabled)
1405
1472
  return true;
1406
1473
  if (id === undefined)
1407
1474
  return false;
1408
1475
  return disabledKeys.has(id);
1409
1476
  }
1477
+ // A section row is never selectable, but it is not disabled either: it stays
1478
+ // focusable and keeps its own action. That is why this check, and not
1479
+ // `isRowKeyDisabled`, is the one that knows about sections.
1480
+ function isRowSelectionDisabled(id, localDisabled = false) {
1481
+ return isRowKeyDisabled(id, localDisabled) || isSectionRowKey(id);
1482
+ }
1410
1483
  function isSelectableBodyRow(row) {
1411
1484
  return (row?.section === 'body' &&
1412
1485
  row.id !== undefined &&
@@ -1422,13 +1495,16 @@ export function createTableContext(options = {}) {
1422
1495
  selectableBodyRowCount = nextSelectableBodyRowCount;
1423
1496
  }
1424
1497
  function isRowDisabled(id, localDisabled = false) {
1425
- return disabledBehavior === 'all' && isRowSelectionDisabled(id, localDisabled);
1498
+ return disabledBehavior === 'all' && isRowKeyDisabled(id, localDisabled);
1426
1499
  }
1427
1500
  function isRowActionDisabled(id, localDisabled = false) {
1428
- return disabledBehavior === 'all' && isRowSelectionDisabled(id, localDisabled);
1501
+ return disabledBehavior === 'all' && isRowKeyDisabled(id, localDisabled);
1429
1502
  }
1430
1503
  function isRowActionable(id, localDisabled = false) {
1431
- return Boolean(onRowAction) && id !== undefined && !isRowActionDisabled(id, localDisabled);
1504
+ return (Boolean(onRowAction) &&
1505
+ id !== undefined &&
1506
+ !isSectionRowKey(id) &&
1507
+ !isRowActionDisabled(id, localDisabled));
1432
1508
  }
1433
1509
  function isRowSelected(id) {
1434
1510
  if (id === undefined)
@@ -1560,8 +1636,8 @@ export function createTableContext(options = {}) {
1560
1636
  if (isRowDisabled(row?.id, row?.disabled))
1561
1637
  continue;
1562
1638
  const bodyCells = getResolvedBodyCellsForRow(rowToken)
1563
- .filter((cell) => Boolean(cell.element) && cell.columnIndex !== undefined && !isCellColumnHidden(cell))
1564
- .sort((left, right) => left.columnIndex - right.columnIndex);
1639
+ .filter((cell) => Boolean(cell.element) && getColumnIndex(cell) >= 0)
1640
+ .sort((left, right) => getColumnIndex(left) - getColumnIndex(right));
1565
1641
  const firstBodyCell = bodyCells[0]?.key;
1566
1642
  if (firstBodyCell) {
1567
1643
  defaultFocusKeyCache = firstBodyCell;
@@ -1603,6 +1679,9 @@ export function createTableContext(options = {}) {
1603
1679
  return -1;
1604
1680
  }
1605
1681
  function getColumnIndex(cell) {
1682
+ if (cell.spansRow) {
1683
+ return getVisibleColumnCount() > 0 ? 0 : -1;
1684
+ }
1606
1685
  if (cell.section === 'header' && cell.columnToken) {
1607
1686
  return getVisibleColumnIndexByToken(cell.columnToken);
1608
1687
  }
@@ -1682,6 +1761,15 @@ export function createTableContext(options = {}) {
1682
1761
  return;
1683
1762
  if (isRowDisabled(row.id, row.disabled))
1684
1763
  return;
1764
+ // Under grid navigation a section row has no row-edge stop: its single
1765
+ // cell spans the row, so every move that would land on the row lands on
1766
+ // that cell instead, and the horizontal keys keep the focus there.
1767
+ if (row.isSection && keyboardNavigation === 'grid') {
1768
+ const [cell] = getResolvedBodyCellsForRow(token);
1769
+ if (cell)
1770
+ focusCellByKey(cell.key);
1771
+ return;
1772
+ }
1685
1773
  focusedCellKey = null;
1686
1774
  focusedRowTarget = { rowToken: token, edge };
1687
1775
  row.element.focus();
@@ -1847,7 +1935,9 @@ export function createTableContext(options = {}) {
1847
1935
  applySelectionChange(new SvelteSet(orderedIds.slice(start, end + 1)), anchor);
1848
1936
  }
1849
1937
  function performRowAction(id) {
1850
- if (!onRowAction || id === undefined || isRowActionDisabled(id))
1938
+ if (!onRowAction || id === undefined)
1939
+ return;
1940
+ if (isSectionRowKey(id) || isRowActionDisabled(id))
1851
1941
  return;
1852
1942
  onRowAction(id);
1853
1943
  }
@@ -2398,6 +2488,8 @@ export function createTableContext(options = {}) {
2398
2488
  registerRow: asCommand(registerRow),
2399
2489
  unregisterRow: asCommand(unregisterRow),
2400
2490
  setLogicalBodyRows: asCommand(setLogicalBodyRows),
2491
+ setSectionRowKeys: asCommand(setSectionRowKeys),
2492
+ isSectionRowKey,
2401
2493
  markBodyRowsInitialized: asCommand(markBodyRowsInitialized),
2402
2494
  getHeaderRowCount,
2403
2495
  getBodyRowCount,
@@ -0,0 +1,31 @@
1
+ <!-- markdownlint-disable MD024 -->
2
+
3
+ # Table.SectionRow
4
+
5
+ ## API reference
6
+
7
+ ### Table.SectionRow
8
+
9
+ Name: `Table.SectionRow`
10
+ Description: Full-width group header row inside `Table.Body`. It has one cell that covers all the visible columns. It takes the focus as a row, but it is not in the selection and does not call `onRowAction`.
11
+
12
+ Public prop type: `TableSectionRowProps`
13
+
14
+ | Prop | Type | Default | Description |
15
+ | ---------- | ------------------ | ----------- | --------------------------------------------------------------------------- |
16
+ | `id` | `string \| number` | `undefined` | Key of the item. It gives the row its place in the logical rows. |
17
+ | `onAction` | `() => void` | `undefined` | Called on click, and on `Enter` or `Space` while the section row has focus. |
18
+ | `class` | `string` | `''` | Class names for the `tr` element. |
19
+ | `children` | `Snippet` | `undefined` | Content of the single cell. |
20
+
21
+ Other attributes, for example `aria-expanded` or `data-*`, go to the `tr` element.
22
+
23
+ ### Data attributes
24
+
25
+ | Attribute | Element | Description |
26
+ | --------------------------- | ---------- | -------------------------------------------- |
27
+ | `data-section-row` | `tr` | Always set. |
28
+ | `data-focused` | `tr`, `td` | Set on the element that has the focus. |
29
+ | `data-focus-visible` | `tr`, `td` | Set when that focus comes from the keyboard. |
30
+ | `data-focus-within` | `tr` | Set when the row or its cell has the focus. |
31
+ | `data-focus-visible-within` | `tr` | Set when that focus comes from the keyboard. |
@@ -0,0 +1,201 @@
1
+ <script lang="ts">
2
+ import { onDestroy } from 'svelte';
3
+ import { useTableContext, useTableSectionContext } from '../root/context.svelte';
4
+ import type { TableSectionRowProps } from '../types.js';
5
+ import {
6
+ shouldShowFocusVisible,
7
+ trackInteractionModality
8
+ } from '../../primitives/input-modality';
9
+ import { handleTableBodyKeydown } from '../utils/handle-body-keydown';
10
+
11
+ let {
12
+ id,
13
+ onAction,
14
+ children,
15
+ class: className = '',
16
+ ...restProps
17
+ }: TableSectionRowProps = $props();
18
+
19
+ const table = useTableContext();
20
+ const section = useTableSectionContext();
21
+ if (section.section !== 'body') {
22
+ throw new Error('`Table.SectionRow` must be used inside `Table.Body`.');
23
+ }
24
+
25
+ const rowToken = table.createInstanceToken('row');
26
+ const cellKey = table.createInstanceToken('cell');
27
+
28
+ let rowElement = $state<HTMLTableRowElement | undefined>(undefined);
29
+ let cellElement = $state<HTMLTableCellElement | undefined>(undefined);
30
+
31
+ // A section row is a row for navigation only. It registers as one so the
32
+ // arrows walk into and out of it, and flags itself so the selection model
33
+ // (select-all, ranges, the header checkbox) and `onRowAction` skip it.
34
+ function syncRowRegistration() {
35
+ table.registerRow({
36
+ token: rowToken,
37
+ section: 'body',
38
+ id,
39
+ disabled: false,
40
+ isSection: true,
41
+ element: rowElement
42
+ });
43
+ }
44
+
45
+ syncRowRegistration();
46
+
47
+ $effect(() => {
48
+ syncRowRegistration();
49
+ });
50
+
51
+ // Under `'grid'` the single cell is the focus target; it registers at the
52
+ // first visible column (`spansRow`), so moving down from any column lands on
53
+ // it and moving down from it lands on the first column of the next row.
54
+ const isCellFocusTarget = $derived(table.keyboardNavigation === 'grid');
55
+ // Under `'row'` the row itself is the focus target, like any other row.
56
+ const isRowFocusTarget = $derived(table.keyboardNavigation === 'row');
57
+
58
+ $effect(() => {
59
+ if (!isCellFocusTarget) return;
60
+ table.registerCell({
61
+ key: cellKey,
62
+ rowToken,
63
+ section: 'body',
64
+ element: cellElement,
65
+ spansRow: true
66
+ });
67
+ });
68
+
69
+ onDestroy(() => {
70
+ // Mirrors `isCellFocusTarget` without reading it: a derived is not safe to
71
+ // read while the component tears down.
72
+ if (table.keyboardNavigation === 'grid') {
73
+ table.unregisterCell(cellKey);
74
+ }
75
+ table.unregisterRow(rowToken);
76
+ });
77
+
78
+ // The cell covers every visible column, the selection column included: that
79
+ // one is a regular `Table.Column`, so the visible count already has it.
80
+ const columnCount = $derived.by(() => {
81
+ void table.layoutEpoch;
82
+ return Math.max(table.getVisibleColumnCount(), 1);
83
+ });
84
+ const ariaRowIndex = $derived.by(() => {
85
+ void table.layoutEpoch;
86
+ return table.getRowAriaIndex(rowToken);
87
+ });
88
+
89
+ const isCellFocused = $derived(isCellFocusTarget ? table.isCellFocused(cellKey) : false);
90
+ const isRowFocused = $derived(isRowFocusTarget ? table.isRowFocusTarget(rowToken) : false);
91
+ const isFocusWithin = $derived(table.isRowFocused(rowToken));
92
+ const isCellFocusVisible = $derived(isCellFocused && table.focusVisible);
93
+ const isRowFocusVisible = $derived(isRowFocused && table.focusVisible);
94
+ const isFocusVisibleWithin = $derived(isFocusWithin && table.focusVisible);
95
+
96
+ const cellTabIndex = $derived.by(() => {
97
+ if (!isCellFocusTarget) return undefined;
98
+ if (table.focusedCellKey === null && table.getHeaderRowCount() > 0) return -1;
99
+ return table.isCellTabStop(cellKey) ? 0 : -1;
100
+ });
101
+ const rowTabIndex = $derived.by(() => {
102
+ if (!isRowFocusTarget) return undefined;
103
+ return table.isRowTabStop(rowToken) ? 0 : -1;
104
+ });
105
+
106
+ function runAction() {
107
+ onAction?.();
108
+ }
109
+
110
+ function handleKeyDown(event: KeyboardEvent, focusTarget: HTMLElement | undefined) {
111
+ handleTableBodyKeydown({
112
+ event,
113
+ table,
114
+ focusTarget,
115
+ isDisabled: false,
116
+ // Under grid navigation the cell is the whole row, so Home and End stay
117
+ // on it. Under row navigation they go to the first and last rows, the
118
+ // same as on any other row.
119
+ onHome: isCellFocusTarget ? () => table.moveToRowStart() : () => table.moveToBodyRowStart(),
120
+ onEnd: isCellFocusTarget ? () => table.moveToRowEnd() : () => table.moveToBodyRowEnd(),
121
+ onEnter: runAction,
122
+ onSpace: runAction
123
+ });
124
+ }
125
+
126
+ function handleRowFocus() {
127
+ if (!isRowFocusTarget) return;
128
+ if (!table.isRowTabStop(rowToken)) return;
129
+ table.setFocusedRow(rowToken, table.getRowFocusEdge(rowToken) ?? 'start');
130
+ table.setFocusVisible(shouldShowFocusVisible(rowElement ?? null));
131
+ }
132
+
133
+ function handleRowKeyDown(event: KeyboardEvent) {
134
+ if (!isRowFocusTarget) return;
135
+ if (event.target !== rowElement) return;
136
+ handleKeyDown(event, rowElement);
137
+ }
138
+
139
+ function handleCellFocus() {
140
+ table.setFocusedCell(cellKey);
141
+ table.setFocusVisible(shouldShowFocusVisible(cellElement ?? null));
142
+ }
143
+
144
+ function handleCellKeyDown(event: KeyboardEvent) {
145
+ if (event.target !== cellElement) return;
146
+ handleKeyDown(event, cellElement);
147
+ }
148
+
149
+ function handleMouseDown(event: MouseEvent) {
150
+ trackInteractionModality(event, cellElement ?? null);
151
+ table.setFocusVisible(false);
152
+ }
153
+
154
+ // A press moves focus to whatever the current mode can focus, so the
155
+ // keyboard carries on from the section row; it never goes through
156
+ // `pressRow`, which is what keeps it out of selection and `onRowAction`.
157
+ function handleClick() {
158
+ if (isCellFocusTarget) {
159
+ table.focusCellByKey(cellKey);
160
+ } else if (isRowFocusTarget) {
161
+ table.focusRowByToken(rowToken, 'start');
162
+ }
163
+ runAction();
164
+ }
165
+ </script>
166
+
167
+ <!-- svelte-ignore a11y_no_redundant_roles -->
168
+ <tr
169
+ bind:this={rowElement}
170
+ role="row"
171
+ class={className}
172
+ tabindex={rowTabIndex}
173
+ data-section-row
174
+ data-focused={isRowFocused ? 'true' : undefined}
175
+ data-focus-visible={isRowFocusVisible ? 'true' : undefined}
176
+ data-focus-within={isFocusWithin ? 'true' : undefined}
177
+ data-focus-visible-within={isFocusVisibleWithin ? 'true' : undefined}
178
+ aria-rowindex={ariaRowIndex}
179
+ onfocus={handleRowFocus}
180
+ onkeydown={handleRowKeyDown}
181
+ {...restProps}
182
+ >
183
+ <td
184
+ bind:this={cellElement}
185
+ role="gridcell"
186
+ colspan={columnCount}
187
+ tabindex={cellTabIndex}
188
+ aria-colindex={1}
189
+ data-focused={isCellFocused ? 'true' : undefined}
190
+ data-focus-visible={isCellFocusVisible ? 'true' : undefined}
191
+ style:box-sizing="border-box"
192
+ onfocus={isCellFocusTarget ? handleCellFocus : undefined}
193
+ onkeydown={isCellFocusTarget ? handleCellKeyDown : undefined}
194
+ onmousedown={handleMouseDown}
195
+ onclick={handleClick}
196
+ >
197
+ {#if children}
198
+ {@render children()}
199
+ {/if}
200
+ </td>
201
+ </tr>
@@ -0,0 +1,4 @@
1
+ import type { TableSectionRowProps } from '../types.js';
2
+ declare const TableSectionRow: import("svelte").Component<TableSectionRowProps, {}, "">;
3
+ type TableSectionRow = ReturnType<typeof TableSectionRow>;
4
+ export default TableSectionRow;
@@ -59,6 +59,11 @@ export type TableHeaderProps = Omit<HTMLAttributes<HTMLTableSectionElement>, 'ch
59
59
  };
60
60
  export type TableBodyVirtualizer = {
61
61
  rowHeight: number;
62
+ /**
63
+ * Height, in px, of a section row, when it differs from `rowHeight`. It needs `isSectionItem` on
64
+ * `Table.Body` to know which items are section rows. Without it, each item is `rowHeight` high.
65
+ */
66
+ sectionRowHeight?: number;
62
67
  /**
63
68
  * Extra rows rendered above and below the viewport, defaulting to 18. It
64
69
  * buffers against row render cost: while the main thread builds rows, the
@@ -73,12 +78,19 @@ type TableBodyBaseProps = Omit<HTMLAttributes<HTMLTableSectionElement>, 'childre
73
78
  export type TableBodyManualProps = TableBodyBaseProps & {
74
79
  items?: undefined;
75
80
  virtualizer?: undefined;
81
+ isSectionItem?: undefined;
76
82
  children?: Snippet;
77
83
  empty?: undefined;
78
84
  };
79
85
  export type TableBodyItemsProps<T extends TableRowItem = TableRowItem> = TableBodyBaseProps & {
80
86
  items: readonly T[];
81
87
  virtualizer?: TableBodyVirtualizer;
88
+ /**
89
+ * Tells which items render a `Table.SectionRow`. A section row that is mounted declares itself,
90
+ * so this is optional without a virtualizer. With one, pass it: it keeps the section rows that
91
+ * are not mounted out of select-all and range selection, and it lets `sectionRowHeight` apply.
92
+ */
93
+ isSectionItem?: (item: T) => boolean;
82
94
  children?: Snippet<[T]>;
83
95
  empty?: Snippet;
84
96
  };
@@ -145,6 +157,20 @@ export type TableRowProps = Omit<HTMLAttributes<HTMLTableRowElement>, 'children'
145
157
  children?: Snippet;
146
158
  class?: string;
147
159
  };
160
+ export type TableSectionRowProps = Omit<HTMLAttributes<HTMLTableRowElement>, 'children' | 'id'> & {
161
+ /**
162
+ * Key of the item this section row stands for. It takes a place in the logical rows (and in
163
+ * `aria-rowindex`) like any row, but it is never selected and never passed to `onRowAction`.
164
+ */
165
+ id?: TableSelectionKey;
166
+ /**
167
+ * Called when the section row is pressed: on click, and on `Enter` or `Space` while it has the
168
+ * focus. This is where a group collapses or expands. The table's `onRowAction` is not called.
169
+ */
170
+ onAction?: () => void;
171
+ children?: Snippet;
172
+ class?: string;
173
+ };
148
174
  export type TableColumnHeaderCellProps = Omit<HTMLAttributes<HTMLTableCellElement>, 'children'> & {
149
175
  children?: Snippet;
150
176
  class?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@human-kit/ui",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "Accessible, typed UI components for Svelte 5 — shipped as native ESM with per-component subpath exports so bundlers only include what you import.",
5
5
  "license": "MIT",
6
6
  "author": "Agustin Delgado <agustindariodelgado@gmail.com>",