@zhangt58/svelte-vtable 0.3.8 → 0.4.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.
package/README.md CHANGED
@@ -142,21 +142,26 @@ A virtualized table component for efficient rendering of large datasets. The com
142
142
 
143
143
  #### Props
144
144
 
145
- | Prop | Type | Default | Description |
146
- | -------------- | ----------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
147
- | `items` | `Array` | `[]` | Array of data items to display |
148
- | `columns` | `ColumnDef[]` | `undefined` | **Unified column definitions** (recommended). When provided, `visibleKeys`, `colWidths`, and `rowSnippet` may be omitted. See [ColumnDef](#columndef) below. |
149
- | `visibleKeys` | `Array` | `[]` | _(Legacy)_ Array of keys to display as column headers. Ignored when `columns` is provided. |
150
- | `sortKey` | `string \| null` | `null` | Current sort key (column header); supports `bind:sortKey` |
151
- | `sortDir` | `'asc' \| 'desc'` | `'asc'` | Sort direction; supports `bind:sortDir` |
152
- | `className` | `string` | `''` | Additional CSS classes |
153
- | `style` | `string` | `''` | Inline styles |
154
- | `emptyMessage` | `string` | `'No items to display.'` | Message when no items |
155
- | `colWidths` | `object \| Array` | `{}` | _(Legacy)_ Column width configuration (stretch weights or pixel values). Ignored when `columns` is provided. |
156
- | `selected` | `any` | `null` | Currently selected item |
157
- | `onselect` | `function` | `undefined` | Callback when a row is selected: `({item, index}) => void` |
158
- | `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. |
159
- | `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). |
145
+ | Prop | Type | Default | Description |
146
+ | --------------- | ----------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
147
+ | `items` | `Array` | `[]` | Array of data items to display |
148
+ | `columns` | `ColumnDef[]` | `undefined` | **Unified column definitions** (recommended). When provided, `visibleKeys`, `colWidths`, and `rowSnippet` may be omitted. See [ColumnDef](#columndef) below. |
149
+ | `visibleKeys` | `Array` | `[]` | _(Legacy)_ Array of keys to display as column headers. Ignored when `columns` is provided. |
150
+ | `sortKey` | `string \| null` | `null` | Current sort key (column header); supports `bind:sortKey` |
151
+ | `sortDir` | `'asc' \| 'desc'` | `'asc'` | Sort direction; supports `bind:sortDir` |
152
+ | `className` | `string` | `''` | Additional CSS classes |
153
+ | `style` | `string` | `''` | Inline styles |
154
+ | `emptyMessage` | `string` | `'No items to display.'` | Message when no items |
155
+ | `colWidths` | `object \| Array` | `{}` | _(Legacy)_ Column width configuration (stretch weights or pixel values). Ignored when `columns` is provided. |
156
+ | `selected` | `any` | `null` | Currently selected item |
157
+ | `onselect` | `function` | `undefined` | Callback when a row is selected: `({item, index}) => void` |
158
+ | `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. |
159
+ | `inlineFilters` | `boolean` | `false` | Renders column filter buttons in table headers. Without `onfilter`, filters are applied locally to `items`. |
160
+ | `columnFilters` | `Array \| null` | `null` | Optional explicit filter configurations, usually from `buildColumnFilters(rows, columns)`. Overrides derived filter options. |
161
+ | `filterItems` | `Array \| null` | `null` | Base data source used to derive inline filter options when `columnFilters` is omitted. Defaults to `items`; pass the unpaged/search-scoped rows when `items` is paged. |
162
+ | `activeFilters` | `Object` | `{}` | Controlled filter state for inline header filters. |
163
+ | `onfilter` | `function` | `undefined` | Callback when inline filters change: `({key, values, allFilters}) => void`. When provided, parent code is responsible for applying filters. |
164
+ | `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). |
160
165
 
161
166
  #### Row Snippet Parameters
162
167
 
