@zhangt58/svelte-vtable 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,419 +1,77 @@
1
1
  <script>
2
2
  import { Badge } from 'flowbite-svelte';
3
- import { ChevronDownOutline, ArrowDownOutline } from 'flowbite-svelte-icons';
4
- import { onDestroy } from 'svelte';
3
+ import { useFilterState } from './filters/useFilterState.svelte.js';
4
+ import FilterColumn from './filters/FilterColumn.svelte';
5
+ import FilterValueList from './filters/FilterValueList.svelte';
6
+ import FilterDateRange from './filters/FilterDateRange.svelte';
5
7
 
6
- // shared default no-op function
7
- const DEFAULT_NOOP = (..._args) => {};
8
-
9
- // Props using Svelte 5 $props()
10
8
  let {
11
- // columnFilters: array of { key, label, uniqueValues }
12
- // where uniqueValues is an array of unique values for that column
13
9
  columnFilters = [],
14
- // layout direction: 'horizontal' or 'vertical'
15
10
  direction = 'horizontal',
16
- // current active filters: { columnKey: [selectedValues] }
17
11
  activeFilters = {},
18
- // Callback when filters change
19
- filterChange = DEFAULT_NOOP,
20
- // Optional callback when sort mode/dir changes: ( { columnKey, mode, dir } )
21
- sortChange = DEFAULT_NOOP,
22
- // CSS class for the container
12
+ onfilter = undefined,
13
+ oncolumnsort = undefined,
23
14
  className = '',
24
- // Whether to show filter counts
25
15
  showCounts = true,
26
- // Virtualization props (defaults)
27
16
  virtualThreshold = 500,
28
17
  virtualItemHeight = 36,
29
18
  virtualOverscan = 5,
30
- // Debounce milliseconds for emitting filterChange (0 = immediate)
31
19
  emitDebounce = 100,
32
- // If the number of options exceeds this threshold, the options are not generated by default
33
- // and the user must click "Load options" to populate them. Set to 0 to always populate.
34
20
  populateThreshold = 200,
35
- // If true, render dropdowns inline (in-flow) so opening them expands the parent container.
36
- // If false, render as absolutely-positioned overlays (old behavior).
37
21
  dropdownInline = true,
22
+ relativeRangePresets = [
23
+ { label: '1h', value: 1, unit: 'hour' },
24
+ { label: '6h', value: 6, unit: 'hour' },
25
+ { label: '12h', value: 12, unit: 'hour' },
26
+ { label: '1d', value: 1, unit: 'day' },
27
+ { label: '7d', value: 7, unit: 'day' },
28
+ { label: '30d', value: 30, unit: 'day' },
29
+ { label: '1y', value: 1, unit: 'year' },
30
+ ],
38
31
  } = $props();
39
32
 
