athena-ui-js 1.2.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 (39) hide show
  1. package/README.md +228 -22
  2. package/package.json +9 -7
  3. package/src/athena-ui.js +33 -10
  4. package/src/libs/config/config.js +8 -1
  5. package/src/libs/core/controls.js +153 -0
  6. package/src/libs/core/dateRange.js +121 -0
  7. package/src/libs/core/dom.js +58 -8
  8. package/src/libs/{hephaestus/HTMLElementGenerator/src/HTMLElementGenerator.js → core/elementGenerator.js} +23 -21
  9. package/src/libs/{hephaestus/HTMLElementGenerator/src → core}/errors.js +7 -5
  10. package/src/libs/core/format.js +51 -0
  11. package/src/libs/core/hungarianControls.js +41 -0
  12. package/src/libs/core/i18n.js +64 -0
  13. package/src/libs/core/theme.js +131 -0
  14. package/src/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.js +4 -6
  15. package/src/libs/hephaestus/LayoutGenerator/footerContentGenerator.js +2 -4
  16. package/src/libs/hephaestus/LayoutGenerator/headerContentGenerator.js +12 -5
  17. package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +3 -3
  18. package/src/libs/hephaestus/MenuGenerator/menuGenerator.js +253 -0
  19. package/src/libs/hephaestus/auth/authState.js +58 -0
  20. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +519 -87
  21. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +121 -4
  22. package/src/libs/hephaestus/componentGenerator/themePicker.js +73 -0
  23. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +88 -8
  24. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +21 -0
  25. package/src/libs/hephaestus/formGenerator/authForms.js +130 -0
  26. package/src/libs/hephaestus/formGenerator/formUtils.js +10 -9
  27. package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +9 -9
  28. package/src/libs/hephaestus/hephaestus.js +7 -2
  29. package/src/libs/hephaestus/inputGenerator/inputGenerator.js +30 -1
  30. package/src/libs/hephaestus/modalGenerator/modalGenerator.js +17 -11
  31. package/src/libs/hephaestus/router/router.js +54 -5
  32. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +290 -16
  33. package/src/libs/libs.js +3 -3
  34. package/src/res/themes/appearance.css +154 -0
  35. package/src/res/themes/default/style.css +609 -0
  36. package/src/theme-boot.js +25 -0
  37. package/src/libs/hephaestus/HTMLControlGenerator/LICENSE +0 -21
  38. package/src/libs/hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js +0 -5
  39. package/src/libs/hephaestus/HTMLElementGenerator/LICENSE +0 -21
@@ -4,7 +4,7 @@
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
6
  import { createCombobox } from "../../core/combobox.js";
7
- import { createDateRange } from "../../core/dateRange.js";
7
+ import { createDateRange, createDateTimeRange } from "../../core/dateRange.js";
8
8
  import { asHandle, cx, el, mount, setContent, uid } from "../../core/dom.js";
9
9
  import { formatBytes, matchesAccept } from "../../core/format.js";
10
10
  import { translate } from "../../core/i18n.js";
@@ -76,6 +76,35 @@ export function generateDateRange(options = {}) {
76
76
  return asHandle(range, { also: wrapper });
77
77
  }
78
78
 
79
+ /**
80
+ * Generates a from / to range with date AND time (datetime-local inputs), and a list of presets: last 15 minutes, hour,
81
+ * 24 hours, 7 days, 30 days, or "Custom". For log filters, charts and reports that need times, not whole days.
82
+ * A preset moves with the clock: getRange() measures it from now when it is called.
83
+ *
84
+ * @param {object} options
85
+ * @param {string|Element} [options.parent]
86
+ * @param {string} [options.label]
87
+ * @param {string} [options.from] initial start, "2026-01-31T08:00"
88
+ * @param {string} [options.to] initial end
89
+ * @param {string} [options.preset] id of the preset to start with ("15m", "1h", "24h", "7d", "30d")
90
+ * @param {{id: string, label?: string, labelKey?: string, minutes: number}[]} [options.presets] your own list
91
+ * @param {boolean} [options.seconds=false]
92
+ * @param {string} [options.min]
93
+ * @param {string} [options.max]
94
+ * @param {(value: {from: string, to: string, preset: string}) => void} [options.onChange]
95
+ * @returns {{element: HTMLElement, getValue: Function, getRange: () => ({from: Date|null, to: Date|null}), setValue: Function, validate: () => string}}
96
+ */
97
+ export function generateDateTimeRange(options = {}) {
98
+ const range = createDateTimeRange(options);
99
+ const wrapper = el("div", { class: "field" });
100
+ const error = el("div", { class: "field-error", attrs: { role: "alert" } });
101
+ if (options.label) wrapper.append(el("span", { class: "field-label", text: options.label }));
102
+ wrapper.append(range.element, error);
103
+ range.element.addEventListener("change", () => { error.textContent = range.validate(); });
104
+ mount(options.parent, wrapper);
105
+ return asHandle(range, { also: wrapper });
106
+ }
107
+
79
108
  /* ------------------FILE UPLOAD------------------- */
