@avlcodemonkey/nilla-components 0.0.0-stage → 0.0.1

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.
Files changed (94) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +21 -0
  3. package/README.md +219 -3
  4. package/THIRD_PARTY_NOTICES.md +48 -0
  5. package/css/alert.css +48 -0
  6. package/css/autocomplete.css +38 -0
  7. package/css/dialog.css +61 -0
  8. package/css/file-to-textarea.css +8 -0
  9. package/css/html-editor.css +172 -0
  10. package/css/json.css +44 -0
  11. package/css/list.css +37 -0
  12. package/css/nav-toggle.css +92 -0
  13. package/css/nilla.css +16 -0
  14. package/css/pjax.css +58 -0
  15. package/css/slider-input.css +16 -0
  16. package/css/table.css +99 -0
  17. package/css/tokens.css +44 -0
  18. package/css/unsaved-changes.css +10 -0
  19. package/css/vendor/wysi.css +406 -0
  20. package/docs/llms.txt +319 -0
  21. package/package.json +121 -5
  22. package/src/components/Alert.js +24 -0
  23. package/src/components/Autocomplete.js +127 -0
  24. package/src/components/BaseComponent.js +78 -0
  25. package/src/components/BaseDialog.js +151 -0
  26. package/src/components/ConfirmDialog.js +34 -0
  27. package/src/components/CopyToClipboard.js +66 -0
  28. package/src/components/DateFormatter.js +51 -0
  29. package/src/components/DateTimeInput.js +63 -0
  30. package/src/components/DisplayToggle.js +53 -0
  31. package/src/components/FileToTextarea.js +81 -0
  32. package/src/components/HtmlEditor.js +309 -0
  33. package/src/components/InfoDialog.js +38 -0
  34. package/src/components/JsonFormatter.js +23 -0
  35. package/src/components/List.js +237 -0
  36. package/src/components/ListSortable.js +8 -0
  37. package/src/components/NavToggle.js +119 -0
  38. package/src/components/PJax.js +888 -0
  39. package/src/components/Share.js +41 -0
  40. package/src/components/SliderInput.js +26 -0
  41. package/src/components/Table.js +758 -0
  42. package/src/components/TimeOffsetSelect.js +29 -0
  43. package/src/components/UnsavedChanges.js +187 -0
  44. package/src/constants/Fetch.js +7 -0
  45. package/src/constants/HttpHeaders.js +19 -0
  46. package/src/constants/HttpMethods.js +14 -0
  47. package/src/constants/SortDirection.js +11 -0
  48. package/src/constants/TableElements.js +25 -0
  49. package/src/constants/TableSettings.js +14 -0
  50. package/src/errors/FetchError.js +7 -0
  51. package/src/events/ListReorderEvent.js +19 -0
  52. package/src/events/PJaxErrorEvent.js +38 -0
  53. package/src/events/PJaxNavigatingEvent.js +46 -0
  54. package/src/index.js +26 -0
  55. package/src/locales/en.json +55 -0
  56. package/src/locales/es.js +9 -0
  57. package/src/locales/es.json +55 -0
  58. package/src/models/TableSort.js +20 -0
  59. package/src/utils/ajaxHeaders.js +10 -0
  60. package/src/utils/announce.js +40 -0
  61. package/src/utils/defineElement.js +13 -0
  62. package/src/utils/editor/blockTools.js +256 -0
  63. package/src/utils/editor/elements.js +18 -0
  64. package/src/utils/editor/input.js +350 -0
  65. package/src/utils/editor/selection.js +125 -0
  66. package/src/utils/editor/tableTools.js +497 -0
  67. package/src/utils/escape.js +20 -0
  68. package/src/utils/fetchJsonArray.js +29 -0
  69. package/src/utils/filterArray.js +18 -0
  70. package/src/utils/formActionUrl.js +10 -0
  71. package/src/utils/formData.js +118 -0
  72. package/src/utils/index.js +18 -0
  73. package/src/utils/indexedCompare.js +18 -0
  74. package/src/utils/isSameOrigin.js +12 -0
  75. package/src/utils/locale.js +36 -0
  76. package/src/utils/notifyChange.js +10 -0
  77. package/src/utils/numberSetting.js +14 -0
  78. package/src/utils/pageLanguage.js +13 -0
  79. package/src/utils/parseUtcDate.js +22 -0
  80. package/src/utils/randomId.js +17 -0
  81. package/src/utils/registerTabTrap.js +60 -0
  82. package/src/utils/renderTemplate.js +44 -0
  83. package/src/utils/requestTimeout.js +12 -0
  84. package/src/utils/response.js +28 -0
  85. package/src/utils/sortedCompare.js +67 -0
  86. package/src/utils/storage.js +40 -0
  87. package/src/vendor/autocomplete.js +515 -0
  88. package/src/vendor/formatDate.js +236 -0
  89. package/src/vendor/licenses/autocomplete.LICENSE.md +21 -0
  90. package/src/vendor/licenses/fecha.LICENSE.md +21 -0
  91. package/src/vendor/licenses/pretty-print-json.LICENSE.md +21 -0
  92. package/src/vendor/licenses/wysi.LICENSE.md +21 -0
  93. package/src/vendor/prettyPrintJson.js +108 -0
  94. package/src/vendor/wyzi.js +2024 -0