40
- // Internal state for selected options per column
41
- let selections = $state({});
42
-
43
- // Track whether options have been loaded (populated) per-column when the list is large
44
- let loadedOptions = $state({});
45
-
46
- // Auto-enable loading for small lists when columnFilters change
47
- $effect(() => {
48
- const initial = {};
49
- for (const col of columnFilters) {
50
- const len = Array.isArray(col.uniqueValues) ? col.uniqueValues.length : 0;
51
- initial[col.key] = populateThreshold <= 0 || len <= populateThreshold;
52
- }
53
- loadedOptions = initial;
33
+ const fs = useFilterState({
34
+ columnFilters: () => columnFilters,
35
+ activeFilters: () => activeFilters,
36
+ emitDebounce: () => emitDebounce,
37
+ onfilter: () => onfilter,
54
38
  });
55
39
 
56
- // --- Debounced emission helpers ---
57
- let _emitTimer = null;
58
- let _pendingEmit = null;
59
-
60
- function scheduleEmit(columnKey, selectedValues) {
61
- // capture latest state snapshot
62
- _pendingEmit = { columnKey, selectedValues, allFilters: selections };
63
-
64
- if (!emitDebounce || emitDebounce <= 0) {
65
- // immediate
66
- flushEmit();
67
- return;
68
- }
69
-
70
- if (_emitTimer) clearTimeout(_emitTimer);
71
- _emitTimer = setTimeout(() => flushEmit(), emitDebounce);
72
- }
73
-
74
- function flushEmit() {
75
- if (!_pendingEmit) return;
76
- const payload = _pendingEmit;
77
- _pendingEmit = null;
78
- if (_emitTimer) {
79
- clearTimeout(_emitTimer);
80
- _emitTimer = null;
81
- }
82
-
83
- try {
84
- /** @type {any} */ (filterChange)(payload);
85
- } catch (err) {
86
- try {
87
- console.error('filterChange threw:', err);
88
- } catch (e) {}
89
- }
90
- }
91
-
92
- // cleanup on destroy to avoid timers running after unmount
93
- onDestroy(() => {
94
- if (_emitTimer) clearTimeout(_emitTimer);
95
- // flush any pending emit synchronously
96
- flushEmit();
97
- });
98
-
99
- // Helper: is this column a date/datetime range filter?
100
- function isDateRangeColumn(col) {
101
- return col.type === 'daterange' || col.type === 'datetimerange';
102
- }
103
-
104
- // Initialize selections from activeFilters
105
- $effect(() => {
106
- const newSelections = {};
107
- for (const col of columnFilters) {
108
- newSelections[col.key] = activeFilters[col.key] ?? (isDateRangeColumn(col) ? {} : []);
109
- }
110
- selections = newSelections;
111
- });
112
-
113
- // Toggle selection for a specific column and value
114
- function toggleSelection(columnKey, value) {
115
- const current = selections[columnKey] || [];
116
- let updated;
117
-
118
- if (current.includes(value)) {
119
- // Remove the value
120
- updated = current.filter((v) => v !== value);
121
- } else {
122
- // Add the value
123
- updated = [...current, value];
124
- }
125
-
126
- selections = { ...selections, [columnKey]: updated };
127
-
128
- // Schedule debounced filter change emission
129
- scheduleEmit(columnKey, updated);
130
- }
131
-
132
- // Clear all selections for a column
133
- function clearColumn(columnKey) {
134
- const col = columnFilters.find((c) => c.key === columnKey);
135
- const empty = isDateRangeColumn(col) ? {} : [];
136
- selections = { ...selections, [columnKey]: empty };
137
- scheduleEmit(columnKey, empty);
138
- }
139
-
140
- // Clear all filters
141
- function clearAllFilters() {
142
- const cleared = {};
143
- for (const col of columnFilters) {
144
- cleared[col.key] = isDateRangeColumn(col) ? {} : [];
145
- }
146
- selections = cleared;
147
-
148
- // emit after debounce (columnKey null indicates global clear)
149
- scheduleEmit(null, []);
150
- }
151
-
152
- // Check if any filters are active
153
- const hasActiveFilters = $derived(() => {
154
- return Object.values(selections).some((val) => {
155
- if (Array.isArray(val)) return val.length > 0;
156
- if (val && typeof val === 'object') return !!(val.from || val.to);
157
- return false;
158
- });
159
- });
160
-
161
- // Count active filters
162
- const activeFilterCount = $derived(() => {
163
- return Object.values(selections).reduce((sum, val) => {
164
- if (Array.isArray(val)) return sum + (val?.length || 0);
165
- if (val && typeof val === 'object' && (val.from || val.to)) return sum + 1;
166
- return sum;
167
- }, 0);
168
- });
169
-
170
- // Toggle dropdown visibility for a column
171
40
  let openDropdowns = $state({});
172
-
173
- // Simple toggle/close functions — dropdowns are controlled only by their
174
- // toggle button and programmatic calls (e.g. Show All / Collapse All).
175
- function toggleDropdown(columnKey) {
176
- const wasOpen = openDropdowns[columnKey];
177
- openDropdowns = { ...openDropdowns, [columnKey]: !wasOpen };
178
- }
179
-
180
- // Sorting state for each column's dropdown
181
- let sortModes = $state({});
182
- // Per-column sort direction: 'asc' or 'desc'
183
- let sortDirs = $state({});
184
-
185
- // Inline header search queries per column (small text filter for options)
186
- let searchQueries = $state({});
187
-
188
- // --- Virtualization settings and state ---
189
- // (virtual props are provided via the main $props() destructure above)
190
-
191
- // DOM refs for per-column scroll containers
192
- let listRefs = $state({});
193
-
194
- // Per-column scroll state: { scrollTop, height }
195
- let virtualScroll = $state({});
196
-
197
- // Svelte action to register list containers and keep virtualScroll updated
198
- function registerList(node, params) {
199
- const key = params && params.key;
200
- if (!key) return { destroy() {} };
201
-
202
- listRefs = { ...listRefs, [key]: node };
203
-
204
- function updateState() {
205
- virtualScroll = {
206
- ...virtualScroll,
207
- [key]: { scrollTop: node.scrollTop, height: node.clientHeight },
208
- };
209
- }
210
-
211
- // initialize
212
- updateState();
213
-
214
- const onScroll = () => updateState();
215
- const onResize = () => updateState();
216
-
217
- node.addEventListener('scroll', onScroll);
218
- // Observe size changes (in case container height changes)
219
- const ro = new ResizeObserver(onResize);
220
- ro.observe(node);
221
-
222
- return {
223
- update(newParams) {
224
- // allow key to be updated (unlikely)
225
- if (!newParams || newParams.key !== key) {
226
- node.removeEventListener('scroll', onScroll);
227
- ro.disconnect();
228
- delete listRefs[key];
229
- }
230
- },
231
- destroy() {
232
- node.removeEventListener('scroll', onScroll);
233
- ro.disconnect();
234
- delete listRefs[key];
235
- // remove virtualScroll entry
236
- const copy = { ...virtualScroll };
237
- delete copy[key];
238
- virtualScroll = copy;
239
- },
240
- };
241
- }
242
-
243
- // Compute virtual slice for a column when the values exceed threshold
244
- function getVirtualSlice(column, values) {
245
- if (!values || values.length <= virtualThreshold) return null;
246
- const vs = virtualScroll[column.key] || { scrollTop: 0, height: 200 };
247
- const itemH = virtualItemHeight;
248
- const height = vs.height || 200;
249
- const overscan = virtualOverscan;
250
-
251
- const start = Math.max(0, Math.floor(vs.scrollTop / itemH) - overscan);
252
- const visibleCount = Math.ceil(height / itemH) + overscan * 2;
253
- const end = Math.min(values.length, start + visibleCount);
254
- const slice = values.slice(start, end);
255
- const top = start * itemH;
256
- const totalHeight = values.length * itemH;
257
-
258
- return { slice, start, end, top, totalHeight };
259
- }
260
-
261
- // --- Helper: extract a numeric sort key from a value ---
262
- // Returns the number itself if numeric, the first number found in a string,
263
- // or 0 if no number can be found.
264
- function extractNumber(v) {
265
- if (v === null || v === undefined) return 0;
266
- if (typeof v === 'number') return v;
267
- const s = String(v);
268
- const match = s.match(/-?\d+(\.\d+)?/);
269
- return match ? parseFloat(match[0]) : 0;
270
- }
271
-
272
- // --- Helper: return the values for a column after applying search + sort ---
273
- function getSortedValues(column) {
274
- // column.uniqueValues is expected to be an array of possible values
275
- const raw = Array.isArray(column.uniqueValues) ? column.uniqueValues.slice() : [];
276
-
277
- // apply search filter if present
278
- const q = (searchQueries[column.key] || '').toString().trim().toLowerCase();
279
- let filtered = raw;
280
- if (q) {
281
- filtered = raw.filter((v) => {
282
- const text = v === null || v === undefined ? '(empty)' : String(v);
283
- return text.toLowerCase().includes(q);
284
- });
285
- }
286
-
287
- // determine sort mode and direction
288
- const mode = sortModes[column.key] || 'name';
289
- const dir = (sortDirs[column.key] || 'asc') === 'asc' ? 1 : -1;
290
-
291
- // stable sort: map-index technique
292
- const withIndex = filtered.map((v, i) => ({ v, i }));
293
-
294
- withIndex.sort((a, b) => {
295
- const va = a.v;
296
- const vb = b.v;
297
-
298
- if (mode === 'count' && column.counts) {
299
- const ca = Number(column.counts[va] ?? 0);
300
- const cb = Number(column.counts[vb] ?? 0);
301
- if (ca !== cb) return (ca - cb) * dir * -1; // higher counts first when desc
302
- // fallback to name compare
303
- }
304
-
305
- if (mode === 'number') {
306
- const na = extractNumber(va);
307
- const nb = extractNumber(vb);
308
- if (na !== nb) return (na - nb) * dir;
309
- // fallback to name compare for equal numeric values
310
- }
311
-
312
- // compare by name
313
- const sa = va === null || va === undefined ? '(empty)' : String(va);
314
- const sb = vb === null || vb === undefined ? '(empty)' : String(vb);
315
- const la = sa.toLowerCase();
316
- const lb = sb.toLowerCase();
317
- if (la < lb) return -1 * dir;
318
- if (la > lb) return 1 * dir;
319
- // maintain stable order
320
- return a.i - b.i;
321
- });
322
-
323
- return withIndex.map((x) => x.v);
324
- }
325
-
326
- // Toggle sort mode for a column. If the same mode is clicked again,
327
- // flip the direction; otherwise set the mode and default to 'desc'.
328
- function toggleSortMode(columnKey, mode) {
329
- const prevMode = sortModes[columnKey];
330
- if (prevMode === mode) {
331
- // flip direction
332
- const prevDir = sortDirs[columnKey] || 'desc';
333
- const nextDir = prevDir === 'asc' ? 'desc' : 'asc';
334
- sortDirs = { ...sortDirs, [columnKey]: nextDir };
335
- } else {
336
- sortModes = { ...sortModes, [columnKey]: mode };
337
- // default first click to descending (common expectation for counts)
338
- sortDirs = { ...sortDirs, [columnKey]: 'desc' };
339
- }
340
- // ensure the mode is set (for first-time clicks)
341
- sortModes = { ...sortModes, [columnKey]: mode };
342
-
343
- const newDir = sortDirs[columnKey] || 'asc';
41
+ const toggle = (key) => (openDropdowns = { ...openDropdowns, [key]: !openDropdowns[key] });
42
+ const showAll = () => {
43
+ const a = {};
44
+ for (const c of columnFilters) a[c.key] = true;
45
+ openDropdowns = a;
46
+ };
47
+ const closeAll = () => (openDropdowns = {});
48
+
49
+ const allOpen = $derived(columnFilters.every((c) => openDropdowns[c.key]));
50
+ const allClosed = $derived(columnFilters.every((c) => !openDropdowns[c.key]));
51
+ const isDateRange = (col) => col.type === 'daterange' || col.type === 'datetimerange';
52
+
53
+ const hasActive = $derived(
54
+ Object.values(fs.selections).some((v) =>
55
+ Array.isArray(v) ? v.length > 0 : !!(v?.from || v?.to),
56
+ ),
57
+ );
58
+ const activeCount = $derived(
59
+ Object.values(fs.selections).reduce((s, v) => {
60
+ if (Array.isArray(v)) return s + (v?.length || 0);
61
+ if (v && typeof v === 'object' && (v.from || v.to)) return s + 1;
62
+ return s;
63
+ }, 0),
64
+ );
65
+
66
+ function handleSortChange(columnKey, { mode, dir }) {
344
67
  try {
345
- // notify parent if it wants to react to sort changes
346
- /** @type {any} */ (sortChange)({ columnKey, mode, dir: newDir });
68
+ if (oncolumnsort) /** @type {any} */ (oncolumnsort)({ key: columnKey, mode, dir });
347
69
  } catch (err) {
348
70
  try {
349
- console.debug('sortChange callback threw', err);
71
+ console.debug('oncolumnsort threw', err);
350
72
  } catch (e) {}
351
73
  }
352
- // debug log
353
- try {
354
- console.debug('toggleSortMode', columnKey, mode, sortDirs[columnKey]);
355
- } catch (e) {}
356
- }
357
-
358
- // Clear selection for a column (from within dropdown)
359
- function clearSelection(columnKey) {
360
- clearColumn(columnKey);
361
- }
362
-
363
- // Check all values for a column
364
- function checkAll(columnKey, values) {
365
- const all = Array.isArray(values) ? values.slice() : [];
366
- selections = { ...selections, [columnKey]: all };
367
- scheduleEmit(columnKey, all);
368
- }
369
-
370
- // Invert selection for a column (values is the full option list)
371
- function invertSelection(columnKey, values) {
372
- const current = new Set(selections[columnKey] || []);
373
- const next = [];
374
- for (const v of Array.isArray(values) ? values : []) {
375
- if (!current.has(v)) next.push(v);
376
- }
377
- selections = { ...selections, [columnKey]: next };
378
- scheduleEmit(columnKey, next);
379
- }
380
-
381
- // Uncheck all -> reuse clearColumn
382
- function checkNone(columnKey) {
383
- clearColumn(columnKey);
384
- }
385
-
386
- // Handle a date/datetime range input change
387
- function handleDateRangeChange(columnKey, field, value) {
388
- const current = selections[columnKey] || {};
389
- const updated = { ...current, [field]: value };
390
- selections = { ...selections, [columnKey]: updated };
391
- scheduleEmit(columnKey, updated);
392
- }
393
-
394
- // Show all dropdowns
395
- function showAllDropdowns() {
396
- const allOpen = {};
397
- for (const col of columnFilters) {
398
- allOpen[col.key] = true;
399
- }
400
- openDropdowns = allOpen;
401
- }
402
-
403
- // Collapse all dropdowns
404
- function collapseAllDropdowns() {
405
- openDropdowns = {};
406
74
  }
407
-
408
- // Check if all dropdowns are open
409
- const allDropdownsOpen = $derived.by(() => {
410
- return columnFilters.every((col) => openDropdowns[col.key]);
411
- });
412
-
413
- // Check if all dropdowns are closed
414
- const allDropdownsClosed = $derived.by(() => {
415
- return columnFilters.every((col) => !openDropdowns[col.key]);
416
- });
417
75
  </script>
418
76
 
419
77
  <div
@@ -422,37 +80,39 @@
422
80
  class:vertical={direction === 'vertical'}
423
81
  >
424
82
  <div class="flex justify-between items-center mb-2 flex-wrap gap-1">
425
- <!-- Left controls: Show All, Close All -->
426
83
  <div class="flex items-center gap-1 flex-wrap">
427
84
  <button
428
- class="px-3 py-1 text-sm text-green-600 bg-transparent border border-green-600 rounded-md hover:bg-green-600 hover:text-white transition-all cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-green-600"
429
- disabled={allDropdownsOpen}
430
- onclick={showAllDropdowns}
431
- title="Show all filter dropdowns"
85
+ class="px-3 py-1 text-sm bg-transparent border rounded-md transition-all cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
86
+ style="color: var(--vtable-color-accent); border-color: var(--vtable-color-accent);"
87
+ disabled={allOpen}
88
+ onclick={showAll}
89
+ onmouseenter={(e) => {
90
+ if (!e.currentTarget.disabled) {
91
+ e.currentTarget.style.backgroundColor = 'var(--vtable-color-accent)';
92
+ e.currentTarget.style.color = '#fff';
93
+ }
94
+ }}
95
+ onmouseleave={(e) => {
96
+ e.currentTarget.style.backgroundColor = '';
97
+ e.currentTarget.style.color = 'var(--vtable-color-accent)';
98
+ }}
99
+ title="Show all filter dropdowns">Show All</button
432
100
  >
433
- Show All
434
- </button>
435
101
  <button
436
102
  class="px-3 py-1 text-sm text-gray-600 bg-transparent border border-gray-600 rounded-md hover:bg-gray-600 hover:text-white transition-all cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-gray-600"
437
- disabled={allDropdownsClosed}
438
- onclick={collapseAllDropdowns}
439
- title="Close all filter dropdowns"
103
+ disabled={allClosed}
104
+ onclick={closeAll}
105
+ title="Close all filter dropdowns">Close All</button
440
106
  >
441
- Close All
442
- </button>
443
107
  </div>
444
-
445
- <!-- Right controls: active badge and Clear All -->
446
108
  <div class="flex items-center gap-2 flex-wrap">
447
- {#if hasActiveFilters()}
448
- <Badge color="blue" rounded>{activeFilterCount()} active</Badge>
109
+ {#if hasActive}
110
+ <Badge color="blue" rounded>{activeCount} active</Badge>
449
111
  <button
450
112
  class="px-3 py-1 text-sm text-red-600 bg-transparent border border-red-600 rounded-md hover:bg-red-600 hover:text-white transition-all cursor-pointer"
451
- onclick={clearAllFilters}
452
- title="Clear all filters"
113
+ onclick={fs.clearAllFilters}
114
+ title="Clear all filters">Clear All</button
453
115
  >
454
- Clear All
455
- </button>
456
116
  {/if}
457
117
  </div>
458
118
  </div>
@@ -463,389 +123,52 @@
463
123
  class:grid-vertical={direction === 'vertical'}
464
124
  >
465
125
  {#each columnFilters as column (column.key)}
466
- {@const _sel = selections[column.key]}
467
- {@const isActive = Array.isArray(_sel) ? _sel.length > 0 : !!(_sel?.from || _sel?.to)}
468
- {@const isOpen = openDropdowns[column.key]}
469
- {@const sortedValues = getSortedValues(column)}
470
- {@const currentSortMode = sortModes[column.key] || 'name'}
471
- {@const currentSortDir = sortDirs[column.key] || 'asc'}
472
-
126
+ {@const sel = fs.selections[column.key]}
127
+ {@const isActive = Array.isArray(sel) ? sel.length > 0 : !!(sel?.from || sel?.to)}
128
+ {@const isOpen = !!openDropdowns[column.key]}
473
129
  <div class="flex flex-col min-w-0 relative">
474
- <button
475
- id="filter-{column.key}"
476
- class="w-full flex justify-between items-center px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:border-gray-400 dark:hover:border-gray-500 focus:outline-none focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-100 dark:focus:ring-blue-900 transition-all cursor-pointer gap-2 {isActive
477
- ? 'border-green-500 dark:border-green-400 bg-green-50 dark:bg-green-900/20'
478
- : ''}"
479
- onclick={() => toggleDropdown(column.key)}
480
- type="button"
481
- >
482
- <span class="flex-1 text-left whitespace-nowrap overflow-hidden text-ellipsis min-w-0">
483
- {column.label || column.key}
484
- </span>
485
- {#if isActive}
486
- {#if Array.isArray(_sel)}
487
- <Badge color="green" rounded class="ml-1">{_sel.length}</Badge>
488
- {:else}
489
- <Badge color="green" rounded class="ml-1">range</Badge>
490
- {/if}
491
- {/if}
492
- <ChevronDownOutline
493
- class="w-5 h-5 shrink-0 transition-transform {isOpen ? 'rotate-180' : ''}"
494
- />
495
- </button>
496
-
130
+ <FilterColumn
131
+ {column}
132
+ {isOpen}
133
+ {isActive}
134
+ selection={sel}
135
+ ontoggle={() => toggle(column.key)}
136
+ />
497
137
  {#if isOpen}
498
138
  <div
499
- class={dropdownInline
500
- ? `mt-1 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg dark:shadow-gray-900 max-h-64 flex flex-col dropdown-menu`
501
- : `absolute top-full mt-1 left-0 right-0 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg dark:shadow-gray-900 max-h-64 flex flex-col dropdown-menu`}
139
+ class={[
140
+ dropdownInline ? '' : 'absolute top-full left-0 right-0',
141
+ 'mt-1 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg dark:shadow-gray-900 flex flex-col dropdown-menu',
142
+ isDateRange(column) ? 'overflow-y-auto' : 'max-h-64',
143
+ ]
144
+ .filter(Boolean)
145
+ .join(' ')}
502
146
  tabindex="-1"
503
147
  data-column={column.key}
504
148
  >
505
- {#if isDateRangeColumn(column)}
506
- <!-- Date / datetime range picker UI -->
507
- {@const inputType = column.type === 'datetimerange' ? 'datetime-local' : 'date'}
508
- {@const dateRange = selections[column.key] || {}}
509
- <div class="p-3 flex flex-col gap-2">
510
- <div class="flex items-center gap-2">
511
- <label
512
- class="text-xs font-medium text-gray-500 dark:text-gray-400 w-8 shrink-0"
513
- for="filter-{column.key}-from"
514
- >
515
- From
516
- </label>
517
- <input
518
- id="filter-{column.key}-from"
519
- type={inputType}
520
- class="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-800 text-gray-700 dark:text-gray-200 focus:outline-none focus:border-blue-500 dark:focus:border-blue-400"
521
- value={dateRange.from || ''}
522
- oninput={(e) =>
523
- handleDateRangeChange(column.key, 'from', e.currentTarget.value)}
524
- />
525
- </div>
526
- <div class="flex items-center gap-2">
527
- <label
528
- class="text-xs font-medium text-gray-500 dark:text-gray-400 w-8 shrink-0"
529
- for="filter-{column.key}-to"
530
- >
531
- To
532
- </label>
533
- <input
534
- id="filter-{column.key}-to"
535
- type={inputType}
536
- class="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-800 text-gray-700 dark:text-gray-200 focus:outline-none focus:border-blue-500 dark:focus:border-blue-400"
537
- value={dateRange.to || ''}
538
- oninput={(e) => handleDateRangeChange(column.key, 'to', e.currentTarget.value)}
539
- />
540
- </div>
541
- {#if dateRange.from || dateRange.to}
542
- <button
543
- type="button"
544
- class="mt-1 self-start px-2 py-0.5 text-xs text-red-600 border border-red-400 rounded hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
545
- onclick={() => clearColumn(column.key)}
546
- >
547
- Clear range
548
- </button>
549
- {/if}
550
- </div>
149
+ {#if isDateRange(column)}
150
+ <FilterDateRange
151
+ {column}
152
+ selection={sel || {}}
153
+ {relativeRangePresets}
154
+ onchange={(u) => fs.updateDateRange(column.key, u)}
155
+ onclear={() => fs.clearColumn(column.key)}
156
+ />
551
157
  {:else}
552
- <!-- Value-selection filter UI (checkboxes) -->
553
- <div class="px-1 py-1 border-b border-gray-200 dark:border-gray-600">
554
- <div class="flex items-center gap-1 w-full min-w-0">
555
- <input
556
- type="text"
557
- placeholder="Filter..."
558
- 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"
559
- bind:value={searchQueries[column.key]}
560
- />
561
-
562
- <div class="flex items-center gap-1">
563
- <button
564
- 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"
565
- class:bg-blue-100={currentSortMode === 'name'}
566
- class:dark:bg-blue-900={currentSortMode === 'name'}
567
- onclick={() => toggleSortMode(column.key, 'name')}
568
- title="Sort by name"
569
- type="button"
570
- >
571
- <span
572
- class="flex flex-col items-center leading-none font-semibold"
573
- style="font-size:0.6rem;"
574
- >
575
- <span>A</span>
576
- <span>Z</span>
577
- </span>
578
- <ArrowDownOutline
579
- class={'w-3 h-3 transition-transform ' +
580
- (currentSortMode === 'name'
581
- ? 'text-blue-900 dark:text-blue-100'
582
- : 'text-gray-400 dark:text-gray-500')}
583
- style={currentSortMode === 'name' && currentSortDir === 'asc'
584
- ? 'transform: rotate(180deg);'
585
- : ''}
586
- aria-hidden="true"
587
- />
588
- </button>
589
-
590
- <button
591
- 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"
592
- class:bg-blue-100={currentSortMode === 'number'}
593
- class:dark:bg-blue-900={currentSortMode === 'number'}
594
- onclick={() => toggleSortMode(column.key, 'number')}
595
- title="Sort by number"
596
- aria-label="Sort by number"
597
- type="button"
598
- >
599
- <span
600
- class="flex flex-col items-center leading-none font-semibold"
601
- style="font-size:0.6rem;"
602
- >
603
- <span>0</span>
604
- <span>9</span>
605
- </span>
606
- <ArrowDownOutline
607
- class={'w-3 h-3 transition-transform ' +
608
- (currentSortMode === 'number'
609
- ? 'text-blue-900 dark:text-blue-100'
610
- : 'text-gray-400 dark:text-gray-500')}
611
- style={currentSortMode === 'number' && currentSortDir === 'asc'
612
- ? 'transform: rotate(180deg);'
613
- : ''}
614
- aria-hidden="true"
615
- />
616
- </button>
617
-
618
- {#if showCounts && column.counts}
619
- <button
620
- 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"
621
- class:bg-blue-100={currentSortMode === 'count'}
622
- class:dark:bg-blue-900={currentSortMode === 'count'}
623
- onclick={() => toggleSortMode(column.key, 'count')}
624
- title="Sort by count"
625
- type="button"
626
- >
627
- <span class="text-sm font-semibold">#</span>
628
- <ArrowDownOutline
629
- class={'w-3 h-3 transition-transform ' +
630
- (currentSortMode === 'count'
631
- ? 'text-blue-900 dark:text-blue-100'
632
- : 'text-gray-400 dark:text-gray-500')}
633
- style={currentSortMode === 'count' && currentSortDir === 'asc'
634
- ? 'transform: rotate(180deg);'
635
- : ''}
636
- aria-hidden="true"
637
- />
638
- </button>
639
- {/if}
640
- </div>
641
- </div>
642
- </div>
643
-
644
- <!-- Action row: Check all / Invert / Uncheck all (icon buttons) -->
645
- <div class="px-2 py-1 border-b border-gray-100 dark:border-gray-600">
646
- <div class="flex items-center justify-between">
647
- <div class="flex items-center gap-1">
648
- <button
649
- type="button"
650
- 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"
651
- onclick={() => checkAll(column.key, sortedValues)}
652
- disabled={sortedValues.length === 0}
653
- aria-label="Check all"
654
- title="Check all"
655
- >
656
- <!-- Checked square icon (higher contrast) -->
657
- <svg
658
- class="w-4 h-4 text-gray-800 dark:text-white"
659
- viewBox="0 0 24 24"
660
- fill="none"
661
- aria-hidden="true"
662
- >
663
- <rect
664
- x="3"
665
- y="3"
666
- width="18"
667
- height="18"
668
- rx="2"
669
- stroke="currentColor"
670
- stroke-width="2.5"
671
- fill="none"
672
- />
673
- <path
674
- d="M7 13l3 3 7-7"
675
- stroke="currentColor"
676
- stroke-width="2"
677
- stroke-linecap="round"
678
- stroke-linejoin="round"
679
- fill="none"
680
- />
681
- </svg>
682
- <span class="text-sm text-gray-800 dark:text-gray-100 select-none">All</span>
683
- </button>
684
-
685
- <button
686
- type="button"
687
- 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"
688
- onclick={() => invertSelection(column.key, sortedValues)}
689
- disabled={sortedValues.length === 0}
690
- aria-label="Invert selection"
691
- title="Invert selection"
692
- >
693
- <!-- Half-checked square icon (left half filled) - higher contrast -->
694
- <svg
695
- class="w-4 h-4 text-gray-800 dark:text-white"
696
- viewBox="0 0 24 24"
697
- fill="none"
698
- aria-hidden="true"
699
- >
700
- <rect
701
- x="3"
702
- y="3"
703
- width="18"
704
- height="18"
705
- rx="2"
706
- stroke="currentColor"
707
- stroke-width="2.5"
708
- fill="none"
709
- />
710
- <rect
711
- x="4"
712
- y="4"
713
- width="8.5"
714
- height="16"
715
- fill="currentColor"
716
- opacity="0.28"
717
- stroke="none"
718
- />
719
- <path
720
- d="M7 13l3 3 7-7"
721
- stroke="currentColor"
722
- stroke-width="2"
723
- stroke-linecap="round"
724
- stroke-linejoin="round"
725
- fill="none"
726
- />
727
- </svg>
728
- <span class="text-sm text-gray-800 dark:text-gray-100 select-none"
729
- >Invert</span
730
- >
731
- </button>
732
-
733
- <button
734
- type="button"
735
- 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"
736
- onclick={() => checkNone(column.key)}
737
- disabled={sortedValues.length === 0}
738
- aria-label="Uncheck all"
739
- title="Uncheck all"
740
- >
741
- <!-- Empty square icon (higher contrast stroke) -->
742
- <svg
743
- class="w-4 h-4 text-gray-800 dark:text-white"
744
- viewBox="0 0 24 24"
745
- fill="none"
746
- aria-hidden="true"
747
- >
748
- <rect
749
- x="3"
750
- y="3"
751
- width="18"
752
- height="18"
753
- rx="2"
754
- stroke="currentColor"
755
- stroke-width="2"
756
- fill="none"
757
- />
758
- </svg>
759
- <span class="text-sm text-gray-800 dark:text-gray-100 select-none">None</span>
760
- </button>
761
- </div>
762
-
763
- <div class="pr-1">
764
- <Badge color="blue" rounded title="Total options">{sortedValues.length}</Badge>
765
- </div>
766
- </div>
767
- </div>
768
-
769
- <div
770
- class="p-1 overflow-y-auto flex-1 max-h-48"
771
- use:registerList={{ key: column.key }}
772
- >
773
- {#if sortedValues.length > populateThreshold && !loadedOptions[column.key]}
774
- <div class="p-1 text-sm text-gray-700 dark:text-gray-200">
775
- Too many options ({sortedValues.length}) to render by default.
776
- <button
777
- 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"
778
- type="button"
779
- onclick={() => (loadedOptions = { ...loadedOptions, [column.key]: true })}
780
- >
781
- Load options
782
- </button>
783
- </div>
784
- {:else if sortedValues.length > virtualThreshold}
785
- {@const v = getVirtualSlice(column, sortedValues)}
786
-
787
- <div style="height:{v.totalHeight}px; position:relative;">
788
- <div style="position:absolute; top:{v.top}px; left:0; right:0;">
789
- {#each v.slice as value, idx (idx)}
790
- {@const isSelected = selections[column.key]?.includes(value)}
791
- {@const displayValue =
792
- value === null || value === undefined ? '(empty)' : String(value)}
793
-
794
- <label
795
- 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"
796
- style="height:{virtualItemHeight}px; box-sizing:border-box;"
797
- >
798
- <input
799
- type="checkbox"
800
- checked={isSelected}
801
- onchange={() => toggleSelection(column.key, value)}
802
- class="w-4 h-4 shrink-0 cursor-pointer accent-blue-500"
803
- />
804
- <span
805
- class="flex-1 text-sm text-gray-700 dark:text-gray-300 select-none min-w-0 overflow-hidden text-ellipsis"
806
- >{displayValue}</span
807
- >
808
- {#if showCounts && column.counts && column.counts[value] !== undefined}
809
- <span class="text-xs text-gray-500 dark:text-gray-400 ml-auto shrink-0"
810
- >({column.counts[value]})</span
811
- >
812
- {/if}
813
- </label>
814
- {/each}
815
- </div>
816
- </div>
817
- {:else if sortedValues.length > 0}
818
- {#each sortedValues as value, idx (idx)}
819
- {@const isSelected = selections[column.key]?.includes(value)}
820
- {@const displayValue =
821
- value === null || value === undefined ? '(empty)' : String(value)}
822
-
823
- <label
824
- 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"
825
- >
826
- <input
827
- type="checkbox"
828
- checked={isSelected}
829
- onchange={() => toggleSelection(column.key, value)}
830
- class="w-4 h-4 shrink-0 cursor-pointer accent-blue-500"
831
- />
832
- <span
833
- class="flex-1 text-sm text-gray-700 dark:text-gray-300 select-none min-w-0 overflow-hidden text-ellipsis"
834
- >{displayValue}</span
835
- >
836
- {#if showCounts && column.counts && column.counts[value] !== undefined}
837
- <span class="text-xs text-gray-500 dark:text-gray-400 ml-auto shrink-0"
838
- >({column.counts[value]})</span
839
- >
840
- {/if}
841
- </label>
842
- {/each}
843
- {:else}
844
- <div class="p-4 text-center text-sm text-gray-400 dark:text-gray-500">
845
- No values available
846
- </div>
847
- {/if}
848
- </div>
158
+ <FilterValueList
159
+ {column}
160
+ selections={sel || []}
161
+ {showCounts}
162
+ {virtualThreshold}
163
+ {virtualItemHeight}
164
+ {virtualOverscan}
165
+ {populateThreshold}
166
+ ontoggle={(v) => fs.toggleSelection(column.key, v)}
167
+ oncheckall={(vs) => fs.checkAll(column.key, vs)}
168
+ oninvert={(vs) => fs.invertSelection(column.key, vs)}
169
+ onchecknone={() => fs.checkNone(column.key)}
170
+ onsortchange={(i) => handleSortChange(column.key, i)}
171
+ />
849
172
  {/if}
850
173
  </div>
851
174
  {/if}
@@ -855,27 +178,20 @@
855
178
  </div>
856
179
 
857
180
  <style>
858
- /* Grid layout classes */
859
181
  .grid-horizontal {
860
182
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
861
183
  }
862
-
863
184
  .grid-vertical {
864
185
  grid-template-columns: 1fr;
865
186
  }
866
-
867
- /* Dropdown menu positioning */
868
187
  .dropdown-menu {
869
188
  z-index: 9999;
870
189
  }
871
-
872
- /* Responsive adjustments */
873
190
  @media (max-width: 768px) {
874
191
  .grid-horizontal {
875
192
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
876
193
  }
877
194
  }
878
-
879
195
  @media (max-width: 640px) {
880
196
  .grid-horizontal {
881
197
  grid-template-columns: 1fr;