athena-ui-js 1.0.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.
@@ -0,0 +1,118 @@
1
+ //dropZoneGenerator for Athena UI
2
+ //Author: Csaba Tóth https://github.com/csabatibortoth/
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ import { asHandle, cx, el, mount, setContent, uid } from "../../core/dom.js";
7
+ import { formatBytes, matchesAccept } from "../../core/format.js";
8
+ import { translate } from "../../core/i18n.js";
9
+
10
+ /**
11
+ * Generates a drag-and-drop area. Files dropped on it (or picked with the browser dialog after a click / Enter / Space)
12
+ * are checked against `accept`, `maxSize` and `maxFiles`; the valid ones are passed to `onDrop`, the rest to `onReject`.
13
+ * Nothing is read or sent: what to do with the files is up to the caller (generateFileUpload builds on this).
14
+ *
15
+ * @param {object} options
16
+ * @param {string|Element} [options.parent]
17
+ * @param {string} [options.id]
18
+ * @param {string} [options.class]
19
+ * @param {*} [options.content] text, Node, array or function; the default is the localized "Drop files here" text
20
+ * @param {string} [options.accept] like ".png,image/*"
21
+ * @param {boolean} [options.multiple=true]
22
+ * @param {number} [options.maxSize] bytes per file
23
+ * @param {number} [options.maxFiles] files accepted per drop
24
+ * @param {boolean} [options.clickable=true] click / Enter / Space opens the file dialog
25
+ * @param {boolean} [options.disabled=false]
26
+ * @param {(files: File[]) => void} [options.onDrop] valid files
27
+ * @param {(rejected: {file: File, reason: string}[]) => void} [options.onReject]
28
+ * @param {(over: boolean) => void} [options.onDragChange] a drag entered / left the area
29
+ * @returns {{element: HTMLElement, input: HTMLInputElement, handleFiles: (files: Iterable<File>) => void,
30
+ * setDisabled: (disabled: boolean) => void, open: () => void}}
31
+ */
32
+ export function createDropZone(options = {}) {
33
+ const { accept, multiple = true, maxSize, maxFiles, clickable = true } = options;
34
+ const hintId = uid("dropzone-hint");
35
+ const input = el("input", { class: "dropzone-input", attrs: { type: "file", accept, multiple, tabindex: "-1", "aria-hidden": "true" } });
36
+ const hint = el("div", { class: "dropzone-content", id: hintId });
37
+ setContent(hint, options.content ?? translate("dropFiles"));
38
+ const element = el("div", {
39
+ id: options.id,
40
+ class: cx("dropzone", options.class),
41
+ attrs: { role: clickable ? "button" : "group", tabindex: clickable ? "0" : null, "aria-describedby": hintId }
42
+ }, hint, input);
43
+ let depth = 0;
44
+ let disabled = false;
45
+
46
+ const setOver = over => {
47
+ element.classList.toggle("dropzone-over", over);
48
+ options.onDragChange?.(over);
49
+ };
50
+ const hasFiles = event => [...(event.dataTransfer?.types ?? [])].includes("Files");
51
+
52
+ function handleFiles(files) {
53
+ const valid = [];
54
+ const rejected = [];
55
+ let list = [...files];
56
+ if (!multiple) list = list.slice(0, 1);
57
+ for (const file of list) {
58
+ if (!matchesAccept(file, accept)) rejected.push({ file, reason: `${translate("validation.pattern")} (${file.name})` });
59
+ else if (maxSize != null && file.size > maxSize) rejected.push({ file, reason: translate("validation.fileSize", { name: file.name, max: formatBytes(maxSize) }) });
60
+ else if (maxFiles != null && valid.length >= maxFiles) rejected.push({ file, reason: translate("validation.maxFiles", { max: maxFiles }) });
61
+ else valid.push(file);
62
+ }
63
+ if (valid.length) options.onDrop?.(valid);
64
+ if (rejected.length) options.onReject?.(rejected);
65
+ }
66
+ const open = () => { if (!disabled) input.click(); };
67
+ function setDisabled(value) {
68
+ disabled = Boolean(value);
69
+ element.classList.toggle("dropzone-disabled", disabled);
70
+ element.setAttribute("aria-disabled", String(disabled));
71
+ if (clickable) element.tabIndex = disabled ? -1 : 0;
72
+ }
73
+
74
+ if (clickable) {
75
+ element.addEventListener("click", open);
76
+ element.addEventListener("keydown", event => {
77
+ if (event.key === "Enter" || event.key === " ") {
78
+ event.preventDefault();
79
+ open();
80
+ }
81
+ });
82
+ }
83
+ input.addEventListener("change", () => {
84
+ handleFiles(input.files);
85
+ input.value = "";
86
+ });
87
+ // The enter / leave pair fires for every child element, so the nesting depth is counted to avoid flicker.
88
+ element.addEventListener("dragenter", event => {
89
+ if (disabled || !hasFiles(event)) return;
90
+ event.preventDefault();
91
+ if (++depth === 1) setOver(true);
92
+ });
93
+ element.addEventListener("dragover", event => {
94
+ if (disabled || !hasFiles(event)) return;
95
+ event.preventDefault();
96
+ event.dataTransfer.dropEffect = "copy";
97
+ });
98
+ element.addEventListener("dragleave", () => {
99
+ if (depth > 0 && --depth === 0) setOver(false);
100
+ });
101
+ element.addEventListener("drop", event => {
102
+ event.preventDefault();
103
+ const wasOver = depth > 0;
104
+ depth = 0;
105
+ if (wasOver) setOver(false);
106
+ if (!disabled && hasFiles(event)) handleFiles(event.dataTransfer.files);
107
+ });
108
+
109
+ setDisabled(options.disabled);
110
+ return { element, input, handleFiles, setDisabled, open };
111
+ }
112
+
113
+ /** Generates a drag-and-drop area into `parent`, see createDropZone. */
114
+ export function generateDropZone(options = {}) {
115
+ const zone = createDropZone(options);
116
+ mount(options.parent, zone.element);
117
+ return asHandle(zone);
118
+ }
@@ -5,11 +5,12 @@
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";
12
12
  import { generateProgress } from "../feedbackGenerator/feedbackGenerator.js";
