@zhangt58/svelte-vtable 0.1.2 → 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.
@@ -27,15 +27,58 @@ export function getUniqueValuesWithCounts(data, key) {
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
35
  return columns.map((col) => {
36
+ const isDateRange = col.type === 'daterange' || col.type === 'datetimerange';
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
+
67
+ return {
68
+ key: col.key,
69
+ label: col.label || col.key,
70
+ type: col.type,
71
+ uniqueValues: [],
72
+ counts: {},
73
+ minValue: hasRange ? fmt(minMs) : null,
74
+ maxValue: hasRange ? fmt(maxMs) : null,
75
+ };
76
+ }
35
77
  const { uniqueValues, counts } = getUniqueValuesWithCounts(data, col.key);
36
78
  return {
37
79
  key: col.key,
38
80
  label: col.label || col.key,
81
+ type: col.type || 'value',
39
82
  uniqueValues,
40
83
  counts,
41
84
  };
@@ -43,9 +86,52 @@ export function buildColumnFilters(data, columns) {
43
86
  }
44
87
 
45
88
  /**
46
- * Apply filters to data with OR logic within columns and AND logic across columns
89
+ * Check whether a value falls within a date/datetime range.
90
+ * Both `from` and `to` are optional; omitting one leaves that end open.
91
+ * Date-only strings (YYYY-MM-DD) are parsed as **local** midnight (i.e. they
92
+ * are treated as `<date>T00:00:00` in the local timezone, not UTC). A date-only
93
+ * `to` value is inclusive through the end of that calendar day (23:59:59.999
94
+ * local time).
95
+ * @param {any} value - The item's date value (string, Date, or number)
96
+ * @param {string|null|undefined} from - Range start (ISO date or datetime-local string)
97
+ * @param {string|null|undefined} to - Range end (ISO date or datetime-local string)
98
+ * @returns {boolean}
99
+ */
100
+ export function matchesDateRange(value, from, to) {
101
+ if (value === null || value === undefined || value === '') return false;
102
+
103
+ // Parse the item date; treat date-only strings as local midnight
104
+ let itemDate;
105
+ if (value instanceof Date) {
106
+ itemDate = value;
107
+ } else {
108
+ const str = String(value);
109
+ itemDate = /^\d{4}-\d{2}-\d{2}$/.test(str) ? new Date(str + 'T00:00:00') : new Date(str);
110
+ }
111
+ if (isNaN(itemDate.getTime())) return false;
112
+
113
+ if (from) {
114
+ const fromDate = /^\d{4}-\d{2}-\d{2}$/.test(from)
115
+ ? new Date(from + 'T00:00:00')
116
+ : new Date(from);
117
+ if (!isNaN(fromDate.getTime()) && itemDate < fromDate) return false;
118
+ }
119
+
120
+ if (to) {
121
+ // Extend date-only "to" to the end of that day so it is fully inclusive
122
+ const toDate = /^\d{4}-\d{2}-\d{2}$/.test(to) ? new Date(to + 'T23:59:59.999') : new Date(to);
123
+ if (!isNaN(toDate.getTime()) && itemDate > toDate) return false;
124
+ }
125
+
126
+ return true;
127
+ }
128
+
129
+ /**
130
+ * Apply filters to data with OR logic within columns and AND logic across columns.
131
+ * Supports both value-selection filters (array) and date/datetime range filters
132
+ * (object with optional `from` and `to` string fields).
47
133
  * @param {Array} data - Array of data objects to filter
48
- * @param {Object} activeFilters - Active filters object { columnKey: [selectedValues] }
134
+ * @param {Object} activeFilters - Active filters: { columnKey: string[] | {from?, to?} }
49
135
  * @returns {Array} Filtered data array
50
136
  */
51
137
  export function applyFilters(data, activeFilters) {
@@ -55,17 +141,20 @@ export function applyFilters(data, activeFilters) {
55
141
 
56
142
  return data.filter((item) => {
57
143
  // 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;
144
+ for (const [columnKey, filterValue] of Object.entries(activeFilters)) {
145
+ if (!filterValue) continue;
61
146
 
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
147
+ if (Array.isArray(filterValue)) {
148
+ // Value-based filter (OR logic within column)
149
+ if (filterValue.length === 0) continue;
150
+ const itemValue = item[columnKey];
151
+ const normalizedItemValue = itemValue ?? '(empty)';
152
+ if (!filterValue.includes(normalizedItemValue)) return false;
153
+ } else if (typeof filterValue === 'object') {
154
+ // Date / datetime range filter
155
+ const { from, to } = filterValue;
156
+ if (!from && !to) continue;
157
+ if (!matchesDateRange(item[columnKey], from, to)) return false;
69
158
  }
70
159
  }
71
160
  return true; // Item matches all column filters
@@ -74,37 +163,48 @@ export function applyFilters(data, activeFilters) {
74
163
 
75
164
  /**
76
165
  * Check if any filters are currently active
77
- * @param {Object} activeFilters - Active filters object { columnKey: [selectedValues] }
166
+ * @param {Object} activeFilters - Active filters object
78
167
  * @returns {boolean} True if any filters are active
79
168
  */
80
169
  export function hasActiveFilters(activeFilters) {
81
- return Object.values(activeFilters).some((arr) => arr && arr.length > 0);
170
+ return Object.values(activeFilters).some((val) => {
171
+ if (Array.isArray(val)) return val.length > 0;
172
+ if (val && typeof val === 'object') return !!(val.from || val.to);
173
+ return false;
174
+ });
82
175
  }
83
176
 
84
177
  /**
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
178
+ * Count total number of active filter selections.
179
+ * Each active date range counts as 1.
180
+ * @param {Object} activeFilters - Active filters object
181
+ * @returns {number} Total count of active filter values/ranges
88
182
  */
89
183
  export function countActiveFilters(activeFilters) {
90
- return Object.values(activeFilters).reduce((sum, arr) => sum + (arr?.length || 0), 0);
184
+ return Object.values(activeFilters).reduce((sum, val) => {
185
+ if (Array.isArray(val)) return sum + (val?.length || 0);
186
+ if (val && typeof val === 'object' && (val.from || val.to)) return sum + 1;
187
+ return sum;
188
+ }, 0);
91
189
  }
92
190
 
93
191
  /**
94
192
  * Clear all filters
95
193
  * @param {Array} columnFilters - Column filters configuration
96
- * @returns {Object} Empty filters object
194
+ * @returns {Object} Cleared filters object (arrays for value columns, empty objects for date ranges)
97
195
  */
98
196
  export function clearAllFilters(columnFilters) {
99
197
  const cleared = {};
100
198
  columnFilters.forEach((col) => {
101
- cleared[col.key] = [];
199
+ const isDateRange = col.type === 'daterange' || col.type === 'datetimerange';
200
+ cleared[col.key] = isDateRange ? {} : [];
102
201
  });
103
202
  return cleared;
104
203
  }
105
204
 
106
205
  /**
107
- * Export active filters as URL search params
206
+ * Export active filters as URL search params.
207
+ * Date range filters are serialised as `<key>_from` and `<key>_to` params.
108
208
  * @param {Object} activeFilters - Active filters object
109
209
  * @returns {URLSearchParams} URL search params object
110
210
  */
@@ -112,8 +212,11 @@ export function filtersToSearchParams(activeFilters) {
112
212
  const params = new URLSearchParams();
113
213
 
114
214
  for (const [key, values] of Object.entries(activeFilters)) {
115
- if (values && values.length > 0) {
215
+ if (Array.isArray(values) && values.length > 0) {
116
216
  params.set(key, values.join(','));
217
+ } else if (values && typeof values === 'object' && !Array.isArray(values)) {
218
+ if (values.from) params.set(`${key}_from`, values.from);
219
+ if (values.to) params.set(`${key}_to`, values.to);
117
220
  }
118
221
  }
119
222
 
@@ -131,10 +234,22 @@ export function searchParamsToFilters(searchParams, columnFilters) {
131
234
  typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
132
235
 
133
236
  const validKeys = new Set(columnFilters.map((c) => c.key));
237
+ const dateRangeKeys = new Set(
238
+ columnFilters
239
+ .filter((c) => c.type === 'daterange' || c.type === 'datetimerange')
240
+ .map((c) => c.key),
241
+ );
134
242
  const filters = {};
135
243
 
136
244
  for (const [key, value] of params.entries()) {
137
- if (validKeys.has(key) && value) {
245
+ if (key.endsWith('_from') || key.endsWith('_to')) {
246
+ const colKey = key.replace(/_from$|_to$/, '');
247
+ if (validKeys.has(colKey) && dateRangeKeys.has(colKey)) {
248
+ if (!filters[colKey]) filters[colKey] = {};
249
+ if (key.endsWith('_from')) filters[colKey].from = value;
250
+ else filters[colKey].to = value;
251
+ }
252
+ } else if (validKeys.has(key) && !dateRangeKeys.has(key) && value) {
138
253
  filters[key] = value
139
254
  .split(',')
140
255
  .map((v) => v.trim())
package/src/lib/index.js CHANGED
@@ -7,6 +7,7 @@ export {
7
7
  getUniqueValuesWithCounts,
8
8
  buildColumnFilters,
9
9
  applyFilters,
10
+ matchesDateRange,
10
11
  hasActiveFilters,
11
12
  countActiveFilters,
12
13
  clearAllFilters,