@zhangt58/svelte-vtable 0.1.3 → 0.1.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhangt58/svelte-vtable",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "A Svelte 5 library for virtualized data tables with sorting, selection, and pagination controls.",
5
5
  "type": "module",
6
6
  "svelte": "./src/lib/index.js",
@@ -35,6 +35,18 @@
35
35
  // If true, render dropdowns inline (in-flow) so opening them expands the parent container.
36
36
  // If false, render as absolutely-positioned overlays (old behavior).
37
37
  dropdownInline = true,
38
+ // Relative-range quick-set presets shown in the datetime range picker.
39
+ // Each entry: { label: string, value: number, unit: 'hour'|'day'|'week'|'month'|'year' }
40
+ // Presets with unit 'hour' are only shown for 'datetimerange' columns.
41
+ relativeRangePresets = /** @type {Array<{label:string,value:number,unit:string}>} */ ([
42
+ { label: '1h', value: 1, unit: 'hour' },
43
+ { label: '6h', value: 6, unit: 'hour' },
44
+ { label: '12h', value: 12, unit: 'hour' },
45
+ { label: '1d', value: 1, unit: 'day' },
46
+ { label: '7d', value: 7, unit: 'day' },
47
+ { label: '30d', value: 30, unit: 'day' },
48
+ { label: '1y', value: 1, unit: 'year' },
49
+ ]),
38
50
  } = $props();
39
51
 
40
52
  // Internal state for selected options per column
@@ -391,6 +403,93 @@
391
403
  scheduleEmit(columnKey, updated);
392
404
  }
393
405
 
