@zhangt58/svelte-vtable 0.1.1 → 0.1.3

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,6 +1,6 @@
1
1
  <script>
2
2
  import { Modal } from 'flowbite-svelte';
3
- import { CloseOutline } from "flowbite-svelte-icons";
3
+ import { CloseOutline } from 'flowbite-svelte-icons';
4
4
  import DataTableFilters from './DataTableFilters.svelte';
5
5
 
6
6
  // Props — make `open` bindable so parent can use `bind:open`
@@ -14,27 +14,31 @@
14
14
  filterChange = (..._args) => {},
15
15
  direction = 'horizontal',
16
16
  showCounts = true,
17
- className = ''
17
+ className = '',
18
18
  } = $props();
19
19
  </script>
20
20
 
21
- <Modal bind:open={open} size="lg" dismissable={false}>
21
+ <Modal bind:open size="lg" dismissable={false}>
22
22
  <div class="flex items-center justify-between mb-2">
23
- <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Filters</h3>
24
- <button
25
- aria-label="Close"
26
- class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white"
27
- onclick={() => open = false}
28
- >
29
- <CloseOutline class="shrink-0 h-6 w-6" />
30
- </button>
23
+ <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Filters</h3>
24
+ <button
25
+ aria-label="Close"
26
+ class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white"
27
+ onclick={() => (open = false)}
28
+ >
29
+ <CloseOutline class="shrink-0 h-6 w-6" />
30
+ </button>
31
31
  </div>
32
32
 
33
33
  <DataTableFilters
34
- columnFilters={columnFilters}
35
- activeFilters={activeFilters}
36
- filterChange={(payload) => { try { return filterChange(payload); } catch (e) {} }}
37
- direction={direction}
38
- showCounts={showCounts}
34
+ {columnFilters}
35
+ {activeFilters}
36
+ filterChange={(payload) => {
37
+ try {
38
+ return filterChange(payload);
39
+ } catch (e) {}
40
+ }}
41
+ {direction}
42
+ {showCounts}
39
43
  />
40
- </Modal>
44
+ </Modal>
@@ -12,7 +12,8 @@
12
12
  border-collapse: collapse;
13
13
  box-sizing: border-box;
14
14
  font-size: 0.875rem; /* 14px - smaller, more compact */
15
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
15
+ font-family:
16
+ -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
16
17
  line-height: 1.4;
17
18
  border: none;
18
19
  }
@@ -71,9 +72,11 @@
71
72
 
72
73
  .dark .datatable-table tbody tr.selected-row {
73
74
  /* brighter, higher-contrast selection in dark mode */
74
- background-color: rgba(14,165,233,0.22) !important; /* stronger visible blue */
75
- box-shadow: inset 6px 0 0 0 rgba(56,189,248,0.85); /* stronger left accent */
76
- transition: background-color 0.12s ease-in-out, box-shadow 0.12s ease-in-out;
75
+ background-color: rgba(14, 165, 233, 0.22) !important; /* stronger visible blue */
76
+ box-shadow: inset 6px 0 0 0 rgba(56, 189, 248, 0.85); /* stronger left accent */
77
+ transition:
78
+ background-color 0.12s ease-in-out,
79
+ box-shadow 0.12s ease-in-out;
77
80
  }
78
81
 
79
82
  /* Also apply to cells to defeat any cell-level background from striping and ensure readable text */
@@ -82,9 +85,9 @@
82
85
  }
83
86
 
84
87
  .dark .datatable-table tbody tr.selected-row td {
85
- background-color: rgba(14,165,233,0.22) !important;
88
+ background-color: rgba(14, 165, 233, 0.22) !important;
86
89
  color: #f0fbff !important; /* ensure high-contrast, very light text */
87
- border-bottom-color: rgba(255,255,255,0.06);
90
+ border-bottom-color: rgba(255, 255, 255, 0.06);
88
91
  }
89
92
 
90
93
  /* Body cell defaults - only bottom border */
@@ -219,9 +222,9 @@
219
222
 
