athena-ui-js 1.1.0 → 1.3.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.
Files changed (45) hide show
  1. package/README.md +273 -23
  2. package/package.json +11 -7
  3. package/src/athena-ui.js +33 -10
  4. package/src/libs/config/config.js +8 -1
  5. package/src/libs/core/combobox.js +1 -1
  6. package/src/libs/core/controls.js +153 -0
  7. package/src/libs/core/dateRange.js +121 -0
  8. package/src/libs/core/dom.js +88 -11
  9. package/src/libs/{hephaestus/HTMLElementGenerator/src/HTMLElementGenerator.js → core/elementGenerator.js} +23 -21
  10. package/src/libs/{hephaestus/HTMLElementGenerator/src → core}/errors.js +7 -5
  11. package/src/libs/core/format.js +51 -0
  12. package/src/libs/core/hungarianControls.js +41 -0
  13. package/src/libs/core/i18n.js +64 -0
  14. package/src/libs/core/theme.js +131 -0
  15. package/src/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.js +4 -6
  16. package/src/libs/hephaestus/LayoutGenerator/footerContentGenerator.js +2 -4
  17. package/src/libs/hephaestus/LayoutGenerator/headerContentGenerator.js +12 -5
  18. package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +3 -3
  19. package/src/libs/hephaestus/MenuGenerator/menuGenerator.js +253 -0
  20. package/src/libs/hephaestus/auth/authState.js +58 -0
  21. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +530 -65
  22. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +124 -6
  23. package/src/libs/hephaestus/componentGenerator/themePicker.js +73 -0
  24. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +100 -13
  25. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +23 -2
  26. package/src/libs/hephaestus/formGenerator/authForms.js +130 -0
  27. package/src/libs/hephaestus/formGenerator/formBuilder.js +5 -5
  28. package/src/libs/hephaestus/formGenerator/formUtils.js +10 -9
  29. package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +9 -9
  30. package/src/libs/hephaestus/hephaestus.js +7 -2
  31. package/src/libs/hephaestus/inputGenerator/dropZoneGenerator.js +2 -2
  32. package/src/libs/hephaestus/inputGenerator/inputGenerator.js +37 -8
  33. package/src/libs/hephaestus/inputGenerator/richTextGenerator.js +2 -2
  34. package/src/libs/hephaestus/modalGenerator/modalGenerator.js +17 -11
  35. package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +20 -11
  36. package/src/libs/hephaestus/router/router.js +56 -6
  37. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +368 -29
  38. package/src/libs/libs.js +3 -3
  39. package/src/res/themes/appearance.css +154 -0
  40. package/src/res/themes/default/style.css +649 -2
  41. package/src/testing.js +71 -0
  42. package/src/theme-boot.js +25 -0
  43. package/src/libs/hephaestus/HTMLControlGenerator/LICENSE +0 -21
  44. package/src/libs/hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js +0 -5
  45. package/src/libs/hephaestus/HTMLElementGenerator/LICENSE +0 -21
@@ -4,6 +4,7 @@
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
6
  import { downloadFile, toCsv } from "../../core/csv.js";
7
+ import { asHandle, resolveElement } from "../../core/dom.js";
7
8
  import { translate } from "../../core/i18n.js";
8
9
  import { clampWidth, virtualWindow } from "../../core/tableMath.js";
9
10
 
@@ -14,6 +15,10 @@ const el = (tag, className, text) => {
14
15
  return element;
15
16
  };
16
17
 
18
+ const addClasses = (node, classes) => {
19
+ for (const name of [classes].flat()) if (name) node.classList.add(...String(name).split(/\s+/).filter(Boolean));
20
+ };
21
+
17
22
  const compare = (a, b) =>
18
23
  typeof a === "number" && typeof b === "number"
19
24
  ? a - b
@@ -45,7 +50,27 @@ const compare = (a, b) =>
45
50
  * of an `editable` column (double click, or Enter / F2 on the focused cell). Return false to reject it.
46
51
  * @param {(row: object) => void} [options.onRowClick]
47
52
  * @param {string} [options.emptyText]
