@zhangt58/svelte-vtable 0.3.8 → 0.4.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
@@ -142,21 +142,25 @@ 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 filter configurations, usually from `buildColumnFilters(allRows, columns)`. When omitted, inline filters derive options from `items`. |
161
+ | `activeFilters` | `Object` | `{}` | Controlled filter state for inline header filters. |
162
+ | `onfilter` | `function` | `undefined` | Callback when inline filters change: `({key, values, allFilters}) => void`. When provided, parent code is responsible for applying filters. |
163
+ | `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
164
 
161
165
  #### Row Snippet Parameters
162
166
 
@@ -175,85 +179,74 @@ The `rowSnippet` receives an object with:
175
179
  // @type {import('@zhangt58/svelte-vtable').ColumnDef}
176
180
  ```
177
181
 
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. |
182
+ | Field | Type | Default | Description |
183
+ | --------------- | --------------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------- |
184
+ | `key` | `string` | required | Data key. Must match a property on the row item. |
185
+ | `label` | `string` | `key` | Column header label. Defaults to `key`. |
186
+ | `width` | `number \| string` | `1` | Stretch weight (number) or CSS value (e.g. `'120px'`). |
187
+ | `sortable` | `boolean` | `true` | Whether clicking the header sorts the table. |
188
+ | `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`. |
189
+ | `headerSnippet` | `Snippet<[{key, label, sortKey, sortDir}]>` | `undefined` | Custom Svelte 5 snippet rendered inside `<th>`. |
190
+ | `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
191
 
188
192
  #### Minimal example using `columns`
189
193
 
190
194
  ```svelte
191
195
  <script>
192
- import { DataTable, buildColumnFilters, applyFilters } from '@zhangt58/svelte-vtable';
196
+ import { DataTable } from '@zhangt58/svelte-vtable';
193
197
 
194
- const items = [...]; // your data
198
+ const items = [
199
+ { id: 1, name: 'Alice', department: 'Engineering', hireDate: '2024-01-15' },
200
+ { id: 2, name: 'Bob', department: 'Sales', hireDate: '2024-03-10' },
201
+ ];
195
202
 
196
203
  /** @type {import('@zhangt58/svelte-vtable').ColumnDef[]} */
197
204
  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' },
205
+ { key: 'id', label: 'ID', width: 1, filterType: 'none' },
206
+ { key: 'name', label: 'Name', width: 3, filterType: 'none' },
207
+ { key: 'department', label: 'Department', width: 2, filterType: 'value' },
208
+ { key: 'hireDate', label: 'Hire Date', width: 2, filterType: 'daterange' },
202
209
  ];
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
210
  </script>
209
211
 
210
- <!-- No visibleKeys, colWidths, or rowSnippet required -->
211
- <DataTable items={filteredItems()} {columns} style="height: 400px" />
212
+ <!-- No visibleKeys, colWidths, rowSnippet, or separate filters required -->
213
+ <DataTable {items} {columns} inlineFilters style="height: 400px" />
212
214
  ```
213
215
 
214
- ### Filter example (filterCallback)
216
+ #### Controlled inline filters
215
217
 
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.
218
+ For pagination, server requests, or shared filter controls, keep filters in the parent and pass the same state to `DataTable`:
217
219
 
218
220
  ```svelte
219
221
  <script>
220
- import { DataTable } from '@zhangt58/svelte-vtable';
222
+ import { DataTable, buildColumnFilters, applyFilters } from '@zhangt58/svelte-vtable';
221
223
 
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' },
224
+ const rows = [
225
+ { department: 'Engineering', hireDate: '2024-01-15' },
226
+ { department: 'Sales', hireDate: '2024-03-10' },
227
+ ];
228
+ const columns = [
229
+ { key: 'department', label: 'Department', filterType: 'value' },
230
+ { key: 'hireDate', label: 'Hire Date', filterType: 'daterange' },
227
231
  ];
228
232
 
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 };
233
+ const columnFilters = buildColumnFilters(rows, columns);
234
+ let activeFilters = $state({});
235
+ const filteredRows = $derived(applyFilters(rows, activeFilters));
236
+
237
+ function handleFilter({ allFilters }) {
238
+ activeFilters = { ...allFilters };
246
239
  }
247
240
  </script>
