compote-ui 0.36.1 → 0.37.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.
@@ -1,4 +1,4 @@
1
- import { type ColumnFiltersState, type ColumnResizeMode, type Row, type RowData, type RowSelectionState, type SortingState, type SvelteTable, type TableState } from '@tanstack/svelte-table';
1
+ import { type ColumnResizeMode, type Row, type RowData, type SvelteTable, type TableState } from '@tanstack/svelte-table';
2
2
  import type { DataTableColumn, DataTableLeafColumn } from './types';
3
3
  declare const dataTableFeatures: {
4
4
  columnVisibilityFeature: import("@tanstack/table-core").TableFeature<import("@tanstack/table-core").ColumnVisibilityFeatureConstructors<import("@tanstack/table-core").TableFeatures, RowData>>;
@@ -18,9 +18,7 @@ export type CreateDataTableOptions<T extends RowData> = {
18
18
  data: T[];
19
19
  columns: DataTableColumn<T>[];
20
20
  columnResizeMode?: ColumnResizeMode;
21
- initialSorting?: SortingState;
22
- initialRowSelection?: RowSelectionState;
23
- initialColumnFilters?: ColumnFiltersState;
21
+ initialState?: Partial<TableState<DataTableFeatures>>;
24
22
  getRowId?: (row: T, index: number, parent?: Row<DataTableFeatures, T>) => string;
25
23
  enableRowSelection?: boolean | ((row: Row<DataTableFeatures, T>) => boolean);
26
24
  enableMultiRowSelection?: boolean | ((row: Row<DataTableFeatures, T>) => boolean);
@@ -39,12 +39,19 @@ export function createTable(options) {
39
39
  return createColumns(options.columns, localeCtx);
40
40
  },
41
41
  initialState: {
42
- columnVisibility: createColumnVisibility(options.columns),
43
- columnSizing: createColumnSizing(options.columns),
44
- columnPinning: createColumnPinning(options.columns),
45
- rowSelection: options.initialRowSelection ?? {},
46
- sorting: options.initialSorting ?? [],
47
- columnFilters: options.initialColumnFilters ?? []
42
+ ...options.initialState,
43
+ columnVisibility: {
44
+ ...createColumnVisibility(options.columns),
45
+ ...options.initialState?.columnVisibility
46
+ },
47
+ columnSizing: {
48
+ ...createColumnSizing(options.columns),
49
+ ...options.initialState?.columnSizing
50
+ },
51
+ columnPinning: options.initialState?.columnPinning ?? createColumnPinning(options.columns),
52
+ rowSelection: options.initialState?.rowSelection ?? {},
53
+ sorting: options.initialState?.sorting ?? [],
54
+ columnFilters: options.initialState?.columnFilters ?? []
48
55
  }
49
56
  }, (state) => ({
50
57
  columnVisibility: state.columnVisibility,
@@ -1,418 +1,394 @@
1
- <script lang="ts" generics="T extends RowData">
2
- import { FlexRender } from '@tanstack/svelte-table';
3
- import type { CellData, ColumnPinningPosition, Header, RowData } from '@tanstack/svelte-table';
4
- import type { HTMLAttributes } from 'svelte/elements';
5
- import { cn, type ClassValue } from 'tailwind-variants';
6
- import { PhArrowSquareOut, PhCaretDown, PhCaretUp, PhCheck, PhX } from '../../icons';
7
- import Checkbox from '../checkbox/checkbox.svelte';
8
- import { getColumnId, type DataTableFeatures, type DataTableInstance } from './create-table';
9
- import type { DataTableColumn, DataTableGroupColumn, DataTableLeafColumn } from './types';
10
-
11
- type Props = Omit<HTMLAttributes<HTMLDivElement>, 'class'> & {
12
- table: DataTableInstance<T>;
13
- columns: DataTableColumn<T>[];
14
- caption?: string;
15
- emptyMessage?: string;
16
- class?: ClassValue;
17
- };
18
-
19
- let {
20
- table,
21
- columns,
22
- caption,
23
- emptyMessage = 'No rows found',
24
- class: className,
25
- ...rest
26
- }: Props = $props();
27
-
28
- function alignClass(align: DataTableColumn<T>['align']) {
29
- return align === 'right' ? 'text-right' : align === 'center' ? 'text-center' : 'text-left';
30
- }
31
-
32
- function justifyClass(align: DataTableColumn<T>['align']) {
33
- return align === 'right'
34
- ? 'justify-end'
35
- : align === 'center'
36
- ? 'justify-center'
37
- : 'justify-start';
38
- }
39
-
40
- function sortButtonDirectionClass(align: DataTableColumn<T>['align']) {
41
- return align === 'right' ? 'flex-row-reverse' : 'flex-row';
42
- }
43
-
44
- function columnSizeStyle(size: number) {
45
- return `width: ${size}px`;
46
- }
47
-
48
- function selectionColumnSizeStyle() {
49
- return 'width: 40px';
50
- }
51
-
52
- function tableSizeStyle() {
53
- return `width: max(100%, ${table.getTotalSize() + (isRowSelectionEnabled ? 40 : 0)}px)`;
54
- }
55
-
56
- function resizeHandleStyle(header: Header<DataTableFeatures, T, CellData>) {
57
- if (table.options.columnResizeMode !== 'onEnd') return undefined;
58
- const deltaOffset = table.store.state.columnResizing.deltaOffset;
59
- if (!header.column.getIsResizing() || deltaOffset === null) return undefined;
60
- return `transform: translateX(${deltaOffset}px)`;
61
- }
62
-
63
- function resizeHandleClass(headerIndex: number, headerCount: number) {
64
- return cn(
65
- 'absolute top-0 z-10 flex h-full w-2 cursor-col-resize touch-none items-center justify-center select-none before:h-4 before:w-px before:bg-border before:content-[""]',
66
- headerIndex === headerCount - 1 ? 'right-0' : '-right-1'
67
- );
68
- }
69
-
70
- function getHeaderSortDirection(
71
- header: Header<DataTableFeatures, T, CellData>,
72
- sortingState: unknown
73
- ) {
74
- void sortingState;
75
- return header.column.getIsSorted();
76
- }
77
-
78
- function getHeaderSortLabel(sortDirection: false | 'asc' | 'desc') {
79
- if (sortDirection === 'asc') return 'Sorted ascending';
80
- if (sortDirection === 'desc') return 'Sorted descending';
81
- return 'Not sorted';
82
- }
83
-
84
- function getHeaderAriaSort(sortDirection: false | 'asc' | 'desc') {
85
- if (sortDirection === 'asc') return 'ascending';
86
- if (sortDirection === 'desc') return 'descending';
87
- return 'none';
88
- }
89
-
90
- function getAllRowsSelectionState(rowSelection: unknown) {
91
- void rowSelection;
92
- const allRowsSelected = table.getIsAllRowsSelected();
93
- const someRowsSelected = table.getIsSomeRowsSelected();
94
- return allRowsSelected ? true : someRowsSelected ? 'indeterminate' : false;
95
- }
96
-
97
- function getRowSelectionState(rowSelection: unknown, rowId: string) {
98
- void rowSelection;
99
- return table.getRow(rowId).getIsSelected();
100
- }
101
-
102
- function getSelectedRowCount(rowSelection: unknown) {
103
- void rowSelection;
104
- return table.getSelectedRowModel().rows.length;
105
- }
106
-
107
- function getBooleanCellValue(value: unknown) {
108
- if (value === true) return true;
109
- if (value === false) return false;
110
- return undefined;
111
- }
112
-
113
- // type PinPosition = 'center' | false | 'left' | 'right';
114
- function getPinningStyle(
115
- column: {
116
- getIsPinned(): ColumnPinningPosition;
117
- getStart(position?: ColumnPinningPosition): number;
118
- getAfter(position?: ColumnPinningPosition): number;
119
- getIsLastColumn(position?: ColumnPinningPosition): boolean;
120
- getIsFirstColumn(position?: ColumnPinningPosition): boolean;
121
- },
122
- isHeader = false
123
- ): string | undefined {
124
- const isPinned = column.getIsPinned();
125
- if (!isPinned) return undefined;
126
-
127
- const zIndex = isHeader ? 15 : 1;
128
- const selectionOffset = isRowSelectionEnabled ? 40 : 0;
129
-
130
- if (isPinned === 'left') {
131
- const left = column.getStart('left') + selectionOffset;
132
- const shadow =
133
- !isHeader && column.getIsLastColumn('left')
134
- ? 'box-shadow: -4px 0 4px -4px var(--compote-border) inset'
135
- : undefined;
136
- return ['position: sticky', `z-index: ${zIndex}`, `left: ${left}px`, shadow]
137
- .filter(Boolean)
138
- .join('; ');
139
- } else {
140
- const right = column.getAfter('right');
141
- const shadow =
142
- !isHeader && column.getIsFirstColumn('right')
143
- ? 'box-shadow: 4px 0 4px -4px var(--compote-border) inset'
144
- : undefined;
145
- return ['position: sticky', `z-index: ${zIndex}`, `right: ${right}px`, shadow]
146
- .filter(Boolean)
147
- .join('; ');
148
- }
149
- }
150
-
151
- function getUrlCellValue(value: unknown) {
152
- if (typeof value !== 'string' || value.trim() === '') return undefined;
153
- return value;
154
- }
155
-
156
- function openUrlCell(value: string) {
157
- window.open(value, '_blank', 'noopener,noreferrer');
158
- }
159
-
160
- function isGroupColumn(column: DataTableColumn<T>): column is DataTableGroupColumn<T> {
161
- return Array.isArray(column.columns);
162
- }
163
-
164
- function isLeafColumn(column: DataTableColumn<T>): column is DataTableLeafColumn<T> {
165
- return !isGroupColumn(column);
166
- }
167
-
168
- function findColumnById(
169
- columnId: string,
170
- candidates: DataTableColumn<T>[]
171
- ): DataTableColumn<T> | undefined {
172
- for (const column of candidates) {
173
- if (isGroupColumn(column)) {
174
- if ((column.id ?? column.header) === columnId) return column;
175
-
176
- const found = findColumnById(columnId, column.columns);
177
- if (found) return found;
178
-
179
- continue;
180
- }
181
-
182
- if (isLeafColumn(column) && getColumnId(column) === columnId) return column;
183
- }
184
- }
185
-
186
- const tableStateKey = $derived(JSON.stringify(table.store.state));
187
- function trackTableState() {
188
- return tableStateKey;
189
- }
190
-
191
- const rowModel = $derived.by(() => {
192
- trackTableState();
193
- return table.getRowModel();
194
- });
195
- const headerGroups = $derived.by(() => {
196
- trackTableState();
197
- return table.getHeaderGroups();
198
- });
199
- const visibleLeafColumns = $derived.by(() => {
200
- trackTableState();
201
- return table.getVisibleLeafColumns();
202
- });
203
- const visibleColumnCount = $derived(visibleLeafColumns.length);
204
- const isRowSelectionEnabled = $derived(Boolean(table.options.enableRowSelection));
205
- const isMultiRowSelectionEnabled = $derived(table.options.enableMultiRowSelection !== false);
206
- const tableColumnCount = $derived(visibleColumnCount + (isRowSelectionEnabled ? 1 : 0));
207
- const renderedColumnCount = $derived(tableColumnCount + 1);
208
- const headerGroupCount = $derived(headerGroups.length);
209
- const allRowsSelectionState = $derived(getAllRowsSelectionState(table.store.state.rowSelection));
210
- const selectedRowCount = $derived(getSelectedRowCount(table.store.state.rowSelection));
211
- const isColumnResizing = $derived(table.store.state.columnResizing.isResizingColumn !== false);
212
- </script>
213
-
214
- <div
215
- class={cn(
216
- 'flex max-h-full min-h-0 flex-col overflow-hidden rounded-lg border border-surface-3 bg-surface-1',
217
- className
218
- )}
219
- {...rest}
220
- >
221
- {#if isColumnResizing}
222
- <div aria-hidden="true" class="fixed inset-0 z-50 cursor-col-resize select-none"></div>
223
- {/if}
224
-
225
- <div class="min-h-0 flex-1 overflow-auto">
226
- <table class="table-fixed border-separate border-spacing-0 text-sm" style={tableSizeStyle()}>
227
- <colgroup>
228
- {#if isRowSelectionEnabled}
229
- <col style={selectionColumnSizeStyle()} />
230
- {/if}
231
- {#each visibleLeafColumns as column (column.id)}
232
- <col style={columnSizeStyle(column.getSize())} />
233
- {/each}
234
- <col />
235
- </colgroup>
236
- {#if caption}
237
- <caption class="sr-only">{caption}</caption>
238
- {/if}
239
- <thead class="sticky top-0 z-20 bg-surface-2 text-left text-ink-dim">
240
- {#each headerGroups as headerGroup, headerGroupIndex (headerGroup.id)}
241
- {@const visibleHeaders = headerGroup.headers.filter((header) => header.colSpan > 0)}
242
- <tr class="h-9">
243
- {#if isRowSelectionEnabled && headerGroupIndex === 0}
244
- <th
245
- class="h-9 border-b border-surface-3 bg-surface-2 px-3 py-0 text-center align-middle leading-5 font-medium"
246
- style="position: sticky; left: 0; z-index: 15"
247
- rowspan={headerGroupCount}
248
- >
249
- {#if isMultiRowSelectionEnabled}
250
- <Checkbox
251
- size="sm"
252
- aria-label="Select all rows"
253
- class="mx-auto size-4"
254
- checked={allRowsSelectionState}
255
- onCheckedChange={({ checked }) => table.toggleAllRowsSelected(checked === true)}
256
- />
257
- {/if}
258
- </th>
259
- {/if}
260
- {#each visibleHeaders as header, headerIndex (header.id)}
261
- {@const columnDef = findColumnById(header.column.id, columns)}
262
- {@const sortDirection = getHeaderSortDirection(header, table.store.state.sorting)}
263
- <th
264
- class={cn(
265
- 'relative h-9 border-b border-surface-3 bg-surface-2 px-3 py-0 align-middle leading-5 font-medium',
266
- alignClass(columnDef?.align)
267
- )}
268
- colspan={header.colSpan}
269
- aria-sort={header.column.getCanSort()
270
- ? getHeaderAriaSort(sortDirection)
271
- : undefined}
272
- style={getPinningStyle(header.column, true)}
273
- >
274
- {#if !header.isPlaceholder}
275
- {#if header.column.getCanSort()}
276
- <button
277
- type="button"
278
- class={cn(
279
- 'inline-flex max-w-full appearance-none items-center gap-1 rounded-sm border-0 bg-transparent p-0 align-middle text-sm leading-5 text-inherit outline-none hover:text-ink data-focus-visible:outline-2 data-focus-visible:outline-offset-2 data-focus-visible:outline-ring',
280
- justifyClass(columnDef?.align),
281
- sortButtonDirectionClass(columnDef?.align)
282
- )}
283
- aria-label={`${getHeaderSortLabel(sortDirection)}. Toggle sorting.`}
284
- onclick={header.column.getToggleSortingHandler()}
285
- >
286
- <span class="min-w-0 truncate">
287
- <FlexRender {header} />
288
- </span>
289
- <span
290
- class="inline-flex size-3.5 shrink-0 items-center justify-center text-ink-dim"
291
- >
292
- {#if sortDirection === 'asc'}
293
- <PhCaretUp class="size-3.5" />
294
- {:else if sortDirection === 'desc'}
295
- <PhCaretDown class="size-3.5" />
296
- {/if}
297
- </span>
298
- </button>
299
- {:else}
300
- <FlexRender {header} />
301
- {/if}
302
- {/if}
303
- {#if header.column.getCanResize()}
304
- <div
305
- aria-hidden="true"
306
- class={resizeHandleClass(headerIndex, visibleHeaders.length)}
307
- style={resizeHandleStyle(header)}
308
- ondblclick={() => header.column.resetSize()}
309
- onmousedown={header.getResizeHandler()}
310
- ontouchstart={header.getResizeHandler()}
311
- ></div>
312
- {/if}
313
- </th>
314
- {/each}
315
- <th aria-hidden="true" class="h-9 border-b border-surface-3 bg-surface-2 p-0"></th>
316
- </tr>
317
- {/each}
318
- </thead>
319
- <tbody>
320
- {#each rowModel.rows as row (row.id)}
321
- {@const rowSelected = getRowSelectionState(table.store.state.rowSelection, row.id)}
322
- <tr
323
- class={cn(
324
- 'group/row border-b border-surface-3 last:border-b-0',
325
- '[--row-bg:var(--compote-surface-1)]',
326
- 'hover:bg-well/60 hover:[--row-bg:color-mix(in_srgb,var(--compote-well)_60%,var(--compote-surface-1))]',
327
- rowSelected &&
328
- 'bg-well/60 [--row-bg:color-mix(in_srgb,var(--compote-well)_60%,var(--compote-surface-1))]'
329
- )}
330
- >
331
- {#if isRowSelectionEnabled}
332
- <td
333
- class="bg-(--row-bg) px-3 py-2 text-center align-middle"
334
- style="position: sticky; left: 0; z-index: 1"
335
- >
336
- <Checkbox
337
- size="sm"
338
- aria-label="Select row"
339
- class="mx-auto size-4"
340
- checked={rowSelected}
341
- disabled={!row.getCanSelect()}
342
- onCheckedChange={({ checked }) => row.toggleSelected(checked === true)}
343
- />
344
- </td>
345
- {/if}
346
- {#each row.getVisibleCells() as cell (cell.id)}
347
- {@const columnDef = findColumnById(cell.column.id, columns)}
348
- <td
349
- class={cn(
350
- 'truncate px-3 py-2',
351
- alignClass(columnDef?.align),
352
- cell.column.getIsPinned() && 'bg-(--row-bg)'
353
- )}
354
- style={getPinningStyle(cell.column)}
355
- >
356
- {#if columnDef?.type === 'boolean'}
357
- {@const value = getBooleanCellValue(cell.getValue())}
358
- {#if value === true}
359
- <span
360
- class="inline-flex size-5 items-center justify-center text-success"
361
- role="img"
362
- aria-label="Yes"
363
- >
364
- <PhCheck class="size-4" />
365
- </span>
366
- {:else if value === false}
367
- <span
368
- class="inline-flex size-5 items-center justify-center text-danger"
369
- role="img"
370
- aria-label="No"
371
- >
372
- <PhX class="size-4" />
373
- </span>
374
- {:else}
375
- -
376
- {/if}
377
- {:else if columnDef?.type === 'url'}
378
- {@const value = getUrlCellValue(cell.getValue())}
379
- {#if value}
380
- <button
381
- type="button"
382
- class={cn(
383
- 'inline-flex max-w-full appearance-none items-center gap-1.5 rounded-sm border-0 bg-transparent p-0 align-middle leading-5 font-medium text-ink underline decoration-border decoration-dotted underline-offset-4 outline-none hover:text-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
384
- justifyClass(columnDef.align)
385
- )}
386
- onclick={() => openUrlCell(value)}
387
- >
388
- <PhArrowSquareOut class="size-3.5 shrink-0" />
389
- </button>
390
- {:else}
391
- -
392
- {/if}
393
- {:else}
394
- <FlexRender {cell} />
395
- {/if}
396
- </td>
397
- {/each}
398
- <td aria-hidden="true" class="p-0"></td>
399
- </tr>
400
- {:else}
401
- <tr>
402
- <td class="px-3 py-10 text-center text-sm text-ink-dim" colspan={renderedColumnCount}>
403
- {emptyMessage}
404
- </td>
405
- </tr>
406
- {/each}
407
- </tbody>
408
- </table>
409
- </div>
410
-
411
- <div class="shrink-0 border-t border-surface-3 bg-surface-2 px-3 py-2 text-sm text-ink-dim">
412
- {#if isRowSelectionEnabled}
413
- {selectedRowCount} of {rowModel.rows.length} rows selected
414
- {:else}
415
- {rowModel.rows.length} rows
416
- {/if}
417
- </div>
418
- </div>
1
+ <script lang="ts" generics="T extends RowData">
2
+ import { FlexRender } from '@tanstack/svelte-table';
3
+ import type { CellData, ColumnPinningPosition, Header, RowData } from '@tanstack/svelte-table';
4
+ import type { HTMLAttributes } from 'svelte/elements';
5
+ import { cn, type ClassValue } from 'tailwind-variants';
6
+ import { PhArrowSquareOut, PhCaretDown, PhCaretUp, PhCheck, PhX } from '../../icons';
7
+ import Checkbox from '../checkbox/checkbox.svelte';
8
+ import { type DataTableFeatures, type DataTableInstance } from './create-table';
9
+ import type { DataTableColumnMeta } from './types';
10
+
11
+ type Props = Omit<HTMLAttributes<HTMLDivElement>, 'class'> & {
12
+ table: DataTableInstance<T>;
13
+ caption?: string;
14
+ emptyMessage?: string;
15
+ class?: ClassValue;
16
+ };
17
+
18
+ let {
19
+ table,
20
+ caption,
21
+ emptyMessage = 'No rows found',
22
+ class: className,
23
+ ...rest
24
+ }: Props = $props();
25
+
26
+ function alignClass(align: DataTableColumnMeta['align']) {
27
+ return align === 'right' ? 'text-right' : align === 'center' ? 'text-center' : 'text-left';
28
+ }
29
+
30
+ function justifyClass(align: DataTableColumnMeta['align']) {
31
+ return align === 'right'
32
+ ? 'justify-end'
33
+ : align === 'center'
34
+ ? 'justify-center'
35
+ : 'justify-start';
36
+ }
37
+
38
+ function sortButtonDirectionClass(align: DataTableColumnMeta['align']) {
39
+ return align === 'right' ? 'flex-row-reverse' : 'flex-row';
40
+ }
41
+
42
+ function columnSizeStyle(size: number) {
43
+ return `width: ${size}px`;
44
+ }
45
+
46
+ function selectionColumnSizeStyle() {
47
+ return 'width: 40px';
48
+ }
49
+
50
+ function tableSizeStyle() {
51
+ return `width: max(100%, ${table.getTotalSize() + (isRowSelectionEnabled ? 40 : 0)}px)`;
52
+ }
53
+
54
+ function resizeHandleStyle(header: Header<DataTableFeatures, T, CellData>) {
55
+ if (table.options.columnResizeMode !== 'onEnd') return undefined;
56
+ const deltaOffset = table.store.state.columnResizing.deltaOffset;
57
+ if (!header.column.getIsResizing() || deltaOffset === null) return undefined;
58
+ return `transform: translateX(${deltaOffset}px)`;
59
+ }
60
+
61
+ function resizeHandleClass(headerIndex: number, headerCount: number) {
62
+ return cn(
63
+ 'absolute top-0 z-10 flex h-full w-2 cursor-col-resize touch-none items-center justify-center select-none before:h-4 before:w-px before:bg-border before:content-[""]',
64
+ headerIndex === headerCount - 1 ? 'right-0' : '-right-1'
65
+ );
66
+ }
67
+
68
+ function getHeaderSortDirection(
69
+ header: Header<DataTableFeatures, T, CellData>,
70
+ sortingState: unknown
71
+ ) {
72
+ void sortingState;
73
+ return header.column.getIsSorted();
74
+ }
75
+
76
+ function getHeaderSortLabel(sortDirection: false | 'asc' | 'desc') {
77
+ if (sortDirection === 'asc') return 'Sorted ascending';
78
+ if (sortDirection === 'desc') return 'Sorted descending';
79
+ return 'Not sorted';
80
+ }
81
+
82
+ function getHeaderAriaSort(sortDirection: false | 'asc' | 'desc') {
83
+ if (sortDirection === 'asc') return 'ascending';
84
+ if (sortDirection === 'desc') return 'descending';
85
+ return 'none';
86
+ }
87
+
88
+ function getAllRowsSelectionState(rowSelection: unknown) {
89
+ void rowSelection;
90
+ const allRowsSelected = table.getIsAllRowsSelected();
91
+ const someRowsSelected = table.getIsSomeRowsSelected();
92
+ return allRowsSelected ? true : someRowsSelected ? 'indeterminate' : false;
93
+ }
94
+
95
+ function getRowSelectionState(rowSelection: unknown, rowId: string) {
96
+ void rowSelection;
97
+ return table.getRow(rowId).getIsSelected();
98
+ }
99
+
100
+ function getSelectedRowCount(rowSelection: unknown) {
101
+ void rowSelection;
102
+ return table.getSelectedRowModel().rows.length;
103
+ }
104
+
105
+ function getBooleanCellValue(value: unknown) {
106
+ if (value === true) return true;
107
+ if (value === false) return false;
108
+ return undefined;
109
+ }
110
+
111
+ // type PinPosition = 'center' | false | 'left' | 'right';
112
+ function getPinningStyle(
113
+ column: {
114
+ getIsPinned(): ColumnPinningPosition;
115
+ getStart(position?: ColumnPinningPosition): number;
116
+ getAfter(position?: ColumnPinningPosition): number;
117
+ getIsLastColumn(position?: ColumnPinningPosition): boolean;
118
+ getIsFirstColumn(position?: ColumnPinningPosition): boolean;
119
+ },
120
+ isHeader = false
121
+ ): string | undefined {
122
+ const isPinned = column.getIsPinned();
123
+ if (!isPinned) return undefined;
124
+
125
+ const zIndex = isHeader ? 15 : 1;
126
+ const selectionOffset = isRowSelectionEnabled ? 40 : 0;
127
+
128
+ if (isPinned === 'left') {
129
+ const left = column.getStart('left') + selectionOffset;
130
+ const shadow =
131
+ !isHeader && column.getIsLastColumn('left')
132
+ ? 'box-shadow: -4px 0 4px -4px var(--compote-border) inset'
133
+ : undefined;
134
+ return ['position: sticky', `z-index: ${zIndex}`, `left: ${left}px`, shadow]
135
+ .filter(Boolean)
136
+ .join('; ');
137
+ } else {
138
+ const right = column.getAfter('right');
139
+ const shadow =
140
+ !isHeader && column.getIsFirstColumn('right')
141
+ ? 'box-shadow: 4px 0 4px -4px var(--compote-border) inset'
142
+ : undefined;
143
+ return ['position: sticky', `z-index: ${zIndex}`, `right: ${right}px`, shadow]
144
+ .filter(Boolean)
145
+ .join('; ');
146
+ }
147
+ }
148
+
149
+ function getUrlCellValue(value: unknown) {
150
+ if (typeof value !== 'string' || value.trim() === '') return undefined;
151
+ return value;
152
+ }
153
+
154
+ function openUrlCell(value: string) {
155
+ window.open(value, '_blank', 'noopener,noreferrer');
156
+ }
157
+
158
+ function getColumnMeta(columnDef: { meta?: unknown }): DataTableColumnMeta | undefined {
159
+ return columnDef.meta as DataTableColumnMeta | undefined;
160
+ }
161
+
162
+ const tableStateKey = $derived(JSON.stringify(table.store.state));
163
+ function trackTableState() {
164
+ return tableStateKey;
165
+ }
166
+
167
+ const rowModel = $derived.by(() => {
168
+ trackTableState();
169
+ return table.getRowModel();
170
+ });
171
+ const headerGroups = $derived.by(() => {
172
+ trackTableState();
173
+ return table.getHeaderGroups();
174
+ });
175
+ const visibleLeafColumns = $derived.by(() => {
176
+ trackTableState();
177
+ return table.getVisibleLeafColumns();
178
+ });
179
+ const visibleColumnCount = $derived(visibleLeafColumns.length);
180
+ const isRowSelectionEnabled = $derived(Boolean(table.options.enableRowSelection));
181
+ const isMultiRowSelectionEnabled = $derived(table.options.enableMultiRowSelection !== false);
182
+ const tableColumnCount = $derived(visibleColumnCount + (isRowSelectionEnabled ? 1 : 0));
183
+ const renderedColumnCount = $derived(tableColumnCount + 1);
184
+ const headerGroupCount = $derived(headerGroups.length);
185
+ const allRowsSelectionState = $derived(getAllRowsSelectionState(table.store.state.rowSelection));
186
+ const selectedRowCount = $derived(getSelectedRowCount(table.store.state.rowSelection));
187
+ const isColumnResizing = $derived(table.store.state.columnResizing.isResizingColumn !== false);
188
+ </script>
189
+
190
+ <div
191
+ class={cn(
192
+ 'flex max-h-full min-h-0 flex-col overflow-hidden rounded-lg border border-surface-3 bg-surface-1',
193
+ className
194
+ )}
195
+ {...rest}
196
+ >
197
+ {#if isColumnResizing}
198
+ <div aria-hidden="true" class="fixed inset-0 z-50 cursor-col-resize select-none"></div>
199
+ {/if}
200
+
201
+ <div class="min-h-0 flex-1 overflow-auto">
202
+ <table class="table-fixed border-separate border-spacing-0 text-sm" style={tableSizeStyle()}>
203
+ <colgroup>
204
+ {#if isRowSelectionEnabled}
205
+ <col style={selectionColumnSizeStyle()} />
206
+ {/if}
207
+ {#each visibleLeafColumns as column (column.id)}
208
+ <col style={columnSizeStyle(column.getSize())} />
209
+ {/each}
210
+ <col />
211
+ </colgroup>
212
+ {#if caption}
213
+ <caption class="sr-only">{caption}</caption>
214
+ {/if}
215
+ <thead class="sticky top-0 z-20 bg-surface-2 text-left text-ink-dim">
216
+ {#each headerGroups as headerGroup, headerGroupIndex (headerGroup.id)}
217
+ {@const visibleHeaders = headerGroup.headers.filter((header) => header.colSpan > 0)}
218
+ <tr class="h-9">
219
+ {#if isRowSelectionEnabled && headerGroupIndex === 0}
220
+ <th
221
+ class="h-9 border-b border-surface-3 bg-surface-2 px-3 py-0 text-center align-middle leading-5 font-medium"
222
+ style="position: sticky; left: 0; z-index: 15"
223
+ rowspan={headerGroupCount}
224
+ >
225
+ {#if isMultiRowSelectionEnabled}
226
+ <Checkbox
227
+ size="sm"
228
+ aria-label="Select all rows"
229
+ class="mx-auto size-4"
230
+ checked={allRowsSelectionState}
231
+ onCheckedChange={({ checked }) => table.toggleAllRowsSelected(checked === true)}
232
+ />
233
+ {/if}
234
+ </th>
235
+ {/if}
236
+ {#each visibleHeaders as header, headerIndex (header.id)}
237
+ {@const columnDef = getColumnMeta(header.column.columnDef)}
238
+ {@const sortDirection = getHeaderSortDirection(header, table.store.state.sorting)}
239
+ <th
240
+ class={cn(
241
+ 'relative h-9 border-b border-surface-3 bg-surface-2 px-3 py-0 align-middle leading-5 font-medium',
242
+ alignClass(columnDef?.align)
243
+ )}
244
+ colspan={header.colSpan}
245
+ aria-sort={header.column.getCanSort()
246
+ ? getHeaderAriaSort(sortDirection)
247
+ : undefined}
248
+ style={getPinningStyle(header.column, true)}
249
+ >
250
+ {#if !header.isPlaceholder}
251
+ {#if header.column.getCanSort()}
252
+ <button
253
+ type="button"
254
+ class={cn(
255
+ 'inline-flex max-w-full appearance-none items-center gap-1 rounded-sm border-0 bg-transparent p-0 align-middle text-sm leading-5 text-inherit outline-none hover:text-ink data-focus-visible:outline-2 data-focus-visible:outline-offset-2 data-focus-visible:outline-ring',
256
+ justifyClass(columnDef?.align),
257
+ sortButtonDirectionClass(columnDef?.align)
258
+ )}
259
+ aria-label={`${getHeaderSortLabel(sortDirection)}. Toggle sorting.`}
260
+ onclick={header.column.getToggleSortingHandler()}
261
+ >
262
+ <span class="min-w-0 truncate">
263
+ <FlexRender {header} />
264
+ </span>
265
+ <span
266
+ class="inline-flex size-3.5 shrink-0 items-center justify-center text-ink-dim"
267
+ >
268
+ {#if sortDirection === 'asc'}
269
+ <PhCaretUp class="size-3.5" />
270
+ {:else if sortDirection === 'desc'}
271
+ <PhCaretDown class="size-3.5" />
272
+ {/if}
273
+ </span>
274
+ </button>
275
+ {:else}
276
+ <FlexRender {header} />
277
+ {/if}
278
+ {/if}
279
+ {#if header.column.getCanResize()}
280
+ <div
281
+ aria-hidden="true"
282
+ class={resizeHandleClass(headerIndex, visibleHeaders.length)}
283
+ style={resizeHandleStyle(header)}
284
+ ondblclick={() => header.column.resetSize()}
285
+ onmousedown={header.getResizeHandler()}
286
+ ontouchstart={header.getResizeHandler()}
287
+ ></div>
288
+ {/if}
289
+ </th>
290
+ {/each}
291
+ <th aria-hidden="true" class="h-9 border-b border-surface-3 bg-surface-2 p-0"></th>
292
+ </tr>
293
+ {/each}
294
+ </thead>
295
+ <tbody>
296
+ {#each rowModel.rows as row (row.id)}
297
+ {@const rowSelected = getRowSelectionState(table.store.state.rowSelection, row.id)}
298
+ <tr
299
+ class={cn(
300
+ 'group/row border-b border-surface-3 last:border-b-0',
301
+ '[--row-bg:var(--compote-surface-1)]',
302
+ 'hover:bg-well/60 hover:[--row-bg:color-mix(in_srgb,var(--compote-well)_60%,var(--compote-surface-1))]',
303
+ rowSelected &&
304
+ 'bg-well/60 [--row-bg:color-mix(in_srgb,var(--compote-well)_60%,var(--compote-surface-1))]'
305
+ )}
306
+ >
307
+ {#if isRowSelectionEnabled}
308
+ <td
309
+ class="bg-(--row-bg) px-3 py-2 text-center align-middle"
310
+ style="position: sticky; left: 0; z-index: 1"
311
+ >
312
+ <Checkbox
313
+ size="sm"
314
+ aria-label="Select row"
315
+ class="mx-auto size-4"
316
+ checked={rowSelected}
317
+ disabled={!row.getCanSelect()}
318
+ onCheckedChange={({ checked }) => row.toggleSelected(checked === true)}
319
+ />
320
+ </td>
321
+ {/if}
322
+ {#each row.getVisibleCells() as cell (cell.id)}
323
+ {@const columnDef = getColumnMeta(cell.column.columnDef)}
324
+ <td
325
+ class={cn(
326
+ 'truncate px-3 py-2',
327
+ alignClass(columnDef?.align),
328
+ cell.column.getIsPinned() && 'bg-(--row-bg)'
329
+ )}
330
+ style={getPinningStyle(cell.column)}
331
+ >
332
+ {#if columnDef?.type === 'boolean'}
333
+ {@const value = getBooleanCellValue(cell.getValue())}
334
+ {#if value === true}
335
+ <span
336
+ class="inline-flex size-5 items-center justify-center text-success"
337
+ role="img"
338
+ aria-label="Yes"
339
+ >
340
+ <PhCheck class="size-4" />
341
+ </span>
342
+ {:else if value === false}
343
+ <span
344
+ class="inline-flex size-5 items-center justify-center text-danger"
345
+ role="img"
346
+ aria-label="No"
347
+ >
348
+ <PhX class="size-4" />
349
+ </span>
350
+ {:else}
351
+ -
352
+ {/if}
353
+ {:else if columnDef?.type === 'url'}
354
+ {@const value = getUrlCellValue(cell.getValue())}
355
+ {#if value}
356
+ <button
357
+ type="button"
358
+ class={cn(
359
+ 'inline-flex max-w-full appearance-none items-center gap-1.5 rounded-sm border-0 bg-transparent p-0 align-middle leading-5 font-medium text-ink underline decoration-border decoration-dotted underline-offset-4 outline-none hover:text-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
360
+ justifyClass(columnDef.align)
361
+ )}
362
+ onclick={() => openUrlCell(value)}
363
+ >
364
+ <PhArrowSquareOut class="size-3.5 shrink-0" />
365
+ </button>
366
+ {:else}
367
+ -
368
+ {/if}
369
+ {:else}
370
+ <FlexRender {cell} />
371
+ {/if}
372
+ </td>
373
+ {/each}
374
+ <td aria-hidden="true" class="p-0"></td>
375
+ </tr>
376
+ {:else}
377
+ <tr>
378
+ <td class="px-3 py-10 text-center text-sm text-ink-dim" colspan={renderedColumnCount}>
379
+ {emptyMessage}
380
+ </td>
381
+ </tr>
382
+ {/each}
383
+ </tbody>
384
+ </table>
385
+ </div>
386
+
387
+ <div class="shrink-0 border-t border-surface-3 bg-surface-2 px-3 py-2 text-sm text-ink-dim">
388
+ {#if isRowSelectionEnabled}
389
+ {selectedRowCount} of {rowModel.rows.length} rows selected
390
+ {:else}
391
+ {rowModel.rows.length} rows
392
+ {/if}
393
+ </div>
394
+ </div>
@@ -2,11 +2,9 @@ import type { RowData } from '@tanstack/svelte-table';
2
2
  import type { HTMLAttributes } from 'svelte/elements';
3
3
  import { type ClassValue } from 'tailwind-variants';
4
4
  import { type DataTableInstance } from './create-table';
5
- import type { DataTableColumn } from './types';
6
5
  declare function $$render<T extends RowData>(): {
7
6
  props: Omit<HTMLAttributes<HTMLDivElement>, "class"> & {
8
7
  table: DataTableInstance<T>;
9
- columns: DataTableColumn<T>[];
10
8
  caption?: string;
11
9
  emptyMessage?: string;
12
10
  class?: ClassValue;
@@ -49,3 +49,9 @@ export type DataTableGroupColumn<T extends RowData> = DataTableColumnBase & {
49
49
  formatLocale?: never;
50
50
  };
51
51
  export type DataTableColumn<T extends RowData> = DataTableLeafColumn<T> | DataTableGroupColumn<T>;
52
+ export type DataTableColumnMeta = {
53
+ align?: DataTableAlign;
54
+ type?: DataTableColumnType;
55
+ formatOptions?: Intl.NumberFormatOptions;
56
+ formatLocale?: string;
57
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "compote-ui",
3
- "version": "0.36.1",
3
+ "version": "0.37.0",
4
4
  "license": "MIT",
5
5
  "scripts": {
6
6
  "dev": "vite dev --open",