@@ -175,87 +180,81 @@ The `rowSnippet` receives an object with:
175
180
  // @type {import('@zhangt58/svelte-vtable').ColumnDef}
176
181
  ```
177
182
 
178
- | Field | Type | Default | Description |
179
- | --------------- | ----------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------- |
180
- | `key` | `string` | required | Data key. Must match a property on the row item. |
181
- | `label` | `string` | `key` | Column header label. Defaults to `key`. |
182
- | `width` | `number \| string` | `1` | Stretch weight (number) or CSS value (e.g. `'120px'`). |
183
- | `sortable` | `boolean` | `true` | Whether clicking the header sorts the table. |
184
- | `filterType` | `'value' \| 'daterange' \| 'datetimerange' \| 'none'` | `'value'` | Filter UI for this column. `'none'` excludes it from `buildColumnFilters`. |
185
- | `headerSnippet` | `Snippet<[{key, label, sortKey, sortDir}]>` | `undefined` | Custom Svelte 5 snippet rendered inside `<th>`. |
186
- | `cellSnippet` | `Snippet<[{item, value, index}]>` | `undefined` | Custom Svelte 5 snippet rendered inside each `<td>`. Used for default row rendering when `rowSnippet` is not provided. |
183
+ | Field | Type | Default | Description |
184
+ | --------------- | --------------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------- |
185
+ | `key` | `string` | required | Data key. Must match a property on the row item. |
186
+ | `label` | `string` | `key` | Column header label. Defaults to `key`. |
187
+ | `width` | `number \| string` | `1` | Stretch weight (number) or CSS value (e.g. `'120px'`). |
188
+ | `sortable` | `boolean` | `true` | Whether clicking the header sorts the table. |
189
+ | `filterType` | `'value' \| 'list' \| 'daterange' \| 'datetimerange' \| 'none'` | `'value'` | Filter UI for this column. `'list'` is an alias for value-list filters; `'none'` excludes it from `buildColumnFilters`. |
190
+ | `headerSnippet` | `Snippet<[{key, label, sortKey, sortDir}]>` | `undefined` | Custom Svelte 5 snippet rendered inside `<th>`. |
191
+ | `cellSnippet` | `Snippet<[{item, value, index}]>` | `undefined` | Custom Svelte 5 snippet rendered inside each `<td>`. Used for default row rendering when `rowSnippet` is not provided. |
187
192
 
188
193
  #### Minimal example using `columns`
189
194
 
190
195
  ```svelte
191
196
  <script>
192
- import { DataTable, buildColumnFilters, applyFilters } from '@zhangt58/svelte-vtable';
197
+ import { DataTable } from '@zhangt58/svelte-vtable';
193
198
 
194
- const items = [...]; // your data
199
+ const items = [
200
+ { id: 1, name: 'Alice', department: 'Engineering', hireDate: '2024-01-15' },
201
+ { id: 2, name: 'Bob', department: 'Sales', hireDate: '2024-03-10' },
202
+ ];
195
203
 
196
204
  /** @type {import('@zhangt58/svelte-vtable').ColumnDef[]} */
197
205
  const columns = [
198
- { key: 'id', label: 'ID', width: 1, filterType: 'none' },
199
- { key: 'name', label: 'Name', width: 3, filterType: 'none' },
200
- { key: 'department', label: 'Department', width: 2, filterType: 'value' },
201
- { key: 'hireDate', label: 'Hire Date', width: 2, filterType: 'daterange' },
206
+ { key: 'id', label: 'ID', width: 1, filterType: 'none' },
207
+ { key: 'name', label: 'Name', width: 3, filterType: 'none' },
208
+ { key: 'department', label: 'Department', width: 2, filterType: 'value' },
209
+ { key: 'hireDate', label: 'Hire Date', width: 2, filterType: 'daterange' },
202
210
  ];
203
-
204
- // Build filters directly from columns — filterType:'none' columns are skipped automatically
205
- let columnFilters = buildColumnFilters(items, columns);
206
- let activeFilters = $state({});
207
- const filteredItems = $derived(applyFilters(items, activeFilters));
208
211
  </script>
