@zhangt58/svelte-vtable 0.1.4 → 0.3.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.
Files changed (36) hide show
  1. package/README.md +177 -44
  2. package/dist/components/DataTable.svelte +489 -0
  3. package/dist/components/DataTable.svelte.d.ts +31 -0
  4. package/dist/components/DataTableControls.svelte +576 -0
  5. package/dist/components/DataTableControls.svelte.d.ts +39 -0
  6. package/dist/components/DataTableFilters.svelte +215 -0
  7. package/dist/components/DataTableFilters.svelte.d.ts +37 -0
  8. package/dist/components/FiltersModal.svelte +65 -0
  9. package/dist/components/FiltersModal.svelte.d.ts +25 -0
  10. package/dist/components/PaginationBar.svelte +86 -0
  11. package/dist/components/PaginationBar.svelte.d.ts +15 -0
  12. package/dist/components/filters/FilterColumn.svelte +53 -0
  13. package/dist/components/filters/FilterColumn.svelte.d.ts +19 -0
  14. package/dist/components/filters/FilterDateRange.svelte +341 -0
  15. package/dist/components/filters/FilterDateRange.svelte.d.ts +19 -0
  16. package/dist/components/filters/FilterValueList.svelte +437 -0
  17. package/dist/components/filters/FilterValueList.svelte.d.ts +33 -0
  18. package/dist/components/filters/useFilterState.svelte.d.ts +25 -0
  19. package/dist/components/filters/useFilterState.svelte.js +132 -0
  20. package/dist/components/flowbite/DataTableControls.svelte +525 -0
  21. package/dist/components/flowbite/DataTableControls.svelte.d.ts +39 -0
  22. package/{src/components → dist/components/flowbite}/FiltersModal.svelte +5 -15
  23. package/dist/components/flowbite/FiltersModal.svelte.d.ts +25 -0
  24. package/dist/filterUtils.d.ts +76 -0
  25. package/{src/lib → dist}/filterUtils.js +48 -46
  26. package/dist/index.d.ts +60 -0
  27. package/dist/index.flowbite.d.ts +3 -0
  28. package/dist/index.flowbite.js +9 -0
  29. package/dist/index.js +49 -0
  30. package/{src/lib → dist}/styles.css +26 -3
  31. package/package.json +38 -17
  32. package/src/components/DataTable.svelte +0 -252
  33. package/src/components/DataTableControls.svelte +0 -500
  34. package/src/components/DataTableFilters.svelte +0 -1225
  35. package/src/lib/dist/styles.css +0 -273
  36. package/src/lib/index.js +0 -16