80
109
 
81
110
  /**
@@ -3,8 +3,6 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- /* global $ */
7
-
8
6
  import { trapFocus } from "../../core/focus.js";
9
7
 
10
8
  const DEFAULT_MODAL_ID = "myModal";
@@ -13,21 +11,29 @@ const DEFAULT_MODAL_ID = "myModal";
13
11
  const releases = new Map();
14
12
 
15
13
  export function openModal(id = DEFAULT_MODAL_ID) {
16
- const modal = $(`#${id}`);
17
- modal.css("display", "block").attr({ role: "dialog", "aria-modal": "true" });
18
- if (modal[0] && !releases.has(id)) {
19
- releases.set(id, trapFocus(modal[0], { onEscape: () => closeModal(id) }));
20
- }
14
+ const modal = document.getElementById(id);
15
+ if (!modal) return;
16
+ modal.classList.add("is-open");
17
+ modal.style.display = "block";
18
+ modal.setAttribute("role", "dialog");
19
+ modal.setAttribute("aria-modal", "true");
20
+ if (!releases.has(id)) releases.set(id, trapFocus(modal, { onEscape: () => closeModal(id) }));
21
21
  }
22
22
 
23
23
  export function closeModal(id = DEFAULT_MODAL_ID) {
24
- $(`#${id}`).css("display", "none");
24
+ const modal = document.getElementById(id);
25
+ if (modal) {
26
+ modal.classList.remove("is-open");
27
+ modal.style.display = "none";
28
+ }
25
29
  releases.get(id)?.();
26
30
  releases.delete(id);
27
31
  }
28
32
 
29
33
  // One delegated handler serves every close button (x), including modals added later.
