athena-ui-js 1.1.0 → 1.2.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.
package/README.md CHANGED
@@ -5,7 +5,7 @@ layout (header, menu, content wrapper, footer) from a single `init()` call, load
5
5
  and theme, and ships the building blocks of a multipurpose application: forms, tables, charts,
6
6
  feedback, navigation, a router and more.
7
7
 
8
- Current version: **1.1.0**
8
+ Current version: **1.2.0**
9
9
 
10
10
  [Quick start](#usage) · [API](#api) · [Components](#charts) · [Themes](#themes) · [Tests](#tests) · [Release notes](#releases)
11
11
 
@@ -17,7 +17,7 @@ Known limits are listed below, so you can judge whether it fits your project:
17
17
 
18
18
  - Rich text uses the deprecated `document.execCommand`. Content is sanitized in the browser, but sanitize it on the server too.
19
19
  - The session cookie is readable from JavaScript. It is a UI state, not a security boundary: authenticate on the server.
20
- - Virtual table rows have to be a fixed height, one line per cell.
20
+ - Virtual table rows have to be a fixed height, one line per cell (set it with `virtual.rowHeight`; the CSS variable `--row-height` follows).
21
21
  - Translations: English and Hungarian.
22
22
 
23
23
  ## Features
@@ -120,7 +120,7 @@ the theme are loaded and the layout is generated.
120
120
  | `header_title_text` | `"Athena UI"` | Title in the header |
121
121
  | `header_img_url` | | Header logo URL |
122
122
  | `copyright` | placeholder text | Footer text, the version is appended |
123
- | `version` | `"1.1.0"` | Version shown in the footer |
123
+ | `version` | `"1.2.0"` | Version shown in the footer |
124
124
  | `bordered` | `true` | Draw a border around the layout blocks |
125
125
  | `generateHeader`, `generateFooter` | `true` | Generate the header / footer block |
126
126
  | `generateHeadercontent`, `generateFooterContent`, `generateWrappercontent` | `true` | Generate the content of the block |
@@ -211,6 +211,9 @@ Click a header to sort (disable with `sortable: false`, or per column). Other op
211
211
  - A column with `editable: true` can be edited with a double click, or Enter / F2 on the focused cell. `onEdit(row, key, value, oldValue)` is called after the edit; return `false` to reject it. Numeric cells stay numbers.
212
212
  - `resizableColumns: true` puts a drag handle on every header edge. The handle is focusable too: Left / Right resize by 10 px, Shift by 50 px, double click resets the column to its configured `width`. Columns take `width`, `minWidth` and `maxWidth`; `onColumnResize(key, width)` and `getColumnWidths()` let you persist the layout.
213
213
  - `virtual: { height: 400, rowHeight: 36, overscan: 5 }` (or `virtual: true`) renders only the rows in view and keeps the scroll bar the size of the whole list, so 10 000+ rows stay fast. Rows have a fixed height (the theme enforces it, one line per cell), the table scrolls inside `height` and its header stays visible. It replaces pagination; filtering, sorting, selection, editing and CSV export work as usual.
214
+ - Hooks and looks: `cellClass(row, column)` and `rowClass(row)` return a class name (or a list) for a cell or a row. `focusableRows: true` makes rows reachable with Tab (`rowLabel(row)` is their aria-label); together with `onRowClick` they open with Enter and Space. `density: "compact"`, and `wrap: true | false` (long text wraps, or stays on one line with an ellipsis). The pager is hidden when there is only one page.
215
+ - Column extras: `render(row, value)` returns text or a Node (built by you, so it is safe by construction), `align: "left" | "center" | "right"`. Text longer than 24 characters gets its full text as a tooltip (`title: false` switches it off).
216
+ - A virtual table that starts empty draws a full window as soon as it gets rows, and measures again when the scroll area changes size.
214
217
  - `exportCsv()` downloads the filtered and sorted rows. Cells that start with `=`, `+`, `-` or `@` are prefixed with `'` so a spreadsheet does not run them as formulas.
215
218
 
216
219
  ### Forms
@@ -266,6 +269,10 @@ const name = await promptDialog("Your name", { validate: v => v ? "" : "Required
266
269
  const choice = await showDialog({ title: "Custom", content: "Pick one", buttons: [{ text: "A", value: "a" }, { text: "B", value: "b" }] });
267
270
  ```
268
271
 
272
+ Options: `size` ("small" 360 px, "medium" 480 px, "large" 720 px, "full") and `class` (extra class on the dialog).
273
+ `showDialog` returns a promise that also carries the open dialog: `const dialog = showDialog({ size: "large", ... }); dialog.element; dialog.close(value);`.
274
+ The dialog is shown by a CSS class, not by an inline style, so a strict Content-Security-Policy works.
275
+
269
276
  Dialogs trap the focus, close with Esc (resolving `null` / `false`) and restore the focus. Text content is
270
277
  never parsed as HTML. `openModal` / `closeModal` got the same focus handling.
271
278
 
@@ -275,6 +282,7 @@ never parsed as HTML. `openModal` / `closeModal` got the same focus handling.
275
282
  generateTabs({ parent: "wrapper", tabs: [{ id: "a", label: "A", content: "First" }, { id: "b", label: "B", content: () => lazyNode() }] });
276
283
  generateAccordion({ parent: "wrapper", items: [{ title: "Q", content: "A", open: true }], multiple: false });
277
284
  generateDropdown({ parent: "wrapper", label: "Actions", items: [{ label: "Edit", onclick }, { divider: true }, { label: "Delete", onclick }] });
285
+ generateDropdown({ parent: "wrapper", icon: "⋮", ariaLabel: "More actions", items: [{ label: "Edit", onclick }] }); // icon only; also caret: true, toggleClass
278
286
  generatePagination({ parent: "wrapper", total: 200, pageSize: 10, onChange: page => load(page) });
279
287
  generateBreadcrumbs({ parent: "wrapper", items: [{ label: "Home", href: "#/" }, { label: "Users" }] });
280
288
  generateSidebar({ parent: "wrapper", active: "home", onSelect: item => go(item.id),
@@ -441,6 +449,29 @@ The default theme is in `src/res/themes/default/style.css`; `{ id: 1 }` is a dar
441
449
 
442
450
  Switch themes at runtime with `setTheme({ id: 1 })`.
443
451
 
452
+ ### Parents and handles
453
+
454
+ Every `parent` option takes an element, an id or a CSS selector (`"wrapper"`, `"#list"`, `".panel > ul"`; an id wins over a selector).
455
+ The components return the same kind of handle: `{ element, update(), destroy() }`, plus their own methods. `destroy()` removes the
456
+ component. `update()` redraws it where that makes sense (`table.update({ rows })`, `chart.update({ series })`, `stat.update({ value })`,
457
+ `progress.update({ value })`) and otherwise just returns the handle. `generateChart` still returns the SVG element, which also carries
458
+ `element`, `update(options)` and `destroy()`.
459
+
460
+ ### Testing your application
461
+
462
+ ```js
463
+ import { JSDOM } from "jsdom";
464
+ import { installDom, until, tick } from "athena-ui-js/testing";
465
+
466
+ const dom = installDom(JSDOM); // window, document, Node, Event, ... become global
467
+ generateDropdown({ parent: "#wrapper", icon: "x", ariaLabel: "More", items: [] });
468
+ await until(() => document.querySelector(".dropdown"), { message: "the dropdown" });
469
+ dom.uninstall();
470
+ ```
471
+
472
+ `installDom` takes your own `JSDOM` class, so Athena UI has no dependency on jsdom. Athena creates its events from the element's own
473
+ window, so they work in jsdom without a global `Event`.
474
+
444
475
  ## Tests
445
476
 
446
477
  ```sh
@@ -481,6 +512,19 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
481
512
 
482
513
  ## Releases
483
514
 
515
+ ### 1.2.0
516
+ #### Added:
517
+ 1. Dialogs: `size` and `class` options, and the open dialog (`element`, `backdrop`, `close()`) on the returned promise
518
+ 2. Tables: `cellClass`, `rowClass`, `focusableRows` / `rowLabel`, `density`, `wrap`, column `render` (text or Node), `align`, tooltip for cut text
519
+ 3. Dropdown: `icon`, `ariaLabel`, `caret`, `toggleClass`; the label is optional
520
+ 4. Every `parent` option takes an element, an id or a CSS selector; the components share the handle `{ element, update(), destroy() }`
521
+ 5. `athena-ui-js/testing`: `installDom`, `until`, `tick`
522
+ #### Changed:
523
+ 1. The dialog backdrop is shown by a CSS class, not by an inline style (works with a strict Content-Security-Policy)
524
+ 2. Virtual tables: a list that starts empty draws a full window, the window is measured again when the scroll area changes size, and the cell padding no longer loses against the application's `td` padding
525
+ 3. The combobox creates its events from the element's own window (no more jsdom errors)
526
+ 4. The pager of a table with one page is hidden
527
+
484
528
  ### 1.1.0
485
529
  #### Added:
486
530
  1. `generateDropZone` / `createDropZone`: drag-and-drop area with file type, size and count checks
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "athena-ui-js",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "A small jQuery based UI framework: generated page layout, menus, login / registration / lost password forms, charts, tables, modals and themes, written as ES modules.",
5
5
  "type": "module",
6
6
  "main": "./src/athena-ui.js",
@@ -10,11 +10,13 @@
10
10
  },
11
11
  "exports": {
12
12
  ".": "./src/athena-ui.js",
13
+ "./testing": "./src/testing.js",
13
14
  "./themes/*": "./src/res/themes/*",
14
15
  "./package.json": "./package.json"
15
16
  },
16
17
  "files": [
17
18
  "src/athena-ui.js",
19
+ "src/testing.js",
18
20
  "src/libs/libs.js",
19
21
  "src/libs/config",
20
22
  "src/libs/hephaestus/hephaestus.js",
package/src/athena-ui.js CHANGED
@@ -2,7 +2,7 @@
2
2
  //Author: Csaba Tóth https://github.com/csabatibortoth/
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
- //Version: 1.1.0
5
+ //Version: 1.2.0
6
6
 
7
7
  /* global $ */
8
8
 
@@ -6,7 +6,7 @@
6
6
  export const BORDERED_CLASS = "default-cointainer-bordered";
7
7
 
8
8
  export const defaults = Object.freeze({
9
- version: "1.1.0",
9
+ version: "1.2.0",
10
10
  container_class: "container",
11
11
  header_class: "header-container",
12
12
  header_menu_class: "header-menu menu",
@@ -36,7 +36,7 @@ export function createCombobox(options = {}) {
36
36
  const element = el("div", { class: cx("combobox", multiple && "combobox-multiple", options.class) }, chips, input, list);
37
37
 
38
38
  const notify = () => {
39
- input.dispatchEvent(new Event("change", { bubbles: true }));
39
+ input.dispatchEvent(new (input.ownerDocument.defaultView.Event)("change", { bubbles: true }));
40
40
  onChange?.(getValue());
41
41
  };
42
42
  const isOpen = () => !list.hidden;
@@ -47,11 +47,38 @@ export function setContent(node, content) {
47
47
  return node;
48
48
  }
49
49
 
50
- // Appends a node to a parent given as element or id. Falls back to the body.
50
+ /**
51
+ * Finds an element from an element, an id or a CSS selector ("#list", ".panel > ul").
52
+ * An id wins over a selector with the same text. Returns null when nothing matches.
53
+ */
54
+ export function resolveElement(target) {
55
+ if (target instanceof Element) return target;
56
+ if (typeof target !== "string" || !target) return null;
57
+ const byId = document.getElementById(target);
58
+ if (byId) return byId;
59
+ try {
60
+ return document.querySelector(target);
61
+ } catch {
62
+ return null; // not a valid selector
63
+ }
64
+ }
65
+
66
+ // Appends a node to a parent given as element, id or selector. Falls back to the body.
51
67
  export function mount(parent, node) {
52
- const host = typeof parent === "string" ? document.getElementById(parent) : parent;
53
- (host ?? document.body).append(node);
68
+ (resolveElement(parent) ?? document.body).append(node);
54
69
  return node;
55
70
  }
56
71
 
72
+ /**
73
+ * Gives a component the same handle as every other one: { element, update(), destroy() }.
74
+ * What the component already has is kept. `update` does nothing unless the component supports it
75
+ * (it returns the handle), `destroy` removes the element (and `also`, e.g. a wrapper around it).
76
+ */
77
+ export function asHandle(handle, { element = handle.element, also } = {}) {
78
+ handle.element ??= element;
79
+ handle.update ??= () => handle;
80
+ handle.destroy ??= () => (also ?? element)?.remove();
81
+ return handle;
82
+ }
83
+
57
84
  export const cx = (...classes) => classes.filter(Boolean).join(" ");
@@ -5,6 +5,8 @@
5
5
 
6
6
  // Dependency free SVG charts: bar, line, pie and donut.
7
7
 
8
+ import { resolveElement } from "../../core/dom.js";
9
+
8
10
  const NS = "http://www.w3.org/2000/svg";
9
11
  const PALETTE = ["#4e79a7", "#f28e2b", "#e15759", "#76b7b2", "#59a14f", "#edc948", "#b07aa1", "#ff9da7", "#9c755f", "#bab0ac"];
10
12
  const MARGIN = { top: 40, right: 20, bottom: 50, left: 55 };
@@ -157,10 +159,42 @@ const DRAWERS = {
157
159
  * @param {number} [options.width=600]
158
160
  * @param {number} [options.height=360]
159
161
  * @param {boolean} [options.legend] default: shown for several series, and for pie / donut
160
- * @returns {SVGElement|null} null when the options are invalid
162
+ * @returns {(SVGElement & {element: SVGElement, update: (options?: object) => void, destroy: () => void})|null}
163
+ * the SVG element, which also carries the handle ({ element, update(options), destroy() }) of the other
164
+ * components; null when the options are invalid. `parent` is an element, an id or a selector.
161
165
  */
162
166
  export function generateChart(options = {}) {
163
- const { type = "bar", parent = "wrapper", id, title, width = 600, height = 360 } = options;
167
+ const svg = buildChart(options);
168
+ if (!svg) return null;
169
+ (resolveElement(options.parent ?? "wrapper") ?? document.body).append(svg);
170
+ return withHandle(svg, options);
171
+ }
172
+
173
+ // update(changes) draws the chart again with the old options plus the changes, in the same place.
174
+ function withHandle(svg, options) {
175
+ let current = svg;
176
+ let used = options;
177
+ const handle = {
178
+ get element() { return current; },
179
+ update(changes = {}) {
180
+ const next = buildChart({ ...used, ...changes });
181
+ if (!next) return current;
182
+ used = { ...used, ...changes };
183
+ current.replaceWith(next);
184
+ current = withHandle(next, used);
185
+ return current;
186
+ },
187
+ destroy() { current.remove(); }
188
+ };
189
+ return Object.defineProperties(svg, {
190
+ element: { get: () => handle.element, configurable: true },
191
+ update: { value: handle.update, configurable: true },
192
+ destroy: { value: handle.destroy, configurable: true }
193
+ });
194
+ }
195
+
196
+ function buildChart(options = {}) {
197
+ const { type = "bar", id, title, width = 600, height = 360 } = options;
164
198
  const draw = DRAWERS[type];
165
199
  const series = (options.series ?? []).filter(s => Array.isArray(s?.data) && s.data.length);
166
200
  if (!draw || !series.length) {
@@ -182,6 +216,5 @@ export function generateChart(options = {}) {
182
216
  if (options.legend ?? (Boolean(pieLegend) || series.length > 1)) {
183
217
  addLegend(svg, pieLegend ?? series.map((s, i) => ({ name: s.name ?? `Series ${i + 1}`, color: colorOf(s, i) })), width, height);
184
218
  }
185
- (document.getElementById(parent) ?? document.body).append(svg);
186
219
  return svg;
187
220
  }
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { cx, el, mount, setContent, uid } from "../../core/dom.js";
6
+ import { asHandle, cx, el, mount, resolveElement, setContent, uid } from "../../core/dom.js";
7
7
 
8
8
  /**
9
9
  * Generates a link. External links open in a new tab and get `rel="noopener noreferrer"`.
@@ -81,7 +81,7 @@ export function generateCard(options = {}) {
81
81
  card.append(body);
82
82
  if (options.footer) card.append(setContent(el("div", { class: "card-footer" }), options.footer));
83
83
  mount(options.parent, card);
84
- return { element: card, body };
84
+ return asHandle({ element: card, body });
85
85
  }
86
86
 
87
87
  /**
@@ -155,7 +155,8 @@ export function generateStat(options = {}) {
155
155
  element.append(el("div", { class: cx("stat-delta", `stat-${kind}`), text: `${arrow} ${Math.abs(options.delta)}%` }));
156
156
  }
157
157
  mount(options.parent, element);
158
- return { element, setValue: text => { value.textContent = String(text); } };
158
+ const setValue = text => { value.textContent = String(text); };
159
+ return asHandle({ element, setValue, update: ({ value: text } = {}) => { if (text != null) setValue(text); } });
159
160
  }
160
161
 
161
162
  /**
@@ -181,7 +182,7 @@ export function generateGrid(options = {}) {
181
182
  * @param {string} text
182
183
  */
183
184
  export function generateTooltip(target, text) {
184
- const node = typeof target === "string" ? document.getElementById(target) : target;
185
+ const node = resolveElement(target);
185
186
  if (!node) return null;
186
187
  const id = uid("tooltip");
187
188
  const tip = el("span", { class: "tooltip-text", id, text, attrs: { role: "tooltip" } });
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { el, setContent, uid } from "../../core/dom.js";
6
+ import { cx, el, setContent, uid } from "../../core/dom.js";
7
7
  import { trapFocus } from "../../core/focus.js";
8
8
  import { translate } from "../../core/i18n.js";
9
9
  import { generateButton } from "../formGenerator/formBuilder.js";
@@ -18,21 +18,25 @@ import { generateButton } from "../formGenerator/formBuilder.js";
18
18
  * @param {{text: string, value?: *, variant?: string, autofocus?: boolean}[]} [options.buttons]
19
19
  * @param {boolean} [options.dismissible=true]
20
20
  * @param {(value) => (boolean|Promise<boolean>)} [options.beforeClose] return false to keep the dialog open
21
- * @returns {Promise<*>} resolves with the pressed button's value
21
+ * @param {"small"|"medium"|"large"|"full"} [options.size="medium"] width of the dialog (360 / 480 / 720 px / the whole window)
22
+ * @param {string} [options.class] extra CSS class(es) of the dialog element
23
+ * @returns {Promise<*> & {element: HTMLElement, backdrop: HTMLElement, close: (value?) => Promise<void>}}
24
+ * resolves with the pressed button's value; the promise also carries the handle of the open dialog
22
25
  */
23
26
  export function showDialog(options = {}) {
24
27
  const { title, content, buttons = [{ text: translate("ok"), value: true }], dismissible = true } = options;
25
- return new Promise(resolve => {
28
+ let handle;
29
+ const promise = new Promise(resolve => {
26
30
  const titleId = uid("dialog-title");
27
31
  const body = setContent(el("div", { class: "dialog-body" }), content);
28
32
  const footer = el("div", { class: "dialog-footer" });
29
33
  const dialog = el("div", {
30
- class: "modal-content dialog",
34
+ class: cx("modal-content dialog", options.size && `dialog-${options.size}`, options.class),
31
35
  attrs: { role: "dialog", "aria-modal": "true", "aria-labelledby": title ? titleId : null }
32
36
  });
33
37
  if (title) dialog.append(el("h2", { class: "dialog-title", id: titleId, text: title }));
34
38
  dialog.append(body, footer);
35
- const backdrop = el("div", { class: "modal dialog-backdrop", attrs: { style: "display: block" } }, dialog);
39
+ const backdrop = el("div", { class: "modal dialog-backdrop" }, dialog);
36
40
 
37
41
  let release = () => {};
38
42
  let closing = false;
@@ -70,7 +74,10 @@ export function showDialog(options = {}) {
70
74
  document.body.append(backdrop);
71
75
  release = trapFocus(dialog, { onEscape: dismissible ? () => close(null) : undefined });
72
76
  dialog.querySelector("[data-autofocus]")?.focus();
77
+ handle = { element: dialog, backdrop, close: value => close(value ?? null) };
73
78
  });
79
+ // The executor above runs synchronously, so the handle exists here.
80
+ return Object.assign(promise, handle);
74
81
  }
75
82
 
76
83
  /** Message with an OK button. Resolves when it is closed. */
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { cx, el, mount, setContent } from "../../core/dom.js";
6
+ import { asHandle, cx, el, mount, setContent } from "../../core/dom.js";
7
7
  import { translate } from "../../core/i18n.js";
8
8
 
9
9
  const TOAST_CONTAINER_ID = "athena-toasts";
@@ -134,5 +134,5 @@ export function generateProgress(options = {}) {
134
134
  };
135
135
  setValue(options.value);
136
136
  mount(options.parent, element);
137
- return { element, setValue };
137
+ return asHandle({ element, setValue, update: ({ value } = {}) => setValue(value) });
138
138
  }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { createCombobox } from "../../core/combobox.js";
7
7
  import { createDateRange } from "../../core/dateRange.js";
8
- import { cx, el, mount, uid } from "../../core/dom.js";
8
+ import { asHandle, cx, el, mount, uid } from "../../core/dom.js";
9
9
  import { translate } from "../../core/i18n.js";
10
10
  import { validateDateRange, validateValue } from "../../core/validation.js";
11
11
  import { createRichText, createWysiwyg } from "../inputGenerator/richTextGenerator.js";
@@ -58,7 +58,7 @@ export function generateButton(options = {}) {
58
58
  sync();
59
59
  }
60
60
  mount(options.parent, element);
61
- return {
61
+ return asHandle({
62
62
  element,
63
63
  setLoading(value) {
64
64
  loading = Boolean(value);
@@ -71,7 +71,7 @@ export function generateButton(options = {}) {
71
71
  setText(text) {
72
72
  label.textContent = text;
73
73
  }
74
- };
74
+ });
75
75
  }
76
76
 
77
77
  /* ------------------FIELD------------------- */
@@ -277,7 +277,7 @@ export function generateField(options = {}) {
277
277
  if (event === "change" || event === "input") onChange?.(getValue(), field);
278
278
  }));
279
279
  });
280
- return field;
280
+ return asHandle(field);
281
281
  }
282
282
 
283
283
  /* ------------------FORM------------------- */
@@ -375,5 +375,5 @@ export function generateForm(options = {}) {
375
375
  });
376
376
 
377
377
  mount(options.parent, element);
378
- return form;
378
+ return asHandle(form);
379
379
  }
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { cx, el, mount, setContent, uid } from "../../core/dom.js";
6
+ import { asHandle, cx, el, mount, setContent, uid } from "../../core/dom.js";
7
7
  import { formatBytes, matchesAccept } from "../../core/format.js";
8
8
  import { translate } from "../../core/i18n.js";
9
9
 
@@ -114,5 +114,5 @@ export function createDropZone(options = {}) {
114
114
  export function generateDropZone(options = {}) {
115
115
  const zone = createDropZone(options);
116
116
  mount(options.parent, zone.element);
117
- return zone;
117
+ return asHandle(zone);
118
118
  }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { createCombobox } from "../../core/combobox.js";
7
7
  import { createDateRange } from "../../core/dateRange.js";
8
- import { cx, el, mount, setContent, uid } from "../../core/dom.js";
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";
11
11
  import { generateButton } from "../formGenerator/formBuilder.js";
@@ -46,7 +46,7 @@ function wrapCombobox(options, mode) {
46
46
  if (options.label) wrapper.append(el("label", { class: "field-label", text: options.label, attrs: { for: id } }));
47
47
  wrapper.append(combo.element);
48
48
  mount(options.parent, wrapper);
49
- return combo;
49
+ return asHandle(combo, { also: wrapper });
50
50
  }
51
51
 
52
52
  /* ------------------DATE RANGE------------------- */
@@ -73,7 +73,7 @@ export function generateDateRange(options = {}) {
73
73
  wrapper.append(range.element, error);
74
74
  range.element.addEventListener("change", () => { error.textContent = range.validate(); });
75
75
  mount(options.parent, wrapper);
76
- return range;
76
+ return asHandle(range, { also: wrapper });
77
77
  }
78
78
 
79
79
  /* ------------------FILE UPLOAD------------------- */
@@ -196,13 +196,13 @@ export function generateFileUpload(options = {}) {
196
196
  }
197
197
 
198
198
  mount(options.parent, element);
199
- return {
199
+ return asHandle({
200
200
  element,
201
201
  getFiles: () => entries.map(entry => entry.file),
202
202
  upload,
203
203
  clear: () => entries.slice().forEach(remove),
204
204
  add
205
- };
205
+ });
206
206
  }
207
207
 
208
208
  /* ------------------STEPPER (wizard)------------------- */
@@ -273,12 +273,12 @@ export function generateStepper(options = {}) {
273
273
 
274
274
  mount(options.parent, element);
275
275
  if (steps.length) show(0);
276
- return {
276
+ return asHandle({
277
277
  element,
278
278
  next,
279
279
  back,
280
280
  // Going back is always possible, going forward only one step at a time through next().
281
281
  goTo: index => { if (index >= 0 && index < current) show(index); },
282
282
  getCurrent: () => current
283
- };
283
+ });
284
284
  }
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { cx, el, mount, uid } from "../../core/dom.js";
6
+ import { asHandle, cx, el, mount, uid } from "../../core/dom.js";
7
7
  import { translate } from "../../core/i18n.js";
8
8
  import { htmlToText, isSafeUrl, sanitizeHtml } from "../../core/sanitize.js";
9
9
 
@@ -244,7 +244,7 @@ export function generateRichText(options = {}) {
244
244
  }
245
245
  wrapper.append(rich.element);
246
246
  mount(options.parent, wrapper);
247
- return rich;
247
+ return asHandle(rich, { also: wrapper });
248
248
  }
249
249
 
250
250
  /**
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { cx, el, mount, setContent, uid } from "../../core/dom.js";
6
+ import { asHandle, cx, el, mount, setContent, uid } from "../../core/dom.js";
7
7
  import { translate } from "../../core/i18n.js";
8
8
  import { pageRange } from "../../core/pagination.js";
9
9
 
@@ -85,7 +85,7 @@ export function generateTabs(options = {}) {
85
85
 
86
86
  mount(options.parent, element);
87
87
  select(options.active ?? tabs.find(tab => !tab.disabled)?.id);
88
- return { element, select, getActive: () => active };
88
+ return asHandle({ element, select, getActive: () => active });
89
89
  }
90
90
 
91
91
  /* ------------------BREADCRUMBS------------------- */
@@ -169,7 +169,7 @@ export function generatePagination(options = {}) {
169
169
 
170
170
  render();
171
171
  mount(options.parent, element);
172
- return {
172
+ return asHandle({
173
173
  element,
174
174
  getPage: () => page,
175
175
  setPage: go,
@@ -177,7 +177,7 @@ export function generatePagination(options = {}) {
177
177
  total = value;
178
178
  render();
179
179
  }
180
- };
180
+ });
181
181
  }
182
182
 
183
183
  /* ------------------ACCORDION------------------- */
@@ -226,7 +226,7 @@ export function generateAccordion(options = {}) {
226
226
  (options.items ?? []).forEach((item, index) => { if (item.open) toggle(index, true); });
227
227
 
228
228
  mount(options.parent, element);
229
- return { element, toggle };
229
+ return asHandle({ element, toggle });
230
230
  }
231
231
 
232
232
  /* ------------------DROPDOWN------------------- */
@@ -236,7 +236,11 @@ export function generateAccordion(options = {}) {
236
236
  *
237
237
  * @param {object} options
238
238
  * @param {string|Element} [options.parent]
239
- * @param {string} options.label button text
239
+ * @param {string} [options.label] button text (leave it out for an icon-only button, and give `ariaLabel`)
240
+ * @param {string|Node} [options.icon] shown before the label, text or a Node (e.g. an SVG); hidden from screen readers
241
+ * @param {string} [options.ariaLabel] accessible name, needed when there is no label
242
+ * @param {boolean} [options.caret=false] show a small arrow after the label
243
+ * @param {string} [options.toggleClass] extra CSS class(es) of the toggle button
240
244
  * @param {{label?: string, onclick?: Function, href?: string, disabled?: boolean, divider?: boolean}[]} options.items
241
245
  * @param {"left"|"right"} [options.align="left"]
242
246
  * @returns {{element: HTMLElement, open: Function, close: Function}}
@@ -245,10 +249,15 @@ export function generateDropdown(options = {}) {
245
249
  const menuId = uid("dropdown");
246
250
  const menu = el("div", { class: cx("dropdown-menu", options.align === "right" && "dropdown-right"), id: menuId, attrs: { role: "menu", hidden: true } });
247
251
  const button = el("button", {
248
- class: "athena-button button-secondary dropdown-toggle",
249
- text: options.label,
250
- attrs: { type: "button", "aria-haspopup": "menu", "aria-expanded": "false", "aria-controls": menuId }
252
+ class: cx("athena-button button-secondary dropdown-toggle", options.icon && !options.label && "dropdown-icon-only", options.toggleClass),
253
+ attrs: {
254
+ type: "button", "aria-haspopup": "menu", "aria-expanded": "false", "aria-controls": menuId,
255
+ "aria-label": options.ariaLabel
256
+ }
251
257
  });
258
+ if (options.icon) button.append(setContent(el("span", { class: "dropdown-icon", attrs: { "aria-hidden": "true" } }), options.icon));
259
+ if (options.label) button.append(document.createTextNode(options.label));
260
+ if (options.caret) button.append(el("span", { class: "dropdown-caret", text: "▾", attrs: { "aria-hidden": "true" } }));
252
261
  const element = el("div", { id: options.id, class: cx("dropdown", options.class) }, button, menu);
253
262
 
254
263
  const enabledItems = () => [...menu.querySelectorAll("[role=menuitem]:not([disabled])")];
@@ -305,7 +314,7 @@ export function generateDropdown(options = {}) {
305
314
  });
306
315
 
307
316
  mount(options.parent, element);
308
- return { element, open, close };
317
+ return asHandle({ element, open, close });
309
318
  }
310
319
 
311
320
  /* ------------------SIDEBAR------------------- */
@@ -384,5 +393,5 @@ export function generateSidebar(options = {}) {
384
393
 
385
394
  mount(options.parent, element);
386
395
  if (options.active) select(options.active);
387
- return { element, select, toggle };
396
+ return asHandle({ element, select, toggle });
388
397
  }
@@ -3,6 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
+ import { resolveElement } from "../../core/dom.js";
6
7
  import { matchRoute, normalizePath, parseQuery } from "./matchRoute.js";
7
8
 
8
9
  /**
@@ -53,7 +54,7 @@ export function createRouter(options = {}) {
53
54
  return;
54
55
  }
55
56
 
56
- const host = document.getElementById(outlet);
57
+ const host = resolveElement(outlet);
57
58
  host?.replaceChildren();
58
59
  currentContext = context;
59
60
  if (!matched) {
@@ -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,15 @@ 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
+ * Column extras: `render(row, value)` returns text or a Node (built by the caller, so safe by construction), `align`
60
+ * ("left" | "center" | "right"), `title` (false switches the tooltip with the full text off).
61
+ * @returns {{element: HTMLElement, update: Function, destroy: Function, setRows: Function, getSelected: () => object[], clearSelection: Function,
49
62
  * getColumnWidths: () => Object<string, number>, toCsv: () => string, exportCsv: (filename?: string) => void}}
50
63
  */
51
64
  export function generateTable(options = {}) {
@@ -57,7 +70,7 @@ export function generateTable(options = {}) {
57
70
  ? { height: 400, rowHeight: 36, overscan: 5, ...(options.virtual === true ? {} : options.virtual) }
58
71
  : null;
59
72
  const pageSize = virtual ? 0 : (options.pageSize ?? 0);
60
- const host = (typeof parent === "string" ? document.getElementById(parent) : parent) ?? document.body;
73
+ const host = resolveElement(parent) ?? document.body;
61
74
  let rows = [...(options.rows ?? [])];
62
75
  let current = rows; // filtered and sorted rows
63
76
  const selected = new Set();
@@ -70,6 +83,9 @@ export function generateTable(options = {}) {
70
83
  root.id = id;
71
84
  const table = el("table", `athena-table ${options.class ?? ""}`.trim());
72
85
  if (resizableColumns) table.classList.add("athena-table-resizable");
86
+ if (options.density === "compact") table.classList.add("athena-table-compact");
87
+ if (options.wrap === true) table.classList.add("athena-table-wrap");
88
+ else if (options.wrap === false) table.classList.add("athena-table-nowrap");
73
89
  let scroller = null;
74
90
  if (virtual) {
75
91
  table.classList.add("athena-table-virtual");
@@ -310,10 +326,23 @@ export function generateTable(options = {}) {
310
326
  function renderRow(row, index) {
311
327
  const tr = el("tr");
312
328
  if (virtual) tr.setAttribute("aria-rowindex", String(index + 2));
329
+ addClasses(tr, options.rowClass?.(row));
313
330
  if (onRowClick) {
314
331
  tr.classList.add("clickable");
315
332
  tr.addEventListener("click", () => onRowClick(row));
316
333
  }
334
+ if (options.focusableRows) {
335
+ tr.tabIndex = 0;
336
+ if (options.rowLabel) tr.setAttribute("aria-label", options.rowLabel(row));
337
+ if (onRowClick) {
338
+ tr.addEventListener("keydown", e => {
339
+ if (e.target === tr && (e.key === "Enter" || e.key === " ")) {
340
+ e.preventDefault();
341
+ onRowClick(row);
342
+ }
343
+ });
344
+ }
345
+ }
317
346
  if (selectable) {
318
347
  const td = el("td", "athena-table-select");
319
348
  const box = el("input");
@@ -332,7 +361,16 @@ export function generateTable(options = {}) {
332
361
  }
333
362
  for (const col of columns) {
334
363
  const value = row[col.key];
335
- const td = el("td", null, col.format ? col.format(value, row) : (value ?? ""));
364
+ const content = col.render ? col.render(row, value) : (col.format ? col.format(value, row) : (value ?? ""));
365
+ const td = el("td");
366
+ if (content instanceof Node) td.append(content);
367
+ else {
368
+ td.textContent = content;
369
+ // Text that may be cut off gets its full text as a tooltip.
370
+ if (col.title !== false && String(content).length > 24) td.title = String(content);
371
+ }
372
+ if (col.align) td.classList.add(`athena-align-${col.align}`);
373
+ addClasses(td, options.cellClass?.(row, col));
336
374
  if (col.editable) {
337
375
  td.classList.add("editable");
338
376
  td.tabIndex = 0;
@@ -361,7 +399,7 @@ export function generateTable(options = {}) {
361
399
  }
362
400
  if (virtual) {
363
401
  const win = virtualWindow({
364
- scrollTop: scroller.scrollTop, viewportHeight: scroller.clientHeight || virtual.height,
402
+ scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
365
403
  rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
366
404
  });
367
405
  windowKey = `${win.start}:${win.end}`;
@@ -379,6 +417,7 @@ export function generateTable(options = {}) {
379
417
  if (!pager) return;
380
418
  const pages = Math.max(1, Math.ceil(total / pageSize));
381
419
  state.page = Math.min(state.page, pages - 1);
420
+ pager.hidden = pages === 1;
382
421
  const button = (text, disabled, delta) => {
383
422
  const b = el("button", null, text);
384
423
  b.type = "button";
@@ -410,6 +449,22 @@ export function generateTable(options = {}) {
410
449
  }
411
450
 
412
451
  // Scrolling only swaps the body, and only when the window of rows really changed.
452
+ // 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
453
+ // starts empty (a tiny scroll area when the rows are set) still draws a full window.
454
+ const viewportHeight = () => Math.max(scroller.clientHeight, Math.min(virtual.height, current.length * virtual.rowHeight));
455
+
456
+ function refreshWindow() {
457
+ const win = virtualWindow({
458
+ scrollTop: scroller.scrollTop, viewportHeight: viewportHeight(),
459
+ rowHeight: virtual.rowHeight, total: current.length, overscan: virtual.overscan
460
+ });
461
+ if (`${win.start}:${win.end}` === windowKey) return;
462
+ const focused = document.activeElement;
463
+ const keepFocus = focused && table.tBodies[0]?.contains(focused);
464
+ table.tBodies[0].replaceWith(renderBody());
465
+ if (keepFocus) scroller.focus({ preventScroll: true });
466
+ }
467
+
413
468
  if (scroller) {
414
469
  let queued = false;
415
470
  scroller.addEventListener("scroll", () => {
@@ -417,22 +472,32 @@ export function generateTable(options = {}) {
417
472
  queued = true;
418
473
  requestAnimationFrame(() => {
419
474
  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 });
475
+ refreshWindow();
429
476
  });
430
477
  });
431
478
  }
432
479
 
480
+ // The window of rows depends on the height of the scroll area, which is unknown while the list is empty or
481
+ // not on screen yet: measure again whenever it changes size.
482
+ if (scroller && typeof ResizeObserver !== "undefined") {
483
+ let lastHeight = 0;
484
+ new ResizeObserver(() => {
485
+ const height = scroller.clientHeight;
486
+ if (height === lastHeight) return;
487
+ lastHeight = height;
488
+ refreshWindow();
489
+ }).observe(scroller);
490
+ }
491
+
433
492
  render();
434
- return {
493
+ return asHandle({
435
494
  element: root,
495
+ // update() draws the table again; update({ rows }) also replaces the rows.
496
+ update(next) {
497
+ if (next?.rows) this.setRows(next.rows);
498
+ else render();
499
+ return this;
500
+ },
436
501
  setRows(newRows) {
437
502
  rows = [...newRows];
438
503
  selected.clear();
@@ -453,5 +518,5 @@ export function generateTable(options = {}) {
453
518
  exportCsv(filename = "table.csv") {
454
519
  downloadFile(filename, toCsv(columns, current));
455
520
  }
456
- };
521
+ });
457
522
  }
@@ -448,16 +448,22 @@ textarea {
448
448
  /* Dialog (built on .modal) */
449
449
 
450
450
  .dialog-backdrop {
451
+ display: block; /* shown by the class, not by an inline style (CSP) */
451
452
  padding-top: 12vh;
452
453
  }
453
454
 
454
455
  .dialog {
455
456
  position: relative;
456
- width: min(480px, 92%);
457
+ width: min(var(--dialog-width, 480px), 92%);
457
458
  border-radius: var(--athena-radius);
458
459
  box-shadow: var(--athena-shadow);
459
460
  }
460
461
 
462
+ .dialog-small { --dialog-width: 360px; }
463
+ .dialog-medium { --dialog-width: 480px; }
464
+ .dialog-large { --dialog-width: 720px; }
465
+ .dialog-full { --dialog-width: 100%; min-height: calc(100vh - 12vh - 40px); }
466
+
461
467
  .dialog-title {
462
468
  margin: 0 28px 12px 0;
463
469
  }
@@ -1141,6 +1147,37 @@ textarea {
1141
1147
  margin-top: 8px;
1142
1148
  }
1143
1149
 
1150
+ .athena-table-pager[hidden] {
1151
+ display: none;
1152
+ }
1153
+
1154
+ /* Table options: density, wrapping, alignment */
1155
+
1156
+ .athena-table.athena-table-compact th,
1157
+ .athena-table.athena-table-compact td {
1158
+ padding: 2px 6px;
1159
+ }
1160
+
1161
+ .athena-table.athena-table-nowrap td {
1162
+ white-space: nowrap;
1163
+ overflow: hidden;
1164
+ text-overflow: ellipsis;
1165
+ max-width: 0;
1166
+ }
1167
+
1168
+ .athena-table.athena-table-wrap td {
1169
+ white-space: normal;
1170
+ overflow-wrap: anywhere;
1171
+ }
1172
+
1173
+ .athena-table td.athena-align-center { text-align: center; }
1174
+ .athena-table td.athena-align-right { text-align: right; }
1175
+
1176
+ .athena-table tr:focus-visible {
1177
+ outline: 2px solid var(--athena-focus, currentColor);
1178
+ outline-offset: -2px;
1179
+ }
1180
+
1144
1181
  /* Charts */
1145
1182
 
1146
1183
  .athena-chart {
@@ -1332,7 +1369,8 @@ textarea {
1332
1369
  }
1333
1370
 
1334
1371
  /* The window of rows is computed from a fixed row height, so every row has to be exactly that high. */
1335
- .athena-table-virtual td {
1372
+ /* The doubled class beats a general `.athena-table td` padding of the application. */
1373
+ .athena-table.athena-table-virtual td {
1336
1374
  box-sizing: border-box;
1337
1375
  height: var(--row-height, 36px);
1338
1376
  padding-top: 0;
package/src/testing.js ADDED
@@ -0,0 +1,71 @@
1
+ //testing helpers 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
+ // Helpers for the tests of an application that uses Athena UI (Node's test runner and jsdom, or a browser).
7
+ // They have no dependency of their own: you give installDom the JSDOM class of your own jsdom.
8
+ //
9
+ // import { JSDOM } from "jsdom";
10
+ // import { installDom, until, tick } from "athena-ui-js/testing";
11
+ // const dom = installDom(JSDOM);
12
+ // ...
13
+ // dom.uninstall();
14
+
15
+ const GLOBALS = ["window", "document", "navigator", "Node", "Element", "HTMLElement", "Event", "CustomEvent", "KeyboardEvent",
16
+ "MouseEvent", "PointerEvent", "DocumentFragment", "MutationObserver", "getComputedStyle", "requestAnimationFrame",
17
+ "cancelAnimationFrame", "localStorage", "location"];
18
+
19
+ const BOUND = new Set(["getComputedStyle", "requestAnimationFrame", "cancelAnimationFrame"]);
20
+
21
+ /**
22
+ * Makes a jsdom window the global one, so Athena components can run in Node.
23
+ * The components create their events from the element's own window, so no global Event is needed for them,
24
+ * but code written without that care (and tests) can still use `new Event(...)`.
25
+ *
26
+ * @param {new (html?: string, options?: object) => {window: object}} JSDOM the JSDOM class of jsdom
27
+ * @param {string} [html] page to start with
28
+ * @param {object} [options] passed to JSDOM (default: url "http://localhost/", pretendToBeVisual so animation frames work)
29
+ * @returns {{window: object, document: Document, uninstall: () => void}}
30
+ */
31
+ export function installDom(JSDOM, html = '<!doctype html><html><body><div id="wrapper"></div></body></html>', options = {}) {
32
+ const dom = new JSDOM(html, { url: "http://localhost/", pretendToBeVisual: true, ...options });
33
+ const { window } = dom;
34
+ const saved = new Map();
35
+ for (const name of GLOBALS) {
36
+ saved.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
37
+ const value = name === "window" ? window : window[name];
38
+ if (value === undefined) continue;
39
+ // Functions of the window (getComputedStyle, requestAnimationFrame, ...) need the window as `this`.
40
+ const bound = BOUND.has(name) ? value.bind(window) : value;
41
+ Object.defineProperty(globalThis, name, { value: bound, configurable: true, writable: true });
42
+ }
43
+ return {
44
+ window,
45
+ document: window.document,
46
+ uninstall() {
47
+ for (const [name, descriptor] of saved) {
48
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
49
+ else delete globalThis[name];
50
+ }
51
+ window.close();
52
+ }
53
+ };
54
+ }
55
+
56
+ /** Waits for `ms` milliseconds (0 = the next turn of the event loop). */
57
+ export const tick = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
58
+
59
+ /**
60
+ * Waits until `condition()` returns something truthy, and returns that value.
61
+ * Throws after `timeout` ms, naming `message`, so a test fails with a reason instead of hanging.
62
+ */
63
+ export async function until(condition, { timeout = 2000, interval = 10, message = "condition" } = {}) {
64
+ const start = Date.now();
65
+ for (;;) {
66
+ const value = await condition();
67
+ if (value) return value;
68
+ if (Date.now() - start > timeout) throw new Error(`Timed out after ${timeout} ms waiting for ${message}`);
69
+ await tick(interval);
70
+ }
71
+ }