@@ -0,0 +1,437 @@
1
+ <script>
2
+ /**
3
+ * Renders the checkbox value-list for a single filter column, including:
4
+ * - per-column search bar
5
+ * - sort buttons (name / number / count)
6
+ * - check-all toolbar (All / Invert / None)
7
+ * - checkbox list with optional virtualization and load-on-demand
8
+ *
9
+ * Props:
10
+ * column — column config { key, label, uniqueValues, counts, ... }
11
+ * selections — current selected values array for this column
12
+ * showCounts — whether to show value counts next to each option
13
+ * virtualThreshold — render virtual list when options exceed this count
14
+ * virtualItemHeight — px height of each checkbox row (for virtual layout)
15
+ * virtualOverscan — extra rows to render above/below the visible window
16
+ * populateThreshold — hide options and show "Load options" when count exceeds this
17
+ * ontoggle — callback(value) when a checkbox is toggled
18
+ * oncheckall — callback(values) when "All" is clicked
19
+ * oninvert — callback(values) when "Invert" is clicked
20
+ * onchecknone — callback() when "None" is clicked
21
+ * onsortchange — callback({ mode, dir }) when sort button is clicked
22
+ */
23
+ let {
24
+ column,
25
+ selections = [],
26
+ showCounts = true,
27
+ virtualThreshold = 500,
28
+ virtualItemHeight = 36,
29
+ virtualOverscan = 5,
30
+ populateThreshold = 200,
31
+ ontoggle,
32
+ oncheckall,
33
+ oninvert,
34
+ onchecknone,
35
+ onsortchange,
36
+ } = $props();
37
+
38
+ // Internal: whether large option sets have been loaded (computed lazily from props)
39
+ const autoLoaded = $derived(
40
+ populateThreshold <= 0 ||
41
+ (Array.isArray(column.uniqueValues) ? column.uniqueValues.length : 0) <= populateThreshold,
42
+ );
43
+ let manuallyLoaded = $state(false);
44
+ const loaded = $derived(autoLoaded || manuallyLoaded);
45
+
46
+ // Internal: sort state
47
+ let sortMode = $state('name');
48
+ let sortDir = $state('asc');
49
+
50
+ // Internal: per-column search query
51
+ let searchQuery = $state('');
52
+
53
+ // Virtual list scroll tracking
54
+ let listRef = $state(null);
55
+ let scrollTop = $state(0);
56
+ let containerHeight = $state(200);
57
+
58
+ $effect(() => {
59
+ if (!listRef) return;
60
+ const ro = new ResizeObserver(() => {
61
+ containerHeight = listRef.clientHeight || 200;
62
+ });
63
+ ro.observe(listRef);
64
+ containerHeight = listRef.clientHeight || 200;
65
+ return () => ro.disconnect();
66
+ });
67
+
68
+ function handleScroll(e) {
69
+ scrollTop = e.currentTarget.scrollTop;
70
+ }
71
+
72
+ // Helper: extract numeric sort key from a value
73
+ function extractNumber(v) {
74
+ if (v === null || v === undefined) return 0;
75
+ if (typeof v === 'number') return v;
76
+ const match = String(v).match(/-?\d+(\.\d+)?/);
77
+ return match ? parseFloat(match[0]) : 0;
78
+ }
79
+
80
+ // Sorted + filtered option values for this column
81
+ const sortedValues = $derived.by(() => {
82
+ const raw = Array.isArray(column.uniqueValues) ? column.uniqueValues.slice() : [];
83
+ const q = searchQuery.trim().toLowerCase();
84
+ const filtered = q
85
+ ? raw.filter((v) => {
86
+ const text = v === null || v === undefined ? '(empty)' : String(v);
87
+ return text.toLowerCase().includes(q);
88
+ })
89
+ : raw;
90
+
91
+ const dir = sortDir === 'asc' ? 1 : -1;
92
+ const withIndex = filtered.map((v, i) => ({ v, i }));
93
+ withIndex.sort((a, b) => {
94
+ const va = a.v;
95
+ const vb = b.v;
96
+ if (sortMode === 'count' && column.counts) {
97
+ const ca = Number(column.counts[va] ?? 0);
98
+ const cb = Number(column.counts[vb] ?? 0);
99
+ if (ca !== cb) return (ca - cb) * dir * -1;
100
+ }
101
+ if (sortMode === 'number') {
102
+ const na = extractNumber(va);
103
+ const nb = extractNumber(vb);
104
+ if (na !== nb) return (na - nb) * dir;
105
+ }
106
+ const sa = va === null || va === undefined ? '(empty)' : String(va);
107
+ const sb = vb === null || vb === undefined ? '(empty)' : String(vb);
108
+ const la = sa.toLowerCase();
109
+ const lb = sb.toLowerCase();
110
+ if (la < lb) return -1 * dir;
111
+ if (la > lb) return 1 * dir;
112
+ return a.i - b.i;
113
+ });
114
+ return withIndex.map((x) => x.v);
115
+ });
116
+
117
+ // Virtual slice when options exceed threshold
118
+ const virtualSlice = $derived.by(() => {
119
+ if (!sortedValues || sortedValues.length <= virtualThreshold) return null;
120
+ const itemH = virtualItemHeight;
121
+ const height = containerHeight;
122
+ const overscan = virtualOverscan;
123
+ const start = Math.max(0, Math.floor(scrollTop / itemH) - overscan);
124
+ const visibleCount = Math.ceil(height / itemH) + overscan * 2;
125
+ const end = Math.min(sortedValues.length, start + visibleCount);
126
+ return {
127
+ slice: sortedValues.slice(start, end),
128
+ top: start * itemH,
129
+ totalHeight: sortedValues.length * itemH,
130
+ };
131
+ });
132
+
133
+ function handleSortClick(mode) {
134
+ if (sortMode === mode) {
135
+ sortDir = sortDir === 'asc' ? 'desc' : 'asc';
136
+ } else {
137
+ sortMode = mode;
138
+ sortDir = 'desc';
139
+ }
140
+ if (onsortchange) onsortchange({ mode: sortMode, dir: sortDir });
141
+ }
142
+ </script>
143
+
144
+ <!-- Search bar + sort buttons -->
145
+ <div class="px-1 py-1 border-b border-gray-200 dark:border-gray-600">
146
+ <div class="flex items-center gap-1 w-full min-w-0">
147
+ <input
148
+ type="text"
149
+ placeholder="Filter..."
150
+ class="p-1 flex-1 min-w-0 px-2 py-1 text-xs border border-gray-200 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-200 focus:outline-none focus:border-blue-500"
151
+ bind:value={searchQuery}
152
+ />
153
+ <div class="flex items-center gap-1">
154
+ <!-- Sort by name -->
155
+ <button
156
+ class="p-0.5 flex-1 flex items-center justify-center gap-1 text-sm text-gray-600 dark:text-gray-400 bg-transparent border border-gray-200 dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-300 transition-all"
157
+ class:bg-blue-100={sortMode === 'name'}
158
+ class:dark:bg-blue-900={sortMode === 'name'}
159
+ onclick={() => handleSortClick('name')}
160
+ title="Sort by name"
161
+ type="button"
162
+ >
163
+ <span
164
+ class="flex flex-col items-center leading-none font-semibold"
165
+ style="font-size:0.6rem;"
166
+ >
167
+ <span>A</span>
168
+ <span>Z</span>
169
+ </span>
170
+ <svg
171
+ class={'w-3 h-3 transition-transform ' +
172
+ (sortMode === 'name'
173
+ ? 'text-blue-900 dark:text-blue-100'
174
+ : 'text-gray-400 dark:text-gray-500')}
175
+ style={sortMode === 'name' && sortDir === 'asc' ? 'transform: rotate(180deg);' : ''}
176
+ xmlns="http://www.w3.org/2000/svg"
177
+ fill="none"
178
+ viewBox="0 0 24 24"
179
+ stroke="currentColor"
180
+ aria-hidden="true"
181
+ >
182
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
183
+ </svg>
184
+ </button>
185
+ <!-- Sort by number -->
186
+ <button
187
+ class="p-0.5 flex-1 flex items-center justify-center gap-1 text-sm text-gray-600 dark:text-gray-400 bg-transparent border border-gray-200 dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-300 transition-all"
188
+ class:bg-blue-100={sortMode === 'number'}
189
+ class:dark:bg-blue-900={sortMode === 'number'}
190
+ onclick={() => handleSortClick('number')}
191
+ title="Sort by number"
192
+ aria-label="Sort by number"
193
+ type="button"
194
+ >
195
+ <span
196
+ class="flex flex-col items-center leading-none font-semibold"
197
+ style="font-size:0.6rem;"
198
+ >
199
+ <span>0</span>
200
+ <span>9</span>
201
+ </span>
202
+ <svg
203
+ class={'w-3 h-3 transition-transform ' +
204
+ (sortMode === 'number'
205
+ ? 'text-blue-900 dark:text-blue-100'
206
+ : 'text-gray-400 dark:text-gray-500')}
207
+ style={sortMode === 'number' && sortDir === 'asc' ? 'transform: rotate(180deg);' : ''}
208
+ xmlns="http://www.w3.org/2000/svg"
209
+ fill="none"
210
+ viewBox="0 0 24 24"
211
+ stroke="currentColor"
212
+ aria-hidden="true"
213
+ >
214
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
215
+ </svg>
216
+ </button>
217
+ <!-- Sort by count (only when counts are available) -->
218
+ {#if showCounts && column.counts}
219
+ <button
220
+ class="p-0.5 flex-1 flex items-center justify-center gap-1 text-sm text-gray-600 dark:text-gray-400 bg-transparent border border-gray-200 dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-300 transition-all"
221
+ class:bg-blue-100={sortMode === 'count'}
222
+ class:dark:bg-blue-900={sortMode === 'count'}
223
+ onclick={() => handleSortClick('count')}
224
+ title="Sort by count"
225
+ type="button"
226
+ >
227
+ <span class="text-sm font-semibold">#</span>
228
+ <svg
229
+ class={'w-3 h-3 transition-transform ' +
230
+ (sortMode === 'count'
231
+ ? 'text-blue-900 dark:text-blue-100'
232
+ : 'text-gray-400 dark:text-gray-500')}
233
+ style={sortMode === 'count' && sortDir === 'asc' ? 'transform: rotate(180deg);' : ''}
234
+ xmlns="http://www.w3.org/2000/svg"
235
+ fill="none"
236
+ viewBox="0 0 24 24"
237
+ stroke="currentColor"
238
+ aria-hidden="true"
239
+ >
240
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
241
+ </svg>
242
+ </button>
243
+ {/if}
244
+ </div>
245
+ </div>
246
+ </div>
247
+
248
+ <!-- Check-all toolbar -->
249
+ <div class="px-2 py-1 border-b border-gray-100 dark:border-gray-600">
250
+ <div class="flex items-center justify-between">
251
+ <div class="flex items-center gap-1">
252
+ <button
253
+ type="button"
254
+ class="p-1 rounded-md flex items-center gap-1 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
255
+ onclick={() => oncheckall && oncheckall(sortedValues)}
256
+ disabled={sortedValues.length === 0}
257
+ aria-label="Check all"
258
+ title="Check all"
259
+ >
260
+ <svg
261
+ class="w-4 h-4 text-gray-800 dark:text-white"
262
+ viewBox="0 0 24 24"
263
+ fill="none"
264
+ aria-hidden="true"
265
+ >
266
+ <rect
267
+ x="3"
268
+ y="3"
269
+ width="18"
270
+ height="18"
271
+ rx="2"
272
+ stroke="currentColor"
273
+ stroke-width="2.5"
274
+ fill="none"
275
+ />
276
+ <path
277
+ d="M7 13l3 3 7-7"
278
+ stroke="currentColor"
279
+ stroke-width="2"
280
+ stroke-linecap="round"
281
+ stroke-linejoin="round"
282
+ fill="none"
283
+ />
284
+ </svg>
285
+ <span class="text-sm text-gray-800 dark:text-gray-100 select-none">All</span>
286
+ </button>
287
+ <button
288
+ type="button"
289
+ class="p-1 rounded-md flex items-center gap-1 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
290
+ onclick={() => oninvert && oninvert(sortedValues)}
291
+ disabled={sortedValues.length === 0}
292
+ aria-label="Invert selection"
293
+ title="Invert selection"
294
+ >
295
+ <svg
296
+ class="w-4 h-4 text-gray-800 dark:text-white"
297
+ viewBox="0 0 24 24"
298
+ fill="none"
299
+ aria-hidden="true"
300
+ >
301
+ <rect
302
+ x="3"
303
+ y="3"
304
+ width="18"
305
+ height="18"
306
+ rx="2"
307
+ stroke="currentColor"
308
+ stroke-width="2.5"
309
+ fill="none"
310
+ />
311
+ <rect
312
+ x="4"
313
+ y="4"
314
+ width="8.5"
315
+ height="16"
316
+ fill="currentColor"
317
+ opacity="0.28"
318
+ stroke="none"
319
+ />
320
+ <path
321
+ d="M7 13l3 3 7-7"
322
+ stroke="currentColor"
323
+ stroke-width="2"
324
+ stroke-linecap="round"
325
+ stroke-linejoin="round"
326
+ fill="none"
327
+ />
328
+ </svg>
329
+ <span class="text-sm text-gray-800 dark:text-gray-100 select-none">Invert</span>
330
+ </button>
331
+ <button
332
+ type="button"
333
+ class="p-1 rounded-md flex items-center gap-1 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
334
+ onclick={() => onchecknone && onchecknone()}
335
+ disabled={sortedValues.length === 0}
336
+ aria-label="Uncheck all"
337
+ title="Uncheck all"
338
+ >
339
+ <svg
340
+ class="w-4 h-4 text-gray-800 dark:text-white"
341
+ viewBox="0 0 24 24"
342
+ fill="none"
343
+ aria-hidden="true"
344
+ >
345
+ <rect
346
+ x="3"
347
+ y="3"
348
+ width="18"
349
+ height="18"
350
+ rx="2"
351
+ stroke="currentColor"
352
+ stroke-width="2"
353
+ fill="none"
354
+ />
355
+ </svg>
356
+ <span class="text-sm text-gray-800 dark:text-gray-100 select-none">None</span>
357
+ </button>
358
+ </div>
359
+ <div class="pr-1">
360
+ <span
361
+ class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300"
362
+ title="Total options">{sortedValues.length}</span
363
+ >
364
+ </div>
365
+ </div>
366
+ </div>
367
+
368
+ <!-- Checkbox list -->
369
+ <div class="p-1 overflow-y-auto flex-1 max-h-48" bind:this={listRef} onscroll={handleScroll}>
370
+ {#if sortedValues.length > populateThreshold && !loaded}
371
+ <div class="p-1 text-sm text-gray-700 dark:text-gray-200">
372
+ Too many options ({sortedValues.length}) to render by default.
373
+ <button
374
+ class="ml-2 px-2 py-1 text-xs rounded bg-gray-100 dark:bg-gray-600 text-gray-800 dark:text-white border border-gray-200 hover:bg-gray-200 dark:hover:bg-gray-500"
375
+ type="button"
376
+ onclick={() => (manuallyLoaded = true)}
377
+ >
378
+ Load options
379
+ </button>
380
+ </div>
381
+ {:else if virtualSlice}
382
+ <div style="height:{virtualSlice.totalHeight}px; position:relative;">
383
+ <div style="position:absolute; top:{virtualSlice.top}px; left:0; right:0;">
384
+ {#each virtualSlice.slice as value, idx (idx)}
385
+ {@const isSelected = selections?.includes(value)}
386
+ {@const displayValue = value === null || value === undefined ? '(empty)' : String(value)}
387
+ <label
388
+ class="flex items-center gap-1 px-2 py-1 cursor-pointer rounded-sm hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors"
389
+ style="height:{virtualItemHeight}px; box-sizing:border-box;"
390
+ >
391
+ <input
392
+ type="checkbox"
393
+ checked={isSelected}
394
+ onchange={() => ontoggle && ontoggle(value)}
395
+ class="w-4 h-4 shrink-0 cursor-pointer accent-blue-500"
396
+ />
397
+ <span
398
+ class="flex-1 text-sm text-gray-700 dark:text-gray-300 select-none min-w-0 overflow-hidden text-ellipsis"
399
+ >{displayValue}</span
400
+ >
401
+ {#if showCounts && column.counts && column.counts[value] !== undefined}
402
+ <span class="text-xs text-gray-500 dark:text-gray-400 ml-auto shrink-0"
403
+ >({column.counts[value]})</span
404
+ >
405
+ {/if}
406
+ </label>
407
+ {/each}
408
+ </div>
409
+ </div>
410
+ {:else if sortedValues.length > 0}
411
+ {#each sortedValues as value, idx (idx)}
412
+ {@const isSelected = selections?.includes(value)}
413
+ {@const displayValue = value === null || value === undefined ? '(empty)' : String(value)}
414
+ <label
415
+ class="flex items-center gap-1 px-2 py-1 cursor-pointer rounded-sm hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors"
416
+ >
417
+ <input
418
+ type="checkbox"
419
+ checked={isSelected}
420
+ onchange={() => ontoggle && ontoggle(value)}
421
+ class="w-4 h-4 shrink-0 cursor-pointer accent-blue-500"
422
+ />
423
+ <span
424
+ class="flex-1 text-sm text-gray-700 dark:text-gray-300 select-none min-w-0 overflow-hidden text-ellipsis"
425
+ >{displayValue}</span
426
+ >
427
+ {#if showCounts && column.counts && column.counts[value] !== undefined}
428
+ <span class="text-xs text-gray-500 dark:text-gray-400 ml-auto shrink-0"
429
+ >({column.counts[value]})</span
430
+ >
431
+ {/if}
432
+ </label>
433
+ {/each}
434
+ {:else}
435
+ <div class="p-4 text-center text-sm text-gray-400 dark:text-gray-500">No values available</div>
436
+ {/if}
437
+ </div>
@@ -0,0 +1,33 @@
1
+ export default FilterValueList;
2
+ type FilterValueList = {
3
+ $on?(type: string, callback: (e: any) => void): () => void;
4
+ $set?(props: Partial<$$ComponentProps>): void;
5
+ };
6
+ declare const FilterValueList: import("svelte").Component<{
7
+ column: any;
8
+ selections?: any[];
9
+ showCounts?: boolean;
10
+ virtualThreshold?: number;
11
+ virtualItemHeight?: number;
12
+ virtualOverscan?: number;
13
+ populateThreshold?: number;
14
+ ontoggle: any;
15
+ oncheckall: any;
16
+ oninvert: any;
17
+ onchecknone: any;
18
+ onsortchange: any;
19
+ }, {}, "">;
20
+ type $$ComponentProps = {
21
+ column: any;
22
+ selections?: any[];
23
+ showCounts?: boolean;
24
+ virtualThreshold?: number;
25
+ virtualItemHeight?: number;
26
+ virtualOverscan?: number;
27
+ populateThreshold?: number;
28
+ ontoggle: any;
29
+ oncheckall: any;
30
+ oninvert: any;
31
+ onchecknone: any;
32
+ onsortchange: any;
33
+ };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Svelte 5 reactive composable that manages per-column filter selections,
3
+ * debounced emission, and selection helpers.
4
+ *
5
+ * @param {object} opts
6
+ * @param {() => Array} opts.columnFilters - reactive getter for column filter configs
7
+ * @param {() => object} opts.activeFilters - reactive getter for active filters
8
+ * @param {() => number} opts.emitDebounce - reactive getter for debounce ms
9
+ * @param {() => Function|undefined} opts.onfilter - reactive getter for onfilter callback
10
+ */
11
+ export function useFilterState(opts: {
12
+ columnFilters: () => any[];
13
+ activeFilters: () => object;
14
+ emitDebounce: () => number;
15
+ onfilter: () => Function | undefined;
16
+ }): {
17
+ readonly selections: {};
18
+ toggleSelection: (columnKey: any, value: any) => void;
19
+ clearColumn: (columnKey: any) => void;
20
+ clearAllFilters: () => void;
21
+ checkAll: (columnKey: any, values: any) => void;
22
+ invertSelection: (columnKey: any, values: any) => void;
23
+ checkNone: (columnKey: any) => void;
24
+ updateDateRange: (columnKey: any, updated: any) => void;
25
+ };
@@ -0,0 +1,132 @@
1
+ import { onDestroy } from 'svelte';
2
+
3
+ function isDateRangeColumn(col) {
4
+ return col.type === 'daterange' || col.type === 'datetimerange';
5
+ }
6
+
7
+ /**
8
+ * Svelte 5 reactive composable that manages per-column filter selections,
9
+ * debounced emission, and selection helpers.
10
+ *
11
+ * @param {object} opts
12
+ * @param {() => Array} opts.columnFilters - reactive getter for column filter configs
13
+ * @param {() => object} opts.activeFilters - reactive getter for active filters
14
+ * @param {() => number} opts.emitDebounce - reactive getter for debounce ms
15
+ * @param {() => Function|undefined} opts.onfilter - reactive getter for onfilter callback
16
+ */
17
+ export function useFilterState(opts) {
18
+ let selections = $state({});
19
+ let _emitTimer = null;
20
+ let _pendingEmit = null;
21
+
22
+ // Sync selections from activeFilters whenever columnFilters or activeFilters change
23
+ $effect(() => {
24
+ const cols = opts.columnFilters();
25
+ const active = opts.activeFilters();
26
+ const newSelections = {};
27
+ for (const col of cols) {
28
+ newSelections[col.key] = active[col.key] ?? (isDateRangeColumn(col) ? {} : []);
29
+ }
30
+ selections = newSelections;
31
+ });
32
+
33
+ function scheduleEmit(columnKey, selectedValues) {
34
+ _pendingEmit = { columnKey, selectedValues, allFilters: selections };
35
+ const delay = opts.emitDebounce();
36
+ if (!delay || delay <= 0) {
37
+ flushEmit();
38
+ return;
39
+ }
40
+ if (_emitTimer) clearTimeout(_emitTimer);
41
+ _emitTimer = setTimeout(() => flushEmit(), delay);
42
+ }
43
+
44
+ function flushEmit() {
45
+ if (!_pendingEmit) return;
46
+ const payload = _pendingEmit;
47
+ _pendingEmit = null;
48
+ if (_emitTimer) {
49
+ clearTimeout(_emitTimer);
50
+ _emitTimer = null;
51
+ }
52
+ const handler = opts.onfilter();
53
+ if (handler !== undefined) {
54
+ try {
55
+ handler({
56
+ key: payload.columnKey,
57
+ values: payload.selectedValues,
58
+ allFilters: payload.allFilters,
59
+ });
60
+ } catch (err) {
61
+ try {
62
+ console.error('onfilter threw:', err);
63
+ } catch (e) {}
64
+ }
65
+ }
66
+ }
67
+
68
+ onDestroy(() => {
69
+ if (_emitTimer) clearTimeout(_emitTimer);
70
+ flushEmit();
71
+ });
72
+
73
+ function toggleSelection(columnKey, value) {
74
+ const current = selections[columnKey] || [];
75
+ const updated = current.includes(value)
76
+ ? current.filter((v) => v !== value)
77
+ : [...current, value];
78
+ selections = { ...selections, [columnKey]: updated };
79
+ scheduleEmit(columnKey, updated);
80
+ }
81
+
82
+ function clearColumn(columnKey) {
83
+ const col = opts.columnFilters().find((c) => c.key === columnKey);
84
+ const empty = isDateRangeColumn(col) ? {} : [];
85
+ selections = { ...selections, [columnKey]: empty };
86
+ scheduleEmit(columnKey, empty);
87
+ }
88
+
89
+ function clearAllFilters() {
90
+ const cleared = {};
91
+ for (const col of opts.columnFilters()) {
92
+ cleared[col.key] = isDateRangeColumn(col) ? {} : [];
93
+ }
94
+ selections = cleared;
95
+ scheduleEmit(null, []);
96
+ }
97
+
98
+ function checkAll(columnKey, values) {
99
+ const all = Array.isArray(values) ? values.slice() : [];
100
+ selections = { ...selections, [columnKey]: all };
101
+ scheduleEmit(columnKey, all);
102
+ }
103
+
104
+ function invertSelection(columnKey, values) {
105
+ const current = new Set(selections[columnKey] || []);
106
+ const next = (Array.isArray(values) ? values : []).filter((v) => !current.has(v));
107
+ selections = { ...selections, [columnKey]: next };
108
+ scheduleEmit(columnKey, next);
109
+ }
110
+
111
+ function checkNone(columnKey) {
112
+ clearColumn(columnKey);
113
+ }
114
+
115
+ function updateDateRange(columnKey, updated) {
116
+ selections = { ...selections, [columnKey]: updated };
117
+ scheduleEmit(columnKey, updated);
118
+ }
119
+
120
+ return {
121
+ get selections() {
122
+ return selections;
123
+ },
124
+ toggleSelection,
125
+ clearColumn,
126
+ clearAllFilters,
127
+ checkAll,
128
+ invertSelection,
129
+ checkNone,
130
+ updateDateRange,
131
+ };
132
+ }