-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable-sortable.js
More file actions
505 lines (433 loc) · 12.5 KB
/
table-sortable.js
File metadata and controls
505 lines (433 loc) · 12.5 KB
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/**
* TableSortableElement - A web component to enable users to sort table data by clicking on column headers.
*
* Based on jquery.easy-sortable-tables.js by Aaron Gustafson
* @see https://github.com/easy-designs/jquery.easy-sortable-tables.js
*
* @element table-sortable
*
* @fires table-sortable:sort - Fired when a column is sorted. Detail: { column: number, direction: 'asc'|'desc', header: HTMLElement }
*
* @slot - Default slot for the table element
*
* @attr {string} label-sortable - Custom label for sortable columns (default: "Click to sort")
* @attr {string} label-ascending - Custom label for ascending sort (default: "sorted ascending. Click to sort descending")
* @attr {string} label-descending - Custom label for descending sort (default: "sorted descending. Click to sort ascending")
*
* @cssprop --table-sortable-indicator-asc - Ascending sort indicator (default: ↑)
* @cssprop --table-sortable-indicator-desc - Descending sort indicator (default: ↓)
*/
export class TableSortableElement extends HTMLElement {
/**
* Inject default styles for sort indicators
* Since this component uses light DOM (not shadow DOM) to work with existing
* table markup, we inject a shared stylesheet into the document head.
* @private
*/
static _injectStyles() {
// Check if styles already exist
if (document.getElementById('table-sortable-styles')) {
return;
}
const style = document.createElement('style');
style.id = 'table-sortable-styles';
style.textContent = `
table-sortable thead th[aria-sort="ascending"] button::after {
content: var(--sort-indicator-asc, '↑') / '';
}
table-sortable thead th[aria-sort="descending"] button::after {
content: var(--sort-indicator-desc, '↓') / '';
}
`;
document.head.appendChild(style);
}
/**
* Find the sort key for a cell
* @private
*/
static _findSortKey(cell) {
if (cell.hasAttribute('data-sort-value')) {
return cell.getAttribute('data-sort-value');
}
const sortKeyElement = cell.querySelector('[data-sort-as]');
if (sortKeyElement) {
// Use the sort key element's text, then append the rest of the cell text
// This matches the original jQuery implementation
const sortKeyText = sortKeyElement.textContent.trim().toUpperCase();
const remainingText = cell.textContent
.replace(sortKeyElement.textContent, '')
.trim()
.toUpperCase();
return sortKeyText + ' ' + remainingText;
}
return cell.textContent.trim().toUpperCase();
}
constructor() {
super();
this._handleSort = this._handleSort.bind(this);
this._handleKeyDown = this._handleKeyDown.bind(this);
this._announcementTimeout = null;
this._pendingInitFrame = null;
}
connectedCallback() {
this._upgradeProperty('labelSortable');
this._upgradeProperty('labelAscending');
this._upgradeProperty('labelDescending');
this._scheduleInitialization();
}
disconnectedCallback() {
if (this._pendingInitFrame !== null) {
cancelAnimationFrame(this._pendingInitFrame);
this._pendingInitFrame = null;
}
this._removeEventListeners();
this._removeLiveRegion();
if (this._announcementTimeout) {
clearTimeout(this._announcementTimeout);
}
}
/**
* Set up the table and make headers sortable
* @private
*/
_setupTable() {
const table = this.querySelector('table');
if (!table) {
console.warn('table-sortable: No table element found');
return;
}
this._table = table;
}
/**
* Ensure colgroup and col elements exist for column styling
* @private
*/
_ensureColgroup() {
if (!this._table) return;
// Check if colgroup already exists
let colgroup = this._table.querySelector('colgroup');
if (!colgroup) {
// Create colgroup
colgroup = document.createElement('colgroup');
// Count columns from thead
const thead = this._table.querySelector('thead tr');
if (!thead) return;
const columnCount = thead.children.length;
// Create col elements
for (let i = 0; i < columnCount; i++) {
const col = document.createElement('col');
colgroup.appendChild(col);
}
// Insert colgroup as first child of table
this._table.insertBefore(colgroup, this._table.firstChild);
}
this._colgroup = colgroup;
}
/**
* Set up accessibility features on sortable headers
* Progressive enhancement: automatically creates buttons in header cells
* @private
*/
_setupAccessibility() {
if (!this._table) return;
const headers = this._table.querySelectorAll('thead th');
headers.forEach((th) => {
// Create a button for the header
const button = document.createElement('button');
button.type = 'button';
button.textContent = th.textContent.trim();
// Clear th and append button
th.textContent = '';
th.appendChild(button);
// Set aria-sort attribute
th.setAttribute('aria-sort', 'none');
});
}
/**
* Get custom label text from attributes
* @private
*/
_getLabel(type) {
const defaults = {
sortable: 'Click to sort',
ascending: 'sorted ascending. Click to sort descending',
descending: 'sorted descending. Click to sort ascending',
};
const labelValues = {
sortable: this.labelSortable,
ascending: this.labelAscending,
descending: this.labelDescending,
};
return labelValues[type] || defaults[type];
}
get labelSortable() {
return this.getAttribute('label-sortable');
}
set labelSortable(value) {
this._reflectStringAttribute('label-sortable', value);
}
get labelAscending() {
return this.getAttribute('label-ascending');
}
set labelAscending(value) {
this._reflectStringAttribute('label-ascending', value);
}
get labelDescending() {
return this.getAttribute('label-descending');
}
set labelDescending(value) {
this._reflectStringAttribute('label-descending', value);
}
/**
* Create a live region for screen reader announcements
* @private
*/
_createLiveRegion() {
this._liveRegion = document.createElement('div');
this._liveRegion.setAttribute('role', 'status');
this._liveRegion.setAttribute('aria-live', 'polite');
this._liveRegion.setAttribute('aria-atomic', 'true');
this._liveRegion.style.position = 'absolute';
this._liveRegion.style.left = '-10000px';
this._liveRegion.style.width = '1px';
this._liveRegion.style.height = '1px';
this._liveRegion.style.overflow = 'hidden';
this.appendChild(this._liveRegion);
}
/**
* Remove the live region
* @private
*/
_removeLiveRegion() {
if (this._liveRegion && this._liveRegion.parentNode) {
this._liveRegion.parentNode.removeChild(this._liveRegion);
}
}
_initialize() {
TableSortableElement._injectStyles();
this._setupTable();
this._ensureColgroup();
this._setupAccessibility();
this._addEventListeners();
this._createLiveRegion();
}
/**
* Announce sorting change to screen readers
* @private
*/
_announceSort(headerText, direction) {
if (!this._liveRegion) return;
const directionLabel =
direction === 1
? this._getLabel('ascending')
: this._getLabel('descending');
const message = `${headerText}, ${directionLabel}`;
// Clear previous announcement
this._liveRegion.textContent = '';
// Delay to ensure screen readers pick up the change
if (this._announcementTimeout) {
clearTimeout(this._announcementTimeout);
}
this._announcementTimeout = setTimeout(() => {
this._liveRegion.textContent = message;
}, 100);
}
/**
* Add event listeners
* @private
*/
_addEventListeners() {
if (!this._table) return;
const buttons = this._table.querySelectorAll('thead th button');
buttons.forEach((button) => {
button.addEventListener('click', this._handleSort);
button.addEventListener('keydown', this._handleKeyDown);
});
}
/**
* Remove event listeners
/**
* Remove event listeners
* @private
*/
_removeEventListeners() {
if (!this._table) return;
const buttons = this._table.querySelectorAll('thead th button');
buttons.forEach((button) => {
button.removeEventListener('click', this._handleSort);
button.removeEventListener('keydown', this._handleKeyDown);
});
}
/**
* Handle keyboard interaction
* @private
*/
_handleKeyDown(event) {
// Activate on Enter or Space
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
this._handleSort(event);
}
}
/**
* Handle sort click/activation
* @private
*/
_handleSort(event) {
event.preventDefault();
const button = event.target.closest('button');
if (!button) return;
const th = button.closest('th');
const column = Array.from(th.parentNode.children).indexOf(th);
const currentDirection = th.classList.contains('up') ? 1 : -1;
const direction = currentDirection === 1 ? -1 : 1;
// Sort the table
this._sortTable(column, direction, th);
// Fire custom event
this.dispatchEvent(
new CustomEvent('table-sortable:sort', {
bubbles: true,
detail: {
column,
direction: direction === 1 ? 'asc' : 'desc',
header: th,
},
}),
);
// Announce to screen readers
const headerText = th.textContent.trim();
this._announceSort(headerText, direction);
}
/**
* Sort the table by the specified column
* @private
*/
_sortTable(column, direction, activeHeader) {
if (!this._table) return;
// Check if we have grouped rows
const hasGroups =
this._table.querySelectorAll('tr[data-table-sort-group]').length >
0;
// Get all rows from tbody elements
const rows = Array.from(this._table.querySelectorAll('tbody tr'));
// Remove all tbody elements
const tbodies = this._table.querySelectorAll('tbody');
tbodies.forEach((tbody) => tbody.remove());
// Clear active states and aria-sort
const allHeaders = this._table.querySelectorAll('thead th');
allHeaders.forEach((header) => {
header.classList.remove('active', 'up', 'down');
header.setAttribute('aria-sort', 'none');
});
// Clear sorted class from all cols
if (this._colgroup) {
const cols = this._colgroup.querySelectorAll('col');
cols.forEach((col) => col.classList.remove('sorted'));
}
// Set active state and aria-sort
activeHeader.classList.add('active', direction === 1 ? 'up' : 'down');
activeHeader.setAttribute(
'aria-sort',
direction === 1 ? 'ascending' : 'descending',
);
// Add sorted class to corresponding col
if (this._colgroup) {
const cols = this._colgroup.querySelectorAll('col');
if (cols[column]) {
cols[column].classList.add('sorted');
}
}
// Assign sort keys to rows
rows.forEach((row) => {
const cell = row.children[column];
if (!cell) {
row._sortKey = '';
return;
}
const sortKey = TableSortableElement._findSortKey(cell);
const numericValue = parseInt(sortKey, 10);
// Use numeric comparison if the value is a valid number
row._sortKey =
!isNaN(numericValue) &&
numericValue.toString() === sortKey.trim()
? numericValue
: sortKey;
});
// Sort rows
rows.sort((a, b) => {
if (a._sortKey < b._sortKey) return -direction;
if (a._sortKey > b._sortKey) return direction;
return 0;
});
// Re-append rows
if (hasGroups) {
this._appendGroupedRows(rows);
} else {
this._appendSingleTbody(rows);
}
// Clean up sort keys
rows.forEach((row) => {
delete row._sortKey;
});
}
/**
* Append rows as grouped tbody elements
* @private
*/
_appendGroupedRows(rows) {
// Group rows by their data-table-sort-group attribute
const groups = new Map();
rows.forEach((row) => {
const group = row.getAttribute('data-table-sort-group');
if (!groups.has(group)) {
groups.set(group, []);
}
groups.get(group).push(row);
});
// Create tbody for each group and append rows
groups.forEach((groupRows) => {
const tbody = document.createElement('tbody');
groupRows.forEach((row) => {
tbody.appendChild(row);
});
this._table.appendChild(tbody);
});
}
/**
* Append rows as a single tbody
* @private
*/
_appendSingleTbody(rows) {
const tbody = document.createElement('tbody');
rows.forEach((row) => {
tbody.appendChild(row);
});
this._table.appendChild(tbody);
}
_scheduleInitialization() {
if (!this.isConnected) {
return;
}
if (this._pendingInitFrame !== null) {
cancelAnimationFrame(this._pendingInitFrame);
}
this._pendingInitFrame = requestAnimationFrame(() => {
this._pendingInitFrame = null;
this._initialize();
});
}
_reflectStringAttribute(attrName, value) {
if (value === null || value === undefined || value === '') {
this.removeAttribute(attrName);
return;
}
this.setAttribute(attrName, String(value));
}
_upgradeProperty(prop) {
if (Object.prototype.hasOwnProperty.call(this, prop)) {
const value = this[prop];
delete this[prop];
this[prop] = value;
}
}
}