48
- * @returns {{element: HTMLElement, setRows: Function, getSelected: () => object[], clearSelection: Function,
53
+ * @param {(row: object, column: object) => (string|string[]|null|undefined)} [options.cellClass] CSS class(es) for a cell
54
+ * @param {(row: object) => (string|string[]|null|undefined)} [options.rowClass] CSS class(es) for a row
55
+ * @param {boolean} [options.focusableRows=false] rows are reachable with Tab and, with `onRowClick`, opened with Enter and Space
56
+ * @param {(row: object) => string} [options.rowLabel] aria-label of a focusable row
57
+ * @param {"normal"|"compact"} [options.density="normal"]
58
+ * @param {boolean} [options.wrap] true lets long text wrap, false keeps one line with an ellipsis (default: wrap, except in virtual tables)
59
+ * @param {(query: {page: number, pageSize: number, cursor: *, sort: ({key: string, descending: boolean}|null), filter: string}) =>
60
+ * Promise<{rows: object[], total?: number, nextCursor?: *}>} [options.dataSource] load the rows from a server instead of
61
+ * keeping them all in the browser. Sorting, the filter box and the pager call it again. Answer with `total` for numbered pages
62
+ * (`page` is 0-based), or with `nextCursor` for a "Load more" button (`cursor` is what the last answer gave, undefined for the
63
+ * first request; the rows are appended). A failed request shows the error with a Retry button.
64
+ * Together with `virtual` the list scrolls like one of `total` rows (every answer must carry `total`): the rows in view are asked for
65
+ * in chunks of `chunkSize` (`page` is the chunk number), rows that have not arrived yet show a placeholder, and sorting or the filter
66
+ * start again from the top.
67
+ * @param {number} [options.chunkSize=50] rows per request of a data source with `virtual`
68
+ * @param {number} [options.filterDelay=300] ms to wait after typing before the data source is asked
69
+ * @param {{label: string, onclick: (row: object) => void, danger?: boolean, hidden?: (row: object) => boolean, ariaLabel?: (row: object) => string}[]} [options.rowActions]
70
+ * a column of buttons at the end of every row
71
+ * Column extras: `render(row, value)` returns text or a Node (built by the caller, so safe by construction), `align`
72
+ * ("left" | "center" | "right"), `title` (false switches the tooltip with the full text off).
73
+ * @returns {{element: HTMLElement, update: Function, destroy: Function, setRows: Function, getSelected: () => object[], clearSelection: Function,
49
74
  * getColumnWidths: () => Object<string, number>, toCsv: () => string, exportCsv: (filename?: string) => void}}
50
75
  */
51
76
  export function generateTable(options = {}) {
@@ -53,11 +78,20 @@ export function generateTable(options = {}) {
53
78
  parent = "wrapper", id = "table", columns = [], sortable = true,
54
79
  filter = false, selectable = false, resizableColumns = false, onRowClick, onSelectionChange
55
80
  } = options;
81
+ const remote = typeof options.dataSource === "function";
82
+ const rowActions = options.rowActions?.length ? options.rowActions : null;
56
83
  const virtual = options.virtual
57
84
  ? { height: 400, rowHeight: 36, overscan: 5, ...(options.virtual === true ? {} : options.virtual) }
58
85
  : null;
59
- const pageSize = virtual ? 0 : (options.pageSize ?? 0);
60
- const host = (typeof parent === "string" ? document.getElementById(parent) : parent) ?? document.body;
86
+ const remoteVirtual = remote && Boolean(virtual);
87
+ const chunkSize = Math.max(1, options.chunkSize ?? 50);
88
+ const chunks = new Map(); // chunk number -> "loading" | "done" | "failed" (remote virtual)
89
+ let flushTimer = 0;
90
+ const pageSize = virtual ? 0 : (options.pageSize ?? (remote ? 25 : 0));
91
+ // What the data source told us: { loading, error, total, nextCursor, cursorMode }
92
+ const server = { loading: false, error: null, total: null, nextCursor: undefined, cursorMode: false, request: 0 };
93
+ const colCount = () => columns.length + (selectable ? 1 : 0) + (rowActions ? 1 : 0);
94
+ const host = resolveElement(parent) ?? document.body;
61
95
  let rows = [...(options.rows ?? [])];
62
96
  let current = rows; // filtered and sorted rows
63
97
  const selected = new Set();
@@ -70,6 +104,9 @@ export function generateTable(options = {}) {
70
104
  root.id = id;
71
105
  const table = el("table", `athena-table ${options.class ?? ""}`.trim());
72
106
  if (resizableColumns) table.classList.add("athena-table-resizable");
107
+ if (options.density === "compact") table.classList.add("athena-table-compact");
108
+ if (options.wrap === true) table.classList.add("athena-table-wrap");
109
+ else if (options.wrap === false) table.classList.add("athena-table-nowrap");
73
110
  let scroller = null;
74
111
  if (virtual) {
75
112
  table.classList.add("athena-table-virtual");
@@ -85,11 +122,14 @@ export function generateTable(options = {}) {
85
122
  filterInput.type = "search";
86
123
  filterInput.placeholder = translate("filter");
87
124
  filterInput.setAttribute("aria-label", translate("filter"));
125
+ let filterTimer = 0;
88
126
  filterInput.addEventListener("input", () => {
89
- state.query = filterInput.value.toLowerCase();
127
+ state.query = remote ? filterInput.value.trim() : filterInput.value.toLowerCase();
90
128
  state.page = 0;
91
129
  if (scroller) scroller.scrollTop = 0;
92
- render();
130
+ if (!remote) return render();
131
+ clearTimeout(filterTimer);
132
+ filterTimer = setTimeout(() => load({ reset: true }), options.filterDelay ?? 300);
93
133
  });
94
134
  root.append(filterInput);
95
135
  }
@@ -104,6 +144,7 @@ export function generateTable(options = {}) {
104
144
  host.append(root);
105
145
 
106
146
  function visibleRows() {
147
+ if (remote) return rows; // the server filtered, sorted and paged them
107
148
  let result = rows;
108
149
  if (state.query) {
109
150
  result = result.filter(row =>
@@ -244,7 +285,8 @@ export function generateTable(options = {}) {
244
285
  const sort = () => {
245
286
  state.descending = state.sortKey === col.key && !state.descending;
246
287
  state.sortKey = col.key;
247
- render();
288
+ if (remote) load({ reset: true });
289
+ else render();
248
290
  };
249
291
  th.addEventListener("click", sort);
250
292
  th.addEventListener("keydown", e => {
@@ -261,6 +303,12 @@ export function generateTable(options = {}) {
261
303
  if (resizableColumns) makeResizer(th, col);
262
304
  tr.append(th);
263
305
  }
306
+ if (rowActions) {
307
+ const th = el("th", "athena-table-actions");
308
+ th.scope = "col";
309
+ th.append(el("span", "athena-visually-hidden", translate("actions")));
310
+ tr.append(th);
311
+ }
264
312
  const thead = el("thead");
265
313
  thead.append(tr);
266
314
  return thead;
@@ -302,7 +350,7 @@ export function generateTable(options = {}) {
302
350
  tr.setAttribute("aria-hidden", "true");
303
351
  tr.style.height = `${height}px`;
304
352
  const td = el("td");
305
- td.colSpan = columns.length + (selectable ? 1 : 0);
353
+ td.colSpan = colCount();
306
354
  tr.append(td);
307
355
  return tr;
308
356
  }
@@ -310,10 +358,32 @@ export function generateTable(options = {}) {
310
358
  function renderRow(row, index) {
311
359
  const tr = el("tr");
312
360
  if (virtual) tr.setAttribute("aria-rowindex", String(index + 2));
361
+ if (row === undefined) {
362
+ // A row of a data source that has not arrived yet
363
+ tr.className = "athena-table-placeholder";
364
+ tr.setAttribute("aria-busy", "true");
365
+ const td = el("td", null, "…");
366
+ td.colSpan = colCount();
367
+ tr.append(td);
368
+ return tr;
369
+ }
370
+ addClasses(tr, options.rowClass?.(row));
313
371
  if (onRowClick) {
314
372
  tr.classList.add("clickable");
315
373
  tr.addEventListener("click", () => onRowClick(row));
316
374
  }
375
+ if (options.focusableRows) {
376
+ tr.tabIndex = 0;
377
+ if (options.rowLabel) tr.setAttribute("aria-label", options.rowLabel(row));
378
+ if (onRowClick) {
379
+ tr.addEventListener("keydown", e => {
380
+ if (e.target === tr && (e.key === "Enter" || e.key === " ")) {
381
+ e.preventDefault();
382
+ onRowClick(row);
383
+ }
384
+ });
385
+ }
386
+ }
317
387
  if (selectable) {
318
388
  const td = el("td", "athena-table-select");
319
389
  const box = el("input");
@@ -332,7 +402,16 @@ export function generateTable(options = {}) {
332
402
  }
333
403
  for (const col of columns) {
334
404
  const value = row[col.key];
335
- const td = el("td", null, col.format ? col.format(value, row) : (value ?? ""));
405
+ const content = col.render ? col.render(row, value) : (col.format ? col.format(value, row) : (value ?? ""));
406
+ const td = el("td");
407
+ if (content instanceof Node) td.append(content);
408
+ else {
409
+ td.textContent = content;
410
+ // Text that may be cut off gets its full text as a tooltip.
411
+ if (col.title !== false && String(content).length > 24) td.title = String(content);
412
+ }
413
+ if (col.align) td.classList.add(`athena-align-${col.align}`);
414
+ addClasses(td, options.cellClass?.(row, col));
336
415
  if (col.editable) {
337
416
  td.classList.add("editable");
338
417
  td.tabIndex = 0;
@@ -346,39 +425,115 @@ export function generateTable(options = {}) {
346
425
  }
347
426
  tr.append(td);
348
427
  }
428
+ if (rowActions) {
429
+ const td = el("td", "athena-table-actions");
430
+ for (const action of rowActions) {
431
+ if (action.hidden?.(row)) continue;
432
+ const button = el("button", `athena-button button-${action.danger ? "danger" : "secondary"} button-small`, action.label);
433
+ button.type = "button";
434
+ if (action.ariaLabel) button.setAttribute("aria-label", action.ariaLabel(row));
435
+ button.addEventListener("click", event => {
436
+ event.stopPropagation();
437
+ action.onclick(row);
438
+ });
439
+ td.append(button);
440
+ }
441
+ tr.append(td);
442
+ }
443
+ return tr;
444
+ }
445
+
446
+ function messageRow(className, text, retry) {
447
+ const td = el("td", className, text);
448
+ td.colSpan = Math.max(colCount(), 1);
449
+ if (retry) {
450
+ const button = el("button", "athena-button button-secondary button-small", translate("retry"));
451
+ button.type = "button";
452
+ button.addEventListener("click", () => load({}));
453
+ td.append(" ", button);
454
+ }
455
+ const tr = el("tr");
456
+ tr.append(td);
349
457
  return tr;
350
458
  }
351
459
 
352
460
  function renderBody() {
353
461
  const tbody = el("tbody");
462
+ if (remote && server.error && !current.length) {
463
+ const row = messageRow("athena-table-error", server.error, true);
464
+ row.firstChild.setAttribute("role", "alert");
465
+ tbody.append(row);
466
+ return tbody;
467
+ }
468
+ if (remote && server.loading && !current.length) {
469
+ tbody.append(messageRow("athena-table-loading", translate("loading")));
470
+ return tbody;
471
+ }
354
472
  if (!current.length) {
355
- const td = el("td", "athena-table-empty", options.emptyText ?? translate("noData"));
356
- td.colSpan = Math.max(columns.length + (selectable ? 1 : 0), 1);
357
- const tr = el("tr");
358
- tr.append(td);
359
- tbody.append(tr);
473
+ tbody.append(messageRow("athena-table-empty", options.emptyText ?? translate("noData")));
360
474
  return tbody;
361
475
  }
362
476
  if (virtual) {
363
477
  const win = virtualWindow({
364
- scrollTop: scroller.scrollTop, viewportHeight: scroller.clientHeight || virtual.height,
478
+ scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
365
479
  rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
366
480
  });
367
481
  windowKey = `${win.start}:${win.end}`;
482
+ if (remoteVirtual) ensureChunks();
368
483
  if (win.offsetTop) tbody.append(spacer(win.offsetTop));
369
484
  for (let i = win.start; i < win.end; i++) tbody.append(renderRow(current[i], i));
370
485
  if (win.offsetBottom) tbody.append(spacer(win.offsetBottom));
371
486
  return tbody;
372
487
  }
373
- const pageRows = pageSize > 0 ? current.slice(state.page * pageSize, (state.page + 1) * pageSize) : current;
488
+ const pageRows = remote ? current : pageSize > 0 ? current.slice(state.page * pageSize, (state.page + 1) * pageSize) : current;
374
489
  for (const row of pageRows) tbody.append(renderRow(row));
375
490
  return tbody;
376
491
  }
377
492
 
493
+ function renderRemotePager() {
494
+ if (server.cursorMode) {
495
+ pager.hidden = !server.nextCursor && !server.error;
496
+ const more = el("button", "athena-button button-secondary", translate("loadMore"));
497
+ more.type = "button";
498
+ more.disabled = server.loading;
499
+ more.addEventListener("click", () => load({ more: true }));
500
+ pager.replaceChildren(more);
501
+ showPagerError();
502
+ return;
503
+ }
504
+ const pages = server.total == null ? state.page + 2 : Math.max(1, Math.ceil(server.total / pageSize));
505
+ pager.hidden = pages === 1;
506
+ const go = delta => () => {
507
+ state.page += delta;
508
+ load({});
509
+ };
510
+ const prev = el("button", null, `‹ ${translate("previous")}`);
511
+ prev.type = "button";
512
+ prev.disabled = state.page === 0 || server.loading;
513
+ prev.addEventListener("click", go(-1));
514
+ const next = el("button", null, `${translate("next")} ›`);
515
+ next.type = "button";
516
+ next.disabled = state.page >= pages - 1 || server.loading;
517
+ next.addEventListener("click", go(1));
518
+ pager.replaceChildren(prev, el("span", null, ` ${translate("page", { page: state.page + 1, pages: server.total == null ? "?" : pages })} `), next);
519
+ showPagerError();
520
+ }
521
+
522
+ // A failed request while rows are on the screen (the next page, "Load more"): say so next to the buttons.
523
+ function showPagerError() {
524
+ if (!server.error || !current.length) return;
525
+ pager.hidden = false;
526
+ const message = el("span", "athena-table-error", server.error);
527
+ message.setAttribute("role", "alert");
528
+ pager.append(" ", message);
529
+ }
530
+
378
531
  function renderPager(total) {
379
532
  if (!pager) return;
533
+ if (remote) return renderRemotePager();
380
534
  const pages = Math.max(1, Math.ceil(total / pageSize));
381
535
  state.page = Math.min(state.page, pages - 1);
536
+ pager.hidden = pages === 1;
382
537
  const button = (text, disabled, delta) => {
383
538
  const b = el("button", null, text);
384
539
  b.type = "button";
@@ -399,6 +554,8 @@ export function generateTable(options = {}) {
399
554
  function render() {
400
555
  const scrollTop = scroller?.scrollTop ?? 0;
401
556
  current = visibleRows();
557
+ root.toggleAttribute("aria-busy", remote && server.loading);
558
+ root.classList.toggle("athena-table-is-loading", remote && server.loading);
402
559
  renderPager(current.length);
403
560
  if (virtual) table.setAttribute("aria-rowcount", String(current.length + 1));
404
561
  const parts = [renderHead(current), renderBody()];
@@ -410,29 +567,211 @@ export function generateTable(options = {}) {
410
567
  }
411
568
 
412
569
  // Scrolling only swaps the body, and only when the window of rows really changed.
570
+ // 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
571
+ // starts empty (a tiny scroll area when the rows are set) still draws a full window.
572
+ const viewportHeight = () => Math.max(scroller.clientHeight, Math.min(virtual.height, current.length * virtual.rowHeight));
573
+
574
+ function refreshWindow(force = false) {
575
+ if (remoteVirtual) ensureChunks();
576
+ const win = virtualWindow({
577
+ scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
578
+ rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
579
+ });
580
+ if (!force && `${win.start}:${win.end}` === windowKey) return;
581
+ const focused = document.activeElement;
582
+ const keepFocus = focused && table.tBodies[0]?.contains(focused);
583
+ table.tBodies[0].replaceWith(renderBody());
584
+ if (keepFocus) scroller.focus({ preventScroll: true });
585
+ }
586
+
413
587
  if (scroller) {
414
588
  let queued = false;
415
589
  scroller.addEventListener("scroll", () => {
416
590
  if (queued) return;
417
591
  queued = true;
418
- requestAnimationFrame(() => {
592
+ // Once per frame; the timer is for pages where frames are paused or late (a hidden tab, a busy page).
593
+ let timer = 0;
594
+ const run = () => {
595
+ if (!queued) return;
419
596
  queued = false;
420
- const win = virtualWindow({
421
- scrollTop: scroller.scrollTop, viewportHeight: scroller.clientHeight || virtual.height,
422
- rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
423
- });
424
- if (`${win.start}:${win.end}` === windowKey) return;
425
- const focused = document.activeElement;
426
- const keepFocus = focused && table.tBodies[0]?.contains(focused);
427
- table.tBodies[0].replaceWith(renderBody());
428
- if (keepFocus) scroller.focus({ preventScroll: true });
597
+ clearTimeout(timer);
598
+ refreshWindow();
599
+ };
600
+ requestAnimationFrame(run);
601
+ timer = setTimeout(run, 100);
602
+ });
603
+ }
604
+
605
+ /**
606
+ * Asks the data source. { reset } starts again from the first page, { more } appends the next cursor page.
607
+ * An answer that arrives after a newer request was made is ignored.
608
+ */
609
+ async function load({ reset = false, more = false } = {}) {
610
+ if (remoteVirtual) return loadVirtual();
611
+ if (reset) {
612
+ state.page = 0;
613
+ server.nextCursor = undefined;
614
+ }
615
+ const request = ++server.request;
616
+ server.loading = true;
617
+ server.error = null;
618
+ render();
619
+ try {
620
+ const answer = await options.dataSource({
621
+ page: state.page,
622
+ pageSize,
623
+ cursor: more ? server.nextCursor : undefined,
624
+ sort: state.sortKey ? { key: state.sortKey, descending: state.descending } : null,
625
+ filter: state.query
429
626
  });
627
+ if (request !== server.request) return;
628
+ const loaded = answer?.rows ?? [];
629
+ server.cursorMode = answer?.nextCursor !== undefined || (more && server.cursorMode);
630
+ server.nextCursor = answer?.nextCursor ?? undefined;
631
+ server.total = answer?.total ?? null;
632
+ rows = more ? [...rows, ...loaded] : [...loaded];
633
+ if (!more) selected.clear();
634
+ } catch (error) {
635
+ if (request !== server.request) return;
636
+ server.error = error?.message ?? String(error);
637
+ if (!more) rows = [];
638
+ } finally {
639
+ if (request === server.request) {
640
+ server.loading = false;
641
+ render();
642
+ if (!more) selectionChanged();
643
+ }
644
+ }
645
+ }
646
+
647
+ /* ------------------REMOTE + VIRTUAL------------------- */
648
+
649
+ const status = remoteVirtual ? el("div", "athena-table-status") : null;
650
+ if (status) {
651
+ status.setAttribute("role", "status");
652
+ root.append(status);
653
+ }
654
+
655
+ function updateStatus() {
656
+ if (!status) return;
657
+ const failed = [...chunks.values()].includes("failed");
658
+ status.replaceChildren();
659
+ status.hidden = !failed;
660
+ if (!failed) return;
661
+ status.append(el("span", "athena-table-error", server.error ?? translate("noData")), " ");
662
+ const retry = el("button", "athena-button button-secondary button-small", translate("retry"));
663
+ retry.type = "button";
664
+ retry.addEventListener("click", () => {
665
+ for (const [chunk, value] of chunks) if (value === "failed") chunks.delete(chunk);
666
+ server.error = null;
667
+ updateStatus();
668
+ ensureChunks();
430
669
  });
670
+ status.append(retry);
671
+ }
672
+
673
+ const query = () => ({ pageSize: chunkSize, cursor: undefined, sort: state.sortKey ? { key: state.sortKey, descending: state.descending } : null, filter: state.query });
674
+
675
+ function place(chunk, list) {
676
+ list.forEach((row, i) => {
677
+ const index = chunk * chunkSize + i;
678
+ if (index < rows.length) rows[index] = row;
679
+ });
680
+ }
681
+
682
+ // Starts again: the first chunk tells how many rows there are, the others come while the person scrolls.
683
+ async function loadVirtual() {
684
+ const generation = ++server.request;
685
+ clearTimeout(flushTimer);
686
+ chunks.clear();
687
+ rows = [];
688
+ selected.clear();
689
+ if (scroller) scroller.scrollTop = 0;
690
+ server.loading = true;
691
+ server.error = null;
692
+ render();
693
+ try {
694
+ const answer = await options.dataSource({ page: 0, ...query() });
695
+ if (generation !== server.request) return;
696
+ if (!Number.isInteger(answer?.total) || answer.total < 0) throw new Error("A data source with virtual scrolling has to answer with total");
697
+ rows = new Array(answer.total);
698
+ place(0, answer.rows ?? []);
699
+ chunks.set(0, "done");
700
+ server.total = answer.total;
701
+ } catch (error) {
702
+ if (generation !== server.request) return;
703
+ server.error = error?.message ?? String(error);
704
+ rows = [];
705
+ } finally {
706
+ if (generation === server.request) {
707
+ server.loading = false;
708
+ render();
709
+ selectionChanged();
710
+ updateStatus();
711
+ if (!server.error) ensureChunks();
712
+ }
713
+ }
714
+ }
715
+
716
+ async function loadChunk(chunk, generation) {
717
+ chunks.set(chunk, "loading");
718
+ try {
719
+ const answer = await options.dataSource({ page: chunk, ...query() });
720
+ if (generation !== server.request) return;
721
+ place(chunk, answer?.rows ?? []);
722
+ chunks.set(chunk, "done");
723
+ } catch (error) {
724
+ if (generation !== server.request) return;
725
+ chunks.set(chunk, "failed");
726
+ server.error = error?.message ?? String(error);
727
+ } finally {
728
+ if (generation === server.request) {
729
+ refreshWindow(true);
730
+ updateStatus();
731
+ }
732
+ }
733
+ }
734
+
735
+ // 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.
736
+ function ensureChunks() {
737
+ clearTimeout(flushTimer);
738
+ const generation = server.request;
739
+ flushTimer = setTimeout(() => {
740
+ if (generation !== server.request || !rows.length) return;
741
+ const win = virtualWindow({
742
+ scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
743
+ rowHeight: virtual.rowHeight, total: rows.length, overscan: virtual.overscan
744
+ });
745
+ const first = Math.floor(win.start / chunkSize);
746
+ const last = Math.floor((win.end - 1) / chunkSize);
747
+ for (let chunk = first; chunk <= last; chunk++) if (!chunks.has(chunk)) loadChunk(chunk, generation);
748
+ }, 40);
749
+ }
750
+
751
+ // The window of rows depends on the height of the scroll area, which is unknown while the list is empty or
752
+ // not on screen yet: measure again whenever it changes size.
753
+ if (scroller && typeof ResizeObserver !== "undefined") {
754
+ let lastHeight = 0;
755
+ new ResizeObserver(() => {
756
+ const height = scroller.clientHeight;
757
+ if (height === lastHeight) return;
758
+ lastHeight = height;
759
+ refreshWindow();
760
+ }).observe(scroller);
431
761
  }
432
762
 
433
763
  render();
434
- return {
764
+ if (remote) load({ reset: true });
765
+ return asHandle({
435
766
  element: root,
767
+ /** Asks the data source again (the first page, keeping sort and filter). Resolves when the answer is shown. */
768
+ reload: () => (remote ? load({ reset: true }) : Promise.resolve()),
769
+ // update() draws the table again; update({ rows }) also replaces the rows.
770
+ update(next) {
771
+ if (next?.rows) this.setRows(next.rows);
772
+ else render();
773
+ return this;
774
+ },
436
775
  setRows(newRows) {
437
776
  rows = [...newRows];
438
777
  selected.clear();
@@ -449,9 +788,9 @@ export function generateTable(options = {}) {
449
788
  },
450
789
  getColumnWidths: () => ({ ...widths }),
451
790
  // The filtered and sorted rows as CSV text
452
- toCsv: () => toCsv(columns, current),
791
+ toCsv: () => toCsv(columns, current.filter(row => row !== undefined)),
453
792
  exportCsv(filename = "table.csv") {
454
- downloadFile(filename, toCsv(columns, current));
793
+ downloadFile(filename, toCsv(columns, current.filter(row => row !== undefined)));
455
794
  }
456
- };
795
+ });
457
796
  }
package/src/libs/libs.js CHANGED
@@ -5,9 +5,9 @@
5
5
 
6
6
  // Classic (non-module) scripts that have to be loaded at runtime because they
7
7
  // register globals. Everything else is a regular ES module import.
8
- const lib = (id, name, path) => ({ id, name, src: new URL(path, import.meta.url).href });
8
+ // `needs`: the script is only loaded when it is wanted ("crypto": enable_encrypt_password is on)
9
+ const lib = (id, name, path, needs) => ({ id, name, needs, src: new URL(path, import.meta.url).href });
9
10
 
10
11
  export default [
11
- lib(0, "HTMLControlGenerator", "hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js"),
12
- lib(10, "crypto-js", "crypto-js/crypto-js.js")
12
+ lib(10, "crypto-js", "crypto-js/crypto-js.js", "crypto")
13
13
  ];