406
+ // --- Date-range slider helpers ---
407
+
408
+ // Parse a date-filter string (e.g. "2024-01-15" or "2024-01-15T08:30") to a ms timestamp.
409
+ // Uses the same rule as filterUtils.matchesDateRange: a bare YYYY-MM-DD string is treated as
410
+ // local midnight (appended with "T00:00:00") so slider thumb positions stay consistent with
411
+ // how records are matched.
412
+ function parseFilterDate(str) {
413
+ if (!str) return NaN;
414
+ return /^\d{4}-\d{2}-\d{2}$/.test(str)
415
+ ? new Date(str + 'T00:00:00').getTime()
416
+ : new Date(str).getTime();
417
+ }
418
+
419
+ // Format a timestamp back to the value expected by <input type="date"> or
420
+ // <input type="datetime-local">.
421
+ function formatAsInputValue(ms, inputType) {
422
+ const d = new Date(ms);
423
+ const pad = (n) => String(n).padStart(2, '0');
424
+ const dateStr = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
425
+ if (inputType === 'datetime-local') {
426
+ return `${dateStr}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
427
+ }
428
+ return dateStr;
429
+ }
430
+
431
+ // Handle the "from" slider thumb moving.
432
+ function handleFromSlider(columnKey, pct, minMs, maxMs, inputType) {
433
+ const current = selections[columnKey] || {};
434
+ const toMs = parseFilterDate(current.to);
435
+ let newFromMs = minMs + (pct / 100) * (maxMs - minMs);
436
+ // Clamp: from must not exceed to
437
+ if (!isNaN(toMs) && newFromMs > toMs) newFromMs = toMs;
438
+ const newFrom = formatAsInputValue(newFromMs, inputType);
439
+ const updated = { ...current, from: newFrom };
440
+ selections = { ...selections, [columnKey]: updated };
441
+ scheduleEmit(columnKey, updated);
442
+ }
443
+
444
+ // Handle the "to" slider thumb moving.
445
+ function handleToSlider(columnKey, pct, minMs, maxMs, inputType) {
446
+ const current = selections[columnKey] || {};
447
+ const fromMs = parseFilterDate(current.from);
448
+ let newToMs = minMs + (pct / 100) * (maxMs - minMs);
449
+ // Clamp: to must not be less than from
450
+ if (!isNaN(fromMs) && newToMs < fromMs) newToMs = fromMs;
451
+ const newTo = formatAsInputValue(newToMs, inputType);
452
+ const updated = { ...current, to: newTo };
453
+ selections = { ...selections, [columnKey]: updated };
454
+ scheduleEmit(columnKey, updated);
455
+ }
456
+
457
+ // Set the date range from a relative preset (e.g. "last 7 days" → from=now-7d, to=now).
458
+ function setRelativeRange(columnKey, value, unit) {
459
+ const now = new Date();
460
+ const from = new Date(now);
461
+ switch (unit) {
462
+ case 'hour':
463
+ from.setHours(from.getHours() - value);
464
+ break;
465
+ case 'day':
466
+ from.setDate(from.getDate() - value);
467
+ break;
468
+ case 'week':
469
+ from.setDate(from.getDate() - value * 7);
470
+ break;
471
+ case 'month':
472
+ from.setMonth(from.getMonth() - value);
473
+ break;
474
+ case 'year':
475
+ from.setFullYear(from.getFullYear() - value);
476
+ break;
477
+ }
478
+ const col = columnFilters.find((c) => c.key === columnKey);
479
+ const inputType = col?.type === 'datetimerange' ? 'datetime-local' : 'date';
480
+ const updated = {
481
+ from: formatAsInputValue(from.getTime(), inputType),
482
+ to: formatAsInputValue(now.getTime(), inputType),
483
+ };
484
+ selections = { ...selections, [columnKey]: updated };
485
+ scheduleEmit(columnKey, updated);
486
+ }
487
+
488
+ // Return the relative presets applicable to a given column type.
489
+ function getApplicablePresets(colType) {
490
+ return relativeRangePresets.filter((p) => p.unit !== 'hour' || colType === 'datetimerange');
491
+ }
492
+
394
493
  // Show all dropdowns
395
494
  function showAllDropdowns() {
396
495
  const allOpen = {};
@@ -496,9 +595,13 @@
496
595
 
497
596
  {#if isOpen}
498
597
  <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`}
598
+ class={[
599
+ dropdownInline ? '' : 'absolute top-full left-0 right-0',
600
+ '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',
601
+ isDateRangeColumn(column) ? 'overflow-y-auto' : 'max-h-64',
602
+ ]
603
+ .filter(Boolean)
604
+ .join(' ')}
502
605
  tabindex="-1"
503
606
  data-column={column.key}
504
607
  >
@@ -506,7 +609,22 @@
506
609
  <!-- Date / datetime range picker UI -->
507
610
  {@const inputType = column.type === 'datetimerange' ? 'datetime-local' : 'date'}
508
611
  {@const dateRange = selections[column.key] || {}}
612
+ {@const minMs = parseFilterDate(column.minValue)}
613
+ {@const maxMs = parseFilterDate(column.maxValue)}
614
+ {@const totalMs = maxMs - minMs}
615
+ {@const fromMs = parseFilterDate(dateRange.from)}
616
+ {@const toMs = parseFilterDate(dateRange.to)}
617
+ {@const fromPct =
618
+ totalMs > 0 && !isNaN(fromMs)
619
+ ? Math.max(0, Math.min(100, ((fromMs - minMs) / totalMs) * 100))
620
+ : 0}
621
+ {@const toPct =
622
+ totalMs > 0 && !isNaN(toMs)
623
+ ? Math.max(0, Math.min(100, ((toMs - minMs) / totalMs) * 100))
624
+ : 100}
625
+ {@const applicablePresets = getApplicablePresets(column.type)}
509
626
  <div class="p-3 flex flex-col gap-2">
627
+ <!-- From input + Earliest shortcut -->
510
628
  <div class="flex items-center gap-2">
511
629
  <label
512
630
  class="text-xs font-medium text-gray-500 dark:text-gray-400 w-8 shrink-0"
@@ -522,7 +640,42 @@
522
640
  oninput={(e) =>
523
641
  handleDateRangeChange(column.key, 'from', e.currentTarget.value)}
524
642
  />
643
+ {#if column.minValue}
644
+ <button
645
+ type="button"
646
+ class="shrink-0 px-2 py-0.5 text-xs rounded border border-indigo-400 text-indigo-700 dark:text-indigo-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors flex items-center"
647
+ title="Set From to the earliest record ({column.minValue})"
648
+ aria-label="Set From to the earliest record"
649
+ onclick={() => handleDateRangeChange(column.key, 'from', column.minValue)}
650
+ >
651
+ <!-- Double-chevron-left icon (Earliest) -->
652
+ <svg
653
+ class="w-4 h-4 text-indigo-700 dark:text-indigo-300"
654
+ viewBox="0 0 24 24"
655
+ fill="none"
656
+ aria-hidden="true"
657
+ >
658
+ <path
659
+ d="M11.5 7.5L7 12l4.5 4.5"
660
+ stroke="currentColor"
661
+ stroke-width="2"
662
+ stroke-linecap="round"
663
+ stroke-linejoin="round"
664
+ fill="none"
665
+ />
666
+ <path
667
+ d="M17.5 7.5L13 12l4.5 4.5"
668
+ stroke="currentColor"
669
+ stroke-width="2"
670
+ stroke-linecap="round"
671
+ stroke-linejoin="round"
672
+ fill="none"
673
+ />
674
+ </svg>
675
+ </button>
676
+ {/if}
525
677
  </div>
678
+ <!-- To input + Latest shortcut -->
526
679
  <div class="flex items-center gap-2">
527
680
  <label
528
681
  class="text-xs font-medium text-gray-500 dark:text-gray-400 w-8 shrink-0"
@@ -537,11 +690,115 @@
537
690
  value={dateRange.to || ''}
538
691
  oninput={(e) => handleDateRangeChange(column.key, 'to', e.currentTarget.value)}
539
692
  />
693
+ {#if column.maxValue}
694
+ <button
695
+ type="button"
696
+ class="shrink-0 px-2 py-0.5 text-xs rounded border border-indigo-400 text-indigo-700 dark:text-indigo-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors flex items-center"
697
+ title="Set To to the latest record ({column.maxValue})"
698
+ aria-label="Set To to the latest record"
699
+ onclick={() => handleDateRangeChange(column.key, 'to', column.maxValue)}
700
+ >
701
+ <!-- Double-chevron-right icon (Latest) -->
702
+ <svg
703
+ class="w-4 h-4 text-indigo-700 dark:text-indigo-300"
704
+ viewBox="0 0 24 24"
705
+ fill="none"
706
+ aria-hidden="true"
707
+ >
708
+ <path
709
+ d="M12.5 7.5L17 12l-4.5 4.5"
710
+ stroke="currentColor"
711
+ stroke-width="2"
712
+ stroke-linecap="round"
713
+ stroke-linejoin="round"
714
+ fill="none"
715
+ />
716
+ <path
717
+ d="M6.5 7.5L11 12l-4.5 4.5"
718
+ stroke="currentColor"
719
+ stroke-width="2"
720
+ stroke-linecap="round"
721
+ stroke-linejoin="round"
722
+ fill="none"
723
+ />
724
+ </svg>
725
+ </button>
726
+ {/if}
540
727
  </div>
728
+
729
+ <!-- Dual-range slider (only when column provides min/max) -->
730
+ {#if column.minValue && column.maxValue && totalMs > 0}
731
+ <div class="dual-range-wrapper" aria-label="Date range slider">
732
+ <!-- Background track -->
733
+ <div class="dual-range-track-bg"></div>
734
+ <!-- Active-range highlight -->
735
+ <div
736
+ class="dual-range-track-fill"
737
+ style="left:{fromPct}%; right:{100 - toPct}%"
738
+ ></div>
739
+ <!-- From thumb -->
740
+ <input
741
+ type="range"
742
+ class="dual-range-input"
743
+ min="0"
744
+ max="100"
745
+ step="0.02"
746
+ value={fromPct}
747
+ style="z-index:{fromPct >= toPct - 2 ? 4 : 3}"
748
+ oninput={(e) =>
749
+ handleFromSlider(
750
+ column.key,
751
+ parseFloat(e.currentTarget.value),
752
+ minMs,
753
+ maxMs,
754
+ inputType,
755
+ )}
756
+ aria-label="Range start"
757
+ />
758
+ <!-- To thumb -->
759
+ <input
760
+ type="range"
761
+ class="dual-range-input"
762
+ min="0"
763
+ max="100"
764
+ step="0.02"
765
+ value={toPct}
766
+ style="z-index:{fromPct >= toPct - 2 ? 3 : 4}"
767
+ oninput={(e) =>
768
+ handleToSlider(
769
+ column.key,
770
+ parseFloat(e.currentTarget.value),
771
+ minMs,
772
+ maxMs,
773
+ inputType,
774
+ )}
775
+ aria-label="Range end"
776
+ />
777
+ </div>
778
+ {/if}
779
+
780
+ <!-- Relative-range quick buttons -->
781
+ {#if applicablePresets.length > 0}
782
+ <div
783
+ class="flex flex-wrap gap-1 pt-1 border-t border-gray-100 dark:border-gray-600"
784
+ >
785
+ {#each applicablePresets as preset (preset.label)}
786
+ <button
787
+ type="button"
788
+ class="px-2 py-0.5 text-xs rounded border border-blue-400 text-blue-700 dark:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors"
789
+ title="Last {preset.value} {preset.unit}{preset.value !== 1 ? 's' : ''}"
790
+ onclick={() => setRelativeRange(column.key, preset.value, preset.unit)}
791
+ >
792
+ Last {preset.label}
793
+ </button>
794
+ {/each}
795
+ </div>
796
+ {/if}
797
+
541
798
  {#if dateRange.from || dateRange.to}
542
799
  <button
543
800
  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"
801
+ class="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
802
  onclick={() => clearColumn(column.key)}
546
803
  >
547
804
  Clear range
@@ -881,4 +1138,88 @@
881
1138
  grid-template-columns: 1fr;
882
1139
  }
883
1140
  }
1141
+
1142
+ /* ── Dual-range slider ─────────────────────────────────────────────────── */
1143
+ .dual-range-wrapper {
1144
+ position: relative;
1145
+ height: 20px;
1146
+ display: flex;
1147
+ align-items: center;
1148
+ margin: 4px 0;
1149
+ }
1150
+
1151
+ .dual-range-track-bg {
1152
+ position: absolute;
1153
+ left: 0;
1154
+ right: 0;
1155
+ height: 4px;
1156
+ border-radius: 2px;
1157
+ background: #d1d5db; /* gray-300 */
1158
+ }
1159
+
1160
+ :global(.dark) .dual-range-track-bg {
1161
+ background: #4b5563; /* gray-600 */
1162
+ }
1163
+
1164
+ .dual-range-track-fill {
1165
+ position: absolute;
1166
+ height: 4px;
1167
+ border-radius: 2px;
1168
+ background: #60a5fa; /* blue-400 */
1169
+ pointer-events: none;
1170
+ }
1171
+
1172
+ :global(.dark) .dual-range-track-fill {
1173
+ background: #3b82f6; /* blue-500 */
1174
+ }
1175
+
1176
+ .dual-range-input {
1177
+ position: absolute;
1178
+ left: 0;
1179
+ width: 100%;
1180
+ height: 4px;
1181
+ background: none;
1182
+ pointer-events: none;
1183
+ appearance: none;
1184
+ -webkit-appearance: none;
1185
+ outline: none;
1186
+ margin: 0;
1187
+ padding: 0;
1188
+ }
1189
+
1190
+ /* Webkit thumb */
1191
+ .dual-range-input::-webkit-slider-thumb {
1192
+ -webkit-appearance: none;
1193
+ appearance: none;
1194
+ pointer-events: all;
1195
+ width: 16px;
1196
+ height: 16px;
1197
+ border-radius: 50%;
1198
+ background: #3b82f6; /* blue-500 */
1199
+ cursor: pointer;
1200
+ border: 2px solid #ffffff;
1201
+ box-shadow: 0 0 0 1px #3b82f6;
1202
+ transition: background 0.15s;
1203
+ }
1204
+
1205
+ .dual-range-input::-webkit-slider-thumb:hover {
1206
+ background: #2563eb; /* blue-600 */
1207
+ }
1208
+
1209
+ /* Firefox thumb */
1210
+ .dual-range-input::-moz-range-thumb {
1211
+ pointer-events: all;
1212
+ width: 14px;
1213
+ height: 14px;
1214
+ border-radius: 50%;
1215
+ background: #3b82f6;
1216
+ cursor: pointer;
1217
+ border: 2px solid #ffffff;
1218
+ box-shadow: 0 0 0 1px #3b82f6;
1219
+ transition: background 0.15s;
1220
+ }
1221
+
1222
+ .dual-range-input::-moz-range-thumb:hover {
1223
+ background: #2563eb;
1224
+ }
884
1225
  </style>
@@ -35,12 +35,43 @@ export function buildColumnFilters(data, columns) {
35
35
  return columns.map((col) => {
36
36
  const isDateRange = col.type === 'daterange' || col.type === 'datetimerange';
37
37
  if (isDateRange) {
38
+ // Scan data to find the min/max timestamps for this column so the UI can
39
+ // offer a dual-range slider and Earliest/Latest shortcut buttons.
40
+ let minMs = Infinity;
41
+ let maxMs = -Infinity;
42
+ for (const item of data) {
43
+ const v = item[col.key];
44
+ if (v === null || v === undefined || v === '') continue;
45
+ const str = String(v);
46
+ const d = /^\d{4}-\d{2}-\d{2}$/.test(str) ? new Date(str + 'T00:00:00') : new Date(str);
47
+ if (!isNaN(d.getTime())) {
48
+ if (d.getTime() < minMs) minMs = d.getTime();
49
+ if (d.getTime() > maxMs) maxMs = d.getTime();
50
+ }
51
+ }
52
+
53
+ const hasRange = isFinite(minMs) && isFinite(maxMs);
54
+
55
+ // Format as the string expected by <input type="date"> or <input type="datetime-local">
56
+ const pad = (n) => String(n).padStart(2, '0');
57
+ const fmtDate = (ms) => {
58
+ const d = new Date(ms);
59
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
60
+ };
61
+ const fmtDatetime = (ms) => {
62
+ const d = new Date(ms);
63
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
64
+ };
65
+ const fmt = col.type === 'datetimerange' ? fmtDatetime : fmtDate;
66
+
38
67
  return {
39
68
  key: col.key,
40
69
  label: col.label || col.key,
41
70
  type: col.type,
42
71
  uniqueValues: [],
43
72
  counts: {},
73
+ minValue: hasRange ? fmt(minMs) : null,
74
+ maxValue: hasRange ? fmt(maxMs) : null,
44
75
  };
45
76
  }
46
77
  const { uniqueValues, counts } = getUniqueValuesWithCounts(data, col.key);