13
+ import { createDropZone } from "./dropZoneGenerator.js";
13
14
 
14
15
  /* ------------------COMBOBOX (autocomplete, multi select)------------------- */
15
16
 
@@ -45,7 +46,7 @@ function wrapCombobox(options, mode) {
45
46
  if (options.label) wrapper.append(el("label", { class: "field-label", text: options.label, attrs: { for: id } }));
46
47
  wrapper.append(combo.element);
47
48
  mount(options.parent, wrapper);
48
- return combo;
49
+ return asHandle(combo, { also: wrapper });
49
50
  }
50
51
 
51
52
  /* ------------------DATE RANGE------------------- */
@@ -72,7 +73,7 @@ export function generateDateRange(options = {}) {
72
73
  wrapper.append(range.element, error);
73
74
  range.element.addEventListener("change", () => { error.textContent = range.validate(); });
74
75
  mount(options.parent, wrapper);
75
- return range;
76
+ return asHandle(range, { also: wrapper });
76
77
  }
77
78
 
78
79
  /* ------------------FILE UPLOAD------------------- */
@@ -98,11 +99,14 @@ export function generateDateRange(options = {}) {
98
99
  export function generateFileUpload(options = {}) {
99
100
  const { accept, multiple = true, maxSize, url, fieldName = "file", autoUpload = true } = options;
100
101
  const entries = [];
101
- const input = el("input", { class: "dropzone-input", attrs: { type: "file", accept, multiple, tabindex: "-1", "aria-hidden": "true" } });
102
- const zone = el("div", { class: "dropzone", attrs: { role: "button", tabindex: "0" } }, el("span", { text: translate("dropFiles") }));
102
+ const zone = createDropZone({
103
+ accept, multiple, maxSize,
104
+ onDrop: files => add(files),
105
+ onReject: rejected => { errors.textContent = rejected.map(item => item.reason).join(" "); }
106
+ });
103
107
  const list = el("ul", { class: "file-list" });
104
108
  const errors = el("div", { class: "field-error", attrs: { role: "alert" } });
105
- const element = el("div", { id: options.id, class: cx("file-upload", options.class) }, zone, input, errors, list);
109
+ const element = el("div", { id: options.id, class: cx("file-upload", options.class) }, zone.element, errors, list);
106
110
 
107
111
  function render(entry) {
108
112
  entry.node ??= el("li", { class: "file-item" });
@@ -191,33 +195,14 @@ export function generateFileUpload(options = {}) {
191
195
  }
192
196
  }
193
197
 
194
- zone.addEventListener("click", () => input.click());
195
- zone.addEventListener("keydown", event => {
196
- if (event.key === "Enter" || event.key === " ") {
197
- event.preventDefault();
198
- input.click();
199
- }
200
- });
201
- input.addEventListener("change", () => {
202
- add(input.files);
203
- input.value = "";
204
- });
205
- zone.addEventListener("dragover", event => { event.preventDefault(); zone.classList.add("dropzone-over"); });
206
- zone.addEventListener("dragleave", () => zone.classList.remove("dropzone-over"));
207
- zone.addEventListener("drop", event => {
208
- event.preventDefault();
209
- zone.classList.remove("dropzone-over");
210
- add(event.dataTransfer.files);
211
- });
212
-
213
198
  mount(options.parent, element);
214
- return {
199
+ return asHandle({
215
200
  element,
216
201
  getFiles: () => entries.map(entry => entry.file),
217
202
  upload,
218
203
  clear: () => entries.slice().forEach(remove),
219
204
  add
220
- };
205
+ });
221
206
  }
222
207
 
223
208
  /* ------------------STEPPER (wizard)------------------- */
@@ -288,12 +273,12 @@ export function generateStepper(options = {}) {
288
273
 
289
274
  mount(options.parent, element);
290
275
  if (steps.length) show(0);
291
- return {
276
+ return asHandle({
292
277
  element,
293
278
  next,
294
279
  back,
295
280
  // Going back is always possible, going forward only one step at a time through next().
296
281
  goTo: index => { if (index >= 0 && index < current) show(index); },
297
282
  getCurrent: () => current
298
- };
283
+ });
299
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
 
@@ -30,9 +30,11 @@ const BUTTONS = {
30
30
  unlink: { label: "rt.unlink", text: "⛓", run: () => exec("unlink") },
31
31
  clear: { label: "rt.clear", text: "⌫", run: () => { exec("removeFormat"); exec("formatBlock", "p"); } },
32
32
  undo: { label: "rt.undo", text: "↶", run: () => exec("undo") },
33
- redo: { label: "rt.redo", text: "↷", run: () => exec("redo") }
33
+ redo: { label: "rt.redo", text: "↷", run: () => exec("redo") },
34
+ source: { label: "rt.source", text: "</>", run: "source", active: () => false, class: "rt-source" }
34
35
  };
35
36
  const DEFAULT_TOOLBAR = ["bold", "italic", "underline", "strike", "|", "h2", "h3", "quote", "|", "ul", "ol", "|", "link", "unlink", "|", "clear", "undo", "redo"];
37
+ const WYSIWYG_TOOLBAR = [...DEFAULT_TOOLBAR, "|", "source"];
36
38
 
37
39
  /**
38
40
  * Generates a rich text editor. The content is HTML restricted to a safe set of tags (paragraphs, headings,
@@ -46,7 +48,8 @@ const DEFAULT_TOOLBAR = ["bold", "italic", "underline", "strike", "|", "h2", "h3
46
48
  * @param {string} [options.value] initial HTML
47
49
  * @param {string} [options.placeholder]
48
50
  * @param {string[]} [options.toolbar] button names (bold, italic, underline, strike, h2, h3, quote, ul, ol, link,
49
- * unlink, clear, undo, redo) and "|" separators
51
+ * unlink, clear, undo, redo, source) and "|" separators. `source` switches between the visual editor and
52
+ * the sanitized HTML source.
50
53
  * @param {number} [options.minHeight=140] px
51
54
  * @param {boolean} [options.disabled]
52
55
  * @param {(html: string) => void} [options.onChange]
@@ -66,7 +69,8 @@ export function createRichText(options = {}) {
66
69
  }
67
70
  });
68
71
  editor.style.minHeight = `${options.minHeight ?? 140}px`;
69
- const root = el("div", { class: cx("richtext", options.disabled && "rt-disabled", options.class) }, toolbar, editor);
72
+ const source = el("textarea", { class: "rt-source-view", attrs: { hidden: true, spellcheck: "false", "aria-label": translate("rt.source") } });
73
+ const root = el("div", { class: cx("richtext", options.disabled && "rt-disabled", options.class) }, toolbar, editor, source);
70
74
  const buttons = [];
71
75
  let savedRange = null;
72
76
 
@@ -112,6 +116,26 @@ export function createRichText(options = {}) {
112
116
  changed();
113
117
  }
114
118
 
119
+ // Source view: the textarea shows the sanitized HTML; leaving it sanitizes what was typed.
120
+ function toggleSource() {
121
+ const open = source.hidden;
122
+ if (open) {
123
+ source.value = getValue();
124
+ source.style.minHeight = editor.style.minHeight;
125
+ } else {
126
+ setValue(source.value);
127
+ changed();
128
+ }
129
+ source.hidden = !open;
130
+ editor.hidden = open;
131
+ root.classList.toggle("rt-source-open", open);
132
+ for (const { button, spec } of buttons) {
133
+ if (spec.run === "source") button.setAttribute("aria-pressed", String(open));
134
+ else button.disabled = open || Boolean(options.disabled);
135
+ }
136
+ (open ? source : editor).focus();
137
+ }
138
+
115
139
  names.forEach(name => {
116
140
  if (name === "|") {
117
141
  toolbar.append(el("span", { class: "rt-separator", attrs: { role: "separator", "aria-hidden": "true" } }));
@@ -127,6 +151,7 @@ export function createRichText(options = {}) {
127
151
  button.addEventListener("mousedown", event => event.preventDefault());
128
152
  button.addEventListener("click", async () => {
129
153
  if (spec.run === "link") await addLink();
154
+ else if (spec.run === "source") toggleSource();
130
155
  else {
131
156
  editor.focus();
132
157
  spec.run();
@@ -151,7 +176,7 @@ export function createRichText(options = {}) {
151
176
 
152
177
  function refresh() {
153
178
  for (const { button, spec } of buttons) {
154
- if (spec.active) button.setAttribute("aria-pressed", String(Boolean(spec.active())));
179
+ if (spec.active && spec.run !== "source") button.setAttribute("aria-pressed", String(Boolean(spec.active())));
155
180
  }
156
181
  }
157
182
  const onSelection = () => {
@@ -186,6 +211,7 @@ export function createRichText(options = {}) {
186
211
  function setValue(html) {
187
212
  editor.innerHTML = sanitizeHtml(html);
188
213
  syncEmpty();
214
+ if (!source.hidden) source.value = getValue();
189
215
  }
190
216
  // <p> instead of <div> for new lines
191
217
  try {
@@ -218,5 +244,14 @@ export function generateRichText(options = {}) {
218
244
  }
219
245
  wrapper.append(rich.element);
220
246
  mount(options.parent, wrapper);
221
- return rich;
247
+ return asHandle(rich, { also: wrapper });
222
248
  }
249
+
250
+ /**
251
+ * Generates a WYSIWYG editor: the rich text editor with the full toolbar plus a `source` button that switches to
252
+ * the (sanitized) HTML source. Takes the same options as createRichText.
253
+ */
254
+ export const createWysiwyg = (options = {}) => createRichText({ ...options, toolbar: options.toolbar ?? WYSIWYG_TOOLBAR });
255
+
256
+ /** Generates a labelled WYSIWYG editor, see createWysiwyg. */
257
+ export const generateWysiwyg = (options = {}) => generateRichText({ ...options, toolbar: options.toolbar ?? WYSIWYG_TOOLBAR });
@@ -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
  }