Repository navigation
Expand file tree
/
Copy pathtable-sortable.js
More file actions
577 lines (500 loc) · 14.3 KB
/
Copy pathtable-sortable.js
File metadata and controls
577 lines (500 loc) · 14.3 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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/**
* 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 ascending")
* @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: ↓)
*/
let nextDescriptionId = 0;
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, '↓') / '';
}
table-sortable .table-sortable-description {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
`;
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._descriptionId = ++nextDescriptionId;
this._descriptionIds = {
sortable: `table-sortable-description-${this._descriptionId}-sortable`,
ascending: `table-sortable-description-${this._descriptionId}-ascending`,
descending: `table-sortable-description-${this._descriptionId}-descending`,
};
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');
const descriptions = Object.entries(this._descriptionIds).map(
([state, id]) => {
const description = document.createElement('span');
description.id = id;
description.className = 'table-sortable-description';
description.textContent = this._getLabel(state);
return description;
},
);
headers.forEach((th) => {
// Create a button for the header
const button = document.createElement('button');
button.type = 'button';
button.textContent = th.textContent.trim();
button.setAttribute(
'aria-describedby',
this._descriptionIds.sortable,
);
// Clear th and append accessible controls
th.textContent = '';
th.appendChild(button);
// Set aria-sort attribute
th.setAttribute('aria-sort', 'none');
});
headers[0]?.append(...descriptions);
}
/**
* Get custom label text from attributes
* @private
*/
_getLabel(type) {
const defaults = {
sortable: 'Click to sort ascending',
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() {
if (this._liveRegion) return;
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);
}
this._liveRegion = null;
}
_initialize() {
TableSortableElement._injectStyles();
this._setupTable();
this._ensureColgroup();
this._setupAccessibility();
this._addEventListeners();
}
/**
* Send a polite screen reader notification
* @private
*/
_notify(message) {
if (typeof this.ariaNotify === 'function') {
this.ariaNotify(message, { priority: 'normal' });
return;
}
this._createLiveRegion();
this._liveRegion.textContent = '';
if (this._announcementTimeout) {
clearTimeout(this._announcementTimeout);
}
this._announcementTimeout = setTimeout(() => {
this._liveRegion.textContent = message;
}, 100);
}
/**
* Announce sorting change to screen readers
* @private
*/
_announceSort(headerText, direction) {
const directionLabel =
direction === 1
? this._getLabel('ascending')
: this._getLabel('descending');
this._notify(`${headerText}, ${directionLabel}`);
}
/**
* 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 = button.textContent.trim();
this._announceSort(headerText, direction);
}
/**
* Sort the table by the specified column
* @private
*/
_sortTable(column, direction, activeHeader) {
if (!this._table) return;
// Get all rows from tbody elements
const rows = Array.from(this._table.querySelectorAll('tbody tr'));
const rowGroups = new Map();
let hasGroups = false;
rows.forEach((row) => {
const group =
row.getAttribute('data-table-sort-group') ??
row.closest('tbody')?.getAttribute('data-table-sort-group') ??
null;
rowGroups.set(row, group);
hasGroups ||= group !== null;
});
// 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');
header
.querySelector('button')
?.setAttribute(
'aria-describedby',
this._descriptionIds.sortable,
);
});
// 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',
);
activeHeader
.querySelector('button')
?.setAttribute(
'aria-describedby',
this._descriptionIds[
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 normalizedSortKey = sortKey.trim();
const isNumeric = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(
normalizedSortKey,
);
const numericValue = isNumeric
? Number(normalizedSortKey)
: Number.NaN;
// Use numeric comparison if the value is a valid number
row._sortKey = Number.isFinite(numericValue)
? 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, rowGroups);
} else {
this._appendSingleTbody(rows);
}
// Clean up sort keys
rows.forEach((row) => {
delete row._sortKey;
});
}
/**
* Append rows as grouped tbody elements
* @private
*/
_appendGroupedRows(rows, rowGroups) {
const groups = new Map();
rows.forEach((row) => {
const group = rowGroups.get(row);
if (!groups.has(group)) {
groups.set(group, []);
}
groups.get(group).push(row);
});
// Create tbody for each group and append rows
groups.forEach((groupRows, group) => {
const tbody = document.createElement('tbody');
if (group !== null) {
tbody.setAttribute('data-table-sort-group', group);
}
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;
}
}
}