220
223
  /* Force the active/current page to use the green tokens (override flowbite's primary/orange).
221
224
  Intentionally specific to reliably win over third-party rules. */
222
- [data-pagination-id] ul li [aria-current="page"] {
225
+ [data-pagination-id] ul li [aria-current='page'] {
223
226
  background-color: #dcfce7 !important; /* bg-green-100 */
224
- color: #16a34a !important; /* text-green-600 */
227
+ color: #16a34a !important; /* text-green-600 */
225
228
  border-color: transparent !important;
226
229
  }
227
230
 
@@ -252,7 +255,7 @@
252
255
  }
253
256
 
254
257
  /* Ellipsis styling: make clickable and visually lighter (JS sets data-ellipsis/data-jump) */
255
- [data-pagination-id] ul li [data-ellipsis="true"] {
258
+ [data-pagination-id] ul li [data-ellipsis='true'] {
256
259
  cursor: pointer;
257
260
  background: transparent !important;
258
261
  color: inherit;
@@ -11,7 +11,7 @@
11
11
  export function getUniqueValuesWithCounts(data, key) {
12
12
  const countMap = {};
13
13
 
14
- data.forEach(item => {
14
+ data.forEach((item) => {
15
15
  const value = item[key];
16
16
  // Handle null/undefined
17
17
  const normalizedValue = value ?? '(empty)';
@@ -20,32 +20,87 @@ export function getUniqueValuesWithCounts(data, key) {
20
20
 
21
21
  return {
22
22
  uniqueValues: Object.keys(countMap),
23
- counts: countMap
23
+ counts: countMap,
24
24
  };
25
25
  }
26
26
 
27
27
  /**
28
28
  * Build column filters configuration from data and column definitions
29
29
  * @param {Array} data - Array of data objects
30
- * @param {Array} columns - Array of column definitions {key, label}
30
+ * @param {Array} columns - Array of column definitions {key, label, type?}
31
+ * Supported types: 'value' (default), 'daterange', 'datetimerange'
31
32
  * @returns {Array} Column filters configuration for DataTableFilters
32
33
  */
33
34
  export function buildColumnFilters(data, columns) {
34
- return columns.map(col => {
35
+ return columns.map((col) => {
36
+ const isDateRange = col.type === 'daterange' || col.type === 'datetimerange';
37
+ if (isDateRange) {
38
+ return {
39
+ key: col.key,
40
+ label: col.label || col.key,
41
+ type: col.type,
42
+ uniqueValues: [],
43
+ counts: {},
44
+ };
45
+ }
35
46
  const { uniqueValues, counts } = getUniqueValuesWithCounts(data, col.key);
36
47
  return {
37
48
  key: col.key,
38
49
  label: col.label || col.key,
50
+ type: col.type || 'value',
39
51
  uniqueValues,
40
- counts
52
+ counts,
41
53
  };
42
54
  });
43
55
  }
44
56
 
45
57
  /**
46
- * Apply filters to data with OR logic within columns and AND logic across columns
58
+ * Check whether a value falls within a date/datetime range.
59
+ * Both `from` and `to` are optional; omitting one leaves that end open.
60
+ * Date-only strings (YYYY-MM-DD) are parsed as **local** midnight (i.e. they
61
+ * are treated as `<date>T00:00:00` in the local timezone, not UTC). A date-only
62
+ * `to` value is inclusive through the end of that calendar day (23:59:59.999
63
+ * local time).
64
+ * @param {any} value - The item's date value (string, Date, or number)
65
+ * @param {string|null|undefined} from - Range start (ISO date or datetime-local string)
66
+ * @param {string|null|undefined} to - Range end (ISO date or datetime-local string)
67
+ * @returns {boolean}
68
+ */
69
+ export function matchesDateRange(value, from, to) {
70
+ if (value === null || value === undefined || value === '') return false;
71
+
72
+ // Parse the item date; treat date-only strings as local midnight
73
+ let itemDate;
74
+ if (value instanceof Date) {
75
+ itemDate = value;
76
+ } else {
77
+ const str = String(value);
78
+ itemDate = /^\d{4}-\d{2}-\d{2}$/.test(str) ? new Date(str + 'T00:00:00') : new Date(str);
79
+ }
80
+ if (isNaN(itemDate.getTime())) return false;
81
+
82
+ if (from) {
83
+ const fromDate = /^\d{4}-\d{2}-\d{2}$/.test(from)
84
+ ? new Date(from + 'T00:00:00')
85
+ : new Date(from);
86
+ if (!isNaN(fromDate.getTime()) && itemDate < fromDate) return false;
87
+ }
88
+
89
+ if (to) {
90
+ // Extend date-only "to" to the end of that day so it is fully inclusive
91
+ const toDate = /^\d{4}-\d{2}-\d{2}$/.test(to) ? new Date(to + 'T23:59:59.999') : new Date(to);
92
+ if (!isNaN(toDate.getTime()) && itemDate > toDate) return false;
93
+ }
94
+
95
+ return true;
96
+ }
97
+
98
+ /**
99
+ * Apply filters to data with OR logic within columns and AND logic across columns.
100
+ * Supports both value-selection filters (array) and date/datetime range filters
101
+ * (object with optional `from` and `to` string fields).
47
102
  * @param {Array} data - Array of data objects to filter
48
- * @param {Object} activeFilters - Active filters object { columnKey: [selectedValues] }
103
+ * @param {Object} activeFilters - Active filters: { columnKey: string[] | {from?, to?} }
49
104
  * @returns {Array} Filtered data array
50
105
  */
51
106
  export function applyFilters(data, activeFilters) {
@@ -53,19 +108,22 @@ export function applyFilters(data, activeFilters) {
53
108
  return data;
54
109
  }
55
110
 
56
- return data.filter(item => {
111
+ return data.filter((item) => {
57
112
  // Check each column filter (AND logic across columns)
58
- for (const [columnKey, selectedValues] of Object.entries(activeFilters)) {
59
- // Skip if no values selected for this column
60
- if (!selectedValues || selectedValues.length === 0) continue;
61
-
62
- // Get the item's value for this column
63
- const itemValue = item[columnKey];
64
- const normalizedItemValue = itemValue ?? '(empty)';
65
-
66
- // Check if item value matches any selected value (OR logic within column)
67
- if (!selectedValues.includes(normalizedItemValue)) {
68
- return false; // Item doesn't match this column filter
113
+ for (const [columnKey, filterValue] of Object.entries(activeFilters)) {
114
+ if (!filterValue) continue;
115
+
116
+ if (Array.isArray(filterValue)) {
117
+ // Value-based filter (OR logic within column)
118
+ if (filterValue.length === 0) continue;
119
+ const itemValue = item[columnKey];
120
+ const normalizedItemValue = itemValue ?? '(empty)';
121
+ if (!filterValue.includes(normalizedItemValue)) return false;
122
+ } else if (typeof filterValue === 'object') {
123
+ // Date / datetime range filter
124
+ const { from, to } = filterValue;
125
+ if (!from && !to) continue;
126
+ if (!matchesDateRange(item[columnKey], from, to)) return false;
69
127
  }
70
128
  }
71
129
  return true; // Item matches all column filters
@@ -74,37 +132,48 @@ export function applyFilters(data, activeFilters) {
74
132
 
75
133
  /**
76
134
  * Check if any filters are currently active
77
- * @param {Object} activeFilters - Active filters object { columnKey: [selectedValues] }
135
+ * @param {Object} activeFilters - Active filters object
78
136
  * @returns {boolean} True if any filters are active
79
137
  */
80
138
  export function hasActiveFilters(activeFilters) {
81
- return Object.values(activeFilters).some(arr => arr && arr.length > 0);
139
+ return Object.values(activeFilters).some((val) => {
140
+ if (Array.isArray(val)) return val.length > 0;
141
+ if (val && typeof val === 'object') return !!(val.from || val.to);
142
+ return false;
143
+ });
82
144
  }
83
145
 
84
146
  /**
85
- * Count total number of active filter selections
86
- * @param {Object} activeFilters - Active filters object { columnKey: [selectedValues] }
87
- * @returns {number} Total count of selected filter values
147
+ * Count total number of active filter selections.
148
+ * Each active date range counts as 1.
149
+ * @param {Object} activeFilters - Active filters object
150
+ * @returns {number} Total count of active filter values/ranges
88
151
  */
89
152
  export function countActiveFilters(activeFilters) {
90
- return Object.values(activeFilters).reduce((sum, arr) => sum + (arr?.length || 0), 0);
153
+ return Object.values(activeFilters).reduce((sum, val) => {
154
+ if (Array.isArray(val)) return sum + (val?.length || 0);
155
+ if (val && typeof val === 'object' && (val.from || val.to)) return sum + 1;
156
+ return sum;
157
+ }, 0);
91
158
  }
92
159
 
93
160
  /**
94
161
  * Clear all filters
95
162
  * @param {Array} columnFilters - Column filters configuration
96
- * @returns {Object} Empty filters object
163
+ * @returns {Object} Cleared filters object (arrays for value columns, empty objects for date ranges)
97
164
  */
98
165
  export function clearAllFilters(columnFilters) {
99
166
  const cleared = {};
100
- columnFilters.forEach(col => {
101
- cleared[col.key] = [];
167
+ columnFilters.forEach((col) => {
168
+ const isDateRange = col.type === 'daterange' || col.type === 'datetimerange';
169
+ cleared[col.key] = isDateRange ? {} : [];
102
170
  });
103
171
  return cleared;
104
172
  }
105
173
 
106
174
  /**
107
- * Export active filters as URL search params
175
+ * Export active filters as URL search params.
176
+ * Date range filters are serialised as `<key>_from` and `<key>_to` params.
108
177
  * @param {Object} activeFilters - Active filters object
109
178
  * @returns {URLSearchParams} URL search params object
110
179
  */
@@ -112,8 +181,11 @@ export function filtersToSearchParams(activeFilters) {
112
181
  const params = new URLSearchParams();
113
182
 
114
183
  for (const [key, values] of Object.entries(activeFilters)) {
115
- if (values && values.length > 0) {
184
+ if (Array.isArray(values) && values.length > 0) {
116
185
  params.set(key, values.join(','));
186
+ } else if (values && typeof values === 'object' && !Array.isArray(values)) {
187
+ if (values.from) params.set(`${key}_from`, values.from);
188
+ if (values.to) params.set(`${key}_to`, values.to);
117
189
  }
118
190
  }
119
191
 
@@ -127,19 +199,32 @@ export function filtersToSearchParams(activeFilters) {
127
199
  * @returns {Object} Active filters object
128
200
  */
129
201
  export function searchParamsToFilters(searchParams, columnFilters) {
130
- const params = typeof searchParams === 'string'
131
- ? new URLSearchParams(searchParams)
132
- : searchParams;
133
-
134
- const validKeys = new Set(columnFilters.map(c => c.key));
202
+ const params =
203
+ typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
204
+
205
+ const validKeys = new Set(columnFilters.map((c) => c.key));
206
+ const dateRangeKeys = new Set(
207
+ columnFilters
208
+ .filter((c) => c.type === 'daterange' || c.type === 'datetimerange')
209
+ .map((c) => c.key),
210
+ );
135
211
  const filters = {};
136
212
 
137
213
  for (const [key, value] of params.entries()) {
138
- if (validKeys.has(key) && value) {
139
- filters[key] = value.split(',').map(v => v.trim()).filter(Boolean);
214
+ if (key.endsWith('_from') || key.endsWith('_to')) {
215
+ const colKey = key.replace(/_from$|_to$/, '');
216
+ if (validKeys.has(colKey) && dateRangeKeys.has(colKey)) {
217
+ if (!filters[colKey]) filters[colKey] = {};
218
+ if (key.endsWith('_from')) filters[colKey].from = value;
219
+ else filters[colKey].to = value;
220
+ }
221
+ } else if (validKeys.has(key) && !dateRangeKeys.has(key) && value) {
222
+ filters[key] = value
223
+ .split(',')
224
+ .map((v) => v.trim())
225
+ .filter(Boolean);
140
226
  }
141
227
  }
142
228
 
143
229
  return filters;
144
230
  }
145
-
package/src/lib/index.js CHANGED
@@ -7,9 +7,10 @@ export {
7
7
  getUniqueValuesWithCounts,
8
8
  buildColumnFilters,
9
9
  applyFilters,
10
+ matchesDateRange,
10
11
  hasActiveFilters,
11
12
  countActiveFilters,
12
13
  clearAllFilters,
13
14
  filtersToSearchParams,
14
- searchParamsToFilters
15
+ searchParamsToFilters,
15
16
  } from './filterUtils.js';
@@ -12,7 +12,8 @@
12
12
  border-collapse: collapse;
13
13
  box-sizing: border-box;
14
14
  font-size: 0.875rem; /* 14px - smaller, more compact */
15
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
15
+ font-family:
16
+ -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
16
17
  line-height: 1.4;
17
18
  border: none;
18
19
  }
@@ -71,9 +72,11 @@
71
72
 
72
73
  :global(.dark) :global(.datatable-table tbody tr.selected-row) {
73
74
  /* brighter, higher-contrast selection in dark mode */
74
- background-color: rgba(14,165,233,0.22) !important; /* stronger visible blue */
75
- box-shadow: inset 6px 0 0 0 rgba(56,189,248,0.85); /* stronger left accent */
76
- transition: background-color 0.12s ease-in-out, box-shadow 0.12s ease-in-out;
75
+ background-color: rgba(14, 165, 233, 0.22) !important; /* stronger visible blue */
76
+ box-shadow: inset 6px 0 0 0 rgba(56, 189, 248, 0.85); /* stronger left accent */
77
+ transition:
78
+ background-color 0.12s ease-in-out,
79
+ box-shadow 0.12s ease-in-out;
77
80
  }
78
81
 
79
82
  /* Also apply to cells to defeat any cell-level background from striping and ensure readable text */
@@ -82,9 +85,9 @@
82
85
  }
83
86
 
84
87
  :global(.dark) :global(.datatable-table tbody tr.selected-row) td {
85
- background-color: rgba(14,165,233,0.22) !important;
88
+ background-color: rgba(14, 165, 233, 0.22) !important;
86
89
  color: #f0fbff !important; /* ensure high-contrast, very light text */
87
- border-bottom-color: rgba(255,255,255,0.06);
90
+ border-bottom-color: rgba(255, 255, 255, 0.06);
88
91
  }
89
92
 
90
93
  /* Body cell defaults - only bottom border */
@@ -219,9 +222,9 @@
219
222
 
220
223
  /* Force the active/current page to use the green tokens (override flowbite's primary/orange).
221
224
  Intentionally specific to reliably win over third-party rules. */
222
- :global([data-pagination-id] ul li [aria-current="page"]) {
225
+ :global([data-pagination-id] ul li [aria-current='page']) {
223
226
  background-color: #dcfce7 !important; /* bg-green-100 */
224
- color: #16a34a !important; /* text-green-600 */
227
+ color: #16a34a !important; /* text-green-600 */
225
228
  border-color: transparent !important;
226
229
  }
227
230
 
@@ -252,7 +255,7 @@
252
255
  }
253
256
 
254
257
  /* Ellipsis styling: make clickable and visually lighter (JS sets data-ellipsis/data-jump) */
255
- :global([data-pagination-id] ul li [data-ellipsis="true"]) {
258
+ :global([data-pagination-id] ul li [data-ellipsis='true']) {
256
259
  cursor: pointer;
257
260
  background: transparent !important;
258
261
  color: inherit;
@@ -267,4 +270,4 @@
267
270
  height: 1.25rem;
268
271
  width: 1.25rem;
269
272
  display: block;
270
- }
273
+ }