forked from Careswitch/svelte-data-table
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataTable.svelte.ts
415 lines (357 loc) · 10.9 KB
/
DataTable.svelte.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
type ValueGetter<T, V> = (row: T) => V;
type Sorter<T, V> = (a: V, b: V, rowA: T, rowB: T) => number;
type Filter<T, V> = (value: V, filterValue: V, row: T) => boolean;
export interface ColumnDef<T, V = any> {
id: string;
key: keyof T;
name: string;
sortable?: boolean;
getValue?: ValueGetter<T, V>;
sorter?: Sorter<T, V>;
filter?: Filter<T, V>;
}
type SortDirection = 'asc' | 'desc' | null;
type TableConfig<T> = {
data: T[];
columns: ColumnDef<T>[];
pageSize?: number;
initialSort?: string;
initialSortDirection?: SortDirection;
initialFilters?: { [id: string]: any[] };
};
type StoreState = {
columnId: string | null;
direction: SortDirection
}
/**
* Represents a data table with sorting, filtering, and pagination capabilities.
* @template T The type of data items in the table.
*/
export class DataTable<T> {
#columns: ColumnDef<T>[];
#pageSize: number;
#originalData = $state<T[]>([]);
#currentPage = $state(1);
#sortState = $state<StoreState>({
columnId: null,
direction: null
});
#filterState = $state<{ [id: string]: Set<any> }>({});
#globalFilter = $state<string>('');
#globalFilterRegex: RegExp | null = null;
#isFilterDirty = true;
#isSortDirty = true;
#filteredData: T[] = [];
#sortedData: T[] = [];
/**
* Creates a new DataTable instance.
* @param {TableConfig<T>} config - The configuration object for the data table.
*/
constructor(config: TableConfig<T>) {
this.#originalData = [...config.data];
this.#columns = config.columns;
this.#pageSize = config.pageSize || 10;
if (config.initialSort) {
this.#sortState = {
columnId: config.initialSort,
direction: config.initialSortDirection || 'asc'
};
}
this.#initializeFilterState(config.initialFilters);
}
#initializeFilterState(initialFilters?: { [id: string]: any[] }) {
this.#columns.forEach((column) => {
const initialFilterValues = initialFilters?.[column.id];
if (initialFilterValues) {
this.#filterState[column.id] = new Set(initialFilterValues);
} else {
this.#filterState[column.id] = new Set();
}
});
}
#getColumnDef(id: string): ColumnDef<T> | undefined {
return this.#columns.find((col) => col.id === id);
}
#getValue(row: T, columnId: string): any {
const colDef = this.#getColumnDef(columnId);
if (!colDef) return undefined;
return colDef.getValue ? colDef.getValue(row) : row[colDef.key];
}
#matchesGlobalFilter = (row: T): boolean => {
if (!this.#globalFilterRegex) return true;
return this.#columns.some((col) => {
const value = this.#getValue(row, col.id);
return typeof value === 'string' && this.#globalFilterRegex!.test(value);
});
};
#matchesFilters = (row: T): boolean => {
return Object.entries(this.#filterState).every(([columnId, filterSet]) => {
if (!filterSet || filterSet.size === 0) return true;
const colDef = this.#getColumnDef(columnId);
if (!colDef) return true;
const value = this.#getValue(row, columnId);
if (colDef.filter) {
for (const filterValue of filterSet) {
if (colDef.filter(value, filterValue, row)) {
return true;
}
}
return false;
}
return filterSet.has(value);
});
};
#applyFilters() {
if (!this.#isFilterDirty) return;
this.#filteredData = this.#originalData.filter(
(row) => this.#matchesGlobalFilter(row) && this.#matchesFilters(row)
);
this.#isFilterDirty = false;
this.#isSortDirty = true;
}
#applySort() {
if (!this.#isSortDirty) return;
const { columnId, direction } = this.#sortState;
if (columnId && direction) {
const colDef = this.#getColumnDef(columnId);
this.#sortedData = [...this.#filteredData].sort((a, b) => {
const aVal = this.#getValue(a, columnId);
const bVal = this.#getValue(b, columnId);
if (aVal === undefined || aVal === null) return direction === 'asc' ? 1 : -1;
if (bVal === undefined || bVal === null) return direction === 'asc' ? -1 : 1;
if (colDef && colDef.sorter) {
return direction === 'asc'
? colDef.sorter(aVal, bVal, a, b)
: colDef.sorter(bVal, aVal, b, a);
}
if (typeof aVal === 'string' && typeof bVal === 'string') {
return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
}
if (aVal < bVal) return direction === 'asc' ? -1 : 1;
if (aVal > bVal) return direction === 'asc' ? 1 : -1;
return 0;
});
} else {
this.#sortedData = [...this.#filteredData];
}
this.#isSortDirty = false;
}
/**
* Sets the current sort state for the table.
*/
setCurrentSortState(value: StoreState) {
this.#sortState = value;
this.#applySort();
}
/**
* Gets the current sort state for the table.
* @returns {StoreState} The current sort state.
*/
getCurrentSortState(): StoreState {
return this.#sortState
}
/**
* Gets or sets the base data rows without any filtering or sorting applied.
* @returns {T[]} An array of all rows.
*/
get baseRows() {
return this.#originalData;
}
/**
* @param {T[]} rows - The array of rows to reset the base data to.
*/
set baseRows(rows: T[]) {
this.#currentPage = 1;
this.#isFilterDirty = true;
this.#originalData = [...rows];
}
/**
* Returns all filtered and sorted rows without pagination.
* @returns {T[]} An array of all filtered and sorted rows.
*/
get allRows() {
// React to changes in original data, filter state, and sort state
this.#originalData;
this.#sortState;
this.#filterState;
this.#globalFilter;
this.#applyFilters();
this.#applySort();
return this.#sortedData;
}
/**
* The current page of rows based on applied filters and sorting.
* @returns {T[]} An array of rows for the current page.
*/
get rows() {
const startIndex = (this.#currentPage - 1) * this.#pageSize;
const endIndex = startIndex + this.#pageSize;
return this.allRows.slice(startIndex, endIndex);
}
/**
* The column definitions for the table.
* @returns {ColumnDef<T>[]} An array of column definitions.
*/
get columns() {
return this.#columns;
}
/**
* The current filter state for all columns.
* @returns {{ [K in keyof T]: Set<any> }} An object representing the filter state that maps column keys to filter values.
*/
get filterState() {
return this.#filterState;
}
/**
* The current sort state for the table.
* @returns {{ column: keyof T | null; direction: SortDirection }} An object representing the sort state with a column key and direction.
*/
get sortState() {
return this.#sortState;
}
/**
* The total number of pages based on the current filters and page size.
* @returns {number} The total number of pages.
*/
get totalPages() {
// React to changes in original data and filter state
this.#originalData;
this.#filterState;
this.#globalFilter;
this.#applyFilters();
return Math.max(1, Math.ceil(this.#filteredData.length / this.#pageSize));
}
/**
* Gets or sets the current page number.
* @returns {number} The current page number.
*/
get currentPage() {
return this.#currentPage;
}
/**
* @param {number} page - The page number to set.
*/
set currentPage(page: number) {
this.#currentPage = Math.max(1, Math.min(page, this.totalPages));
}
/**
* Indicates whether the user can navigate to the previous page.
* @returns {boolean} True if there's a previous page available, false otherwise.
*/
get canGoBack() {
// React to changes in filter state
this.#filterState;
this.#globalFilterRegex;
return this.currentPage > 1 && this.#filteredData.length > 0;
}
/**
* Indicates whether the user can navigate to the next page.
* @returns {boolean} True if there's a next page available, false otherwise.
*/
get canGoForward() {
// React to changes in filter state
this.#filterState;
this.#globalFilterRegex;
return this.currentPage < this.totalPages && this.#filteredData.length > 0;
}
/**
* Gets or sets the global filter string.
* @returns {string} The current global filter string.
*/
get globalFilter() {
return this.#globalFilter;
}
/**
* @param {string} value - The global filter string to set.
*/
set globalFilter(value: string) {
this.#globalFilter = value;
try {
this.#globalFilterRegex = value.trim() !== '' ? new RegExp(`(?:${value})`, 'i') : null;
} catch (error) {
console.error('Invalid regex pattern:', error);
this.#globalFilterRegex = null;
}
this.#currentPage = 1;
this.#isFilterDirty = true;
}
/**
* Toggles the sort direction for the specified column.
* @param {string} columnId - The column id to toggle sorting for.
*/
toggleSort = (columnId: string) => {
const colDef = this.#getColumnDef(columnId);
if (!colDef || colDef.sortable === false) return;
this.#isSortDirty = true;
if (this.#sortState.columnId === columnId) {
this.#sortState = {
columnId,
direction:
this.#sortState.direction === 'asc'
? 'desc'
: this.#sortState.direction === 'desc'
? null
: 'asc'
};
} else {
this.#sortState = { columnId, direction: 'asc' };
}
};
/**
* Gets the current sort state for the specified column.
* @param {string} columnId - The column id to get the sort state for.
*/
getSortState = (columnId: string): SortDirection => {
return this.#sortState.columnId === columnId ? this.#sortState.direction : null;
};
/**
* Indicates whether the specified column is sortable.
* @param {string} columnId - The column id to check.
*/
isSortable = (columnId: string): boolean => {
const colDef = this.#getColumnDef(columnId);
return colDef?.sortable !== false;
};
/**
* Sets the filter values for the specified column.
* @param {string} columnId - The column id to set the filter values for.
* @param {any[]} values - The filter values to set.
*/
setFilter = (columnId: string, values: any[]) => {
this.#isFilterDirty = true;
this.#filterState = { ...this.#filterState, [columnId]: new Set(values) };
this.#currentPage = 1;
};
/**
* Clears the filter values for the specified column.
* @param {string} columnId - The column id to clear the filter values for.
*/
clearFilter = (columnId: string) => {
this.#isFilterDirty = true;
this.#filterState = { ...this.#filterState, [columnId]: new Set() };
this.#currentPage = 1;
};
/**
* Toggles the filter value for the specified column.
* @param {string} columnId - The column id to toggle the filter value for.
* @param {any} value - The filter value to toggle.
*/
toggleFilter = (columnId: string, value: any) => {
this.#isFilterDirty = true;
this.#filterState = {
...this.#filterState,
[columnId]: this.isFilterActive(columnId, value)
? new Set([...this.#filterState[columnId]].filter((v) => v !== value))
: new Set([...this.#filterState[columnId], value])
};
this.#currentPage = 1;
};
/**
* Indicates whether the specified filter value is active for the specified column.
* @param {string} columnId - The column id to check.
* @param {any} value - The filter value to check.
*/
isFilterActive = (columnId: string, value: any): boolean => {
return this.#filterState[columnId].has(value);
};
}