30
- $(document).on("click.athenaModal", ".close", function () {
31
- const modal = $(this).closest(".modal");
32
- closeModal(modal.length ? modal.attr("id") : DEFAULT_MODAL_ID);
34
+ // One delegated handler serves every close button (x), including modals added later.
35
+ document.addEventListener("click", event => {
36
+ const button = event.target.closest?.(".close");
37
+ if (!button) return;
38
+ closeModal(button.closest(".modal")?.id || DEFAULT_MODAL_ID);
33
39
  });
@@ -18,12 +18,33 @@ import { matchRoute, normalizePath, parseQuery } from "./matchRoute.js";
18
18
  * @param {(context) => void} [options.notFound] called when no route matches
19
19
  * @param {(context) => (boolean|string|void|Promise)} [options.beforeEach] guard: return false to cancel,
20
20
  * or a path to redirect to (login redirect)
21
- * @param {(context) => void} [options.afterEach]
21
+ * @param {(context) => void} [options.afterEach] same as onShown
22
+ * @param {(context, route) => void} [options.onRender] called after the outlet was emptied, before the page function runs
23
+ * @param {(context, route) => void} [options.onShown] called after the page function finished (and it was not replaced by a newer
24
+ * navigation): the place to set the title, move the focus to the content, scroll to the top
25
+ * @param {boolean} [options.focusContent=false] after a page is shown the outlet gets the focus (it is made focusable for that), so a
26
+ * screen reader starts reading the new page and the keyboard continues there
27
+ * @param {boolean} [options.scrollTop=false] scroll to the top after a page is shown
28
+ * @param {object} [options.auth] sign-in rules for routes, see the route options below
29
+ * @param {() => boolean} [options.auth.isSignedIn]
30
+ * @param {(role: string) => boolean} [options.auth.hasRole]
31
+ * @param {string} [options.auth.loginPath="/login"] where `auth: true` routes send a visitor who is not signed in (with `?next=<path>`)
32
+ * @param {string} [options.auth.homePath="/"] where `guestOnly` routes send a signed-in person
33
+ * @param {string} [options.auth.forbiddenPath] where a person without the role goes (default: homePath)
22
34
  * @param {string} [options.titlePrefix] document title is `${titlePrefix}${route.title}`
23
- * @returns {{start: Function, stop: Function, navigate: Function, current: Function, href: Function}}
35
+ *
36
+ * A route is a page function, or an object: `{ handler, title, auth: true, guestOnly: true, roles: ["admin"], guard(context) }`.
37
+ * `auth`, `guestOnly` and `roles` are checked with options.auth; `guard` is a function that gets the same context and returns
38
+ * false (stay where you are), a path (redirect) or anything else (go on); it runs after the rules.
39
+ * @returns {{start: Function, stop: Function, navigate: Function, current: Function, href: Function,
40
+ * onChange: (listener: (context) => void) => Function}}
41
+ * `onChange(listener)` is called with the context after every page that is shown (menus and breadcrumbs follow the router
42
+ * with it) and returns a function that stops it.
24
43
  */
25
44
  export function createRouter(options = {}) {
26
45
  const { routes = {}, outlet = "wrapper", mode = "hash", notFound, beforeEach, afterEach, titlePrefix = "" } = options;
46
+ const rules = { loginPath: "/login", homePath: "/", ...options.auth };
47
+ const listeners = new Set();
27
48
  const entries = Object.entries(routes).map(([pattern, route]) => [pattern, typeof route === "function" ? { handler: route } : route]);
28
49
  let currentContext = null;
29
50
  let renderToken = 0;
@@ -33,6 +54,16 @@ export function createRouter(options = {}) {
33
54
  ? location.hash.replace(/^#/, "") || "/"
34
55
  : location.pathname + location.search;
35
56
 
57
+ // The rules of a route and its own guard. Returns false, a path to redirect to, or undefined.
58
+ async function checkRoute(route, context) {
59
+ const signedIn = Boolean(rules.isSignedIn?.());
60
+ if (route.guestOnly && signedIn) return rules.homePath;
61
+ if (route.auth && !signedIn) return `${rules.loginPath}?next=${encodeURIComponent(context.path)}`;
62
+ if (route.roles?.length && !route.roles.some(role => rules.hasRole?.(role))) return rules.forbiddenPath ?? rules.homePath;
63
+ const result = await route.guard?.(context);
64
+ return result === false || typeof result === "string" ? result : undefined;
65
+ }
66
+
36
67
  async function render(raw, depth = 0) {
37
68
  const token = ++renderToken;
38
69
  const path = normalizePath(raw);
@@ -47,8 +78,13 @@ export function createRouter(options = {}) {
47
78
  }
48
79
  const context = { path, params: matched?.params ?? {}, query };
49
80
 
50
- const guard = await beforeEach?.(context);
51
- if (token !== renderToken || guard === false) return;
81
+ let guard = await beforeEach?.(context);
82
+ if (token !== renderToken) return;
83
+ if (guard !== false && typeof guard !== "string" && matched) {
84
+ guard = await checkRoute(matched.route, context);
85
+ if (token !== renderToken) return;
86
+ }
87
+ if (guard === false) return;
52
88
  if (typeof guard === "string" && depth < 5) {
53
89
  navigate(guard, { replace: true });
54
90
  return;
@@ -57,13 +93,22 @@ export function createRouter(options = {}) {
57
93
  const host = resolveElement(outlet);
58
94
  host?.replaceChildren();
59
95
  currentContext = context;
96
+ options.onRender?.(context, matched?.route);
60
97
  if (!matched) {
61
98
  notFound?.(context);
62
99
  } else {
63
100
  if (matched.route.title) document.title = titlePrefix + matched.route.title;
64
101
  await matched.route.handler(context);
65
102
  }
66
- if (token === renderToken) afterEach?.(context);
103
+ if (token !== renderToken) return;
104
+ if (options.focusContent && host) {
105
+ if (!host.hasAttribute("tabindex")) host.setAttribute("tabindex", "-1");
106
+ host.focus({ preventScroll: true });
107
+ }
108
+ if (options.scrollTop) window.scrollTo(0, 0);
109
+ options.onShown?.(context, matched?.route);
110
+ afterEach?.(context);
111
+ listeners.forEach(listener => listener(context));
67
112
  }
68
113
 
69
114
  const onChange = () => render(readLocation());
@@ -97,6 +142,10 @@ export function createRouter(options = {}) {
97
142
  },
98
143
  navigate,
99
144
  current: () => currentContext,
145
+ onChange(listener) {
146
+ listeners.add(listener);
147
+ return () => listeners.delete(listener);
148
+ },
100
149
  // Value for an anchor's href.
101
150
  href: path => mode === "hash" ? `#${path}` : path
102
151
  };
@@ -56,6 +56,18 @@ const compare = (a, b) =>
56
56
  * @param {(row: object) => string} [options.rowLabel] aria-label of a focusable row
57
57
  * @param {"normal"|"compact"} [options.density="normal"]
58
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
59
71
  * Column extras: `render(row, value)` returns text or a Node (built by the caller, so safe by construction), `align`
60
72
  * ("left" | "center" | "right"), `title` (false switches the tooltip with the full text off).
61
73
  * @returns {{element: HTMLElement, update: Function, destroy: Function, setRows: Function, getSelected: () => object[], clearSelection: Function,
@@ -66,10 +78,19 @@ export function generateTable(options = {}) {
66
78
  parent = "wrapper", id = "table", columns = [], sortable = true,
67
79
  filter = false, selectable = false, resizableColumns = false, onRowClick, onSelectionChange
68
80
  } = options;
81
+ const remote = typeof options.dataSource === "function";
82
+ const rowActions = options.rowActions?.length ? options.rowActions : null;
69
83
  const virtual = options.virtual
70
84
  ? { height: 400, rowHeight: 36, overscan: 5, ...(options.virtual === true ? {} : options.virtual) }
71
85
  : null;
72
- const pageSize = virtual ? 0 : (options.pageSize ?? 0);
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);
73
94
  const host = resolveElement(parent) ?? document.body;
74
95
  let rows = [...(options.rows ?? [])];
75
96
  let current = rows; // filtered and sorted rows
@@ -101,11 +122,14 @@ export function generateTable(options = {}) {
101
122
  filterInput.type = "search";
102
123
  filterInput.placeholder = translate("filter");
103
124
  filterInput.setAttribute("aria-label", translate("filter"));
125
+ let filterTimer = 0;
104
126
  filterInput.addEventListener("input", () => {
105
- state.query = filterInput.value.toLowerCase();
127
+ state.query = remote ? filterInput.value.trim() : filterInput.value.toLowerCase();
106
128
  state.page = 0;
107
129
  if (scroller) scroller.scrollTop = 0;
108
- render();
130
+ if (!remote) return render();
131
+ clearTimeout(filterTimer);
132
+ filterTimer = setTimeout(() => load({ reset: true }), options.filterDelay ?? 300);
109
133
  });
110
134
  root.append(filterInput);
111
135
  }
@@ -120,6 +144,7 @@ export function generateTable(options = {}) {
120
144
  host.append(root);
121
145
 
122
146
  function visibleRows() {
147
+ if (remote) return rows; // the server filtered, sorted and paged them
123
148
  let result = rows;
124
149
  if (state.query) {
125
150
  result = result.filter(row =>
@@ -260,7 +285,8 @@ export function generateTable(options = {}) {
260
285
  const sort = () => {
261
286
  state.descending = state.sortKey === col.key && !state.descending;
262
287
  state.sortKey = col.key;
263
- render();
288
+ if (remote) load({ reset: true });
289
+ else render();
264
290
  };
265
291
  th.addEventListener("click", sort);
266
292
  th.addEventListener("keydown", e => {
@@ -277,6 +303,12 @@ export function generateTable(options = {}) {
277
303
  if (resizableColumns) makeResizer(th, col);
278
304
  tr.append(th);
279
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
+ }
280
312
  const thead = el("thead");
281
313
  thead.append(tr);
282
314
  return thead;
@@ -318,7 +350,7 @@ export function generateTable(options = {}) {
318
350
  tr.setAttribute("aria-hidden", "true");
319
351
  tr.style.height = `${height}px`;
320
352
  const td = el("td");
321
- td.colSpan = columns.length + (selectable ? 1 : 0);
353
+ td.colSpan = colCount();
322
354
  tr.append(td);
323
355
  return tr;
324
356
  }
@@ -326,6 +358,15 @@ export function generateTable(options = {}) {
326
358
  function renderRow(row, index) {
327
359
  const tr = el("tr");
328
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
+ }
329
370
  addClasses(tr, options.rowClass?.(row));
330
371
  if (onRowClick) {
331
372
  tr.classList.add("clickable");
@@ -384,17 +425,52 @@ export function generateTable(options = {}) {
384
425
  }
385
426
  tr.append(td);
386
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);
387
457
  return tr;
388
458
  }
389
459
 
390
460
  function renderBody() {
391
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
+ }
392
472
  if (!current.length) {
393
- const td = el("td", "athena-table-empty", options.emptyText ?? translate("noData"));
394
- td.colSpan = Math.max(columns.length + (selectable ? 1 : 0), 1);
395
- const tr = el("tr");
396
- tr.append(td);
397
- tbody.append(tr);
473
+ tbody.append(messageRow("athena-table-empty", options.emptyText ?? translate("noData")));
398
474
  return tbody;
399
475
  }
400
476
  if (virtual) {
@@ -403,18 +479,58 @@ export function generateTable(options = {}) {
403
479
  rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
404
480
  });
405
481
  windowKey = `${win.start}:${win.end}`;
482
+ if (remoteVirtual) ensureChunks();
406
483
  if (win.offsetTop) tbody.append(spacer(win.offsetTop));
407
484
  for (let i = win.start; i < win.end; i++) tbody.append(renderRow(current[i], i));
408
485
  if (win.offsetBottom) tbody.append(spacer(win.offsetBottom));
409
486
  return tbody;
410
487
  }
411
- 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;
412
489
  for (const row of pageRows) tbody.append(renderRow(row));
413
490
  return tbody;
414
491
  }
415
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
+
416
531
  function renderPager(total) {
417
532
  if (!pager) return;
533
+ if (remote) return renderRemotePager();
418
534
  const pages = Math.max(1, Math.ceil(total / pageSize));
419
535
  state.page = Math.min(state.page, pages - 1);
420
536
  pager.hidden = pages === 1;
@@ -438,6 +554,8 @@ export function generateTable(options = {}) {
438
554
  function render() {
439
555
  const scrollTop = scroller?.scrollTop ?? 0;
440
556
  current = visibleRows();
557
+ root.toggleAttribute("aria-busy", remote && server.loading);
558
+ root.classList.toggle("athena-table-is-loading", remote && server.loading);
441
559
  renderPager(current.length);
442
560
  if (virtual) table.setAttribute("aria-rowcount", String(current.length + 1));
443
561
  const parts = [renderHead(current), renderBody()];
@@ -453,12 +571,13 @@ export function generateTable(options = {}) {
453
571
  // starts empty (a tiny scroll area when the rows are set) still draws a full window.
454
572
  const viewportHeight = () => Math.max(scroller.clientHeight, Math.min(virtual.height, current.length * virtual.rowHeight));
455
573
 
456
- function refreshWindow() {
574
+ function refreshWindow(force = false) {
575
+ if (remoteVirtual) ensureChunks();
457
576
  const win = virtualWindow({
458
577
  scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
459
578
  rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
460
579
  });
461
- if (`${win.start}:${win.end}` === windowKey) return;
580
+ if (!force && `${win.start}:${win.end}` === windowKey) return;
462
581
  const focused = document.activeElement;
463
582
  const keepFocus = focused && table.tBodies[0]?.contains(focused);
464
583
  table.tBodies[0].replaceWith(renderBody());
@@ -470,13 +589,165 @@ export function generateTable(options = {}) {
470
589
  scroller.addEventListener("scroll", () => {
471
590
  if (queued) return;
472
591
  queued = true;
473
- 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;
474
596
  queued = false;
597
+ clearTimeout(timer);
475
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
476
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();
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;
477
679
  });
478
680
  }
479
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
+
480
751
  // The window of rows depends on the height of the scroll area, which is unknown while the list is empty or
481
752
  // not on screen yet: measure again whenever it changes size.
482
753
  if (scroller && typeof ResizeObserver !== "undefined") {
@@ -490,8 +761,11 @@ export function generateTable(options = {}) {
490
761
  }
491
762
 
492
763
  render();
764
+ if (remote) load({ reset: true });
493
765
  return asHandle({
494
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()),
495
769
  // update() draws the table again; update({ rows }) also replaces the rows.
496
770
  update(next) {
497
771
  if (next?.rows) this.setRows(next.rows);
@@ -514,9 +788,9 @@ export function generateTable(options = {}) {
514
788
  },
515
789
  getColumnWidths: () => ({ ...widths }),
516
790
  // The filtered and sorted rows as CSV text
517
- toCsv: () => toCsv(columns, current),
791
+ toCsv: () => toCsv(columns, current.filter(row => row !== undefined)),
518
792
  exportCsv(filename = "table.csv") {
519
- downloadFile(filename, toCsv(columns, current));
793
+ downloadFile(filename, toCsv(columns, current.filter(row => row !== undefined)));
520
794
  }
521
795
  });
522
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
  ];