248
241
 
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>
242
+ <DataTable
243
+ items={filteredRows}
244
+ {columns}
245
+ inlineFilters
246
+ {columnFilters}
247
+ {activeFilters}
248
+ onfilter={handleFilter}
249
+ />
257
250
  ```
258
251
 
259
252
  #### Column Widths
@@ -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
+ buildColumnFilters,
9
+ hasActiveFilterValue,
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,23 @@
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 this component's items.
35
+ columnFilters = null,
36
+ activeFilters = {},
37
+ // onfilter({ key, values, allFilters }) makes filtering parent-managed.
38
+ // When omitted, inline filters are applied locally to this table's items.
39
+ onfilter = undefined,
40
+ oncolumnsort = undefined,
41
+ showCounts = true,
42
+ virtualThreshold = 500,
43
+ virtualItemHeight = 36,
44
+ virtualOverscan = 5,
45
+ populateThreshold = 200,
46
+ emitDebounce = 100,
47
+ relativeRangePresets = DEFAULT_RELATIVE_RANGE_PRESETS,
23
48
  // Allow consumers to disable virtualization (useful when paginating by fixed item counts).
24
49
  // If `virtualize` is false we ask the wrapped VirtualList to render as a normal list/table
25
50
  // by setting its `isDisabled` prop. Default: true (virtualization enabled).
@@ -39,15 +64,39 @@
39
64
  // Fast lookup map: key → ColumnDef.
40
65
  const colDefMap = $derived(Object.fromEntries(columns.map((c) => [c.key, c])));
41
66
 
67
+ const effectiveColumnFilters = $derived.by(() => {
68
+ if (Array.isArray(columnFilters)) return columnFilters;
69
+ if (!inlineFilters) return [];
70
+ return buildColumnFilters(items, columns);
71
+ });
72
+
73
+ const filterDefMap = $derived(
74
+ Object.fromEntries(effectiveColumnFilters.map((filter) => [filter.key, filter])),
75
+ );
76
+
77
+ const filterState = useFilterState({
78
+ columnFilters: () => effectiveColumnFilters,
79
+ activeFilters: () => activeFilters || {},
80
+ emitDebounce: () => emitDebounce,
81
+ onfilter: () => onfilter,
82
+ });
83
+
84
+ let openFilterKey = $state(null);
85
+
86
+ const filteredItems = $derived.by(() => {
87
+ if (!inlineFilters || onfilter !== undefined) return items;
88
+ return applyFilters(items, filterState.selections);
89
+ });
90
+
42
91
  // Internal sorted array derived from items + current sort state.
43
92
  // When onsort is provided the parent manages sorting (server-side), so we
44
93
  // pass items through unchanged. Otherwise we sort locally.
45
94
  const sortedItems = $derived.by(() => {
46
- if (onsort !== undefined || !sortKey) return items;
95
+ if (onsort !== undefined || !sortKey) return filteredItems;
47
96
 
48
97
  const key = sortKey;
49
98
  const dir = sortDir;
50
- return [...items].sort((a, b) => {
99
+ return [...filteredItems].sort((a, b) => {
51
100
  const aVal = a[key];
52
101
  const bVal = b[key];
53
102
 
@@ -103,6 +152,28 @@
103
152
  }
104
153
  }
105
154
 
155
+ function toggleFilter(key) {
156
+ openFilterKey = openFilterKey === key ? null : key;
157
+ }
158
+
159
+ function closeFilter() {
160
+ openFilterKey = null;
161
+ }
162
+
163
+ function handleKeydown(event) {
164
+ if (event.key === 'Escape') closeFilter();
165
+ }
166
+
167
+ function handleColumnFilterSort(columnKey, { mode, dir }) {
168
+ try {
169
+ if (oncolumnsort) /** @type {any} */ (oncolumnsort)({ key: columnKey, mode, dir });
170
+ } catch (err) {
171
+ try {
172
+ console.debug('oncolumnsort threw', err);
173
+ } catch (e) {}
174
+ }
175
+ }
176
+
106
177
  // Normalize colWidths: treat numeric values as stretch weights and pass through CSS strings.
107
178
  // Memoized: only recomputes when effectiveVisibleKeys or effectiveColWidths changes.
108
179
  const colWidthMap = $derived(normalizeColWidths());
@@ -159,8 +230,10 @@
159
230
  }
160
231
  </script>
161
232
 
233
+ <svelte:window onclick={closeFilter} onkeydown={handleKeydown} />
234
+
162
235
  <section class="virtual-data-table {className}" {style}>
163
- {#if items && items.length > 0}
236
+ {#if sortedItems && sortedItems.length > 0}
164
237
  <!-- When `virtualize` is false we instruct VirtualList to render as a normal list/table
165
238
  by setting `isDisabled`. This ensures pagination based on item counts shows the
166
239
  exact number of rows expected (useful when rows have variable height). -->
@@ -179,30 +252,67 @@
179
252
  </colgroup>
180
253
  <thead class="sticky-header">
181
254
  <tr>
182
- {#each effectiveVisibleKeys as key}
255
+ {#each effectiveVisibleKeys as key, columnIndex}
183
256
  {@const colDef = colDefMap[key]}
257
+ {@const filterDef = filterDefMap[key]}
184
258
  {@const label = colDef?.label ?? key}
185
259
  {@const isSortable = colDef?.sortable !== false}
260
+ {@const selection = filterDef ? filterState.selections[filterDef.key] : undefined}
261
+ {@const isFilterActive = hasActiveFilterValue(selection)}
186
262
  <th
187
263
  style="width: {calcColWidth(key)}"
188
- class={isSortable ? 'cursor-pointer select-none' : 'select-none'}
189
- onclick={isSortable ? () => handleSort(key) : undefined}
264
+ class="select-none"
190
265
  aria-sort={sortKey === key
191
266
  ? sortDir === 'asc'
192
267
  ? 'ascending'
193
268
  : 'descending'
194
269
  : 'none'}
195
270
  >
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}
271
+ <div class="vtable-header-content">
272
+ {#if colDef?.headerSnippet}
273
+ <div class="min-w-0 flex-1">
274
+ {@render colDef.headerSnippet({ key, label, sortKey, sortDir })}
275
+ </div>
276
+ {:else if isSortable}
277
+ <button
278
+ type="button"
279
+ class="vtable-header-sort-button min-w-0 flex-1 cursor-pointer"
280
+ onclick={() => handleSort(key)}
281
+ >
282
+ <span class="min-w-0 truncate">{label}</span>
283
+ {#if sortKey === key}
284
+ <span aria-hidden="true">{sortDir === 'asc' ? '▲' : '▼'}</span>
285
+ {/if}
286
+ </button>
287
+ {:else}
288
+ <span class="min-w-0 flex-1 truncate">{label}</span>
289
+ {/if}
290
+
291
+ {#if inlineFilters && filterDef}
292
+ <ColumnHeaderFilter
293
+ column={filterDef}
294
+ {selection}
295
+ isOpen={openFilterKey === filterDef.key}
296
+ isActive={isFilterActive}
297
+ align={columnIndex > effectiveVisibleKeys.length / 2 ? 'right' : 'left'}
298
+ {showCounts}
299
+ {virtualThreshold}
300
+ {virtualItemHeight}
301
+ {virtualOverscan}
302
+ {populateThreshold}
303
+ {relativeRangePresets}
304
+ ontoggle={() => toggleFilter(filterDef.key)}
305
+ onclear={() => filterState.clearColumn(filterDef.key)}
306
+ onvaluetoggle={(value) => filterState.toggleSelection(filterDef.key, value)}
307
+ oncheckall={(values) => filterState.checkAll(filterDef.key, values)}
308
+ oninvert={(values) => filterState.invertSelection(filterDef.key, values)}
309
+ onchecknone={() => filterState.checkNone(filterDef.key)}
310
+ ondaterangechange={(updated) =>
311
+ filterState.updateDateRange(filterDef.key, updated)}
312
+ onsortchange={(payload) => handleColumnFilterSort(filterDef.key, payload)}
313
+ />
314
+ {/if}
315
+ </div>
206
316
  </th>
207
317
  {/each}
208
318
  </tr>
@@ -353,6 +463,31 @@
353
463
  align-items: center;
354
464
  gap: 0.25rem;
355
465
  }
466
+ :global(.datatable-table thead th) {
467
+ position: relative;
468
+ }
469
+ :global(.datatable-table thead th .vtable-header-content) {
470
+ display: flex;
471
+ align-items: center;
472
+ justify-content: space-between;
473
+ gap: 0.25rem;
474
+ min-width: 0;
475
+ width: 100%;
476
+ }
477
+ :global(.datatable-table thead th .vtable-header-sort-button) {
478
+ appearance: none;
479
+ border: 0;
480
+ background: transparent;
481
+ color: inherit;
482
+ font: inherit;
483
+ letter-spacing: inherit;
484
+ text-transform: inherit;
485
+ padding: 0;
486
+ display: inline-flex;
487
+ align-items: center;
488
+ gap: 0.25rem;
489
+ text-align: left;
490
+ }
356
491
  /* Allow certain long cells to wrap fully if explicitly requested */
357
492
  :global(.datatable-table td.wrap) {
358
493
  white-space: normal;
@@ -14,6 +14,18 @@ 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
+ activeFilters?: Record<string, any>;
20
+ onfilter?: any;
21
+ oncolumnsort?: any;
22
+ showCounts?: boolean;
23
+ virtualThreshold?: number;
24
+ virtualItemHeight?: number;
25
+ virtualOverscan?: number;
26
+ populateThreshold?: number;
27
+ emitDebounce?: number;
28
+ relativeRangePresets?: typeof DEFAULT_RELATIVE_RANGE_PRESETS;
17
29
  virtualize?: boolean;
18
30
  }, {}, "sortKey" | "sortDir">;
19
31
  type $$ComponentProps = {
@@ -27,5 +39,18 @@ type $$ComponentProps = {
27
39
  selected?: any;
28
40
  onselect?: any;
29
41
  onsort?: any;
42
+ inlineFilters?: boolean;
43
+ columnFilters?: any;
44
+ activeFilters?: Record<string, any>;
45
+ onfilter?: any;
46
+ oncolumnsort?: any;
47
+ showCounts?: boolean;
48
+ virtualThreshold?: number;
49
+ virtualItemHeight?: number;
50
+ virtualOverscan?: number;
51
+ populateThreshold?: number;
52
+ emitDebounce?: number;
53
+ relativeRangePresets?: typeof DEFAULT_RELATIVE_RANGE_PRESETS;
30
54
  virtualize?: boolean;
31
55
  };
56
+ 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 } from '../filterUtils.js';
4
5
 
5
6
  // Props for search, pagination (perPage made bindable using Svelte 5 rune $bindable)
6
7
  let {
@@ -34,18 +35,7 @@
34
35
  { value: 100, name: '100 rows' },
35
36
  ];
36
37
 
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
- });
38
+ const activeFilterCount = $derived(countActiveFilters(activeFilters));
49
39
 
50
40
  // totalPages derived from totalItems and perPage
51
41
  const totalPages = $derived(Math.max(1, Math.ceil(totalItems / perPage)));
@@ -452,6 +442,31 @@
452
442
  align-items: center;
453
443
  gap: 0.25rem;
454
444
  }
445
+ :global(.datatable-table thead th) {
446
+ position: relative;
447
+ }
448
+ :global(.datatable-table thead th .vtable-header-content) {
449
+ display: flex;
450
+ align-items: center;
451
+ justify-content: space-between;
452
+ gap: 0.25rem;
453
+ min-width: 0;
454
+ width: 100%;
455
+ }
456
+ :global(.datatable-table thead th .vtable-header-sort-button) {
457
+ appearance: none;
458
+ border: 0;
459
+ background: transparent;
460
+ color: inherit;
461
+ font: inherit;
462
+ letter-spacing: inherit;
463
+ text-transform: inherit;
464
+ padding: 0;
465
+ display: inline-flex;
466
+ align-items: center;
467
+ gap: 0.25rem;
468
+ text-align: left;
469
+ }
455
470
  /* Allow certain long cells to wrap fully if explicitly requested */
456
471
  :global(.datatable-table td.wrap) {
457
472
  white-space: normal;
@@ -3,6 +3,7 @@
3
3
  import FilterColumn from './filters/FilterColumn.svelte';
4
4
  import FilterValueList from './filters/FilterValueList.svelte';
5
5
  import FilterDateRange from './filters/FilterDateRange.svelte';
6
+ import { DEFAULT_RELATIVE_RANGE_PRESETS } from '../filterUtils.js';
6
7
 
7
8
  let {
8
9
  columnFilters = [],
@@ -18,15 +19,7 @@
18
19
  emitDebounce = 100,
19
20
  populateThreshold = 200,
20
21
  dropdownInline = true,
21
- relativeRangePresets = [
22
- { label: '1h', value: 1, unit: 'hour' },
23
- { label: '6h', value: 6, unit: 'hour' },
24
- { label: '12h', value: 12, unit: 'hour' },
25
- { label: '1d', value: 1, unit: 'day' },
26
- { label: '7d', value: 7, unit: 'day' },
27
- { label: '30d', value: 30, unit: 'day' },
28
- { label: '1y', value: 1, unit: 'year' },
29
- ],
22
+ relativeRangePresets = DEFAULT_RELATIVE_RANGE_PRESETS,
30
23
  } = $props();
31
24
 
32
25
  const fs = useFilterState({
@@ -17,7 +17,7 @@ declare const DataTableFilters: import("svelte").Component<{
17
17
  emitDebounce?: number;
18
18
  populateThreshold?: number;
19
19
  dropdownInline?: boolean;
20
- relativeRangePresets?: any[];
20
+ relativeRangePresets?: typeof DEFAULT_RELATIVE_RANGE_PRESETS;
21
21
  }, {}, "">;
22
22
  type $$ComponentProps = {
23
23
  columnFilters?: any[];
@@ -33,5 +33,6 @@ type $$ComponentProps = {
33
33
  emitDebounce?: number;
34
34
  populateThreshold?: number;
35
35
  dropdownInline?: boolean;
36
- relativeRangePresets?: any[];
36
+ relativeRangePresets?: typeof DEFAULT_RELATIVE_RANGE_PRESETS;
37
37
  };
38
+ import { DEFAULT_RELATIVE_RANGE_PRESETS } from '../filterUtils.js';
@@ -0,0 +1,142 @@
1
+ <script>
2
+ import FilterValueList from './FilterValueList.svelte';
3
+ import FilterDateRange from './FilterDateRange.svelte';
4
+ import { DEFAULT_RELATIVE_RANGE_PRESETS } from '../../filterUtils.js';
5
+
6
+ let {
7
+ column,
8
+ selection = [],
9
+ isOpen = false,
10
+ isActive = false,
11
+ align = 'left',
12
+ showCounts = true,
13
+ virtualThreshold = 500,
14
+ virtualItemHeight = 36,
15
+ virtualOverscan = 5,
16
+ populateThreshold = 200,
17
+ relativeRangePresets = DEFAULT_RELATIVE_RANGE_PRESETS,
18
+ ontoggle = undefined,
19
+ onclear = undefined,
20
+ onvaluetoggle = undefined,
21
+ oncheckall = undefined,
22
+ oninvert = undefined,
23
+ onchecknone = undefined,
24
+ ondaterangechange = undefined,
25
+ onsortchange = undefined,
26
+ } = $props();
27
+
28
+ const isDateRange = $derived(column.type === 'daterange' || column.type === 'datetimerange');
29
+ const label = $derived(column.label || column.key);
30
+ const activeBadge = $derived(Array.isArray(selection) ? String(selection.length) : '1');
31
+
32
+ function stopEvent(event) {
33
+ event.stopPropagation();
34
+ }
35
+
36
+ function handleToggle(event) {
37
+ event.stopPropagation();
38
+ if (ontoggle) ontoggle();
39
+ }
40
+
41
+ function handleMenuKeydown(event) {
42
+ if (event.key !== 'Escape') event.stopPropagation();
43
+ }
44
+ </script>
45
+
46
+ <div class="relative inline-flex shrink-0 normal-case tracking-normal">
47
+ <button
48
+ type="button"
49
+ class={'relative inline-flex h-7 w-7 items-center justify-center rounded border text-gray-500 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:text-gray-300 ' +
50
+ (isActive
51
+ ? 'dark:bg-gray-700'
52
+ : 'border-transparent hover:border-gray-300 hover:bg-gray-100 dark:hover:border-gray-600 dark:hover:bg-gray-700')}
53
+ style={isActive
54
+ ? 'border-color: var(--vtable-color-accent-border); background-color: color-mix(in srgb, var(--vtable-color-accent-light) 70%, white); color: var(--vtable-color-accent-text);'
55
+ : ''}
56
+ aria-label="Filter {label}"
57
+ aria-expanded={isOpen}
58
+ aria-controls="vtable-filter-menu-{column.key}"
59
+ title="Filter {label}"
60
+ onclick={handleToggle}
61
+ >
62
+ <svg
63
+ class="h-4 w-4"
64
+ xmlns="http://www.w3.org/2000/svg"
65
+ fill="none"
66
+ viewBox="0 0 24 24"
67
+ stroke="currentColor"
68
+ aria-hidden="true"
69
+ >
70
+ <path
71
+ stroke-linecap="round"
72
+ stroke-linejoin="round"
73
+ stroke-width="2"
74
+ d="M3 5h18l-7 8v5l-4 2v-7L3 5z"
75
+ />
76
+ </svg>
77
+
78
+ {#if isActive}
79
+ <span
80
+ class="absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-semibold leading-none text-white"
81
+ style="background-color: var(--vtable-color-accent);"
82
+ aria-hidden="true">{activeBadge}</span
83
+ >
84
+ {/if}
85
+ </button>
86
+
87
+ {#if isOpen}
88
+ <div
89
+ id="vtable-filter-menu-{column.key}"
90
+ class="absolute top-full z-50 mt-1 w-72 max-w-[calc(100vw-2rem)] overflow-hidden rounded-md border border-gray-300 bg-white text-left text-sm font-normal normal-case tracking-normal text-gray-700 shadow-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 dark:shadow-gray-900"
91
+ class:left-0={align !== 'right'}
92
+ class:right-0={align === 'right'}
93
+ role="dialog"
94
+ aria-label="Filter {label}"
95
+ tabindex="-1"
96
+ onclick={stopEvent}
97
+ onkeydown={handleMenuKeydown}
98
+ >
99
+ <div
100
+ class="flex items-center justify-between gap-2 border-b border-gray-200 px-3 py-2 dark:border-gray-600"
101
+ >
102
+ <span class="min-w-0 truncate text-xs font-semibold text-gray-600 dark:text-gray-200">
103
+ {label}
104
+ </span>
105
+ {#if isActive}
106
+ <button
107
+ type="button"
108
+ class="shrink-0 rounded border border-red-300 px-2 py-0.5 text-xs text-red-600 transition-colors hover:bg-red-50 dark:border-red-500 dark:text-red-300 dark:hover:bg-red-900/20"
109
+ onclick={() => onclear && onclear()}
110
+ >
111
+ Clear
112
+ </button>
113
+ {/if}
114
+ </div>
115
+
116
+ {#if isDateRange}
117
+ <FilterDateRange
118
+ {column}
119
+ selection={selection || {}}
120
+ {relativeRangePresets}
121
+ onchange={(updated) => ondaterangechange && ondaterangechange(updated)}
122
+ onclear={() => onclear && onclear()}
123
+ />
124
+ {:else}
125
+ <FilterValueList
126
+ {column}
127
+ selections={selection || []}
128
+ {showCounts}
129
+ {virtualThreshold}
130
+ {virtualItemHeight}
131
+ {virtualOverscan}
132
+ {populateThreshold}
133
+ ontoggle={(value) => onvaluetoggle && onvaluetoggle(value)}
134
+ oncheckall={(values) => oncheckall && oncheckall(values)}
135
+ oninvert={(values) => oninvert && oninvert(values)}
136
+ onchecknone={() => onchecknone && onchecknone()}
137
+ onsortchange={(payload) => onsortchange && onsortchange(payload)}
138
+ />
139
+ {/if}
140
+ </div>
141
+ {/if}
142
+ </div>
@@ -0,0 +1,48 @@
1
+ export default ColumnHeaderFilter;
2
+ type ColumnHeaderFilter = {
3
+ $on?(type: string, callback: (e: any) => void): () => void;
4
+ $set?(props: Partial<$$ComponentProps>): void;
5
+ };
6
+ declare const ColumnHeaderFilter: import("svelte").Component<{
7
+ column: any;
8
+ selection?: any[];
9
+ isOpen?: boolean;
10
+ isActive?: boolean;
11
+ align?: string;
12
+ showCounts?: boolean;
13
+ virtualThreshold?: number;
14
+ virtualItemHeight?: number;
15
+ virtualOverscan?: number;
16
+ populateThreshold?: number;
17
+ relativeRangePresets?: typeof DEFAULT_RELATIVE_RANGE_PRESETS;
18
+ ontoggle?: any;
19
+ onclear?: any;
20
+ onvaluetoggle?: any;
21
+ oncheckall?: any;
22
+ oninvert?: any;
23
+ onchecknone?: any;
24
+ ondaterangechange?: any;
25
+ onsortchange?: any;
26
+ }, {}, "">;
27
+ type $$ComponentProps = {
28
+ column: any;
29
+ selection?: any[];
30
+ isOpen?: boolean;
31
+ isActive?: boolean;
32
+ align?: string;
33
+ showCounts?: boolean;
34
+ virtualThreshold?: number;
35
+ virtualItemHeight?: number;
36
+ virtualOverscan?: number;
37
+ populateThreshold?: number;
38
+ relativeRangePresets?: typeof DEFAULT_RELATIVE_RANGE_PRESETS;
39
+ ontoggle?: any;
40
+ onclear?: any;
41
+ onvaluetoggle?: any;
42
+ oncheckall?: any;
43
+ oninvert?: any;
44
+ onchecknone?: any;
45
+ ondaterangechange?: any;
46
+ onsortchange?: any;
47
+ };
48
+ import { DEFAULT_RELATIVE_RANGE_PRESETS } from '../../filterUtils.js';
@@ -1,8 +1,5 @@
1
1
  import { onDestroy } from 'svelte';
2
-
3
- function isDateRangeColumn(col) {
4
- return col.type === 'daterange' || col.type === 'datetimerange';
5
- }
2
+ import { isDateRangeColumn } from '../../filterUtils.js';
6
3
 
7
4
  /**
8
5
  * Svelte 5 reactive composable that manages per-column filter selections,
@@ -2,6 +2,7 @@
2
2
  import { Search, Badge, Select } from 'flowbite-svelte';
3
3
  import FiltersModal from './FiltersModal.svelte';
4
4
  import PaginationBar from '../PaginationBar.svelte';
5
+ import { countActiveFilters } from '../../filterUtils.js';
5
6
 
6
7
  // Props for search, pagination (perPage made bindable using Svelte 5 rune $bindable)
7
8
  let {
@@ -35,18 +36,7 @@
35
36
  { value: 100, name: '100 rows' },
36
37
  ];
37
38
 
38
- // count of active filters (sum of selected values per column)
39
- const activeFilterCount = $derived.by(() => {
40
- try {
41
- return Object.values(activeFilters || {}).reduce((sum, v) => {
42
- if (Array.isArray(v)) return sum + v.length;
43
- if (v && typeof v === 'object' && (v.from || v.to)) return sum + 1;
44
- return sum;
45
- }, 0);
46
- } catch (e) {
47
- return 0;
48
- }
49
- });
39
+ const activeFilterCount = $derived(countActiveFilters(activeFilters));
50
40
 
51
41
  // totalPages derived from totalItems and perPage
52
42
  const totalPages = $derived(Math.max(1, Math.ceil(totalItems / perPage)));
@@ -210,8 +200,20 @@
210
200
  }}
211
201
  >
212
202
  <!-- Funnel/filter icon (inline SVG) -->
213
- <svg class="h-4 w-4 shrink-0" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
214
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2a1 1 0 01-.293.707L13 13.414V19a1 1 0 01-.553.894l-4 2A1 1 0 017 21v-7.586L3.293 6.707A1 1 0 013 6V4z" />
203
+ <svg
204
+ class="h-4 w-4 shrink-0"
205
+ xmlns="http://www.w3.org/2000/svg"
206
+ fill="none"
207
+ viewBox="0 0 24 24"
208
+ stroke="currentColor"
209
+ aria-hidden="true"
210
+ >
211
+ <path
212
+ stroke-linecap="round"
213
+ stroke-linejoin="round"
214
+ stroke-width="2"
215
+ d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2a1 1 0 01-.293.707L13 13.414V19a1 1 0 01-.553.894l-4 2A1 1 0 017 21v-7.586L3.293 6.707A1 1 0 013 6V4z"
216
+ />
215
217
  </svg>
216
218
  <span class="text-sm">Filters</span>
217
219
  </button>
@@ -391,6 +393,31 @@
391
393
  align-items: center;
392
394
  gap: 0.25rem;
393
395
  }
396
+ :global(.datatable-table thead th) {
397
+ position: relative;
398
+ }
399
+ :global(.datatable-table thead th .vtable-header-content) {
400
+ display: flex;
401
+ align-items: center;
402
+ justify-content: space-between;
403
+ gap: 0.25rem;
404
+ min-width: 0;
405
+ width: 100%;
406
+ }
407
+ :global(.datatable-table thead th .vtable-header-sort-button) {
408
+ appearance: none;
409
+ border: 0;
410
+ background: transparent;
411
+ color: inherit;
412
+ font: inherit;
413
+ letter-spacing: inherit;
414
+ text-transform: inherit;
415
+ padding: 0;
416
+ display: inline-flex;
417
+ align-items: center;
418
+ gap: 0.25rem;
419
+ text-align: left;
420
+ }
394
421
  /* Allow certain long cells to wrap fully if explicitly requested */
395
422
  :global(.datatable-table td.wrap) {
396
423
  white-space: normal;
@@ -1,6 +1,21 @@
1
1
  /**
2
- * Utility functions for working with DataTableFilters
2
+ * Resolve a filter config's type from either ColumnDef.filterType or filter config type.
3
+ * @param {object|string|undefined|null} column
4
+ * @returns {string|undefined}
5
+ */
6
+ export function getFilterType(column: object | string | undefined | null): string | undefined;
7
+ /**
8
+ * Check whether a column filter is date/datetime range based.
9
+ * @param {object|string|undefined|null} column
10
+ * @returns {boolean}
11
+ */
12
+ export function isDateRangeColumn(column: object | string | undefined | null): boolean;
13
+ /**
14
+ * Check whether a single filter value is active.
15
+ * @param {unknown} value
16
+ * @returns {boolean}
3
17
  */
18
+ export function hasActiveFilterValue(value: unknown): boolean;
4
19
  /**
5
20
  * Extract unique values and their counts from an array of objects for a given key
6
21
  * @param {Array} data - Array of data objects
@@ -47,6 +62,12 @@ export function applyFilters(data: any[], activeFilters: any): any[];
47
62
  * @returns {boolean} True if any filters are active
48
63
  */
49
64
  export function hasActiveFilters(activeFilters: any): boolean;
65
+ /**
66
+ * Count one filter value. Value-list filters count each selected value; ranges count as 1.
67
+ * @param {unknown} value
68
+ * @returns {number}
69
+ */
70
+ export function countActiveFilterValue(value: unknown): number;
50
71
  /**
51
72
  * Count total number of active filter selections.
52
73
  * Each active date range counts as 1.
@@ -74,3 +95,11 @@ export function filtersToSearchParams(activeFilters: any): URLSearchParams;
74
95
  * @returns {Object} Active filters object
75
96
  */
76
97
  export function searchParamsToFilters(searchParams: URLSearchParams | string, columnFilters: any[]): any;
98
+ /**
99
+ * Utility functions for working with DataTableFilters
100
+ */
101
+ export const DEFAULT_RELATIVE_RANGE_PRESETS: {
102
+ label: string;
103
+ value: number;
104
+ unit: string;
105
+ }[];
@@ -2,6 +2,50 @@
2
2
  * Utility functions for working with DataTableFilters
3
3
  */
4
4
 
5
+ export const DEFAULT_RELATIVE_RANGE_PRESETS = [
6
+ { label: '1h', value: 1, unit: 'hour' },
7
+ { label: '6h', value: 6, unit: 'hour' },
8
+ { label: '12h', value: 12, unit: 'hour' },
9
+ { label: '1d', value: 1, unit: 'day' },
10
+ { label: '7d', value: 7, unit: 'day' },
11
+ { label: '30d', value: 30, unit: 'day' },
12
+ { label: '1y', value: 1, unit: 'year' },
13
+ ];
14
+
15
+ /**
16
+ * Resolve a filter config's type from either ColumnDef.filterType or filter config type.
17
+ * @param {object|string|undefined|null} column
18
+ * @returns {string|undefined}
19
+ */
20
+ export function getFilterType(column) {
21
+ if (typeof column === 'string') return column;
22
+ return column?.type ?? column?.filterType;
23
+ }
24
+
25
+ /**
26
+ * Check whether a column filter is date/datetime range based.
27
+ * @param {object|string|undefined|null} column
28
+ * @returns {boolean}
29
+ */
30
+ export function isDateRangeColumn(column) {
31
+ const type = getFilterType(column);
32
+ return type === 'daterange' || type === 'datetimerange';
33
+ }
34
+
35
+ /**
36
+ * Check whether a single filter value is active.
37
+ * @param {unknown} value
38
+ * @returns {boolean}
39
+ */
40
+ export function hasActiveFilterValue(value) {
41
+ if (Array.isArray(value)) return value.length > 0;
42
+ if (value && typeof value === 'object') {
43
+ const range = /** @type {{from?: unknown, to?: unknown}} */ (value);
44
+ return !!(range.from || range.to);
45
+ }
46
+ return false;
47
+ }
48
+
5
49
  /**
6
50
  * Extract unique values and their counts from an array of objects for a given key
7
51
  * @param {Array} data - Array of data objects
@@ -41,11 +85,10 @@ export function getUniqueValuesWithCounts(data, key) {
41
85
  * @returns {Array} Column filters configuration for DataTableFilters
42
86
  */
43
87
  export function buildColumnFilters(data, columns) {
44
- const isDateRangeType = (ft) => ft === 'daterange' || ft === 'datetimerange';
45
88
  return columns
46
89
  .filter((col) => col.filterType !== 'none')
47
90
  .map((col) => {
48
- if (isDateRangeType(col.filterType)) {
91
+ if (isDateRangeColumn(col.filterType)) {
49
92
  // Scan data to find the min/max timestamps for this column so the UI can
50
93
  // offer a dual-range slider and Earliest/Latest shortcut buttons.
51
94
  let minMs = Infinity;
@@ -162,9 +205,7 @@ export function applyFilters(data, activeFilters) {
162
205
 
163
206
  if (Array.isArray(itemValue)) {
164
207
  // array value - check if any element matches the filter values
165
- const hasMatch = itemValue.some((v) =>
166
- filterValue.includes(String(v ?? ''))
167
- );
208
+ const hasMatch = itemValue.some((v) => filterValue.includes(String(v ?? '')));
168
209
  if (!hasMatch) return false;
169
210
  } else {
170
211
  // scalar value - treat null/undefined as '(empty)'
@@ -188,11 +229,17 @@ export function applyFilters(data, activeFilters) {
188
229
  * @returns {boolean} True if any filters are active
189
230
  */
190
231
  export function hasActiveFilters(activeFilters) {
191
- return Object.values(activeFilters).some((val) => {
192
- if (Array.isArray(val)) return val.length > 0;
193
- if (val && typeof val === 'object') return !!(val.from || val.to);
194
- return false;
195
- });
232
+ return Object.values(activeFilters || {}).some(hasActiveFilterValue);
233
+ }
234
+
235
+ /**
236
+ * Count one filter value. Value-list filters count each selected value; ranges count as 1.
237
+ * @param {unknown} value
238
+ * @returns {number}
239
+ */
240
+ export function countActiveFilterValue(value) {
241
+ if (Array.isArray(value)) return value.length;
242
+ return hasActiveFilterValue(value) ? 1 : 0;
196
243
  }
197
244
 
198
245
  /**
@@ -202,10 +249,8 @@ export function hasActiveFilters(activeFilters) {
202
249
  * @returns {number} Total count of active filter values/ranges
203
250
  */
204
251
  export function countActiveFilters(activeFilters) {
205
- return Object.values(activeFilters).reduce((sum, val) => {
206
- if (Array.isArray(val)) return sum + (val?.length || 0);
207
- if (val && typeof val === 'object' && (val.from || val.to)) return sum + 1;
208
- return sum;
252
+ return Object.values(activeFilters || {}).reduce((sum, val) => {
253
+ return sum + countActiveFilterValue(val);
209
254
  }, 0);
210
255
  }
211
256
 
@@ -217,8 +262,7 @@ export function countActiveFilters(activeFilters) {
217
262
  export function clearAllFilters(columnFilters) {
218
263
  const cleared = {};
219
264
  columnFilters.forEach((col) => {
220
- const isDateRange = col.type === 'daterange' || col.type === 'datetimerange';
221
- cleared[col.key] = isDateRange ? {} : [];
265
+ cleared[col.key] = isDateRangeColumn(col) ? {} : [];
222
266
  });
223
267
  return cleared;
224
268
  }
@@ -256,9 +300,7 @@ export function searchParamsToFilters(searchParams, columnFilters) {
256
300
 
257
301
  const validKeys = new Set(columnFilters.map((c) => c.key));
258
302
  const dateRangeKeys = new Set(
259
- columnFilters
260
- .filter((c) => c.type === 'daterange' || c.type === 'datetimerange')
261
- .map((c) => c.key),
303
+ columnFilters.filter((c) => isDateRangeColumn(c)).map((c) => c.key),
262
304
  );
263
305
  const filters = {};
264
306
 
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ export { default as DataTable } from "./components/DataTable.svelte";
4
4
  export { default as FilterColumn } from "./components/filters/FilterColumn.svelte";
5
5
  export { default as FilterValueList } from "./components/filters/FilterValueList.svelte";
6
6
  export { default as FilterDateRange } from "./components/filters/FilterDateRange.svelte";
7
+ export { default as ColumnHeaderFilter } from "./components/filters/ColumnHeaderFilter.svelte";
7
8
  export { useFilterState } from "./components/filters/useFilterState.svelte.js";
8
9
  /**
9
10
  * Unified column definition for DataTable.
@@ -31,12 +32,12 @@ export type ColumnDef<T extends Record<string, unknown> = Record<string, unknown
31
32
  sortable?: boolean;
32
33
  /**
33
34
  * Filter UI to render for this column:
34
- * - `'value'` — checkbox list of unique values (default)
35
+ * - `'value'`/`'list'` — checkbox list of unique values (default)
35
36
  * - `'daterange'` — date-only range picker
36
37
  * - `'datetimerange'` — datetime range picker
37
38
  * - `'none'` — no filter UI for this column
38
39
  */
39
- filterType?: "value" | "daterange" | "datetimerange" | "none";
40
+ filterType?: "value" | "list" | "daterange" | "datetimerange" | "none";
40
41
  /**
41
42
  * Custom Svelte 5 snippet rendered inside the `<th>`. Receives
42
43
  * `{ key, label, sortKey, sortDir }`.
@@ -57,4 +58,4 @@ export type ColumnDef<T extends Record<string, unknown> = Record<string, unknown
57
58
  index: number;
58
59
  }]>;
59
60
  };
60
- export { getUniqueValuesWithCounts, buildColumnFilters, applyFilters, matchesDateRange, hasActiveFilters, countActiveFilters, clearAllFilters, filtersToSearchParams, searchParamsToFilters } from "./filterUtils.js";
61
+ export { DEFAULT_RELATIVE_RANGE_PRESETS, getFilterType, getUniqueValuesWithCounts, buildColumnFilters, applyFilters, matchesDateRange, isDateRangeColumn, hasActiveFilterValue, countActiveFilterValue, hasActiveFilters, countActiveFilters, clearAllFilters, filtersToSearchParams, searchParamsToFilters } from "./filterUtils.js";
package/dist/index.js CHANGED
@@ -6,14 +6,20 @@ export { default as DataTable } from './components/DataTable.svelte';
6
6
  export { default as FilterColumn } from './components/filters/FilterColumn.svelte';
7
7
  export { default as FilterValueList } from './components/filters/FilterValueList.svelte';
8
8
  export { default as FilterDateRange } from './components/filters/FilterDateRange.svelte';
9
+ export { default as ColumnHeaderFilter } from './components/filters/ColumnHeaderFilter.svelte';
9
10
  export { useFilterState } from './components/filters/useFilterState.svelte.js';
10
11
 
11
12
  // Export filter utility functions
12
13
  export {
14
+ DEFAULT_RELATIVE_RANGE_PRESETS,
15
+ getFilterType,
13
16
  getUniqueValuesWithCounts,
14
17
  buildColumnFilters,
15
18
  applyFilters,
16
19
  matchesDateRange,
20
+ isDateRangeColumn,
21
+ hasActiveFilterValue,
22
+ countActiveFilterValue,
17
23
  hasActiveFilters,
18
24
  countActiveFilters,
19
25
  clearAllFilters,
@@ -34,9 +40,9 @@ export {
34
40
  * CSS width value such as `'120px'`. Defaults to `1` (equal stretch).
35
41
  * @property {boolean} [sortable] - Whether clicking the column header sorts the
36
42
  * table. Defaults to `true`.
37
- * @property {'value'|'daterange'|'datetimerange'|'none'} [filterType]
43
+ * @property {'value'|'list'|'daterange'|'datetimerange'|'none'} [filterType]
38
44
  * Filter UI to render for this column:
39
- * - `'value'` — checkbox list of unique values (default)
45
+ * - `'value'`/`'list'` — checkbox list of unique values (default)
40
46
  * - `'daterange'` — date-only range picker
41
47
  * - `'datetimerange'` — datetime range picker
42
48
  * - `'none'` — no filter UI for this column
package/dist/styles.css CHANGED
@@ -139,6 +139,34 @@
139
139
  gap: 0.25rem;
140
140
  }
141
141
 
142
+ :global(.datatable-table thead th) {
143
+ position: relative;
144
+ }
145
+
146
+ :global(.datatable-table thead th .vtable-header-content) {
147
+ display: flex;
148
+ align-items: center;
149
+ justify-content: space-between;
150
+ gap: 0.25rem;
151
+ min-width: 0;
152
+ width: 100%;
153
+ }
154
+
155
+ :global(.datatable-table thead th .vtable-header-sort-button) {
156
+ appearance: none;
157
+ border: 0;
158
+ background: transparent;
159
+ color: inherit;
160
+ font: inherit;
161
+ letter-spacing: inherit;
162
+ text-transform: inherit;
163
+ padding: 0;
164
+ display: inline-flex;
165
+ align-items: center;
166
+ gap: 0.25rem;
167
+ text-align: left;
168
+ }
169
+
142
170
  /* Allow certain long cells to wrap fully if explicitly requested */
143
171
  :global(.datatable-table td.wrap) {
144
172
  white-space: normal;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhangt58/svelte-vtable",
3
- "version": "0.3.8",
3
+ "version": "0.4.0",
4
4
  "description": "A Svelte 5 library for virtualized data tables with sorting, selection, and pagination controls.",
5
5
  "type": "module",
6
6
  "sideEffects": [