@zhangt58/svelte-vtable 0.1.3 → 0.2.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
@@ -61,7 +61,7 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
61
61
  <DataTableFilters
62
62
  {columnFilters}
63
63
  {activeFilters}
64
- filterChange={({ allFilters }) => (activeFilters = allFilters)}
64
+ onfilter={({ allFilters }) => (activeFilters = allFilters)}
65
65
  />
66
66
 
67
67
  <!-- Search and pagination controls -->
@@ -70,20 +70,20 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
70
70
  currentPage={ui.currentPage}
71
71
  perPage={ui.perPage}
72
72
  totalItems={items.length}
73
- pagechange={(e) => (ui.currentPage = e.currentPage)}
74
- searchchange={(e) => (ui.searchQuery = e.search)}
73
+ onpage={({ page }) => (ui.currentPage = page)}
74
+ onsearch={({ search }) => (ui.searchQuery = search)}
75
75
  />
76
76
 
77
77
  <!-- Virtualized table -->
78
78
  <DataTable
79
79
  {items}
80
80
  {visibleKeys}
81
- sortKey={ui.sortKey}
82
- sortDir={ui.sortDir}
83
- sortCallback={(key) => {
84
- /* handle sort */
81
+ bind:sortKey={ui.sortKey}
82
+ bind:sortDir={ui.sortDir}
83
+ onsort={({ key, dir }) => {
84
+ /* optionally trigger a server fetch here */
85
85
  }}
86
- selectCallback={(detail) => {
86
+ onselect={({ item, index }) => {
87
87
  /* handle selection */
88
88
  }}
89
89
  {colWidths}
@@ -106,20 +106,21 @@ A virtualized table component for efficient rendering of large datasets. The com
106
106
 
107
107
  #### Props
108
108
 
109
- | Prop | Type | Default | Description |
110
- | ---------------- | ----------------- | ------------------------ | ------------------------------------------------------------ |
111
- | `items` | `Array` | `[]` | Array of data items to display |
112
- | `visibleKeys` | `Array` | `[]` | Array of keys/titles to display as column headers |
113
- | `sortKey` | `string \| null` | `null` | Current sort key (column header) |
114
- | `sortDir` | `'asc' \| 'desc'` | `'asc'` | Sort direction |
115
- | `className` | `string` | `''` | Additional CSS classes |
116
- | `style` | `string` | `''` | Inline styles |
117
- | `emptyMessage` | `string` | `'No items to display.'` | Message when no items |
118
- | `colWidths` | `object \| Array` | `{}` | Column width configuration (stretch weights or pixel values) |
119
- | `selected` | `any` | `null` | Currently selected item |
120
- | `selectCallback` | `function` | `() => {}` | Callback when a row is selected: `({item, index}) => void` |
121
- | `sortCallback` | `function` | `defaultSort` | Callback when sorting: `(headerKey) => void` |
122
- | `rowSnippet` | `Snippet` | required | Svelte 5 snippet for rendering rows |
109
+ | Prop | Type | Default | Description |
110
+ | -------------- | ----------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
111
+ | `items` | `Array` | `[]` | Array of data items to display |
112
+ | `columns` | `ColumnDef[]` | `undefined` | **Unified column definitions** (recommended). When provided, `visibleKeys`, `colWidths`, and `rowSnippet` may be omitted. See [ColumnDef](#columndef) below. |
113
+ | `visibleKeys` | `Array` | `[]` | _(Legacy)_ Array of keys to display as column headers. Ignored when `columns` is provided. |
114
+ | `sortKey` | `string \| null` | `null` | Current sort key (column header); supports `bind:sortKey` |
115
+ | `sortDir` | `'asc' \| 'desc'` | `'asc'` | Sort direction; supports `bind:sortDir` |
116
+ | `className` | `string` | `''` | Additional CSS classes |
117
+ | `style` | `string` | `''` | Inline styles |
118
+ | `emptyMessage` | `string` | `'No items to display.'` | Message when no items |
119
+ | `colWidths` | `object \| Array` | `{}` | _(Legacy)_ Column width configuration (stretch weights or pixel values). Ignored when `columns` is provided. |
120
+ | `selected` | `any` | `null` | Currently selected item |
121
+ | `onselect` | `function` | `undefined` | Callback when a row is selected: `({item, index}) => void` |
122
+ | `onsort` | `function` | `undefined` | Callback when sort changes: `({key, dir}) => void`. When provided, local sorting is skipped (server-side sort pattern). Omit entirely (do not pass `() => {}`) to enable local sorting. |
123
+ | `rowSnippet` | `Snippet` | `undefined` | Svelte 5 snippet for rendering rows. Optional when `columns` is provided (a default row is rendered using each column's `cellSnippet` or raw value). |
123
124
 
124
125
  #### Row Snippet Parameters
125
126
 
@@ -130,6 +131,50 @@ The `rowSnippet` receives an object with:
130
131
  - `select` - Function to call to select this row
131
132
  - `selected` - Currently selected item (for comparison)
132
133
 
134
+ ### ColumnDef
135
+
136
+ `ColumnDef` is the unified column configuration object. Import the JSDoc type via:
137
+
138
+ ```js
139
+ // @type {import('@zhangt58/svelte-vtable').ColumnDef}
140
+ ```
141
+
142
+ | Field | Type | Default | Description |
143
+ | --------------- | ----------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------- |
144
+ | `key` | `string` | required | Data key. Must match a property on the row item. |
145
+ | `label` | `string` | `key` | Column header label. Defaults to `key`. |
146
+ | `width` | `number \| string` | `1` | Stretch weight (number) or CSS value (e.g. `'120px'`). |
147
+ | `sortable` | `boolean` | `true` | Whether clicking the header sorts the table. |
148
+ | `filterType` | `'value' \| 'daterange' \| 'datetimerange' \| 'none'` | `'value'` | Filter UI for this column. `'none'` excludes it from `buildColumnFilters`. |
149
+ | `headerSnippet` | `Snippet<[{key, label, sortKey, sortDir}]>` | `undefined` | Custom Svelte 5 snippet rendered inside `<th>`. |
150
+ | `cellSnippet` | `Snippet<[{item, value, index}]>` | `undefined` | Custom Svelte 5 snippet rendered inside each `<td>`. Used for default row rendering when `rowSnippet` is not provided. |
151
+
152
+ #### Minimal example using `columns`
153
+
154
+ ```svelte
155
+ <script>
156
+ import { DataTable, buildColumnFilters, applyFilters } from '@zhangt58/svelte-vtable';
157
+
158
+ const items = [...]; // your data
159
+
160
+ /** @type {import('@zhangt58/svelte-vtable').ColumnDef[]} */
161
+ const columns = [
162
+ { key: 'id', label: 'ID', width: 1, filterType: 'none' },
163
+ { key: 'name', label: 'Name', width: 3, filterType: 'none' },
164
+ { key: 'department', label: 'Department', width: 2, filterType: 'value' },
165
+ { key: 'hireDate', label: 'Hire Date', width: 2, filterType: 'daterange' },
166
+ ];
167
+
168
+ // Build filters directly from columns — filterType:'none' columns are skipped automatically
169
+ let columnFilters = buildColumnFilters(items, columns);
170
+ let activeFilters = $state({});
171
+ const filteredItems = $derived(applyFilters(items, activeFilters));
172
+ </script>
173
+
174
+ <!-- No visibleKeys, colWidths, or rowSnippet required -->
175
+ <DataTable items={filteredItems()} {columns} style="height: 400px" />
176
+ ```
177
+
133
178
  ### Filter example (filterCallback)
134
179
 
135
180
  Below is a minimal example showing how to wire the `filterCallback` prop on `VirtualDataTable` to apply per-column inline filters emitted by the header inputs. The idea: keep a small `filters` map in your component, compute a derived `filteredItems` list, and update `filters` when the table emits a column filter change.
@@ -197,14 +242,17 @@ Controls component for search and pagination.
197
242
 
198
243
  #### Props
199
244
 
200
- | Prop | Type | Default | Description |
201
- | -------------- | ---------- | ---------- | ---------------------------------------------------- |
202
- | `search` | `string` | `''` | Current search query |
203
- | `currentPage` | `number` | `1` | Current page number |
204
- | `perPage` | `number` | `25` | Items per page |
205
- | `totalItems` | `number` | `0` | Total number of items |
206
- | `pagechange` | `function` | `() => {}` | Callback for page changes: `({currentPage}) => void` |
207
- | `searchchange` | `function` | `() => {}` | Callback for search changes: `({search}) => void` |
245
+ | Prop | Type | Default | Description |
246
+ | ----------------- | ---------- | ----------- | -------------------------------------------------------------------------------------------------------- |
247
+ | `search` | `string` | `''` | Current search query |
248
+ | `currentPage` | `number` | `1` | Current page number |
249
+ | `perPage` | `number` | `25` | Items per page |
250
+ | `totalItems` | `number` | `0` | Total number of items |
251
+ | `onpage` | `function` | `undefined` | Callback for page changes: `({page}) => void` |
252
+ | `onsearch` | `function` | `undefined` | Callback for search changes: `({search}) => void` |
253
+ | `onfilterstoggle` | `function` | `undefined` | Callback when filters panel toggled: `({visible}) => void` |
254
+ | `onperpage` | `function` | `undefined` | Callback when per-page changes: `({perPage}) => void` |
255
+ | `onfilter` | `function` | `undefined` | Callback when filters change (passed through to DataTableFilters): `({key, values, allFilters}) => void` |
208
256
 
209
257
  ### DataTableFilters
210
258
 
@@ -212,14 +260,15 @@ Multi-select filter component with flexible layout options. Implements OR logic
212
260
 
213
261
  #### Props
214
262
 
215
- | Prop | Type | Default | Description |
216
- | --------------- | ---------------------------- | -------------- | -------------------------------------------------------- |
217
- | `columnFilters` | `Array` | `[]` | Array of filter configurations (see below) |
218
- | `direction` | `'horizontal' \| 'vertical'` | `'horizontal'` | Layout direction for filter grid |
219
- | `activeFilters` | `Object` | `{}` | Current active filters `{ columnKey: [selectedValues] }` |
220
- | `filterChange` | `function` | `() => {}` | Callback when filters change |
221
- | `className` | `string` | `''` | Additional CSS classes |
222
- | `showCounts` | `boolean` | `true` | Whether to show value counts |
263
+ | Prop | Type | Default | Description |
264
+ | --------------- | ---------------------------- | -------------- | ------------------------------------------------------------------- |
265
+ | `columnFilters` | `Array` | `[]` | Array of filter configurations (see below) |
266
+ | `direction` | `'horizontal' \| 'vertical'` | `'horizontal'` | Layout direction for filter grid |
267
+ | `activeFilters` | `Object` | `{}` | Current active filters `{ columnKey: [selectedValues] }` |
268
+ | `onfilter` | `function` | `undefined` | Callback when filters change: `({key, values, allFilters}) => void` |
269
+ | `oncolumnsort` | `function` | `undefined` | Callback when column sort changes: `({key, mode, dir}) => void` |
270
+ | `className` | `string` | `''` | Additional CSS classes |
271
+ | `showCounts` | `boolean` | `true` | Whether to show value counts |
223
272
 
224
273
  #### columnFilters Structure
225
274
 
@@ -284,7 +333,7 @@ Example usage with data filtering:
284
333
  <DataTableFilters
285
334
  {columnFilters}
286
335
  {activeFilters}
287
- filterChange={({ allFilters }) => (activeFilters = allFilters)}
336
+ onfilter={({ allFilters }) => (activeFilters = allFilters)}
288
337
  direction="horizontal"
289
338
  showCounts={true}
290
339
  />
@@ -348,16 +397,63 @@ Optional recommendation: add `prepare` to `package.json` so that `npm install` i
348
397
 
349
398
  This is optional — the current `prepublishOnly` is sufficient for publishing.
350
399
 
351
- ## CSS Custom Properties
400
+ ## Theming
352
401
 
353
- Override these CSS variables to customize appearance:
402
+ svelte-vtable exposes a set of CSS custom properties (variables) as its theming contract. All accent-coloured elements (active pagination button, active filter badge, filter button active state, dual-range slider) read from these variables, so you can re-theme the library without forking source or reconfiguring Tailwind.
403
+
404
+ ### Default values
354
405
 
355
406
  ```css
356
407
  :root {
357
- --tbl-head-bg: #f8f9fa; /* Header background */
408
+ --vtable-color-accent: #16a34a; /* green-600 — active elements */
409
+ --vtable-color-accent-light: #dcfce7; /* green-100 — active element background */
410
+ --vtable-color-accent-border: #22c55e; /* green-500 — active element border */
411
+ --vtable-color-accent-text: #15803d; /* green-700 — active element text */
412
+
413
+ --vtable-color-danger: #dc2626; /* red-600 — destructive actions */
414
+ --vtable-color-info: #3b82f6; /* blue-500 — dual-range slider */
415
+
416
+ --vtable-radius: 0.375rem; /* rounded-md */
417
+ --vtable-row-height: 2.25rem; /* virtual-scroll row height hint */
358
418
  }
359
419
  ```
360
420
 
421
+ ### Overriding the theme
422
+
423
+ Set any property on `:root` for a global override, or on a wrapper element for a scoped override:
424
+
425
+ ```css
426
+ /* app.css — global purple theme */
427
+ :root {
428
+ --vtable-color-accent: #7c3aed;
429
+ --vtable-color-accent-light: #ede9fe;
430
+ --vtable-color-accent-border: #8b5cf6;
431
+ --vtable-color-accent-text: #6d28d9;
432
+ }
433
+ ```
434
+
435
+ ```svelte
436
+ <!-- Scoped to a single section of a page -->
437
+ <div
438
+ style="--vtable-color-accent: #7c3aed; --vtable-color-accent-light: #ede9fe; --vtable-color-accent-border: #8b5cf6; --vtable-color-accent-text: #6d28d9;"
439
+ >
440
+ <DataTableControls ... />
441
+ <DataTable ... />
442
+ </div>
443
+ ```
444
+
445
+ ### What changes with `--vtable-color-accent`
446
+
447
+ | Element | Before (default green) | After override |
448
+ | ------------------------------------ | ----------------------------- | --------------------------------- |
449
+ | Active pagination button | green-100 bg + green-600 text | `accent-light` bg + `accent` text |
450
+ | Active filter count badge (controls) | green-600 background | `accent` background |
451
+ | Active filter button border | green-500 | `accent-border` |
452
+ | Active filter badge (count / range) | green-600 background | `accent` background |
453
+ | "Show All" button | green-600 border + text | `accent` border + text |
454
+
455
+ The live example at `examples/ThemedExample.svelte` lets you switch between green, purple, orange, and rose themes at runtime.
456
+
361
457
  ## TypeScript
362
458
 
363
459
  The library is written in JavaScript with JSDoc annotations. Type checking is available via `svelte-check`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhangt58/svelte-vtable",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "A Svelte 5 library for virtualized data tables with sorting, selection, and pagination controls.",
5
5
  "type": "module",
6
6
  "svelte": "./src/lib/index.js",
@@ -1,21 +1,53 @@
1
1
  <script>
2
2
  import { VirtualList } from 'svelte-virtuallists';
3
3
 
4
- // shared default no-op function (accepts any args) so prop types allow being called with a payload
5
- const DEFAULT_NOOP = (..._args) => {};
4
+ // Runic props: accept props via $props() so the component matches the
5
+ // project's runes-style components. Include the `select` callback prop.
6
+ let {
7
+ items = [],
8
+ // Unified column definitions array (required).
9
+ // @type {import('../lib/index.js').ColumnDef[]}
10
+ columns = [],
11
+ // sortKey/sortDir are bindable so parents can observe or control sort state.
12
+ sortKey = $bindable(null),
13
+ sortDir = $bindable('asc'),
14
+ className = '',
15
+ style = '',
16
+ emptyMessage = 'No items to display.',
17
+ selected = null,
18
+ // onselect({ item, index }) — called when a row is selected
19
+ onselect = undefined,
20
+ // onsort({ key, dir }) is called whenever sort changes.
21
+ // When provided, no local sorting is applied (server-side sort pattern).
22
+ onsort = undefined,
23
+ // Allow consumers to disable virtualization (useful when paginating by fixed item counts).
24
+ // If `virtualize` is false we ask the wrapped VirtualList to render as a normal list/table
25
+ // by setting its `isDisabled` prop. Default: true (virtualization enabled).
26
+ virtualize = true,
27
+ } = $props();
6
28
 
7
- // Default sort behavior: sort by the header string alphabetically, toggling asc/desc
8
- // and actually sort the items array
9
- function defaultSort(key) {
10
- if (sortKey === key) {
11
- sortDir = sortDir === 'asc' ? 'desc' : 'asc';
12
- } else {
13
- sortKey = key;
14
- sortDir = 'asc';
15
- }
29
+ // --- Derived values from ColumnDef[] ---
30
+
31
+ // Keys of columns to display.
32
+ const effectiveVisibleKeys = $derived(columns.map((c) => c.key));
33
+
34
+ // Width configuration: build an object keyed by column key.
35
+ const effectiveColWidths = $derived(
36
+ Object.fromEntries(columns.map((c) => [c.key, c.width ?? 1])),
37
+ );
16
38
 
17
- // Actually sort the items array
18
- items = [...items].sort((a, b) => {
39
+ // Fast lookup map: key → ColumnDef.
40
+ const colDefMap = $derived(Object.fromEntries(columns.map((c) => [c.key, c])));
41
+
42
+ // Internal sorted array derived from items + current sort state.
43
+ // When onsort is provided the parent manages sorting (server-side), so we
44
+ // pass items through unchanged. Otherwise we sort locally.
45
+ const sortedItems = $derived.by(() => {
46
+ if (onsort !== undefined || !sortKey) return items;
47
+
48
+ const key = sortKey;
49
+ const dir = sortDir;
50
+ return [...items].sort((a, b) => {
19
51
  const aVal = a[key];
20
52
  const bVal = b[key];
21
53
 
@@ -34,103 +66,65 @@
34
66
  sensitivity: 'base',
35
67
  });
36
68
 
37
- // Apply sort direction
38
- return sortDir === 'asc' ? comparison : -comparison;
69
+ return dir === 'asc' ? comparison : -comparison;
39
70
  });
40
- }
41
-
42
- // Runic props: accept props via $props() so the component matches the
43
- // project's runes-style components. Include the `select` callback prop.
44
- let {
45
- items = [],
46
- visibleKeys = [],
47
- // treat sortKey/sortDir as normal props; parent may control them and
48
- // provide a `sort` callback to update them.
49
- sortKey = null,
50
- sortDir = 'asc',
51
- className = '',
52
- style = '',
53
- emptyMessage = 'No items to display.',
54
- colWidths = {},
55
- selected = null,
56
- // external selection callback with a safe default no-op
57
- selectCallback = DEFAULT_NOOP,
58
- // new prop name: sortCallback defaulting to `defaultSort` (alphabetical string sort)
59
- sortCallback = defaultSort,
60
- // New prop: allow consumers to disable virtualization (useful when paginating by fixed item counts)
61
- // If `virtualize` is false we ask the wrapped VirtualList to render as a normal list/table
62
- // by setting its `isDisabled` prop. Default: true (virtualization enabled).
63
- virtualize = true,
64
- // <slot> -> @render migration
65
- rowSnippet,
66
- } = $props();
71
+ });
67
72
 
68
73
  // expose selection via the callback prop (if provided)
69
74
  function selectItem(item, index) {
70
75
  selected = item;
71
76
  try {
72
- callSelectCallback({ item, index });
73
- } catch (err) {
74
- try {
75
- console.error('selectCallback threw:', err);
76
- } catch (e) {}
77
- }
78
- }
79
-
80
- // Wrapper that casts the possibly-typed callback to any before invoking so callers may pass a payload
81
- function callSelectCallback(payload) {
82
- try {
83
- /** @type {any} */ (selectCallback)(payload);
77
+ if (onselect !== undefined) {
78
+ onselect({ item, index });
79
+ }
84
80
  } catch (err) {
85
81
  try {
86
- console.error('selectCallback threw:', err);
82
+ console.error('onselect threw:', err);
87
83
  } catch (e) {}
88
84
  }
89
85
  }
90
86
 
91
- // When header is clicked update the exported sortKey/sortDir so parents
92
- // using bind:sortKey / bind:sortDir receive updates (no event dispatching).
87
+ // When a header is clicked, toggle/update sortKey and sortDir, then notify
88
+ // the parent via onsort. Parents using bind:sortKey / bind:sortDir will
89
+ // receive the updated values automatically.
93
90
  function handleSort(key) {
94
- // Delegate sorting to the configured callback (by default `defaultSort` will run)
91
+ if (sortKey === key) {
92
+ sortDir = sortDir === 'asc' ? 'desc' : 'asc';
93
+ } else {
94
+ sortKey = key;
95
+ sortDir = 'asc';
96
+ }
95
97
  try {
96
- sortCallback(key);
98
+ if (onsort) onsort({ key: sortKey, dir: sortDir });
97
99
  } catch (err) {
98
100
  try {
99
- console.error('sortCallback threw:', err);
101
+ console.error('onsort threw:', err);
100
102
  } catch (e) {}
101
103
  }
102
104
  }
103
105
 
104
- // Normalize colWidths: handle object or array input, treat numeric as stretch weights.
105
- // NOTE: percentage strings (e.g. '30%') are no longer supported and will be ignored with a warning.
106
+ // Normalize colWidths: treat numeric values as stretch weights and pass through CSS strings.
107
+ // Memoized: only recomputes when effectiveVisibleKeys or effectiveColWidths changes.
108
+ const colWidthMap = $derived(normalizeColWidths());
109
+
106
110
  function normalizeColWidths() {
107
111
  const map = {};
112
+ const keys = effectiveVisibleKeys;
113
+ const widths = effectiveColWidths;
108
114
 
109
- // Build an ordered list of entries for visibleKeys
110
- const entries = visibleKeys.map((key, i) => {
111
- let v;
112
- if (Array.isArray(colWidths)) v = colWidths[i];
113
- else if (colWidths && typeof colWidths === 'object') v = colWidths[key];
114
- else v = undefined;
115
- return { key, v };
116
- });
117
-
118
- // Collect numeric stretch weights and pass-through non-percent strings
119
115
  const numeric = [];
120
116
  const otherStrings = [];
121
117
 
122
- for (const e of entries) {
123
- const v = e.v;
118
+ for (const key of keys) {
119
+ const v = widths[key];
124
120
  if (typeof v === 'number' && !Number.isNaN(v)) {
125
- numeric.push({ key: e.key, w: v });
121
+ numeric.push({ key, w: v });
126
122
  } else if (typeof v === 'string') {
127
123
  const s = v.trim();
128
- if (s.endsWith('%')) {
129
- // Percent strings are intentionally unsupported now - ignore silently
130
- } else {
131
- // keep other string units (e.g., '120px')
132
- otherStrings.push({ key: e.key, v: s });
124
+ if (!s.endsWith('%')) {
125
+ otherStrings.push({ key, v: s });
133
126
  }
127
+ // percent strings are intentionally unsupported — ignore silently
134
128
  }
135
129
  }
136
130
 
@@ -149,7 +143,7 @@
149
143
  });
150
144
  }
151
145
 
152
- // Copy through non-percent strings (e.g. '120px')
146
+ // Copy through non-percent CSS strings (e.g. '120px')
153
147
  for (const o of otherStrings) {
154
148
  map[o.key] = o.v;
155
149
  }
@@ -158,40 +152,10 @@
158
152
  }
159
153
 
160
154
  // Compute column width by key (fallback to even distribution)
161
- function calcColWidth(key, index) {
162
- try {
163
- const norm = normalizeColWidths();
164
- if (norm && norm[key] !== undefined) return String(norm[key]);
165
-
166
- // Fallbacks: accept string widths (e.g. '120px') passed directly by the user.
167
- // Numeric values should be provided as stretch weights and will be handled
168
- // by normalizeColWidths(); if we encounter numeric values here, warn and ignore them.
169
- if (Array.isArray(colWidths) && colWidths[index] !== undefined) {
170
- const v = colWidths[index];
171
- if (typeof v === 'string') {
172
- const s = v.trim();
173
- if (!s.endsWith('%')) {
174
- return v; // e.g. '120px'
175
- }
176
- // percent strings are ignored silently
177
- }
178
- }
179
- if (typeof colWidths === 'object' && colWidths[key] !== undefined) {
180
- const v = colWidths[key];
181
- if (typeof v === 'string') {
182
- const s = v.trim();
183
- if (!s.endsWith('%')) {
184
- return v; // e.g. '120px'
185
- }
186
- // percent strings are ignored silently
187
- }
188
- }
189
- } catch (err) {
190
- // ignore and fall through to defaults
191
- }
192
- const n = Math.max(1, visibleKeys.length);
193
- const pct = Math.floor(100 / n);
194
- return pct + '%';
155
+ function calcColWidth(key) {
156
+ if (colWidthMap[key] !== undefined) return String(colWidthMap[key]);
157
+ const n = Math.max(1, effectiveVisibleKeys.length);
158
+ return Math.floor(100 / n) + '%';
195
159
  }
196
160
  </script>
197
161
 
@@ -201,7 +165,7 @@
201
165
  by setting `isDisabled`. This ensures pagination based on item counts shows the
202
166
  exact number of rows expected (useful when rows have variable height). -->
203
167
  <VirtualList
204
- {items}
168
+ items={sortedItems}
205
169
  isTable
206
170
  isDisabled={!virtualize}
207
171
  class="datatable-table max-w-full max-h-full overflow-auto"
@@ -209,29 +173,36 @@
209
173
  <!-- colgroup enforces the column widths so table-layout: fixed distributes as intended -->
210
174
  {#snippet header()}
211
175
  <colgroup>
212
- {#each visibleKeys as key, i}
213
- <col style="width: {calcColWidth(key, i)}" />
176
+ {#each effectiveVisibleKeys as key}
177
+ <col style="width: {calcColWidth(key)}" />
214
178
  {/each}
215
179
  </colgroup>
216
180
  <thead class="sticky-header">
217
181
  <tr>
218
- {#each visibleKeys as key, i}
182
+ {#each effectiveVisibleKeys as key}
183
+ {@const colDef = colDefMap[key]}
184
+ {@const label = colDef?.label ?? key}
185
+ {@const isSortable = colDef?.sortable !== false}
219
186
  <th
220
- style="width: {calcColWidth(key, i)}"
221
- class="cursor-pointer select-none"
222
- onclick={() => handleSort(key)}
187
+ style="width: {calcColWidth(key)}"
188
+ class={isSortable ? 'cursor-pointer select-none' : 'select-none'}
189
+ onclick={isSortable ? () => handleSort(key) : undefined}
223
190
  aria-sort={sortKey === key
224
191
  ? sortDir === 'asc'
225
192
  ? 'ascending'
226
193
  : 'descending'
227
194
  : 'none'}
228
195
  >
229
- <div class="inline-flex items-center gap-1">
230
- <span>{key}</span>
231
- {#if sortKey === key}
232
- <span aria-hidden="true">{sortDir === 'asc' ? '▲' : '▼'}</span>
233
- {/if}
234
- </div>
196
+ {#if colDef?.headerSnippet}
197
+ {@render colDef.headerSnippet({ key, label, sortKey, sortDir })}
198
+ {:else}
199
+ <div class="inline-flex items-center gap-1">
200
+ <span>{label}</span>
201
+ {#if sortKey === key}
202
+ <span aria-hidden="true">{sortDir === 'asc' ? '▲' : '▼'}</span>
203
+ {/if}
204
+ </div>
205
+ {/if}
235
206
  </th>
236
207
  {/each}
237
208
  </tr>
@@ -239,7 +210,18 @@
239
210
  {/snippet}
240
211
 
241
212
  {#snippet vl_slot({ index, item })}
242
- {@render rowSnippet({ item, index, select: () => selectItem(item, index), selected })}
213
+ <!-- Default row rendering using each column's cellSnippet or raw value -->
214
+ <tr onclick={() => selectItem(item, index)} class={selected === item ? 'selected' : ''}>
215
+ {#each columns as col}
216
+ <td>
217
+ {#if col.cellSnippet}
218
+ {@render col.cellSnippet({ item, value: item[col.key], index })}
219
+ {:else}
220
+ {item[col.key] ?? ''}
221
+ {/if}
222
+ </td>
223
+ {/each}
224
+ </tr>
243
225
  {/snippet}
244
226
  </VirtualList>
245
227
  {:else}