@@ -0,0 +1,758 @@
1
+ import FetchError from '../errors/FetchError.js';
2
+ import announce from '../utils/announce.js';
3
+ import TableSettings from '../constants/TableSettings.js';
4
+ import SortDirection from '../constants/SortDirection.js';
5
+ import { formDataToUrl, formToObject, objectToForm } from '../utils/formData.js';
6
+ import HttpMethods from '../constants/HttpMethods.js';
7
+ import renderTemplate from '../utils/renderTemplate.js';
8
+ import BaseComponent from './BaseComponent.js';
9
+ import indexedCompare from '../utils/indexedCompare.js';
10
+ import sortedCompare from '../utils/sortedCompare.js';
11
+ import filterArray from '../utils/filterArray.js';
12
+ import TableElements from '../constants/TableElements.js';
13
+ import TableSort from '../models/TableSort.js';
14
+ import defineElement from '../utils/defineElement.js';
15
+ import { readStorage, writeStorage } from '../utils/storage.js';
16
+ import fetchJsonArray from '../utils/fetchJsonArray.js';
17
+ import formActionUrl from '../utils/formActionUrl.js';
18
+ import notifyChange from '../utils/notifyChange.js';
19
+ import numberSetting from '../utils/numberSetting.js';
20
+ import requestTimeout from '../utils/requestTimeout.js';
21
+
22
+ /**
23
+ * @typedef IndexedRow
24
+ * @type {object}
25
+ * @property {number} _index Unique identifier for the row.
26
+ */
27
+
28
+ /**
29
+ * Web component for rendering table data.
30
+ */
31
+ class Table extends BaseComponent {
32
+ /**
33
+ * Unique identifier for this table.
34
+ * @type {string}
35
+ */
36
+ #key = '';
37
+
38
+ /**
39
+ * Url to request data from the server.
40
+ * @type {string}
41
+ */
42
+ #srcUrl = '';
43
+
44
+ /**
45
+ * ID for form to include with request.
46
+ * @type {string}
47
+ */
48
+ #srcForm = '';
49
+
50
+ /**
51
+ * Max number of results to display, or 0 for all of them.
52
+ * @type {number}
53
+ */
54
+ #maxResults = 0;
55
+
56
+ /**
57
+ * Values the filter form's hidden fields were rendered with, by name, as JSON. Unchanged ones aren't saved, so a
58
+ * value such as an antiforgery token always comes from the server.
59
+ * @type {Map<string, string>}
60
+ */
61
+ #renderedHiddenValues = new Map();
62
+
63
+ /**
64
+ * Data fetched from the server.
65
+ * @type {Array<IndexedRow>}
66
+ */
67
+ #rows = [];
68
+
69
+ /**
70
+ * Data from the server filtered based on current display settings.
71
+ * @type {Array<IndexedRow>}
72
+ */
73
+ #filteredRows = [];
74
+
75
+ /**
76
+ * Sort settings for the table.
77
+ * @type {Array<TableSort>}
78
+ */
79
+ #tableSorts = [];
80
+
81
+ /**
82
+ * Total number of rows based on current table filters.
83
+ * @type {number}
84
+ */
85
+ #filteredRowTotal = 0;
86
+
87
+ /**
88
+ * Current page number.
89
+ * @type {number}
90
+ */
91
+ #currentPage = 0;
92
+
93
+ /**
94
+ * Number of rows to display per page.
95
+ * @type {number}
96
+ */
97
+ #perPage = 10;
98
+
99
+ /**
100
+ * Total number of pages.
101
+ * @type {number}
102
+ */
103
+ #maxPage = 0;
104
+
105
+ /**
106
+ * String to filter data for.
107
+ * @type {string}
108
+ */
109
+ #search = '';
110
+
111
+ /**
112
+ * Tracks the timeout for re-filtering data.
113
+ * @type {number}
114
+ */
115
+ #debounceTimer = 0;
116
+
117
+ /**
118
+ * Indicates data is currently being fetched from the server if true.
119
+ * @type {boolean}
120
+ */
121
+ #loading = false;
122
+
123
+ /**
124
+ * Indicates an error occurred fetching data from the server if true.
125
+ * @type {boolean}
126
+ */
127
+ #error = false;
128
+
129
+ /**
130
+ * What screen reader users were last told, or undefined until they use the table.
131
+ * @type {string|undefined}
132
+ */
133
+ #announced;
134
+
135
+ /**
136
+ * Form to include with requests.
137
+ * @type {HTMLFormElement|null}
138
+ */
139
+ #formElement = null;
140
+
141
+ /**
142
+ * Loads the data again instead of submitting the form.
143
+ * @param {SubmitEvent} event Submit event.
144
+ */
145
+ #submitListener = (event) => {
146
+ event.preventDefault();
147
+ event.stopImmediatePropagation();
148
+ this.#announced ??= '';
149
+
150
+ if (!this.#loading) {
151
+ this.#fetchData();
152
+ }
153
+ };
154
+
155
+ /**
156
+ * Initialize table by loading settings from sessionStorage, processing HTML to add event handlers, and fetching data from the server.
157
+ */
158
+ constructor() {
159
+ super('table');
160
+
161
+ this.#key = this.dataset.key;
162
+ this.#srcUrl = this.dataset.srcUrl;
163
+ this.#srcForm = this.dataset.srcForm;
164
+
165
+ this.#maxResults = numberSetting(this.dataset.maxResults, 0, { integer: true });
166
+
167
+ // check sessionStorage for saved settings
168
+ const pageSize = numberSetting(this.dataset.pageSize, 10, { integer: true });
169
+ this.#perPage = Number(this.#loadSetting(TableSettings.PerPage) ?? pageSize);
170
+ this.#currentPage = Number(this.#loadSetting(TableSettings.CurrentPage) ?? '0');
171
+ this.#search = this.#loadSetting(TableSettings.Search) ?? '';
172
+ // saved sort wins over the default, even if it's empty because the user removed all sorting
173
+ this.#tableSorts = this.#savedSorts() ?? this.#defaultSorts();
174
+
175
+ this.#setupHeader();
176
+ this.#setupFooter();
177
+ this.#setupStatus();
178
+ this.#setupSorting();
179
+ this.#setupForm();
180
+ }
181
+
182
+ /**
183
+ * Fetches data to populate the table once the component is connected to the DOM, and listens to the form, which may be
184
+ * outside the table.
185
+ */
186
+ connectedCallback() {
187
+ this.#formElement?.addEventListener('submit', this.#submitListener);
188
+ // fetchData is async but we can fire & forget here
189
+ this.#fetchData();
190
+ }
191
+
192
+ /**
193
+ * Clean up when removing component.
194
+ */
195
+ disconnectedCallback() {
196
+ this.#formElement?.removeEventListener('submit', this.#submitListener);
197
+ super.disconnectedCallback();
198
+ }
199
+
200
+ /**
201
+ * Loads the sort settings from sessionStorage.
202
+ * @returns {Array<TableSort>|undefined} Saved sort, or undefined if nothing usable is saved.
203
+ */
204
+ #savedSorts() {
205
+ try {
206
+ const sorts = JSON.parse(this.#loadSetting(TableSettings.Sort) ?? 'null');
207
+ return Array.isArray(sorts) && sorts.every(x => typeof x?.property === 'string') ? sorts : undefined;
208
+ } catch {
209
+ return undefined;
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Builds the initial sort settings from the `data-sort-property` and `data-sort-direction` attributes.
215
+ * @returns {Array<TableSort>} Default sort, or an empty array if the table doesn't specify one that matches a column header.
216
+ */
217
+ #defaultSorts() {
218
+ const { sortProperty, sortDirection } = this.dataset;
219
+ // without a matching header, the user would have no way to remove the sort
220
+ const headers = [...this.querySelectorAll('th[data-property]')];
221
+ if (!headers.some(x => /** @type {HTMLElement} */ (x).dataset.property === sortProperty)) {
222
+ return [];
223
+ }
224
+
225
+ const direction = sortDirection === SortDirection.Desc ? SortDirection.Desc : SortDirection.Asc;
226
+ return [{ property: sortProperty, direction }];
227
+ }
228
+
229
+ /**
230
+ * Sets the default value and adds event handler for the search input.
231
+ */
232
+ #setupHeader() {
233
+ const searchInput = /** @type {HTMLInputElement} */ (this.getElement(TableElements.Search));
234
+ if (searchInput) {
235
+ searchInput.value = this.#search;
236
+ searchInput.addEventListener('input', (/** @type {InputEvent} */ e) => this.#onSearchInput(e));
237
+
238
+ // focusing scrolls the search box into view, so only do it when the page asks
239
+ if (this.dataset.searchAutofocus === 'true') {
240
+ searchInput.focus();
241
+ }
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Add event handlers for the buttons for moving between pages.
247
+ */
248
+ #setupFooter() {
249
+ this.getElement(TableElements.FirstPage)?.addEventListener('click', () => this.#setPage(0));
250
+ this.getElement(TableElements.PreviousPage)?.addEventListener('click', () => this.#setPage(Math.max(this.#currentPage - 1, 0)));
251
+ this.getElement(TableElements.NextPage)?.addEventListener('click', () => this.#setPage(Math.min(this.#currentPage + 1, this.#maxPage)));
252
+ this.getElement(TableElements.LastPage)?.addEventListener('click', () => this.#setPage(this.#maxPage));
253
+
254
+ const tablePerPageSelect = /** @type {HTMLSelectElement} */ (this.getElement(TableElements.PerPage));
255
+ if (tablePerPageSelect) {
256
+ tablePerPageSelect.value = `${this.#perPage}`;
257
+ tablePerPageSelect.addEventListener('change', (/** @type {InputEvent} */ e) => this.#onPerPageChange(e));
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Add event handlers for table status functionality.
263
+ */
264
+ #setupStatus() {
265
+ this.getElement(TableElements.Retry)?.addEventListener('click', () => this.#onRetryClick());
266
+ }
267
+
268
+ /**
269
+ * Add event handlers for table sorting functionality. Each sortable header's content goes in a button, so it can be
270
+ * reached and pressed with the keyboard. A header that already has a button keeps it, and one with another control is
271
+ * left alone, since a button can't contain controls.
272
+ */
273
+ #setupSorting() {
274
+ const headers = /** @type {HTMLElement[]} */ ([...this.querySelectorAll('th[data-property]')]);
275
+ for (const th of headers) {
276
+ if (!th.querySelector('a[href], button, input, select, textarea, label, details, [tabindex]')) {
277
+ const button = document.createElement('button');
278
+ button.type = 'button';
279
+ button.setAttribute(`data-table-${TableElements.SortButton}`, '');
280
+ button.append(...th.childNodes);
281
+ th.append(button);
282
+ }
283
+ // clicks on the button, including from the keyboard, bubble to the header
284
+ th.addEventListener('click', () => this.#onSortClick(th));
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Gets the values of the names that only hidden inputs use. A checkbox's hidden companion isn't one.
290
+ * @param {HTMLFormElement} formElement Form to read.
291
+ * @returns {Array<[string, string]>} Names and their values as JSON.
292
+ */
293
+ static #hiddenValues(formElement) {
294
+ const fields = /** @type {HTMLInputElement[]} */ ([...formElement.elements]);
295
+ return Object.entries(formToObject(formElement))
296
+ .filter(([name]) => fields.every(x => x.name !== name || x.type === 'hidden'))
297
+ .map(([name, value]) => [name, JSON.stringify(value)]);
298
+ }
299
+
300
+ /**
301
+ * Gets the filter form's values worth saving.
302
+ * @param {HTMLFormElement} formElement Filter form.
303
+ * @returns {object} Values, without hidden fields that still hold what they were rendered with.
304
+ */
305
+ #formSettings(formElement) {
306
+ const data = formToObject(formElement);
307
+ for (const [name, rendered] of this.#renderedHiddenValues) {
308
+ if (JSON.stringify(data[name]) === rendered) {
309
+ delete data[name];
310
+ }
311
+ }
312
+ return data;
313
+ }
314
+
315
+ /**
316
+ * Tells components in the form, such as display toggles, that its values changed.
317
+ * @param {HTMLFormElement} formElement Form that was restored.
318
+ */
319
+ static #notifyFields(formElement) {
320
+ const fields = /** @type {HTMLInputElement[]} */ ([...formElement.elements]);
321
+ // an autocomplete takes a change to its display input as the user typing something it doesn't know
322
+ fields.filter(x => x.name && !x.hasAttribute('data-autocomplete-display')).forEach(notifyChange);
323
+ }
324
+
325
+ /**
326
+ * Finds the form and restores its saved values.
327
+ */
328
+ #setupForm() {
329
+ if (!this.#srcForm) {
330
+ return;
331
+ }
332
+
333
+ const formElement = /** @type {HTMLFormElement} */ (document.getElementById(this.#srcForm));
334
+ if (!formElement) {
335
+ return;
336
+ }
337
+ this.#formElement = formElement;
338
+
339
+ // read before restoring, while the fields hold what the server sent
340
+ this.#renderedHiddenValues = new Map(Table.#hiddenValues(formElement));
341
+
342
+ const json = this.#loadSetting(TableSettings.FormData);
343
+ if (json) {
344
+ try {
345
+ const data = JSON.parse(json);
346
+ if (data) {
347
+ objectToForm(data, formElement);
348
+ // wait until the data is loading, so a page that submits the form on change doesn't load it twice
349
+ queueMicrotask(() => Table.#notifyFields(formElement));
350
+ }
351
+ } catch {
352
+ /* empty */
353
+ }
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Fetch data from the server at the URL specified in the `src` property.
359
+ */
360
+ async #fetchData() {
361
+ if (!(this.#srcUrl || this.#srcForm)) {
362
+ return;
363
+ }
364
+
365
+ this.#loading = true;
366
+ this.#error = false;
367
+
368
+ // save the current page for later so we can try to navigate to it after reloading data
369
+ const originalPage = this.#currentPage;
370
+
371
+ // first clear out the existing data and update the table
372
+ this.#rows = [];
373
+ this.#filterData();
374
+
375
+ // now request new data
376
+ try {
377
+ let url = this.#srcUrl;
378
+
379
+ /** @type {{ method?: string, body?: FormData, timeout: number }} */
380
+ const options = { timeout: requestTimeout(this.dataset.timeout) };
381
+
382
+ if (this.#srcForm) {
383
+ const formElement = /** @type {HTMLFormElement} */ (document.getElementById(this.#srcForm));
384
+ if (formElement) {
385
+ const formData = new FormData(formElement);
386
+ // read attributes, since a field named "action" or "method" hides the form's property of that name
387
+ const action = formActionUrl(formElement.getAttribute('action'));
388
+ if (!action) {
389
+ throw new FetchError('The filter form\'s action is not a URL.');
390
+ }
391
+ if (formElement.getAttribute('method')?.toUpperCase() === HttpMethods.POST) {
392
+ url = action.href;
393
+ options.body = formData;
394
+ options.method = HttpMethods.POST;
395
+ } else {
396
+ // GET can't have a body, so the fields go in the query string like a normal form submit
397
+ url = formDataToUrl(action, formData).href;
398
+ }
399
+
400
+ this.#saveSetting(TableSettings.FormData, JSON.stringify(this.#formSettings(formElement)));
401
+ }
402
+ }
403
+
404
+ const json = await fetchJsonArray(url, options);
405
+
406
+ this.#rows = json.map((x, index) => ({ ...x, _index: index }));
407
+ } catch (ex) {
408
+ console.error(ex);
409
+ this.#rows = [];
410
+ this.#error = true;
411
+ } finally {
412
+ this.#loading = false;
413
+ }
414
+
415
+ // try to navigate to the original page after reloading data
416
+ if (originalPage) {
417
+ this.#currentPage = originalPage;
418
+ this.#saveSetting(TableSettings.CurrentPage, this.#currentPage);
419
+ }
420
+
421
+ this.#filterData();
422
+ }
423
+
424
+ /**
425
+ * Updates the DOM based on the table properties.
426
+ */
427
+ #update() {
428
+ this.#updateSearch();
429
+ this.#updateRowNumbers();
430
+ this.#updatePageButtons();
431
+ this.#updateStatus();
432
+ this.#updateSortHeaders();
433
+ this.#updateRows();
434
+ this.#announce();
435
+ }
436
+
437
+ /**
438
+ * Enable/disable search input.
439
+ */
440
+ #updateSearch() {
441
+ const searchInput = /** @type {HTMLInputElement} */ (this.getElement(TableElements.Search));
442
+ if (searchInput) {
443
+ searchInput.disabled = this.#loading || this.#error;
444
+ }
445
+ }
446
+ /**
447
+ * Updates the start, end, and total numbers.
448
+ */
449
+ #updateRowNumbers() {
450
+ const startRowSpan = this.getElement(TableElements.StartRow);
451
+ if (startRowSpan) {
452
+ const startRowNum = this.#filteredRowTotal ? (this.#currentPage * this.#perPage) + 1 : 0;
453
+ startRowSpan.textContent = `${this.#loading || this.#error ? 0 : startRowNum}`;
454
+ }
455
+
456
+ const endRowSpan = this.getElement(TableElements.EndRow);
457
+ if (endRowSpan) {
458
+ const endRowNum = this.#filteredRowTotal ? Math.min((this.#currentPage + 1) * this.#perPage, this.#filteredRowTotal) : 0;
459
+ endRowSpan.textContent = `${this.#loading || this.#error ? 0 : endRowNum}`;
460
+ }
461
+
462
+ const filteredRowsSpan = this.getElement(TableElements.FilteredRows);
463
+ if (filteredRowsSpan) {
464
+ filteredRowsSpan.textContent = `${this.#loading || this.#error ? 0 : this.#filteredRowTotal}`;
465
+ }
466
+
467
+ const maxResultsSpan = this.getElement(TableElements.MaxResults);
468
+ if (maxResultsSpan) {
469
+ maxResultsSpan.hidden = !this.#maxResults || this.#rows.length <= this.#maxResults;
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Enable/disable paging buttons.
475
+ */
476
+ #updatePageButtons() {
477
+ const shouldDisable = this.#loading || this.#error;
478
+
479
+ const firstPageButton = /** @type {HTMLButtonElement} */ (this.getElement(TableElements.FirstPage));
480
+ if (firstPageButton) {
481
+ firstPageButton.disabled = shouldDisable || this.#currentPage === 0;
482
+ }
483
+
484
+ const previousPageButton = /** @type {HTMLButtonElement} */ (this.getElement(TableElements.PreviousPage));
485
+ if (previousPageButton) {
486
+ previousPageButton.disabled = shouldDisable || this.#currentPage === 0;
487
+ }
488
+
489
+ const nextPageButton = /** @type {HTMLButtonElement} */ (this.getElement(TableElements.NextPage));
490
+ if (nextPageButton) {
491
+ nextPageButton.disabled = shouldDisable || this.#currentPage === this.#maxPage;
492
+ }
493
+
494
+ const lastPageButton = /** @type {HTMLButtonElement} */ (this.getElement(TableElements.LastPage));
495
+ if (lastPageButton) {
496
+ lastPageButton.disabled = shouldDisable || this.#currentPage === this.#maxPage;
497
+ }
498
+
499
+ const tablePerPageSelect = /** @type {HTMLSelectElement} */ (this.getElement(TableElements.PerPage));
500
+ if (tablePerPageSelect) {
501
+ tablePerPageSelect.disabled = shouldDisable;
502
+ }
503
+ }
504
+
505
+ /**
506
+ * Shows/hides the table loading and error indicators.
507
+ */
508
+ #updateStatus() {
509
+ const status = [
510
+ [TableElements.Loading, !this.#loading],
511
+ [TableElements.Error, !this.#error],
512
+ [TableElements.Empty, this.#loading || this.#error || this.#filteredRowTotal !== 0],
513
+ ];
514
+ for (const [key, hidden] of status) {
515
+ const el = this.getElement(key);
516
+ if (el) {
517
+ el.hidden = hidden;
518
+ }
519
+ }
520
+
521
+ // hide the status row when it has nothing to show, so it doesn't leave an empty row above the data
522
+ const statusRow = this.getElement(TableElements.Status);
523
+ if (statusRow) {
524
+ statusRow.hidden = status.every(([, hidden]) => hidden);
525
+ }
526
+ }
527
+
528
+ /**
529
+ * Marks each sorted header with `aria-sort`, which says the direction to screen readers and draws the arrow in CSS.
530
+ */
531
+ #updateSortHeaders() {
532
+ const headers = /** @type {HTMLElement[]} */ ([...this.querySelectorAll('th[data-property]')]);
533
+ for (const th of headers) {
534
+ const sortOrder = this.#sortOrder(th.dataset.property);
535
+ if (sortOrder === SortDirection.Asc) {
536
+ th.setAttribute('aria-sort', 'ascending');
537
+ } else if (sortOrder === SortDirection.Desc) {
538
+ th.setAttribute('aria-sort', 'descending');
539
+ } else {
540
+ th.removeAttribute('aria-sort');
541
+ }
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Tells screen reader users what the table shows now, in the page's own words: an error, that it's empty, or the row counts.
547
+ */
548
+ #announce() {
549
+ // not while loading, nor as the page loads, when the table isn't what the user is doing
550
+ if (this.#announced === undefined || this.#loading) {
551
+ return;
552
+ }
553
+
554
+ const message = [TableElements.Error, TableElements.Empty].map(x => this.getElement(x)).find(x => x && !x.hidden);
555
+ const counts = this.getElement(TableElements.StartRow)?.parentElement;
556
+ const text = (message ?? (counts?.querySelector('button, input, select') ? undefined : counts))?.textContent ?? '';
557
+ if (text !== this.#announced) {
558
+ this.#announced = text;
559
+ announce(text);
560
+ }
561
+ }
562
+
563
+ /**
564
+ * Determines which type of sorting to use to display sort icon.
565
+ * @param {string} property Property to find sort icon for.
566
+ * @returns {SortDirection|undefined} Order of sorting for this property.
567
+ */
568
+ #sortOrder(property) {
569
+ const index = property ? this.#tableSorts.findIndex(x => x.property === property) : -1;
570
+ return index === -1 ? undefined : this.#tableSorts[index].direction;
571
+ }
572
+
573
+ /**
574
+ * Removes existing table rows and renders new rows using the filtered data.
575
+ */
576
+ #updateRows() {
577
+ const rows = this.querySelectorAll(`tbody tr:not([data-table-${TableElements.Status}])`);
578
+ for (const x of rows) {
579
+ x.remove();
580
+ }
581
+
582
+ const tbody = this.querySelector('tbody');
583
+ if (!tbody) {
584
+ throw new DOMException('Table body missing.');
585
+ }
586
+ const template = tbody.querySelector('template');
587
+ if (!template) {
588
+ throw new DOMException('Table row template missing.');
589
+ }
590
+
591
+ // reading innerHTML serializes the template, so do it once rather than for every row
592
+ const rowTemplate = template.innerHTML;
593
+ const html = this.#filteredRows.map(row => renderTemplate(rowTemplate, row)).join('\n');
594
+ tbody.insertAdjacentHTML('beforeend', html);
595
+ }
596
+
597
+ /**
598
+ * Load a value from session storage.
599
+ * @param {string} name Key to store the value as.
600
+ * @returns {string} Value from session storage if found, else null.
601
+ */
602
+ #loadSetting(name) {
603
+ // without data-key there's nothing to tell this table's settings from another table's, so nothing is saved
604
+ return this.#key ? readStorage('sessionStorage', `${this.#key}_${name}`) : null;
605
+ }
606
+
607
+ /**
608
+ * Saves a value to session storage.
609
+ * @param {string} name Key to save the value to.
610
+ * @param {string|number} value Value to save to storage.
611
+ */
612
+ #saveSetting(name, value) {
613
+ if (this.#key) {
614
+ writeStorage('sessionStorage', `${this.#key}_${name}`, value.toString());
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Create a new array of results, filter by the search query, and sort.
620
+ */
621
+ #filterData() {
622
+ // only search the properties the table shows, so a row doesn't match on a value the user can't see, like its id
623
+ const properties = [...this.querySelectorAll('th[data-property]')].map(x => /** @type {HTMLElement} */ (x).dataset.property ?? '');
624
+ let filteredData = this.#search
625
+ ? (this.#rows?.filter(filterArray.bind(null, this.#search, properties)) ?? [])
626
+ : [...(this.#rows ?? [])];
627
+
628
+ if (this.#maxResults) {
629
+ filteredData = filteredData.slice(0, this.#maxResults);
630
+ }
631
+
632
+ // sort the new array
633
+ if (filteredData.length) {
634
+ filteredData.sort(this.#tableSorts?.length ? sortedCompare.bind(null, this.#tableSorts) : indexedCompare);
635
+ }
636
+
637
+ // cache the total number of filtered records and max number of pages for paging
638
+ this.#filteredRowTotal = filteredData.length;
639
+ this.#maxPage = Math.max(Math.ceil(this.#filteredRowTotal / this.#perPage) - 1, 0);
640
+ if (this.#currentPage > this.#maxPage) {
641
+ this.#currentPage = 0;
642
+ this.#saveSetting(TableSettings.CurrentPage, 0);
643
+ }
644
+
645
+ // determine the correct slice of data for the current page, and reassign our array to trigger the update
646
+ this.#filteredRows = filteredData.slice(this.#perPage * this.#currentPage, (this.#perPage * this.#currentPage) + this.#perPage);
647
+
648
+ this.#update();
649
+ }
650
+
651
+ /**
652
+ * Handle input in search box and filter data.
653
+ * @param {InputEvent} event Input event to get search value from.
654
+ */
655
+ #onSearchInput(event) {
656
+ if (this.#loading || this.#error) {
657
+ return;
658
+ }
659
+
660
+ const target = /** @type {HTMLInputElement} */ (event?.target);
661
+ const newValue = target?.value;
662
+ if (this.#debounceTimer) {
663
+ clearTimeout(this.#debounceTimer);
664
+ }
665
+ this.#debounceTimer = window.setTimeout(() => {
666
+ if (this.#search !== newValue) {
667
+ this.#currentPage = 0;
668
+ this.#saveSetting(TableSettings.CurrentPage, 0);
669
+ }
670
+
671
+ this.#announced ??= '';
672
+ this.#search = newValue;
673
+ this.#saveSetting(TableSettings.Search, newValue);
674
+
675
+ this.#filterData();
676
+ }, 250);
677
+ }
678
+
679
+ /**
680
+ * Handle input for per page select box and update data to display.
681
+ * @param {InputEvent} event Input event to get per page value from.
682
+ */
683
+ #onPerPageChange(event) {
684
+ if (this.#loading || this.#error) {
685
+ return;
686
+ }
687
+
688
+ const target = /** @type {HTMLSelectElement} */ (event?.target);
689
+ const newVal = Number(target?.value ?? '10');
690
+ if (this.#perPage !== newVal) {
691
+ this.#currentPage = 0;
692
+ this.#saveSetting(TableSettings.CurrentPage, 0);
693
+ }
694
+
695
+ this.#announced ??= '';
696
+ this.#perPage = newVal;
697
+ this.#saveSetting(TableSettings.PerPage, newVal);
698
+
699
+ this.#filterData();
700
+ }
701
+
702
+ /**
703
+ * Move to specific page of table.
704
+ * @param {number} page Page to move to, zero based.
705
+ */
706
+ #setPage(page) {
707
+ if (this.#loading || this.#error) {
708
+ return;
709
+ }
710
+
711
+ this.#announced ??= '';
712
+ this.#currentPage = page < 0 || page > this.#maxPage ? 0 : page;
713
+ this.#saveSetting(TableSettings.CurrentPage, this.#currentPage);
714
+ this.#filterData();
715
+ }
716
+
717
+ /**
718
+ * Handle click in table header to sort by a column.
719
+ * @param {HTMLElement} elem TH that was clicked on.
720
+ */
721
+ #onSortClick(elem) {
722
+ if (this.#loading || this.#error) {
723
+ return;
724
+ }
725
+
726
+ const { property } = elem.dataset;
727
+ if (!property) {
728
+ return;
729
+ }
730
+
731
+ const index = this.#tableSorts.findIndex(x => x.property === property);
732
+ if (index === -1) {
733
+ this.#tableSorts.push({ property, direction: SortDirection.Asc });
734
+ } else if (this.#tableSorts[index].direction === SortDirection.Asc) {
735
+ this.#tableSorts[index].direction = SortDirection.Desc;
736
+ } else {
737
+ this.#tableSorts = this.#tableSorts.filter(x => x.property !== property);
738
+ }
739
+
740
+ this.#saveSetting(TableSettings.Sort, JSON.stringify(this.#tableSorts));
741
+
742
+ this.#filterData();
743
+ }
744
+
745
+ /**
746
+ * Lets user try to reload data in case of a failure.
747
+ */
748
+ async #onRetryClick() {
749
+ if (!this.#loading) {
750
+ this.#announced ??= '';
751
+ await this.#fetchData();
752
+ }
753
+ }
754
+ }
755
+
756
+ defineElement('nilla-table', Table);
757
+
758
+ export default Table;