209
212
 
210
- <!-- No visibleKeys, colWidths, or rowSnippet required -->
211
- <DataTable items={filteredItems()} {columns} style="height: 400px" />
213
+ <!-- No visibleKeys, colWidths, rowSnippet, or separate filters required -->
214
+ <DataTable {items} {columns} inlineFilters style="height: 400px" />
212
215
  ```
213
216
 
214
- ### Filter example (filterCallback)
217
+ #### Controlled inline filters
215
218
 
216
- 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.
219
+ For pagination, server requests, or shared filter controls, keep filters in the parent and pass the same state to `DataTable`:
217
220
 
218
221
  ```svelte
219
222
  <script>
220
- import { DataTable } from '@zhangt58/svelte-vtable';
223
+ import { DataTable, applyFilters } from '@zhangt58/svelte-vtable';
221
224
 
222
- // raw dataset you want to display/filter
223
- const rawItems = [
224
- { id: 1, name: 'Alice', email: 'alice@example.com' },
225
- { id: 2, name: 'Bob', email: 'bob@example.com' },
226
- { id: 3, name: 'Carol', email: 'carol@example.com' },
225
+ const rows = [
226
+ { department: 'Engineering', hireDate: '2024-01-15' },
227
+ { department: 'Sales', hireDate: '2024-03-10' },
227
228
  ];
229
+ const columns = [
230
+ { key: 'department', label: 'Department', filterType: 'value' },
231
+ { key: 'hireDate', label: 'Hire Date', filterType: 'daterange' },
232
+ ];
233
+
234
+ let activeFilters = $state({});
235
+ const optionRows = $derived(rows); // Apply search or server scoping here when needed.
236
+ const filteredRows = $derived(applyFilters(optionRows, activeFilters));
237
+ const pagedRows = $derived(filteredRows.slice(0, 25));
228
238
 
229
- // per-column filter values
230
- let filters = {};
231
-
232
- // derived, reactive filtered list
233
- $: filteredItems = rawItems.filter((item) =>
234
- Object.entries(filters).every(
235
- ([k, v]) =>
236
- !v ||
237
- String(item[k] ?? '')
238
- .toLowerCase()
239
- .includes(v.toLowerCase()),
240
- ),
241
- );
242
-
243
- // called when a ColumnHeader emits a filter event: { key, value }
244
- function handleFilter({ key, value }) {
245
- filters = { ...filters, [key]: value };
239
+ function handleFilter({ allFilters }) {
240
+ activeFilters = { ...allFilters };
246
241
  }
247
242
  </script>
248
243
 
249
- <DataTable items={filteredItems} visibleKeys={['name', 'email']} filterCallback={handleFilter}>
250
- {#snippet rowSnippet({ item, index, select, selected })}
251
- <tr onclick={select}>
252
- <td>{item.name}</td>
253
- <td>{item.email}</td>
254
- </tr>
255
- {/snippet}
256
- </DataTable>
244
+ <DataTable
245
+ items={pagedRows}
246
+ {columns}
247
+ inlineFilters
248
+ filterItems={optionRows}
249
+ {activeFilters}
250
+ onfilter={handleFilter}
251
+ />
257
252
  ```
258
253
 
254
+ When `filterItems` and `activeFilters` are provided, derived filter options are faceted per column: each column is built from `filterItems` after applying the other active filters, but not that column's own filter. This keeps date range bounds and value choices available when the current column filter temporarily matches zero rows.
255
+
256
+ Date range quick presets such as `Last 7d` are relative to the current wall-clock date/time. Presets that would match no rows in the current option source are disabled.
257
+
259
258
  #### Column Widths
260
259
 
261
260
  Column widths can be specified as:
@@ -278,17 +277,21 @@ Controls component for search and pagination.
278
277
 
279
278
  #### Props
280
279
 
281
- | Prop | Type | Default | Description |
282
- | ----------------- | ---------- | ----------- | -------------------------------------------------------------------------------------------------------- |
283
- | `search` | `string` | `''` | Current search query |
284
- | `currentPage` | `number` | `1` | Current page number |
285
- | `perPage` | `number` | `25` | Items per page |
286
- | `totalItems` | `number` | `0` | Total number of items |
287
- | `onpage` | `function` | `undefined` | Callback for page changes: `({page}) => void` |
288
- | `onsearch` | `function` | `undefined` | Callback for search changes: `({search}) => void` |
289
- | `onfilterstoggle` | `function` | `undefined` | Callback when filters panel toggled: `({visible}) => void` |
290
- | `onperpage` | `function` | `undefined` | Callback when per-page changes: `({perPage}) => void` |
291
- | `onfilter` | `function` | `undefined` | Callback when filters change (passed through to DataTableFilters): `({key, values, allFilters}) => void` |
280
+ | Prop | Type | Default | Description |
281
+ | ----------------- | --------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------- |
282
+ | `search` | `string` | `''` | Current search query |
283
+ | `currentPage` | `number` | `1` | Current page number |
284
+ | `perPage` | `number` | `25` | Items per page |
285
+ | `totalItems` | `number` | `0` | Total number of items |
286
+ | `onpage` | `function` | `undefined` | Callback for page changes: `({page}) => void` |
287
+ | `onsearch` | `function` | `undefined` | Callback for search changes: `({search}) => void` |
288
+ | `onfilterstoggle` | `function` | `undefined` | Callback when filters panel toggled: `({visible}) => void` |
289
+ | `onperpage` | `function` | `undefined` | Callback when per-page changes: `({perPage}) => void` |
290
+ | `columnFilters` | `Array \| null` | `null` | Optional explicit modal filter configurations. Overrides derived filter options. |
291
+ | `columns` | `ColumnDef[]` | `[]` | Column definitions used with `filterItems` to derive modal filter options. |
292
+ | `filterItems` | `Array \| null` | `null` | Base data source used to derive modal filter options. Pass unpaged/search-scoped rows; active peer filters are applied per column. |
293
+ | `activeFilters` | `Object` | `{}` | Current active filters used for the modal state and faceted option derivation. |
294
+ | `onfilter` | `function` | `undefined` | Callback when filters change (passed through to DataTableFilters): `({key, values, allFilters}) => void` |
292
295
 
293
296
  ### DataTableFilters
294
297
 
@@ -1,5 +1,13 @@
1
1
  <script>
2
2
  import { VirtualList } from 'svelte-virtuallists';
3
+ import ColumnHeaderFilter from './filters/ColumnHeaderFilter.svelte';
4
+ import { useFilterState } from './filters/useFilterState.svelte.js';
5
+ import {
6
+ DEFAULT_RELATIVE_RANGE_PRESETS,
7
+ applyFilters,
8
+ hasActiveFilterValue,
9
+ resolveColumnFilters,
10
+ } from '../filterUtils.js';
3
11
 
4
12
  // Runic props: accept props via $props() so the component matches the
5
13
  // project's runes-style components. Include the `select` callback prop.
@@ -20,6 +28,25 @@
20
28
  // onsort({ key, dir }) is called whenever sort changes.
21
29
  // When provided, no local sorting is applied (server-side sort pattern).
22
30
  onsort = undefined,
31
+ // Render per-column filter controls in table headers.
32
+ inlineFilters = false,
33
+ // Filter configs can be provided from all source rows. When omitted and
34
+ // inlineFilters is true, configs are derived from filterItems or this component's items.
35
+ columnFilters = null,
36
+ // Base data source used to build inline filter option lists when columnFilters is omitted.
37
+ filterItems = null,
38
+ activeFilters = {},
39
+ // onfilter({ key, values, allFilters }) makes filtering parent-managed.
40
+ // When omitted, inline filters are applied locally to this table's items.
41
+ onfilter = undefined,
42
+ oncolumnsort = undefined,
43
+ showCounts = true,
44
+ virtualThreshold = 500,
45
+ virtualItemHeight = 36,
46
+ virtualOverscan = 5,
47
+ populateThreshold = 200,
48
+ emitDebounce = 100,
49
+ relativeRangePresets = DEFAULT_RELATIVE_RANGE_PRESETS,
23
50
  // Allow consumers to disable virtualization (useful when paginating by fixed item counts).
24
51
  // If `virtualize` is false we ask the wrapped VirtualList to render as a normal list/table
25
52
  // by setting its `isDisabled` prop. Default: true (virtualization enabled).
@@ -39,15 +66,43 @@
39
66
  // Fast lookup map: key → ColumnDef.
40
67
  const colDefMap = $derived(Object.fromEntries(columns.map((c) => [c.key, c])));
41
68
 
69
+ const effectiveColumnFilters = $derived.by(() => {
70
+ return resolveColumnFilters({
71
+ columnFilters,
72
+ columns,
73
+ filterItems: Array.isArray(filterItems) ? filterItems : items,
74
+ activeFilters,
75
+ enabled: inlineFilters,
76
+ });
77
+ });
78
+
79
+ const filterDefMap = $derived(
80
+ Object.fromEntries(effectiveColumnFilters.map((filter) => [filter.key, filter])),
81
+ );
82
+
83
+ const filterState = useFilterState({
84
+ columnFilters: () => effectiveColumnFilters,
85
+ activeFilters: () => activeFilters || {},
86
+ emitDebounce: () => emitDebounce,
87
+ onfilter: () => onfilter,
88
+ });
89
+
90
+ let openFilterKey = $state(null);
91
+
92
+ const filteredItems = $derived.by(() => {
93
+ if (!inlineFilters || onfilter !== undefined) return items;
94
+ return applyFilters(items, filterState.selections);
95
+ });
96
+
42
97
  // Internal sorted array derived from items + current sort state.
43
98
  // When onsort is provided the parent manages sorting (server-side), so we
44
99
  // pass items through unchanged. Otherwise we sort locally.
45
100
  const sortedItems = $derived.by(() => {
46
- if (onsort !== undefined || !sortKey) return items;
101
+ if (onsort !== undefined || !sortKey) return filteredItems;
47
102
 
48
103
  const key = sortKey;
49
104
  const dir = sortDir;
50
- return [...items].sort((a, b) => {
105
+ return [...filteredItems].sort((a, b) => {
51
106
  const aVal = a[key];
52
107
  const bVal = b[key];
53
108
 
@@ -103,6 +158,28 @@
103
158
  }
104
159
  }
105
160
 
161
+ function toggleFilter(key) {
162
+ openFilterKey = openFilterKey === key ? null : key;
163
+ }
164
+
165
+ function closeFilter() {
166
+ openFilterKey = null;
167
+ }
168
+
169
+ function handleKeydown(event) {
170
+ if (event.key === 'Escape') closeFilter();
171
+ }
172
+
173
+ function handleColumnFilterSort(columnKey, { mode, dir }) {
174
+ try {
175
+ if (oncolumnsort) /** @type {any} */ (oncolumnsort)({ key: columnKey, mode, dir });
176
+ } catch (err) {
177
+ try {
178
+ console.debug('oncolumnsort threw', err);
179
+ } catch (e) {}
180
+ }
181
+ }
182
+
106
183
  // Normalize colWidths: treat numeric values as stretch weights and pass through CSS strings.
107
184
  // Memoized: only recomputes when effectiveVisibleKeys or effectiveColWidths changes.
108
185
  const colWidthMap = $derived(normalizeColWidths());
@@ -159,13 +236,15 @@
159
236
  }
160
237
  </script>
161
238
 
239
+ <svelte:window onclick={closeFilter} onkeydown={handleKeydown} />
240
+
162
241
  <section class="virtual-data-table {className}" {style}>
163
- {#if items && items.length > 0}
242
+ {#if columns.length > 0}
164
243
  <!-- When `virtualize` is false we instruct VirtualList to render as a normal list/table
165
244
  by setting `isDisabled`. This ensures pagination based on item counts shows the
166
245
  exact number of rows expected (useful when rows have variable height). -->
167
246
  <VirtualList
168
- items={sortedItems}
247
+ items={Array.isArray(sortedItems) ? sortedItems : []}
169
248
  isTable
170
249
  isDisabled={!virtualize}
171
250
  class="datatable-table max-w-full max-h-full overflow-auto"
@@ -179,30 +258,67 @@
179
258
  </colgroup>
180
259
  <thead class="sticky-header">
181
260
  <tr>
182
- {#each effectiveVisibleKeys as key}
261
+ {#each effectiveVisibleKeys as key, columnIndex}
183
262
  {@const colDef = colDefMap[key]}
263
+ {@const filterDef = filterDefMap[key]}
184
264
  {@const label = colDef?.label ?? key}
185
265
  {@const isSortable = colDef?.sortable !== false}
266
+ {@const selection = filterDef ? filterState.selections[filterDef.key] : undefined}
267
+ {@const isFilterActive = hasActiveFilterValue(selection)}
186
268
  <th
187
269
  style="width: {calcColWidth(key)}"
188
- class={isSortable ? 'cursor-pointer select-none' : 'select-none'}
189
- onclick={isSortable ? () => handleSort(key) : undefined}
270
+ class="select-none"
190
271
  aria-sort={sortKey === key
191
272
  ? sortDir === 'asc'
192
273
  ? 'ascending'
193
274
  : 'descending'
194
275
  : 'none'}
195
276
  >
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}
277
+ <div class="vtable-header-content">
278
+ {#if colDef?.headerSnippet}
279
+ <div class="min-w-0 flex-1">
280
+ {@render colDef.headerSnippet({ key, label, sortKey, sortDir })}
281
+ </div>
282
+ {:else if isSortable}
283
+ <button
284
+ type="button"
285
+ class="vtable-header-sort-button min-w-0 flex-1 cursor-pointer"
286
+ onclick={() => handleSort(key)}
287
+ >
288
+ <span class="min-w-0 truncate">{label}</span>
289
+ {#if sortKey === key}
290
+ <span aria-hidden="true">{sortDir === 'asc' ? '▲' : '▼'}</span>
291
+ {/if}
292
+ </button>
293
+ {:else}
294
+ <span class="min-w-0 flex-1 truncate">{label}</span>
295
+ {/if}
296
+
297
+ {#if inlineFilters && filterDef}
298
+ <ColumnHeaderFilter
299
+ column={filterDef}
300
+ {selection}
301
+ isOpen={openFilterKey === filterDef.key}
302
+ isActive={isFilterActive}
303
+ align={columnIndex > effectiveVisibleKeys.length / 2 ? 'right' : 'left'}
304
+ {showCounts}
305
+ {virtualThreshold}
306
+ {virtualItemHeight}
307
+ {virtualOverscan}
308
+ {populateThreshold}
309
+ {relativeRangePresets}
310
+ ontoggle={() => toggleFilter(filterDef.key)}
311
+ onclear={() => filterState.clearColumn(filterDef.key)}
312
+ onvaluetoggle={(value) => filterState.toggleSelection(filterDef.key, value)}
313
+ oncheckall={(values) => filterState.checkAll(filterDef.key, values)}
314
+ oninvert={(values) => filterState.invertSelection(filterDef.key, values)}
315
+ onchecknone={() => filterState.checkNone(filterDef.key)}
316
+ ondaterangechange={(updated) =>
317
+ filterState.updateDateRange(filterDef.key, updated)}
318
+ onsortchange={(payload) => handleColumnFilterSort(filterDef.key, payload)}
319
+ />
320
+ {/if}
321
+ </div>
206
322
  </th>
207
323
  {/each}
208
324
  </tr>
@@ -224,6 +340,9 @@
224
340
  </tr>
225
341
  {/snippet}
226
342
  </VirtualList>
343
+ {#if !sortedItems || sortedItems.length === 0}
344
+ <div class="p-4 text-center text-slate-500">{emptyMessage}</div>
345
+ {/if}
227
346
  {:else}
228
347
  <div class="p-4 text-center text-slate-500">{emptyMessage}</div>
229
348
  {/if}
@@ -353,6 +472,31 @@
353
472
  align-items: center;
354
473
  gap: 0.25rem;
355
474
  }
475
+ :global(.datatable-table thead th) {
476
+ position: relative;
477
+ }
478
+ :global(.datatable-table thead th .vtable-header-content) {
479
+ display: flex;
480
+ align-items: center;
481
+ justify-content: space-between;
482
+ gap: 0.25rem;
483
+ min-width: 0;
484
+ width: 100%;
485
+ }
486
+ :global(.datatable-table thead th .vtable-header-sort-button) {
487
+ appearance: none;
488
+ border: 0;
489
+ background: transparent;
490
+ color: inherit;
491
+ font: inherit;
492
+ letter-spacing: inherit;
493
+ text-transform: inherit;
494
+ padding: 0;
495
+ display: inline-flex;
496
+ align-items: center;
497
+ gap: 0.25rem;
498
+ text-align: left;
499
+ }
356
500
  /* Allow certain long cells to wrap fully if explicitly requested */
357
501
  :global(.datatable-table td.wrap) {
358
502
  white-space: normal;
@@ -14,6 +14,19 @@ declare const DataTable: import("svelte").Component<{
14
14
  selected?: any;
15
15
  onselect?: any;
16
16
  onsort?: any;
17
+ inlineFilters?: boolean;
18
+ columnFilters?: any;
19
+ filterItems?: any;
20
+ activeFilters?: Record<string, any>;
21
+ onfilter?: any;
22
+ oncolumnsort?: any;
23
+ showCounts?: boolean;
24
+ virtualThreshold?: number;
25
+ virtualItemHeight?: number;
26
+ virtualOverscan?: number;
27
+ populateThreshold?: number;
28
+ emitDebounce?: number;
29
+ relativeRangePresets?: typeof DEFAULT_RELATIVE_RANGE_PRESETS;
17
30
  virtualize?: boolean;
18
31
  }, {}, "sortKey" | "sortDir">;
19
32
  type $$ComponentProps = {
@@ -27,5 +40,19 @@ type $$ComponentProps = {
27
40
  selected?: any;
28
41
  onselect?: any;
29
42
  onsort?: any;
43
+ inlineFilters?: boolean;
44
+ columnFilters?: any;
45
+ filterItems?: any;
46
+ activeFilters?: Record<string, any>;
47
+ onfilter?: any;
48
+ oncolumnsort?: any;
49
+ showCounts?: boolean;
50
+ virtualThreshold?: number;
51
+ virtualItemHeight?: number;
52
+ virtualOverscan?: number;
53
+ populateThreshold?: number;
54
+ emitDebounce?: number;
55
+ relativeRangePresets?: typeof DEFAULT_RELATIVE_RANGE_PRESETS;
30
56
  virtualize?: boolean;
31
57
  };
58
+ import { DEFAULT_RELATIVE_RANGE_PRESETS } from '../filterUtils.js';
@@ -1,6 +1,7 @@
1
1
  <script>
2
2
  import FiltersModal from './FiltersModal.svelte';
3
3
  import PaginationBar from './PaginationBar.svelte';
4
+ import { countActiveFilters, resolveColumnFilters } from '../filterUtils.js';
4
5
 
5
6
  // Props for search, pagination (perPage made bindable using Svelte 5 rune $bindable)
6
7
  let {
@@ -14,8 +15,11 @@
14
15
  filtersVisible = false,
15
16
  // callback when toggle changes: onfilterstoggle({ visible })
16
17
  onfilterstoggle = undefined,
17
- // optional DataTableFilters inputs - when provided, this component will render the filters
18
- columnFilters = [],
18
+ // optional DataTableFilters inputs - explicit configs override derived configs
19
+ columnFilters = null,
20
+ // optional column definitions + base row source used to derive modal filter options
21
+ columns = [],
22
+ filterItems = null,
19
23
  activeFilters = {},
20
24
  // onfilter({ key, values, allFilters }) — passed through to DataTableFilters
21
25
  /** @type {((..._args: any[]) => void) | undefined} */
@@ -34,18 +38,16 @@
34
38
  { value: 100, name: '100 rows' },
35
39
  ];
36
40
 
37
- // count of active filters (sum of selected values per column, including daterange/datetimerange)
38
- const activeFilterCount = $derived.by(() => {
39
- try {
40
- return Object.values(activeFilters || {}).reduce((sum, v) => {
41
- if (Array.isArray(v)) return sum + v.length;
42
- if (v && typeof v === 'object' && (v.from || v.to)) return sum + 1;
43
- return sum;
44
- }, 0);
45
- } catch (e) {
46
- return 0;
47
- }
48
- });
41
+ const activeFilterCount = $derived(countActiveFilters(activeFilters));
42
+
43
+ const effectiveColumnFilters = $derived.by(() =>
44
+ resolveColumnFilters({
45
+ columnFilters,
46
+ columns,
47
+ filterItems,
48
+ activeFilters,
49
+ }),
50
+ );
49
51
 
50
52
  // totalPages derived from totalItems and perPage
51
53
  const totalPages = $derived(Math.max(1, Math.ceil(totalItems / perPage)));
@@ -320,7 +322,7 @@
320
322
 
321
323
  <FiltersModal
322
324
  bind:open={filtersVisible}
323
- {columnFilters}
325
+ columnFilters={effectiveColumnFilters}
324
326
  {activeFilters}
325
327
  {onfilter}
326
328
  {direction}
@@ -452,6 +454,31 @@
452
454
  align-items: center;
453
455
  gap: 0.25rem;
454
456
  }
457
+ :global(.datatable-table thead th) {
458
+ position: relative;
459
+ }
460
+ :global(.datatable-table thead th .vtable-header-content) {
461
+ display: flex;
462
+ align-items: center;
463
+ justify-content: space-between;
464
+ gap: 0.25rem;
465
+ min-width: 0;
466
+ width: 100%;
467
+ }
468
+ :global(.datatable-table thead th .vtable-header-sort-button) {
469
+ appearance: none;
470
+ border: 0;
471
+ background: transparent;
472
+ color: inherit;
473
+ font: inherit;
474
+ letter-spacing: inherit;
475
+ text-transform: inherit;
476
+ padding: 0;
477
+ display: inline-flex;
478
+ align-items: center;
479
+ gap: 0.25rem;
480
+ text-align: left;
481
+ }
455
482
  /* Allow certain long cells to wrap fully if explicitly requested */
456
483
  :global(.datatable-table td.wrap) {
457
484
  white-space: normal;
@@ -12,7 +12,9 @@ declare const DataTableControls: import("svelte").Component<{
12
12
  onsearch?: any;
13
13
  filtersVisible?: boolean;
14
14
  onfilterstoggle?: any;
15
- columnFilters?: any[];
15
+ columnFilters?: any;
16
+ columns?: any[];
17
+ filterItems?: any;
16
18
  activeFilters?: Record<string, any>;
17
19
  onfilter?: any;
18
20
  direction?: string;
@@ -29,7 +31,9 @@ type $$ComponentProps = {
29
31
  onsearch?: any;
30
32
  filtersVisible?: boolean;
31
33
  onfilterstoggle?: any;
32
- columnFilters?: any[];
34
+ columnFilters?: any;
35
+ columns?: any[];
36
+ filterItems?: any;
33
37
  activeFilters?: Record<string, any>;
34
38
  onfilter?: any;
35
39
  direction?: string;