athena-ui-js 2.5.1 → 2.6.0

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.
@@ -1,825 +1,837 @@
1
- //tableGenerator for Athena UI
2
- //Author: Csaba Tóth https://github.com/csabatibortoth/
3
- //LICENCE: MIT
4
- //Repository: https://github.com/csabatibortoth/athena-ui
5
-
6
- import { downloadFile, toCsv } from "../../core/csv.js";
7
- import { asHandle, resolveElement } from "../../core/dom.js";
8
- import { translate } from "../../core/i18n.js";
9
- import { animate, fadeIn, prefersReducedMotion } from "../../core/motion.js";
10
- import { clampWidth, virtualWindow } from "../../core/tableMath.js";
11
-
12
- const el = (tag, className, text) => {
13
- const element = document.createElement(tag);
14
- if (className) element.className = className;
15
- if (text != null) element.textContent = text;
16
- return element;
17
- };
18
-
19
- const addClasses = (node, classes) => {
20
- for (const name of [classes].flat()) if (name) node.classList.add(...String(name).split(/\s+/).filter(Boolean));
21
- };
22
-
23
- const compare = (a, b) =>
24
- typeof a === "number" && typeof b === "number"
25
- ? a - b
26
- : String(a ?? "").localeCompare(String(b ?? ""), undefined, { numeric: true });
27
-
28
- /**
29
- * Generates a table (optional filter box, sortable headers, pagination, row selection, inline
30
- * editing, resizable columns, virtual scrolling, CSV export) and appends it to its parent.
31
- *
32
- * @param {object} options
33
- * @param {string|Element} [options.parent] id or element, defaults to "wrapper"
34
- * @param {string} [options.id] id of the table wrapper (default: "table")
35
- * @param {string} [options.class] extra CSS class of the table
36
- * @param {string} [options.caption]
37
- * @param {{key: string, label?: string, width?: number, sortable?: boolean, editable?: boolean, align?: "left"|"center"|"right", title?: boolean,
38
- * format?: (value, row) => string, render?: (row: object, value) => (string|Node)}[]} options.columns
39
- * `format` writes the text of a cell; `render` builds its content instead (a badge, a link, buttons: an element, or text). Every cell carries its column
40
- * label in `data-label`, so a stylesheet can show a row as a block on a narrow screen, with the label next to the value.
41
- * @param {object[]} [options.rows] row objects, read by column key
42
- * @param {boolean} [options.sortable=true] click on a header sorts by it
43
- * @param {boolean} [options.filter=false] show a text filter above the table
44
- * @param {number} [options.pageSize=0] rows per page, 0 disables pagination
45
- * @param {boolean} [options.selectable=false] checkbox column; the header checkbox selects every filtered row
46
- * @param {boolean} [options.resizableColumns=false] drag the edge of a header (or use the arrow keys on it) to resize;
47
- * double click resets the width
48
- * @param {{height?: number, rowHeight?: number, overscan?: number}|boolean} [options.virtual] render only the rows
49
- * in view, for lists of thousands of rows. Rows have a fixed height (default 36 px) and the table scrolls
50
- * inside `height` (default 400 px). Replaces pagination.
51
- * @param {(key: string, width: number) => void} [options.onColumnResize]
52
- * @param {(rows: object[]) => void} [options.onSelectionChange]
53
- * @param {(row: object, key: string, value, oldValue) => (boolean|void)} [options.onEdit] called after an edit
54
- * of an `editable` column (double click, or Enter / F2 on the focused cell). Return false to reject it.
55
- * @param {(row: object) => void} [options.onRowClick]
56
- * @param {string} [options.emptyText]
57
- * @param {(row: object, column: object) => (string|string[]|null|undefined)} [options.cellClass] CSS class(es) for a cell
58
- * @param {(row: object) => (string|string[]|null|undefined)} [options.rowClass] CSS class(es) for a row
59
- * @param {boolean} [options.focusableRows=false] rows are reachable with Tab and, with `onRowClick`, opened with Enter and Space
60
- * @param {(row: object) => string} [options.rowLabel] aria-label of a focusable row
61
- * @param {"normal"|"compact"} [options.density="normal"]
62
- * @param {boolean} [options.wrap] true lets long text wrap, false keeps one line with an ellipsis (default: wrap, except in virtual tables)
63
- * @param {(query: {page: number, pageSize: number, cursor: *, sort: ({key: string, descending: boolean}|null), filter: string}) =>
64
- * Promise<{rows: object[], total?: number, nextCursor?: *}>} [options.dataSource] load the rows from a server instead of
65
- * keeping them all in the browser. Sorting, the filter box and the pager call it again. Answer with `total` for numbered pages
66
- * (`page` is 0-based), or with `nextCursor` for a "Load more" button (`cursor` is what the last answer gave, undefined for the
67
- * first request; the rows are appended). A failed request shows the error with a Retry button.
68
- * Together with `virtual` the list scrolls like one of `total` rows (every answer must carry `total`): the rows in view are asked for
69
- * in chunks of `chunkSize` (`page` is the chunk number), rows that have not arrived yet show a placeholder, and sorting or the filter
70
- * start again from the top.
71
- * @param {number} [options.chunkSize=50] rows per request of a data source with `virtual`
72
- * @param {boolean} [options.animateRows=false] rows slide to their new place when the table is sorted, filtered or changes page, and new rows fade in
73
- * (at most 60 rows are animated, none under reduced motion, none in a virtual table)
74
- * @param {number} [options.filterDelay=300] ms to wait after typing before the data source is asked
75
- * @param {{label: string, onclick: (row: object) => void, danger?: boolean, hidden?: (row: object) => boolean, ariaLabel?: (row: object) => string}[]} [options.rowActions]
76
- * a column of buttons at the end of every row
77
- * Column extras: `render(row, value)` returns text or a Node (built by the caller, so safe by construction), `align`
78
- * ("left" | "center" | "right"), `title` (false switches the tooltip with the full text off).
79
- * @returns {{element: HTMLElement, update: Function, destroy: Function, setRows: Function, getSelected: () => object[], clearSelection: Function,
80
- * getColumnWidths: () => Object<string, number>, toCsv: () => string, exportCsv: (filename?: string) => void}}
81
- */
82
- export function generateTable(options = {}) {
83
- const {
84
- parent = "wrapper", id = "table", columns = [], sortable = true,
85
- filter = false, selectable = false, resizableColumns = false, onRowClick, onSelectionChange
86
- } = options;
87
- const remote = typeof options.dataSource === "function";
88
- const rowActions = options.rowActions?.length ? options.rowActions : null;
89
- const virtual = options.virtual
90
- ? { height: 400, rowHeight: 36, overscan: 5, ...(options.virtual === true ? {} : options.virtual) }
91
- : null;
92
- const remoteVirtual = remote && Boolean(virtual);
93
- const chunkSize = Math.max(1, options.chunkSize ?? 50);
94
- const chunks = new Map(); // chunk number -> "loading" | "done" | "failed" (remote virtual)
95
- let flushTimer = 0;
96
- const pageSize = virtual ? 0 : (options.pageSize ?? (remote ? 25 : 0));
97
- // What the data source told us: { loading, error, total, nextCursor, cursorMode }
98
- const server = { loading: false, error: null, total: null, nextCursor: undefined, cursorMode: false, request: 0 };
99
- const colCount = () => columns.length + (selectable ? 1 : 0) + (rowActions ? 1 : 0);
100
- const host = resolveElement(parent) ?? document.body;
101
- let rows = [...(options.rows ?? [])];
102
- let current = rows; // filtered and sorted rows
103
- const selected = new Set();
104
- const widths = {}; // column key -> px, set by the user (or by options)
105
- for (const col of columns) if (col.width) widths[col.key] = col.width;
106
- const state = { sortKey: null, descending: false, page: 0, query: "" };
107
- let windowKey = "";
108
-
109
- const root = el("div", "athena-table-wrapper");
110
- root.id = id;
111
- const table = el("table", `athena-table ${options.class ?? ""}`.trim());
112
- if (resizableColumns) table.classList.add("athena-table-resizable");
113
- if (options.density === "compact") table.classList.add("athena-table-compact");
114
- if (options.wrap === true) table.classList.add("athena-table-wrap");
115
- else if (options.wrap === false) table.classList.add("athena-table-nowrap");
116
- let scroller = null;
117
- if (virtual) {
118
- table.classList.add("athena-table-virtual");
119
- scroller = el("div", "athena-table-scroll");
120
- scroller.style.maxHeight = `${virtual.height}px`;
121
- scroller.style.setProperty("--row-height", `${virtual.rowHeight}px`);
122
- scroller.tabIndex = 0;
123
- scroller.setAttribute("role", "region");
124
- scroller.setAttribute("aria-label", options.caption ?? id);
125
- }
126
- if (filter) {
127
- const filterInput = el("input", "athena-table-filter");
128
- filterInput.type = "search";
129
- filterInput.placeholder = translate("filter");
130
- filterInput.setAttribute("aria-label", translate("filter"));
131
- let filterTimer = 0;
132
- filterInput.addEventListener("input", () => {
133
- state.query = remote ? filterInput.value.trim() : filterInput.value.toLowerCase();
134
- state.page = 0;
135
- if (scroller) scroller.scrollTop = 0;
136
- if (!remote) return render();
137
- clearTimeout(filterTimer);
138
- filterTimer = setTimeout(() => load({ reset: true }), options.filterDelay ?? 300);
139
- });
140
- root.append(filterInput);
141
- }
142
- if (scroller) {
143
- scroller.append(table);
144
- root.append(scroller);
145
- } else {
146
- root.append(table);
147
- }
148
- const pager = pageSize > 0 ? el("div", "athena-table-pager") : null;
149
- if (pager) root.append(pager);
150
- host.append(root);
151
-
152
- function visibleRows() {
153
- if (remote) return rows; // the server filtered, sorted and paged them
154
- let result = rows;
155
- if (state.query) {
156
- result = result.filter(row =>
157
- columns.some(col => String(row[col.key] ?? "").toLowerCase().includes(state.query)));
158
- }
159
- if (state.sortKey) {
160
- const dir = state.descending ? -1 : 1;
161
- result = [...result].sort((a, b) => dir * compare(a[state.sortKey], b[state.sortKey]));
162
- }
163
- return result;
164
- }
165
-
166
- const selectionChanged = () => onSelectionChange?.([...selected]);
167
-
168
- /* ------------------COLUMN WIDTHS------------------- */
169
-
170
- const totalWidth = () => Object.keys(widths).length === columns.length
171
- ? columns.reduce((sum, col) => sum + widths[col.key], 0) + (selectable ? 40 : 0)
172
- : 0;
173
-
174
- function renderColgroup() {
175
- const group = el("colgroup");
176
- if (selectable) {
177
- const col = el("col");
178
- col.style.width = "40px";
179
- group.append(col);
180
- }
181
- for (const column of columns) {
182
- const col = el("col");
183
- if (widths[column.key]) col.style.width = `${widths[column.key]}px`;
184
- group.append(col);
185
- }
186
- return group;
187
- }
188
-
189
- // Freezes the current widths, so dragging one edge does not move the others.
190
- function freezeWidths() {
191
- if (Object.keys(widths).length === columns.length) return;
192
- const heads = table.querySelectorAll("thead th:not(.athena-table-select)");
193
- columns.forEach((col, i) => { widths[col.key] ??= clampWidth(heads[i]?.offsetWidth ?? 120); });
194
- }
195
-
196
- function applyWidths() {
197
- const group = table.querySelector("colgroup");
198
- if (!group) return;
199
- const cols = [...group.children].slice(selectable ? 1 : 0);
200
- columns.forEach((col, i) => { if (widths[col.key]) cols[i].style.width = `${widths[col.key]}px`; });
201
- // With every width known the table is laid out by them, so dragging one edge moves nothing else.
202
- const total = totalWidth();
203
- table.style.tableLayout = total ? "fixed" : "";
204
- table.style.width = total ? `${total}px` : "";
205
- }
206
-
207
- function setWidth(col, width) {
208
- freezeWidths();
209
- widths[col.key] = clampWidth(width, col.minWidth ?? 40, col.maxWidth ?? 1200);
210
- applyWidths();
211
- options.onColumnResize?.(col.key, widths[col.key]);
212
- }
213
-
214
- function makeResizer(th, col) {
215
- const handle = el("span", "athena-col-resizer");
216
- handle.setAttribute("role", "separator");
217
- handle.setAttribute("aria-orientation", "vertical");
218
- handle.setAttribute("aria-label", `${translate("resizeColumn")}: ${col.label ?? col.key}`);
219
- handle.tabIndex = 0;
220
- // The handle sits inside a sortable header, so it must not trigger the sort.
221
- handle.addEventListener("click", e => e.stopPropagation());
222
- handle.addEventListener("keydown", e => {
223
- e.stopPropagation();
224
- const step = e.shiftKey ? 50 : 10;
225
- if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
226
- e.preventDefault();
227
- freezeWidths();
228
- setWidth(col, widths[col.key] + (e.key === "ArrowRight" ? step : -step));
229
- }
230
- });
231
- handle.addEventListener("dblclick", e => {
232
- e.stopPropagation();
233
- delete widths[col.key];
234
- if (col.width) widths[col.key] = col.width;
235
- if (!Object.keys(widths).length) {
236
- table.style.tableLayout = "";
237
- table.style.width = "";
238
- }
239
- render();
240
- });
241
- handle.addEventListener("pointerdown", e => {
242
- e.preventDefault();
243
- e.stopPropagation();
244
- freezeWidths();
245
- const startX = e.clientX;
246
- const startWidth = widths[col.key];
247
- try {
248
- handle.setPointerCapture(e.pointerId);
249
- } catch { /* the pointer is gone already */ }
250
- handle.classList.add("resizing");
251
- const move = ev => setWidth(col, startWidth + (ev.clientX - startX));
252
- const stop = () => {
253
- handle.classList.remove("resizing");
254
- handle.removeEventListener("pointermove", move);
255
- handle.removeEventListener("pointerup", stop);
256
- handle.removeEventListener("pointercancel", stop);
257
- };
258
- handle.addEventListener("pointermove", move);
259
- handle.addEventListener("pointerup", stop);
260
- handle.addEventListener("pointercancel", stop);
261
- });
262
- th.append(handle);
263
- }
264
-
265
- /* ------------------RENDER------------------- */
266
-
267
- function renderHead(all) {
268
- const tr = el("tr");
269
- if (selectable) {
270
- const th = el("th", "athena-table-select");
271
- const box = el("input");
272
- box.type = "checkbox";
273
- box.setAttribute("aria-label", translate("selectAll"));
274
- const chosen = all.filter(row => selected.has(row)).length;
275
- box.checked = all.length > 0 && chosen === all.length;
276
- box.indeterminate = chosen > 0 && chosen < all.length;
277
- box.addEventListener("change", () => {
278
- all.forEach(row => (box.checked ? selected.add(row) : selected.delete(row)));
279
- selectionChanged();
280
- render();
281
- });
282
- th.append(box);
283
- tr.append(th);
284
- }
285
- for (const col of columns) {
286
- const th = el("th", null, col.label ?? col.key);
287
- th.scope = "col";
288
- if (sortable && col.sortable !== false) {
289
- th.classList.add("sortable");
290
- th.tabIndex = 0;
291
- const sort = () => {
292
- state.descending = state.sortKey === col.key && !state.descending;
293
- state.sortKey = col.key;
294
- if (remote) load({ reset: true });
295
- else render();
296
- };
297
- th.addEventListener("click", sort);
298
- th.addEventListener("keydown", e => {
299
- if (e.target === th && (e.key === "Enter" || e.key === " ")) {
300
- e.preventDefault();
301
- sort();
302
- }
303
- });
304
- if (state.sortKey === col.key) {
305
- th.append(el("span", "sort-indicator", state.descending ? " ▼" : " ▲"));
306
- th.setAttribute("aria-sort", state.descending ? "descending" : "ascending");
307
- }
308
- }
309
- if (resizableColumns) makeResizer(th, col);
310
- tr.append(th);
311
- }
312
- if (rowActions) {
313
- const th = el("th", "athena-table-actions");
314
- th.scope = "col";
315
- th.append(el("span", "athena-visually-hidden", translate("actions")));
316
- tr.append(th);
317
- }
318
- const thead = el("thead");
319
- thead.append(tr);
320
- return thead;
321
- }
322
-
323
- // Replaces the cell content with an input until the edit is confirmed (Enter, blur) or cancelled (Esc).
324
- function startEdit(td, row, col) {
325
- if (td.querySelector("input")) return;
326
- const oldValue = row[col.key];
327
- const input = el("input", "athena-table-edit");
328
- input.type = typeof oldValue === "number" ? "number" : "text";
329
- input.value = oldValue ?? "";
330
- let finished = false;
331
- const finish = commit => {
332
- if (finished) return;
333
- finished = true;
334
- if (commit && input.value !== String(oldValue ?? "")) {
335
- const value = typeof oldValue === "number" && input.value !== "" ? Number(input.value) : input.value;
336
- row[col.key] = value;
337
- if (options.onEdit?.(row, col.key, value, oldValue) === false) row[col.key] = oldValue;
338
- }
339
- render();
340
- };
341
- input.addEventListener("keydown", e => {
342
- if (e.key === "Enter") finish(true);
343
- else if (e.key === "Escape") {
344
- e.stopPropagation();
345
- finish(false);
346
- }
347
- });
348
- input.addEventListener("blur", () => finish(true));
349
- td.replaceChildren(input);
350
- input.focus();
351
- input.select();
352
- }
353
-
354
- function spacer(height) {
355
- const tr = el("tr", "athena-table-spacer");
356
- tr.setAttribute("aria-hidden", "true");
357
- tr.style.height = `${height}px`;
358
- const td = el("td");
359
- td.colSpan = colCount();
360
- tr.append(td);
361
- return tr;
362
- }
363
-
364
- const rowOf = new WeakMap(); // the element of a row -> its row object, to find the same row again after a redraw (animateRows)
365
- let rendered = false;
366
-
367
- function renderRow(row, index) {
368
- const tr = el("tr");
369
- if (row !== undefined) rowOf.set(tr, row);
370
- if (virtual) tr.setAttribute("aria-rowindex", String(index + 2));
371
- if (row === undefined) {
372
- // A row of a data source that has not arrived yet
373
- tr.className = "athena-table-placeholder";
374
- tr.setAttribute("aria-busy", "true");
375
- const td = el("td", null, "…");
376
- td.colSpan = colCount();
377
- tr.append(td);
378
- return tr;
379
- }
380
- addClasses(tr, options.rowClass?.(row));
381
- if (onRowClick) {
382
- tr.classList.add("clickable");
383
- tr.addEventListener("click", () => onRowClick(row));
384
- }
385
- if (options.focusableRows) {
386
- tr.tabIndex = 0;
387
- if (options.rowLabel) tr.setAttribute("aria-label", options.rowLabel(row));
388
- if (onRowClick) {
389
- tr.addEventListener("keydown", e => {
390
- if (e.target === tr && (e.key === "Enter" || e.key === " ")) {
391
- e.preventDefault();
392
- onRowClick(row);
393
- }
394
- });
395
- }
396
- }
397
- if (selectable) {
398
- const td = el("td", "athena-table-select");
399
- const box = el("input");
400
- box.type = "checkbox";
401
- box.checked = selected.has(row);
402
- tr.classList.toggle("selected", box.checked);
403
- box.addEventListener("click", e => e.stopPropagation());
404
- box.addEventListener("change", () => {
405
- if (box.checked) selected.add(row);
406
- else selected.delete(row);
407
- selectionChanged();
408
- render();
409
- });
410
- td.append(box);
411
- tr.append(td);
412
- }
413
- for (const col of columns) {
414
- const value = row[col.key];
415
- const content = col.render ? col.render(row, value) : (col.format ? col.format(value, row) : (value ?? ""));
416
- const td = el("td");
417
- td.dataset.label = col.label ?? col.key;
418
- if (content instanceof Node) td.append(content);
419
- else {
420
- td.textContent = content;
421
- // Text that may be cut off gets its full text as a tooltip.
422
- if (col.title !== false && String(content).length > 24) td.title = String(content);
423
- }
424
- if (col.align) td.classList.add(`athena-align-${col.align}`);
425
- addClasses(td, options.cellClass?.(row, col));
426
- if (col.editable) {
427
- td.classList.add("editable");
428
- td.tabIndex = 0;
429
- td.addEventListener("dblclick", () => startEdit(td, row, col));
430
- td.addEventListener("keydown", e => {
431
- if ((e.key === "Enter" || e.key === "F2") && e.target === td) {
432
- e.preventDefault();
433
- startEdit(td, row, col);
434
- }
435
- });
436
- }
437
- tr.append(td);
438
- }
439
- if (rowActions) {
440
- const td = el("td", "athena-table-actions");
441
- for (const action of rowActions) {
442
- if (action.hidden?.(row)) continue;
443
- const button = el("button", `athena-button button-${action.danger ? "danger" : "secondary"} button-small`, action.label);
444
- button.type = "button";
445
- if (action.ariaLabel) button.setAttribute("aria-label", action.ariaLabel(row));
446
- button.addEventListener("click", event => {
447
- event.stopPropagation();
448
- action.onclick(row);
449
- });
450
- td.append(button);
451
- }
452
- tr.append(td);
453
- }
454
- return tr;
455
- }
456
-
457
- function messageRow(className, text, retry) {
458
- const td = el("td", className, text);
459
- td.colSpan = Math.max(colCount(), 1);
460
- if (retry) {
461
- const button = el("button", "athena-button button-secondary button-small", translate("retry"));
462
- button.type = "button";
463
- button.addEventListener("click", () => load({}));
464
- td.append(" ", button);
465
- }
466
- const tr = el("tr");
467
- tr.append(td);
468
- return tr;
469
- }
470
-
471
- function renderBody() {
472
- const tbody = el("tbody");
473
- if (remote && server.error && !current.length) {
474
- const row = messageRow("athena-table-error", server.error, true);
475
- row.firstChild.setAttribute("role", "alert");
476
- tbody.append(row);
477
- return tbody;
478
- }
479
- if (remote && server.loading && !current.length) {
480
- tbody.append(messageRow("athena-table-loading", translate("loading")));
481
- return tbody;
482
- }
483
- if (!current.length) {
484
- tbody.append(messageRow("athena-table-empty", options.emptyText ?? translate("noData")));
485
- return tbody;
486
- }
487
- if (virtual) {
488
- const win = virtualWindow({
489
- scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
490
- rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
491
- });
492
- windowKey = `${win.start}:${win.end}`;
493
- if (remoteVirtual) ensureChunks();
494
- if (win.offsetTop) tbody.append(spacer(win.offsetTop));
495
- for (let i = win.start; i < win.end; i++) tbody.append(renderRow(current[i], i));
496
- if (win.offsetBottom) tbody.append(spacer(win.offsetBottom));
497
- return tbody;
498
- }
499
- const pageRows = remote ? current : pageSize > 0 ? current.slice(state.page * pageSize, (state.page + 1) * pageSize) : current;
500
- for (const row of pageRows) tbody.append(renderRow(row));
501
- return tbody;
502
- }
503
-
504
- function renderRemotePager() {
505
- if (server.cursorMode) {
506
- pager.hidden = !server.nextCursor && !server.error;
507
- const more = el("button", "athena-button button-secondary", translate("loadMore"));
508
- more.type = "button";
509
- more.disabled = server.loading;
510
- more.addEventListener("click", () => load({ more: true }));
511
- pager.replaceChildren(more);
512
- showPagerError();
513
- return;
514
- }
515
- const pages = server.total == null ? state.page + 2 : Math.max(1, Math.ceil(server.total / pageSize));
516
- pager.hidden = pages === 1;
517
- const go = delta => () => {
518
- state.page += delta;
519
- load({});
520
- };
521
- const prev = el("button", null, `‹ ${translate("previous")}`);
522
- prev.type = "button";
523
- prev.disabled = state.page === 0 || server.loading;
524
- prev.addEventListener("click", go(-1));
525
- const next = el("button", null, `${translate("next")} ›`);
526
- next.type = "button";
527
- next.disabled = state.page >= pages - 1 || server.loading;
528
- next.addEventListener("click", go(1));
529
- pager.replaceChildren(prev, el("span", null, ` ${translate("page", { page: state.page + 1, pages: server.total == null ? "?" : pages })} `), next);
530
- showPagerError();
531
- }
532
-
533
- // A failed request while rows are on the screen (the next page, "Load more"): say so next to the buttons.
534
- function showPagerError() {
535
- if (!server.error || !current.length) return;
536
- pager.hidden = false;
537
- const message = el("span", "athena-table-error", server.error);
538
- message.setAttribute("role", "alert");
539
- pager.append(" ", message);
540
- }
541
-
542
- function renderPager(total) {
543
- if (!pager) return;
544
- if (remote) return renderRemotePager();
545
- const pages = Math.max(1, Math.ceil(total / pageSize));
546
- state.page = Math.min(state.page, pages - 1);
547
- pager.hidden = pages === 1;
548
- const button = (text, disabled, delta) => {
549
- const b = el("button", null, text);
550
- b.type = "button";
551
- b.disabled = disabled;
552
- b.addEventListener("click", () => {
553
- state.page += delta;
554
- render();
555
- });
556
- return b;
557
- };
558
- pager.replaceChildren(
559
- button(`‹ ${translate("previous")}`, state.page === 0, -1),
560
- el("span", null, ` ${translate("page", { page: state.page + 1, pages })} `),
561
- button(`${translate("next")} ›`, state.page >= pages - 1, 1)
562
- );
563
- }
564
-
565
- function render() {
566
- const scrollTop = scroller?.scrollTop ?? 0;
567
- current = visibleRows();
568
- root.toggleAttribute("aria-busy", remote && server.loading);
569
- root.classList.toggle("athena-table-is-loading", remote && server.loading);
570
- renderPager(current.length);
571
- if (virtual) table.setAttribute("aria-rowcount", String(current.length + 1));
572
- // Where the rows were before (FLIP): the same row object is the same row
573
- const before = options.animateRows && rendered && !virtual && !prefersReducedMotion()
574
- ? new Map([...(table.tBodies[0]?.rows ?? [])].slice(0, 60).map(tr => [rowOf.get(tr), tr.getBoundingClientRect()]).filter(([row]) => row !== undefined))
575
- : null;
576
- const parts = [renderHead(current), renderBody()];
577
- if (resizableColumns || Object.keys(widths).length) parts.unshift(renderColgroup());
578
- if (options.caption) parts.unshift(el("caption", null, options.caption));
579
- table.replaceChildren(...parts);
580
- if (before?.size) {
581
- for (const tr of [...table.tBodies[0].rows].slice(0, 60)) {
582
- const row = rowOf.get(tr);
583
- if (row === undefined) continue;
584
- const old = before.get(row);
585
- if (!old) {
586
- fadeIn(tr);
587
- continue;
588
- }
589
- const now = tr.getBoundingClientRect();
590
- if (Math.abs(old.top - now.top) > 1) animate(tr, [{ translate: `0 ${old.top - now.top}px` }, { translate: "0 0" }], { easing: "cubic-bezier(0.2, 0, 0, 1)" });
591
- }
592
- }
593
- rendered = true;
594
- if (Object.keys(widths).length) applyWidths();
595
- if (scroller) scroller.scrollTop = scrollTop;
596
- }
597
-
598
- // Scrolling only swaps the body, and only when the window of rows really changed.
599
- // The scroll area is as high as the rows, up to `virtual.height`. That is also the least it can show, so a list that
600
- // starts empty (a tiny scroll area when the rows are set) still draws a full window.
601
- const viewportHeight = () => Math.max(scroller.clientHeight, Math.min(virtual.height, current.length * virtual.rowHeight));
602
-
603
- function refreshWindow(force = false) {
604
- if (remoteVirtual) ensureChunks();
605
- const win = virtualWindow({
606
- scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
607
- rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
608
- });
609
- if (!force && `${win.start}:${win.end}` === windowKey) return;
610
- const focused = document.activeElement;
611
- const keepFocus = focused && table.tBodies[0]?.contains(focused);
612
- table.tBodies[0].replaceWith(renderBody());
613
- if (keepFocus) scroller.focus({ preventScroll: true });
614
- }
615
-
616
- if (scroller) {
617
- let queued = false;
618
- scroller.addEventListener("scroll", () => {
619
- if (queued) return;
620
- queued = true;
621
- // Once per frame; the timer is for pages where frames are paused or late (a hidden tab, a busy page).
622
- let timer = 0;
623
- const run = () => {
624
- if (!queued) return;
625
- queued = false;
626
- clearTimeout(timer);
627
- refreshWindow();
628
- };
629
- requestAnimationFrame(run);
630
- timer = setTimeout(run, 100);
631
- });
632
- }
633
-
634
- /**
635
- * Asks the data source. { reset } starts again from the first page, { more } appends the next cursor page.
636
- * An answer that arrives after a newer request was made is ignored.
637
- */
638
- async function load({ reset = false, more = false } = {}) {
639
- if (remoteVirtual) return loadVirtual();
640
- if (reset) {
641
- state.page = 0;
642
- server.nextCursor = undefined;
643
- }
644
- const request = ++server.request;
645
- server.loading = true;
646
- server.error = null;
647
- render();
648
- try {
649
- const answer = await options.dataSource({
650
- page: state.page,
651
- pageSize,
652
- cursor: more ? server.nextCursor : undefined,
653
- sort: state.sortKey ? { key: state.sortKey, descending: state.descending } : null,
654
- filter: state.query
655
- });
656
- if (request !== server.request) return;
657
- const loaded = answer?.rows ?? [];
658
- server.cursorMode = answer?.nextCursor !== undefined || (more && server.cursorMode);
659
- server.nextCursor = answer?.nextCursor ?? undefined;
660
- server.total = answer?.total ?? null;
661
- rows = more ? [...rows, ...loaded] : [...loaded];
662
- if (!more) selected.clear();
663
- } catch (error) {
664
- if (request !== server.request) return;
665
- server.error = error?.message ?? String(error);
666
- if (!more) rows = [];
667
- } finally {
668
- if (request === server.request) {
669
- server.loading = false;
670
- render();
671
- if (!more) selectionChanged();
672
- }
673
- }
674
- }
675
-
676
- /* ------------------REMOTE + VIRTUAL------------------- */
677
-
678
- const status = remoteVirtual ? el("div", "athena-table-status") : null;
679
- if (status) {
680
- status.setAttribute("role", "status");
681
- root.append(status);
682
- }
683
-
684
- function updateStatus() {
685
- if (!status) return;
686
- const failed = [...chunks.values()].includes("failed");
687
- status.replaceChildren();
688
- status.hidden = !failed;
689
- if (!failed) return;
690
- status.append(el("span", "athena-table-error", server.error ?? translate("noData")), " ");
691
- const retry = el("button", "athena-button button-secondary button-small", translate("retry"));
692
- retry.type = "button";
693
- retry.addEventListener("click", () => {
694
- for (const [chunk, value] of chunks) if (value === "failed") chunks.delete(chunk);
695
- server.error = null;
696
- updateStatus();
697
- ensureChunks();
698
- });
699
- status.append(retry);
700
- }
701
-
702
- const query = () => ({ pageSize: chunkSize, cursor: undefined, sort: state.sortKey ? { key: state.sortKey, descending: state.descending } : null, filter: state.query });
703
-
704
- function place(chunk, list) {
705
- list.forEach((row, i) => {
706
- const index = chunk * chunkSize + i;
707
- if (index < rows.length) rows[index] = row;
708
- });
709
- }
710
-
711
- // Starts again: the first chunk tells how many rows there are, the others come while the person scrolls.
712
- async function loadVirtual() {
713
- const generation = ++server.request;
714
- clearTimeout(flushTimer);
715
- chunks.clear();
716
- rows = [];
717
- selected.clear();
718
- if (scroller) scroller.scrollTop = 0;
719
- server.loading = true;
720
- server.error = null;
721
- render();
722
- try {
723
- const answer = await options.dataSource({ page: 0, ...query() });
724
- if (generation !== server.request) return;
725
- if (!Number.isInteger(answer?.total) || answer.total < 0) throw new Error("A data source with virtual scrolling has to answer with total");
726
- rows = new Array(answer.total);
727
- place(0, answer.rows ?? []);
728
- chunks.set(0, "done");
729
- server.total = answer.total;
730
- } catch (error) {
731
- if (generation !== server.request) return;
732
- server.error = error?.message ?? String(error);
733
- rows = [];
734
- } finally {
735
- if (generation === server.request) {
736
- server.loading = false;
737
- render();
738
- selectionChanged();
739
- updateStatus();
740
- if (!server.error) ensureChunks();
741
- }
742
- }
743
- }
744
-
745
- async function loadChunk(chunk, generation) {
746
- chunks.set(chunk, "loading");
747
- try {
748
- const answer = await options.dataSource({ page: chunk, ...query() });
749
- if (generation !== server.request) return;
750
- place(chunk, answer?.rows ?? []);
751
- chunks.set(chunk, "done");
752
- } catch (error) {
753
- if (generation !== server.request) return;
754
- chunks.set(chunk, "failed");
755
- server.error = error?.message ?? String(error);
756
- } finally {
757
- if (generation === server.request) {
758
- refreshWindow(true);
759
- updateStatus();
760
- }
761
- }
762
- }
763
-
764
- // Asks for the chunks under the rows in view (and the rows around them). Waits a moment, so scrolling past does not ask for everything.
765
- function ensureChunks() {
766
- clearTimeout(flushTimer);
767
- const generation = server.request;
768
- flushTimer = setTimeout(() => {
769
- if (generation !== server.request || !rows.length) return;
770
- const win = virtualWindow({
771
- scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
772
- rowHeight: virtual.rowHeight, total: rows.length, overscan: virtual.overscan
773
- });
774
- const first = Math.floor(win.start / chunkSize);
775
- const last = Math.floor((win.end - 1) / chunkSize);
776
- for (let chunk = first; chunk <= last; chunk++) if (!chunks.has(chunk)) loadChunk(chunk, generation);
777
- }, 40);
778
- }
779
-
780
- // The window of rows depends on the height of the scroll area, which is unknown while the list is empty or
781
- // not on screen yet: measure again whenever it changes size.
782
- if (scroller && typeof ResizeObserver !== "undefined") {
783
- let lastHeight = 0;
784
- new ResizeObserver(() => {
785
- const height = scroller.clientHeight;
786
- if (height === lastHeight) return;
787
- lastHeight = height;
788
- refreshWindow();
789
- }).observe(scroller);
790
- }
791
-
792
- render();
793
- if (remote) load({ reset: true });
794
- return asHandle({
795
- element: root,
796
- /** Asks the data source again (the first page, keeping sort and filter). Resolves when the answer is shown. */
797
- reload: () => (remote ? load({ reset: true }) : Promise.resolve()),
798
- // update() draws the table again; update({ rows }) also replaces the rows.
799
- update(next) {
800
- if (next?.rows) this.setRows(next.rows);
801
- else render();
802
- return this;
803
- },
804
- setRows(newRows) {
805
- rows = [...newRows];
806
- selected.clear();
807
- state.page = 0;
808
- if (scroller) scroller.scrollTop = 0;
809
- render();
810
- selectionChanged();
811
- },
812
- getSelected: () => [...selected],
813
- clearSelection() {
814
- selected.clear();
815
- render();
816
- selectionChanged();
817
- },
818
- getColumnWidths: () => ({ ...widths }),
819
- // The filtered and sorted rows as CSV text
820
- toCsv: () => toCsv(columns, current.filter(row => row !== undefined)),
821
- exportCsv(filename = "table.csv") {
822
- downloadFile(filename, toCsv(columns, current.filter(row => row !== undefined)));
823
- }
824
- });
825
- }
1
+ //tableGenerator for Athena UI
2
+ //Author: Csaba Tóth https://github.com/csabatibortoth/
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ import { downloadFile, toCsv } from "../../core/csv.js";
7
+ import { asHandle, resolveElement } from "../../core/dom.js";
8
+ import { translate } from "../../core/i18n.js";
9
+ import { animate, fadeIn, prefersReducedMotion } from "../../core/motion.js";
10
+ import { clampWidth, virtualWindow } from "../../core/tableMath.js";
11
+
12
+ const el = (tag, className, text) => {
13
+ const element = document.createElement(tag);
14
+ if (className) element.className = className;
15
+ if (text != null) element.textContent = text;
16
+ return element;
17
+ };
18
+
19
+ const addClasses = (node, classes) => {
20
+ for (const name of [classes].flat()) if (name) node.classList.add(...String(name).split(/\s+/).filter(Boolean));
21
+ };
22
+
23
+ const compare = (a, b) =>
24
+ typeof a === "number" && typeof b === "number"
25
+ ? a - b
26
+ : String(a ?? "").localeCompare(String(b ?? ""), undefined, { numeric: true });
27
+
28
+ /**
29
+ * Generates a table (optional filter box, sortable headers, pagination, row selection, inline
30
+ * editing, resizable columns, virtual scrolling, CSV export) and appends it to its parent.
31
+ *
32
+ * @param {object} options
33
+ * @param {string|Element} [options.parent] id or element, defaults to "wrapper"
34
+ * @param {string} [options.id] id of the table wrapper (default: "table")
35
+ * @param {string} [options.class] extra CSS class of the table
36
+ * @param {string} [options.caption]
37
+ * @param {{key: string, label?: string, width?: number, sortable?: boolean, editable?: boolean, align?: "left"|"center"|"right", title?: boolean,
38
+ * format?: (value, row) => string, render?: (row: object, value) => (string|Node)}[]} options.columns
39
+ * `format` writes the text of a cell; `render` builds its content instead (a badge, a link, buttons: an element, or text). Every cell carries its column
40
+ * label in `data-label`, so a stylesheet can show a row as a block on a narrow screen, with the label next to the value.
41
+ * @param {object[]} [options.rows] row objects, read by column key
42
+ * @param {boolean} [options.sortable=true] click on a header sorts by it
43
+ * @param {boolean} [options.filter=false] show a text filter above the table
44
+ * @param {number} [options.pageSize=0] rows per page, 0 disables pagination
45
+ * @param {boolean} [options.selectable=false] checkbox column; the header checkbox selects every filtered row
46
+ * @param {boolean} [options.resizableColumns=false] drag the edge of a header (or use the arrow keys on it) to resize;
47
+ * double click resets the width
48
+ * @param {{height?: number, rowHeight?: number, overscan?: number}|boolean} [options.virtual] render only the rows
49
+ * in view, for lists of thousands of rows. Rows have a fixed height (default 36 px) and the table scrolls
50
+ * inside `height` (default 400 px). Replaces pagination.
51
+ * @param {(key: string, width: number) => void} [options.onColumnResize]
52
+ * @param {(rows: object[]) => void} [options.onSelectionChange]
53
+ * @param {(row: object, key: string, value, oldValue) => (boolean|void)} [options.onEdit] called after an edit
54
+ * of an `editable` column (double click, or Enter / F2 on the focused cell). Return false to reject it.
55
+ * @param {(row: object) => void} [options.onRowClick]
56
+ * @param {string} [options.emptyText]
57
+ * @param {(row: object, column: object) => (string|string[]|null|undefined)} [options.cellClass] CSS class(es) for a cell
58
+ * @param {(row: object) => (string|string[]|null|undefined)} [options.rowClass] CSS class(es) for a row
59
+ * @param {boolean} [options.focusableRows=false] rows are reachable with Tab and, with `onRowClick`, opened with Enter and Space
60
+ * @param {(row: object) => string} [options.rowLabel] aria-label of a focusable row
61
+ * @param {"normal"|"compact"} [options.density="normal"]
62
+ * @param {boolean} [options.wrap] true lets long text wrap, false keeps one line with an ellipsis (default: wrap, except in virtual tables)
63
+ * @param {(query: {page: number, pageSize: number, cursor: *, sort: ({key: string, descending: boolean}|null), filter: string}) =>
64
+ * Promise<{rows: object[], total?: number, nextCursor?: *}>} [options.dataSource] load the rows from a server instead of
65
+ * keeping them all in the browser. Sorting, the filter box and the pager call it again. Answer with `total` for numbered pages
66
+ * (`page` is 0-based), or with `nextCursor` for a "Load more" button (`cursor` is what the last answer gave, undefined for the
67
+ * first request; the rows are appended). A failed request shows the error with a Retry button.
68
+ * Together with `virtual` the list scrolls like one of `total` rows (every answer must carry `total`): the rows in view are asked for
69
+ * in chunks of `chunkSize` (`page` is the chunk number), rows that have not arrived yet show a placeholder, and sorting or the filter
70
+ * start again from the top.
71
+ * @param {number} [options.chunkSize=50] rows per request of a data source with `virtual`
72
+ * @param {boolean} [options.animateRows=false] rows slide to their new place when the table is sorted, filtered or changes page, and new rows fade in
73
+ * (at most 60 rows are animated, none under reduced motion, none in a virtual table)
74
+ * @param {boolean|number} [options.stack=false] a narrow table shows every row as a block, with the label of the column next to each value (no sideways scrolling).
75
+ * true: when the table is narrower than 600 px; a number: the width in px below which it stacks. It follows the width of the table, not of the screen,
76
+ * and the table gets the class `is-stacked` while it is stacked. Not for virtual tables (their rows have a fixed height).
77
+ * @param {number} [options.filterDelay=300] ms to wait after typing before the data source is asked
78
+ * @param {{label: string, onclick: (row: object) => void, danger?: boolean, hidden?: (row: object) => boolean, ariaLabel?: (row: object) => string}[]} [options.rowActions]
79
+ * a column of buttons at the end of every row
80
+ * Column extras: `render(row, value)` returns text or a Node (built by the caller, so safe by construction), `align`
81
+ * ("left" | "center" | "right"), `title` (false switches the tooltip with the full text off).
82
+ * @returns {{element: HTMLElement, update: Function, destroy: Function, setRows: Function, getSelected: () => object[], clearSelection: Function,
83
+ * getColumnWidths: () => Object<string, number>, toCsv: () => string, exportCsv: (filename?: string) => void}}
84
+ */
85
+ export function generateTable(options = {}) {
86
+ const {
87
+ parent = "wrapper", id = "table", columns = [], sortable = true,
88
+ filter = false, selectable = false, resizableColumns = false, onRowClick, onSelectionChange
89
+ } = options;
90
+ const remote = typeof options.dataSource === "function";
91
+ const rowActions = options.rowActions?.length ? options.rowActions : null;
92
+ const virtual = options.virtual
93
+ ? { height: 400, rowHeight: 36, overscan: 5, ...(options.virtual === true ? {} : options.virtual) }
94
+ : null;
95
+ const remoteVirtual = remote && Boolean(virtual);
96
+ const chunkSize = Math.max(1, options.chunkSize ?? 50);
97
+ const chunks = new Map(); // chunk number -> "loading" | "done" | "failed" (remote virtual)
98
+ let flushTimer = 0;
99
+ const pageSize = virtual ? 0 : (options.pageSize ?? (remote ? 25 : 0));
100
+ // What the data source told us: { loading, error, total, nextCursor, cursorMode }
101
+ const server = { loading: false, error: null, total: null, nextCursor: undefined, cursorMode: false, request: 0 };
102
+ const colCount = () => columns.length + (selectable ? 1 : 0) + (rowActions ? 1 : 0);
103
+ const host = resolveElement(parent) ?? document.body;
104
+ let rows = [...(options.rows ?? [])];
105
+ let current = rows; // filtered and sorted rows
106
+ const selected = new Set();
107
+ const widths = {}; // column key -> px, set by the user (or by options)
108
+ for (const col of columns) if (col.width) widths[col.key] = col.width;
109
+ const state = { sortKey: null, descending: false, page: 0, query: "" };
110
+ let windowKey = "";
111
+
112
+ const root = el("div", "athena-table-wrapper");
113
+ root.id = id;
114
+ const table = el("table", `athena-table ${options.class ?? ""}`.trim());
115
+ if (resizableColumns) table.classList.add("athena-table-resizable");
116
+ if (options.density === "compact") table.classList.add("athena-table-compact");
117
+ if (options.wrap === true) table.classList.add("athena-table-wrap");
118
+ else if (options.wrap === false) table.classList.add("athena-table-nowrap");
119
+ // `stack`: a row becomes a block while the table is narrower than the breakpoint (the style is in the theme: .athena-table-stackable.is-stacked)
120
+ const stackAt = options.stack === true ? 600 : Number(options.stack) || 0;
121
+ if (stackAt && !virtual) {
122
+ root.classList.add("athena-table-stackable");
123
+ const apply = () => root.classList.toggle("is-stacked", root.clientWidth > 0 && root.clientWidth < stackAt);
124
+ // Stacking changes the height of the table: do it in the next frame, or the observer reports a loop
125
+ if (typeof ResizeObserver !== "undefined") new ResizeObserver(() => requestAnimationFrame(apply)).observe(root);
126
+ apply();
127
+ }
128
+ let scroller = null;
129
+ if (virtual) {
130
+ table.classList.add("athena-table-virtual");
131
+ scroller = el("div", "athena-table-scroll");
132
+ scroller.style.maxHeight = `${virtual.height}px`;
133
+ scroller.style.setProperty("--row-height", `${virtual.rowHeight}px`);
134
+ scroller.tabIndex = 0;
135
+ scroller.setAttribute("role", "region");
136
+ scroller.setAttribute("aria-label", options.caption ?? id);
137
+ }
138
+ if (filter) {
139
+ const filterInput = el("input", "athena-table-filter");
140
+ filterInput.type = "search";
141
+ filterInput.placeholder = translate("filter");
142
+ filterInput.setAttribute("aria-label", translate("filter"));
143
+ let filterTimer = 0;
144
+ filterInput.addEventListener("input", () => {
145
+ state.query = remote ? filterInput.value.trim() : filterInput.value.toLowerCase();
146
+ state.page = 0;
147
+ if (scroller) scroller.scrollTop = 0;
148
+ if (!remote) return render();
149
+ clearTimeout(filterTimer);
150
+ filterTimer = setTimeout(() => load({ reset: true }), options.filterDelay ?? 300);
151
+ });
152
+ root.append(filterInput);
153
+ }
154
+ if (scroller) {
155
+ scroller.append(table);
156
+ root.append(scroller);
157
+ } else {
158
+ root.append(table);
159
+ }
160
+ const pager = pageSize > 0 ? el("div", "athena-table-pager") : null;
161
+ if (pager) root.append(pager);
162
+ host.append(root);
163
+
164
+ function visibleRows() {
165
+ if (remote) return rows; // the server filtered, sorted and paged them
166
+ let result = rows;
167
+ if (state.query) {
168
+ result = result.filter(row =>
169
+ columns.some(col => String(row[col.key] ?? "").toLowerCase().includes(state.query)));
170
+ }
171
+ if (state.sortKey) {
172
+ const dir = state.descending ? -1 : 1;
173
+ result = [...result].sort((a, b) => dir * compare(a[state.sortKey], b[state.sortKey]));
174
+ }
175
+ return result;
176
+ }
177
+
178
+ const selectionChanged = () => onSelectionChange?.([...selected]);
179
+
180
+ /* ------------------COLUMN WIDTHS------------------- */
181
+
182
+ const totalWidth = () => Object.keys(widths).length === columns.length
183
+ ? columns.reduce((sum, col) => sum + widths[col.key], 0) + (selectable ? 40 : 0)
184
+ : 0;
185
+
186
+ function renderColgroup() {
187
+ const group = el("colgroup");
188
+ if (selectable) {
189
+ const col = el("col");
190
+ col.style.width = "40px";
191
+ group.append(col);
192
+ }
193
+ for (const column of columns) {
194
+ const col = el("col");
195
+ if (widths[column.key]) col.style.width = `${widths[column.key]}px`;
196
+ group.append(col);
197
+ }
198
+ return group;
199
+ }
200
+
201
+ // Freezes the current widths, so dragging one edge does not move the others.
202
+ function freezeWidths() {
203
+ if (Object.keys(widths).length === columns.length) return;
204
+ const heads = table.querySelectorAll("thead th:not(.athena-table-select)");
205
+ columns.forEach((col, i) => { widths[col.key] ??= clampWidth(heads[i]?.offsetWidth ?? 120); });
206
+ }
207
+
208
+ function applyWidths() {
209
+ const group = table.querySelector("colgroup");
210
+ if (!group) return;
211
+ const cols = [...group.children].slice(selectable ? 1 : 0);
212
+ columns.forEach((col, i) => { if (widths[col.key]) cols[i].style.width = `${widths[col.key]}px`; });
213
+ // With every width known the table is laid out by them, so dragging one edge moves nothing else.
214
+ const total = totalWidth();
215
+ table.style.tableLayout = total ? "fixed" : "";
216
+ table.style.width = total ? `${total}px` : "";
217
+ }
218
+
219
+ function setWidth(col, width) {
220
+ freezeWidths();
221
+ widths[col.key] = clampWidth(width, col.minWidth ?? 40, col.maxWidth ?? 1200);
222
+ applyWidths();
223
+ options.onColumnResize?.(col.key, widths[col.key]);
224
+ }
225
+
226
+ function makeResizer(th, col) {
227
+ const handle = el("span", "athena-col-resizer");
228
+ handle.setAttribute("role", "separator");
229
+ handle.setAttribute("aria-orientation", "vertical");
230
+ handle.setAttribute("aria-label", `${translate("resizeColumn")}: ${col.label ?? col.key}`);
231
+ handle.tabIndex = 0;
232
+ // The handle sits inside a sortable header, so it must not trigger the sort.
233
+ handle.addEventListener("click", e => e.stopPropagation());
234
+ handle.addEventListener("keydown", e => {
235
+ e.stopPropagation();
236
+ const step = e.shiftKey ? 50 : 10;
237
+ if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
238
+ e.preventDefault();
239
+ freezeWidths();
240
+ setWidth(col, widths[col.key] + (e.key === "ArrowRight" ? step : -step));
241
+ }
242
+ });
243
+ handle.addEventListener("dblclick", e => {
244
+ e.stopPropagation();
245
+ delete widths[col.key];
246
+ if (col.width) widths[col.key] = col.width;
247
+ if (!Object.keys(widths).length) {
248
+ table.style.tableLayout = "";
249
+ table.style.width = "";
250
+ }
251
+ render();
252
+ });
253
+ handle.addEventListener("pointerdown", e => {
254
+ e.preventDefault();
255
+ e.stopPropagation();
256
+ freezeWidths();
257
+ const startX = e.clientX;
258
+ const startWidth = widths[col.key];
259
+ try {
260
+ handle.setPointerCapture(e.pointerId);
261
+ } catch { /* the pointer is gone already */ }
262
+ handle.classList.add("resizing");
263
+ const move = ev => setWidth(col, startWidth + (ev.clientX - startX));
264
+ const stop = () => {
265
+ handle.classList.remove("resizing");
266
+ handle.removeEventListener("pointermove", move);
267
+ handle.removeEventListener("pointerup", stop);
268
+ handle.removeEventListener("pointercancel", stop);
269
+ };
270
+ handle.addEventListener("pointermove", move);
271
+ handle.addEventListener("pointerup", stop);
272
+ handle.addEventListener("pointercancel", stop);
273
+ });
274
+ th.append(handle);
275
+ }
276
+
277
+ /* ------------------RENDER------------------- */
278
+
279
+ function renderHead(all) {
280
+ const tr = el("tr");
281
+ if (selectable) {
282
+ const th = el("th", "athena-table-select");
283
+ const box = el("input");
284
+ box.type = "checkbox";
285
+ box.setAttribute("aria-label", translate("selectAll"));
286
+ const chosen = all.filter(row => selected.has(row)).length;
287
+ box.checked = all.length > 0 && chosen === all.length;
288
+ box.indeterminate = chosen > 0 && chosen < all.length;
289
+ box.addEventListener("change", () => {
290
+ all.forEach(row => (box.checked ? selected.add(row) : selected.delete(row)));
291
+ selectionChanged();
292
+ render();
293
+ });
294
+ th.append(box);
295
+ tr.append(th);
296
+ }
297
+ for (const col of columns) {
298
+ const th = el("th", null, col.label ?? col.key);
299
+ th.scope = "col";
300
+ if (sortable && col.sortable !== false) {
301
+ th.classList.add("sortable");
302
+ th.tabIndex = 0;
303
+ const sort = () => {
304
+ state.descending = state.sortKey === col.key && !state.descending;
305
+ state.sortKey = col.key;
306
+ if (remote) load({ reset: true });
307
+ else render();
308
+ };
309
+ th.addEventListener("click", sort);
310
+ th.addEventListener("keydown", e => {
311
+ if (e.target === th && (e.key === "Enter" || e.key === " ")) {
312
+ e.preventDefault();
313
+ sort();
314
+ }
315
+ });
316
+ if (state.sortKey === col.key) {
317
+ th.append(el("span", "sort-indicator", state.descending ? " ▼" : " ▲"));
318
+ th.setAttribute("aria-sort", state.descending ? "descending" : "ascending");
319
+ }
320
+ }
321
+ if (resizableColumns) makeResizer(th, col);
322
+ tr.append(th);
323
+ }
324
+ if (rowActions) {
325
+ const th = el("th", "athena-table-actions");
326
+ th.scope = "col";
327
+ th.append(el("span", "athena-visually-hidden", translate("actions")));
328
+ tr.append(th);
329
+ }
330
+ const thead = el("thead");
331
+ thead.append(tr);
332
+ return thead;
333
+ }
334
+
335
+ // Replaces the cell content with an input until the edit is confirmed (Enter, blur) or cancelled (Esc).
336
+ function startEdit(td, row, col) {
337
+ if (td.querySelector("input")) return;
338
+ const oldValue = row[col.key];
339
+ const input = el("input", "athena-table-edit");
340
+ input.type = typeof oldValue === "number" ? "number" : "text";
341
+ input.value = oldValue ?? "";
342
+ let finished = false;
343
+ const finish = commit => {
344
+ if (finished) return;
345
+ finished = true;
346
+ if (commit && input.value !== String(oldValue ?? "")) {
347
+ const value = typeof oldValue === "number" && input.value !== "" ? Number(input.value) : input.value;
348
+ row[col.key] = value;
349
+ if (options.onEdit?.(row, col.key, value, oldValue) === false) row[col.key] = oldValue;
350
+ }
351
+ render();
352
+ };
353
+ input.addEventListener("keydown", e => {
354
+ if (e.key === "Enter") finish(true);
355
+ else if (e.key === "Escape") {
356
+ e.stopPropagation();
357
+ finish(false);
358
+ }
359
+ });
360
+ input.addEventListener("blur", () => finish(true));
361
+ td.replaceChildren(input);
362
+ input.focus();
363
+ input.select();
364
+ }
365
+
366
+ function spacer(height) {
367
+ const tr = el("tr", "athena-table-spacer");
368
+ tr.setAttribute("aria-hidden", "true");
369
+ tr.style.height = `${height}px`;
370
+ const td = el("td");
371
+ td.colSpan = colCount();
372
+ tr.append(td);
373
+ return tr;
374
+ }
375
+
376
+ const rowOf = new WeakMap(); // the element of a row -> its row object, to find the same row again after a redraw (animateRows)
377
+ let rendered = false;
378
+
379
+ function renderRow(row, index) {
380
+ const tr = el("tr");
381
+ if (row !== undefined) rowOf.set(tr, row);
382
+ if (virtual) tr.setAttribute("aria-rowindex", String(index + 2));
383
+ if (row === undefined) {
384
+ // A row of a data source that has not arrived yet
385
+ tr.className = "athena-table-placeholder";
386
+ tr.setAttribute("aria-busy", "true");
387
+ const td = el("td", null, "…");
388
+ td.colSpan = colCount();
389
+ tr.append(td);
390
+ return tr;
391
+ }
392
+ addClasses(tr, options.rowClass?.(row));
393
+ if (onRowClick) {
394
+ tr.classList.add("clickable");
395
+ tr.addEventListener("click", () => onRowClick(row));
396
+ }
397
+ if (options.focusableRows) {
398
+ tr.tabIndex = 0;
399
+ if (options.rowLabel) tr.setAttribute("aria-label", options.rowLabel(row));
400
+ if (onRowClick) {
401
+ tr.addEventListener("keydown", e => {
402
+ if (e.target === tr && (e.key === "Enter" || e.key === " ")) {
403
+ e.preventDefault();
404
+ onRowClick(row);
405
+ }
406
+ });
407
+ }
408
+ }
409
+ if (selectable) {
410
+ const td = el("td", "athena-table-select");
411
+ const box = el("input");
412
+ box.type = "checkbox";
413
+ box.checked = selected.has(row);
414
+ tr.classList.toggle("selected", box.checked);
415
+ box.addEventListener("click", e => e.stopPropagation());
416
+ box.addEventListener("change", () => {
417
+ if (box.checked) selected.add(row);
418
+ else selected.delete(row);
419
+ selectionChanged();
420
+ render();
421
+ });
422
+ td.append(box);
423
+ tr.append(td);
424
+ }
425
+ for (const col of columns) {
426
+ const value = row[col.key];
427
+ const content = col.render ? col.render(row, value) : (col.format ? col.format(value, row) : (value ?? ""));
428
+ const td = el("td");
429
+ td.dataset.label = col.label ?? col.key;
430
+ if (content instanceof Node) td.append(content);
431
+ else {
432
+ td.textContent = content;
433
+ // Text that may be cut off gets its full text as a tooltip.
434
+ if (col.title !== false && String(content).length > 24) td.title = String(content);
435
+ }
436
+ if (col.align) td.classList.add(`athena-align-${col.align}`);
437
+ addClasses(td, options.cellClass?.(row, col));
438
+ if (col.editable) {
439
+ td.classList.add("editable");
440
+ td.tabIndex = 0;
441
+ td.addEventListener("dblclick", () => startEdit(td, row, col));
442
+ td.addEventListener("keydown", e => {
443
+ if ((e.key === "Enter" || e.key === "F2") && e.target === td) {
444
+ e.preventDefault();
445
+ startEdit(td, row, col);
446
+ }
447
+ });
448
+ }
449
+ tr.append(td);
450
+ }
451
+ if (rowActions) {
452
+ const td = el("td", "athena-table-actions");
453
+ for (const action of rowActions) {
454
+ if (action.hidden?.(row)) continue;
455
+ const button = el("button", `athena-button button-${action.danger ? "danger" : "secondary"} button-small`, action.label);
456
+ button.type = "button";
457
+ if (action.ariaLabel) button.setAttribute("aria-label", action.ariaLabel(row));
458
+ button.addEventListener("click", event => {
459
+ event.stopPropagation();
460
+ action.onclick(row);
461
+ });
462
+ td.append(button);
463
+ }
464
+ tr.append(td);
465
+ }
466
+ return tr;
467
+ }
468
+
469
+ function messageRow(className, text, retry) {
470
+ const td = el("td", className, text);
471
+ td.colSpan = Math.max(colCount(), 1);
472
+ if (retry) {
473
+ const button = el("button", "athena-button button-secondary button-small", translate("retry"));
474
+ button.type = "button";
475
+ button.addEventListener("click", () => load({}));
476
+ td.append(" ", button);
477
+ }
478
+ const tr = el("tr");
479
+ tr.append(td);
480
+ return tr;
481
+ }
482
+
483
+ function renderBody() {
484
+ const tbody = el("tbody");
485
+ if (remote && server.error && !current.length) {
486
+ const row = messageRow("athena-table-error", server.error, true);
487
+ row.firstChild.setAttribute("role", "alert");
488
+ tbody.append(row);
489
+ return tbody;
490
+ }
491
+ if (remote && server.loading && !current.length) {
492
+ tbody.append(messageRow("athena-table-loading", translate("loading")));
493
+ return tbody;
494
+ }
495
+ if (!current.length) {
496
+ tbody.append(messageRow("athena-table-empty", options.emptyText ?? translate("noData")));
497
+ return tbody;
498
+ }
499
+ if (virtual) {
500
+ const win = virtualWindow({
501
+ scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
502
+ rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
503
+ });
504
+ windowKey = `${win.start}:${win.end}`;
505
+ if (remoteVirtual) ensureChunks();
506
+ if (win.offsetTop) tbody.append(spacer(win.offsetTop));
507
+ for (let i = win.start; i < win.end; i++) tbody.append(renderRow(current[i], i));
508
+ if (win.offsetBottom) tbody.append(spacer(win.offsetBottom));
509
+ return tbody;
510
+ }
511
+ const pageRows = remote ? current : pageSize > 0 ? current.slice(state.page * pageSize, (state.page + 1) * pageSize) : current;
512
+ for (const row of pageRows) tbody.append(renderRow(row));
513
+ return tbody;
514
+ }
515
+
516
+ function renderRemotePager() {
517
+ if (server.cursorMode) {
518
+ pager.hidden = !server.nextCursor && !server.error;
519
+ const more = el("button", "athena-button button-secondary", translate("loadMore"));
520
+ more.type = "button";
521
+ more.disabled = server.loading;
522
+ more.addEventListener("click", () => load({ more: true }));
523
+ pager.replaceChildren(more);
524
+ showPagerError();
525
+ return;
526
+ }
527
+ const pages = server.total == null ? state.page + 2 : Math.max(1, Math.ceil(server.total / pageSize));
528
+ pager.hidden = pages === 1;
529
+ const go = delta => () => {
530
+ state.page += delta;
531
+ load({});
532
+ };
533
+ const prev = el("button", null, `‹ ${translate("previous")}`);
534
+ prev.type = "button";
535
+ prev.disabled = state.page === 0 || server.loading;
536
+ prev.addEventListener("click", go(-1));
537
+ const next = el("button", null, `${translate("next")} ›`);
538
+ next.type = "button";
539
+ next.disabled = state.page >= pages - 1 || server.loading;
540
+ next.addEventListener("click", go(1));
541
+ pager.replaceChildren(prev, el("span", null, ` ${translate("page", { page: state.page + 1, pages: server.total == null ? "?" : pages })} `), next);
542
+ showPagerError();
543
+ }
544
+
545
+ // A failed request while rows are on the screen (the next page, "Load more"): say so next to the buttons.
546
+ function showPagerError() {
547
+ if (!server.error || !current.length) return;
548
+ pager.hidden = false;
549
+ const message = el("span", "athena-table-error", server.error);
550
+ message.setAttribute("role", "alert");
551
+ pager.append(" ", message);
552
+ }
553
+
554
+ function renderPager(total) {
555
+ if (!pager) return;
556
+ if (remote) return renderRemotePager();
557
+ const pages = Math.max(1, Math.ceil(total / pageSize));
558
+ state.page = Math.min(state.page, pages - 1);
559
+ pager.hidden = pages === 1;
560
+ const button = (text, disabled, delta) => {
561
+ const b = el("button", null, text);
562
+ b.type = "button";
563
+ b.disabled = disabled;
564
+ b.addEventListener("click", () => {
565
+ state.page += delta;
566
+ render();
567
+ });
568
+ return b;
569
+ };
570
+ pager.replaceChildren(
571
+ button(`‹ ${translate("previous")}`, state.page === 0, -1),
572
+ el("span", null, ` ${translate("page", { page: state.page + 1, pages })} `),
573
+ button(`${translate("next")} ›`, state.page >= pages - 1, 1)
574
+ );
575
+ }
576
+
577
+ function render() {
578
+ const scrollTop = scroller?.scrollTop ?? 0;
579
+ current = visibleRows();
580
+ root.toggleAttribute("aria-busy", remote && server.loading);
581
+ root.classList.toggle("athena-table-is-loading", remote && server.loading);
582
+ renderPager(current.length);
583
+ if (virtual) table.setAttribute("aria-rowcount", String(current.length + 1));
584
+ // Where the rows were before (FLIP): the same row object is the same row
585
+ const before = options.animateRows && rendered && !virtual && !prefersReducedMotion()
586
+ ? new Map([...(table.tBodies[0]?.rows ?? [])].slice(0, 60).map(tr => [rowOf.get(tr), tr.getBoundingClientRect()]).filter(([row]) => row !== undefined))
587
+ : null;
588
+ const parts = [renderHead(current), renderBody()];
589
+ if (resizableColumns || Object.keys(widths).length) parts.unshift(renderColgroup());
590
+ if (options.caption) parts.unshift(el("caption", null, options.caption));
591
+ table.replaceChildren(...parts);
592
+ if (before?.size) {
593
+ for (const tr of [...table.tBodies[0].rows].slice(0, 60)) {
594
+ const row = rowOf.get(tr);
595
+ if (row === undefined) continue;
596
+ const old = before.get(row);
597
+ if (!old) {
598
+ fadeIn(tr);
599
+ continue;
600
+ }
601
+ const now = tr.getBoundingClientRect();
602
+ if (Math.abs(old.top - now.top) > 1) animate(tr, [{ translate: `0 ${old.top - now.top}px` }, { translate: "0 0" }], { easing: "cubic-bezier(0.2, 0, 0, 1)" });
603
+ }
604
+ }
605
+ rendered = true;
606
+ if (Object.keys(widths).length) applyWidths();
607
+ if (scroller) scroller.scrollTop = scrollTop;
608
+ }
609
+
610
+ // Scrolling only swaps the body, and only when the window of rows really changed.
611
+ // The scroll area is as high as the rows, up to `virtual.height`. That is also the least it can show, so a list that
612
+ // starts empty (a tiny scroll area when the rows are set) still draws a full window.
613
+ const viewportHeight = () => Math.max(scroller.clientHeight, Math.min(virtual.height, current.length * virtual.rowHeight));
614
+
615
+ function refreshWindow(force = false) {
616
+ if (remoteVirtual) ensureChunks();
617
+ const win = virtualWindow({
618
+ scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
619
+ rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
620
+ });
621
+ if (!force && `${win.start}:${win.end}` === windowKey) return;
622
+ const focused = document.activeElement;
623
+ const keepFocus = focused && table.tBodies[0]?.contains(focused);
624
+ table.tBodies[0].replaceWith(renderBody());
625
+ if (keepFocus) scroller.focus({ preventScroll: true });
626
+ }
627
+
628
+ if (scroller) {
629
+ let queued = false;
630
+ scroller.addEventListener("scroll", () => {
631
+ if (queued) return;
632
+ queued = true;
633
+ // Once per frame; the timer is for pages where frames are paused or late (a hidden tab, a busy page).
634
+ let timer = 0;
635
+ const run = () => {
636
+ if (!queued) return;
637
+ queued = false;
638
+ clearTimeout(timer);
639
+ refreshWindow();
640
+ };
641
+ requestAnimationFrame(run);
642
+ timer = setTimeout(run, 100);
643
+ });
644
+ }
645
+
646
+ /**
647
+ * Asks the data source. { reset } starts again from the first page, { more } appends the next cursor page.
648
+ * An answer that arrives after a newer request was made is ignored.
649
+ */
650
+ async function load({ reset = false, more = false } = {}) {
651
+ if (remoteVirtual) return loadVirtual();
652
+ if (reset) {
653
+ state.page = 0;
654
+ server.nextCursor = undefined;
655
+ }
656
+ const request = ++server.request;
657
+ server.loading = true;
658
+ server.error = null;
659
+ render();
660
+ try {
661
+ const answer = await options.dataSource({
662
+ page: state.page,
663
+ pageSize,
664
+ cursor: more ? server.nextCursor : undefined,
665
+ sort: state.sortKey ? { key: state.sortKey, descending: state.descending } : null,
666
+ filter: state.query
667
+ });
668
+ if (request !== server.request) return;
669
+ const loaded = answer?.rows ?? [];
670
+ server.cursorMode = answer?.nextCursor !== undefined || (more && server.cursorMode);
671
+ server.nextCursor = answer?.nextCursor ?? undefined;
672
+ server.total = answer?.total ?? null;
673
+ rows = more ? [...rows, ...loaded] : [...loaded];
674
+ if (!more) selected.clear();
675
+ } catch (error) {
676
+ if (request !== server.request) return;
677
+ server.error = error?.message ?? String(error);
678
+ if (!more) rows = [];
679
+ } finally {
680
+ if (request === server.request) {
681
+ server.loading = false;
682
+ render();
683
+ if (!more) selectionChanged();
684
+ }
685
+ }
686
+ }
687
+
688
+ /* ------------------REMOTE + VIRTUAL------------------- */
689
+
690
+ const status = remoteVirtual ? el("div", "athena-table-status") : null;
691
+ if (status) {
692
+ status.setAttribute("role", "status");
693
+ root.append(status);
694
+ }
695
+
696
+ function updateStatus() {
697
+ if (!status) return;
698
+ const failed = [...chunks.values()].includes("failed");
699
+ status.replaceChildren();
700
+ status.hidden = !failed;
701
+ if (!failed) return;
702
+ status.append(el("span", "athena-table-error", server.error ?? translate("noData")), " ");
703
+ const retry = el("button", "athena-button button-secondary button-small", translate("retry"));
704
+ retry.type = "button";
705
+ retry.addEventListener("click", () => {
706
+ for (const [chunk, value] of chunks) if (value === "failed") chunks.delete(chunk);
707
+ server.error = null;
708
+ updateStatus();
709
+ ensureChunks();
710
+ });
711
+ status.append(retry);
712
+ }
713
+
714
+ const query = () => ({ pageSize: chunkSize, cursor: undefined, sort: state.sortKey ? { key: state.sortKey, descending: state.descending } : null, filter: state.query });
715
+
716
+ function place(chunk, list) {
717
+ list.forEach((row, i) => {
718
+ const index = chunk * chunkSize + i;
719
+ if (index < rows.length) rows[index] = row;
720
+ });
721
+ }
722
+
723
+ // Starts again: the first chunk tells how many rows there are, the others come while the person scrolls.
724
+ async function loadVirtual() {
725
+ const generation = ++server.request;
726
+ clearTimeout(flushTimer);
727
+ chunks.clear();
728
+ rows = [];
729
+ selected.clear();
730
+ if (scroller) scroller.scrollTop = 0;
731
+ server.loading = true;
732
+ server.error = null;
733
+ render();
734
+ try {
735
+ const answer = await options.dataSource({ page: 0, ...query() });
736
+ if (generation !== server.request) return;
737
+ if (!Number.isInteger(answer?.total) || answer.total < 0) throw new Error("A data source with virtual scrolling has to answer with total");
738
+ rows = new Array(answer.total);
739
+ place(0, answer.rows ?? []);
740
+ chunks.set(0, "done");
741
+ server.total = answer.total;
742
+ } catch (error) {
743
+ if (generation !== server.request) return;
744
+ server.error = error?.message ?? String(error);
745
+ rows = [];
746
+ } finally {
747
+ if (generation === server.request) {
748
+ server.loading = false;
749
+ render();
750
+ selectionChanged();
751
+ updateStatus();
752
+ if (!server.error) ensureChunks();
753
+ }
754
+ }
755
+ }
756
+
757
+ async function loadChunk(chunk, generation) {
758
+ chunks.set(chunk, "loading");
759
+ try {
760
+ const answer = await options.dataSource({ page: chunk, ...query() });
761
+ if (generation !== server.request) return;
762
+ place(chunk, answer?.rows ?? []);
763
+ chunks.set(chunk, "done");
764
+ } catch (error) {
765
+ if (generation !== server.request) return;
766
+ chunks.set(chunk, "failed");
767
+ server.error = error?.message ?? String(error);
768
+ } finally {
769
+ if (generation === server.request) {
770
+ refreshWindow(true);
771
+ updateStatus();
772
+ }
773
+ }
774
+ }
775
+
776
+ // Asks for the chunks under the rows in view (and the rows around them). Waits a moment, so scrolling past does not ask for everything.
777
+ function ensureChunks() {
778
+ clearTimeout(flushTimer);
779
+ const generation = server.request;
780
+ flushTimer = setTimeout(() => {
781
+ if (generation !== server.request || !rows.length) return;
782
+ const win = virtualWindow({
783
+ scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
784
+ rowHeight: virtual.rowHeight, total: rows.length, overscan: virtual.overscan
785
+ });
786
+ const first = Math.floor(win.start / chunkSize);
787
+ const last = Math.floor((win.end - 1) / chunkSize);
788
+ for (let chunk = first; chunk <= last; chunk++) if (!chunks.has(chunk)) loadChunk(chunk, generation);
789
+ }, 40);
790
+ }
791
+
792
+ // The window of rows depends on the height of the scroll area, which is unknown while the list is empty or
793
+ // not on screen yet: measure again whenever it changes size.
794
+ if (scroller && typeof ResizeObserver !== "undefined") {
795
+ let lastHeight = 0;
796
+ new ResizeObserver(() => {
797
+ const height = scroller.clientHeight;
798
+ if (height === lastHeight) return;
799
+ lastHeight = height;
800
+ refreshWindow();
801
+ }).observe(scroller);
802
+ }
803
+
804
+ render();
805
+ if (remote) load({ reset: true });
806
+ return asHandle({
807
+ element: root,
808
+ /** Asks the data source again (the first page, keeping sort and filter). Resolves when the answer is shown. */
809
+ reload: () => (remote ? load({ reset: true }) : Promise.resolve()),
810
+ // update() draws the table again; update({ rows }) also replaces the rows.
811
+ update(next) {
812
+ if (next?.rows) this.setRows(next.rows);
813
+ else render();
814
+ return this;
815
+ },
816
+ setRows(newRows) {
817
+ rows = [...newRows];
818
+ selected.clear();
819
+ state.page = 0;
820
+ if (scroller) scroller.scrollTop = 0;
821
+ render();
822
+ selectionChanged();
823
+ },
824
+ getSelected: () => [...selected],
825
+ clearSelection() {
826
+ selected.clear();
827
+ render();
828
+ selectionChanged();
829
+ },
830
+ getColumnWidths: () => ({ ...widths }),
831
+ // The filtered and sorted rows as CSV text
832
+ toCsv: () => toCsv(columns, current.filter(row => row !== undefined)),
833
+ exportCsv(filename = "table.csv") {
834
+ downloadFile(filename, toCsv(columns, current.filter(row => row !== undefined)));
835
+ }
836
+ });
837
+ }