athena-ui-js 2.6.1 → 2.7.1

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: **2.6.1**
8
+ Current version: **2.7.1**
9
9
 
10
10
  [Quick start](#usage) · [API](#api) · [Components](#charts) · [Themes](#themes) · [Tests](#tests) · [Release notes](#releases)
11
11
 
@@ -517,11 +517,27 @@ editor.getValue(); // safe HTML, "" when empty
517
517
  The date range uses the native date pickers; the end picker starts at the chosen start date and a reversed range typed by
518
518
  hand is reported. The rich text editor produces a restricted set of HTML (paragraphs, headings, bold / italic / underline /
519
519
  strike, lists, quotes, code, links). Everything else (scripts, styles, iframes, images, event attributes, `javascript:` and
520
- `data:` links) is removed when the content is set, pasted, dropped and read, so the value is safe to store and show with
521
- `innerHTML`; links get `rel="noopener noreferrer"`. Toolbar buttons: `bold`, `italic`, `underline`, `strike`, `h2`, `h3`,
520
+ `data:` links) is removed when the content is set, pasted, dropped and read; links get `rel="noopener noreferrer"`. This
521
+ is a layer of defense in the browser, not a guarantee for what you store: see [Sanitizing HTML](#sanitizing-html). Toolbar buttons: `bold`, `italic`, `underline`, `strike`, `h2`, `h3`,
522
522
  `quote`, `ul`, `ol`, `link`, `unlink`, `clear`, `undo`, `redo`. The editor is built on `contenteditable` and
523
523
  `document.execCommand`, which every browser still supports; sanitize on the server as well, as with any HTML you accept.
524
524
 
525
+ ##### Sanitizing HTML
526
+
527
+ The sanitizer (`sanitizeHtml`, `isSafeUrl`) is an allow-list that rebuilds the markup: the input is parsed in an inert
528
+ document, only the listed elements are copied (`p`, `br`, `strong`, `em`, `u`, `s`, lists, headings `h1` to `h4`,
529
+ `blockquote`, `code`, `pre`, `a`, `hr`, `sub`, `sup`), every attribute is dropped except a checked `href`, and scripts,
530
+ styles, frames, SVG, MathML, forms and the like are removed with their content. A link may point to `http(s):`, `mailto:`,
531
+ `tel:`, `#...` or a path (`/path`, `./a`, `../a`); a path that a browser would read as another site (`//host`, and `/\host`,
532
+ because browsers treat a backslash in an http(s) URL as a slash) is refused.
533
+
534
+ **Treat it as defense in depth.** It runs in the page of the person who is typing, which an attacker controls: a request that
535
+ bypasses the page, or a stored value from another source, was never sanitized. So **sanitize again on the server before you
536
+ store or render content that came from users**, with a maintained server-side sanitizer, and keep a Content-Security-Policy
537
+ without `'unsafe-inline'` (Athena UI needs none). The sanitizer relies on the parser of the browser it runs in.
538
+ `htmlToText` returns text only. The regression tests (`tests/browser`) feed it malformed markup, SVG and MathML, DOM-clobbering
539
+ names and dangerous URL schemes.
540
+
525
541
  ```js
526
542
  generateDropZone({ parent: "wrapper", accept: "image/*", maxSize: 2 * 1024 * 1024, maxFiles: 3,
527
543
  onDrop: files => {}, onReject: rejected => rejected.forEach(({ file, reason }) => {}) });
@@ -643,6 +659,7 @@ const manager = createThemeManager({ themes: [{ id: "athena", name: "Athena" },
643
659
  manager.setTheme("contrast"); manager.setMode("dark"); // "system" | "light" | "dark"; saved in localStorage, other tabs follow
644
660
  manager.onChange(({ theme, mode, dark }) => redrawChartsOrWhatever());
645
661
  generateThemePicker({ parent: "account-page", manager }); // radio groups with a small preview of every theme
662
+ generateThemePicker({ parent: "account-page", manager, previewModes: "both" }); // the light and the dark picture of every theme side by side
646
663
  ```
647
664
 
648
665
  **The contract of a theme** (also at the top of `appearance.css`): a theme is a pair of CSS blocks that set the tokens
@@ -672,6 +689,7 @@ Two `datetime-local` inputs and a list of presets (your own with `presets: [{ id
672
689
  ```js
673
690
  generatePageHeader({ parent: "wrapper", title: "Hosts", description: "All monitored machines", breadcrumbs: [{ label: "Home", href: "#/" }, { label: "Hosts" }], actions: [addButton] });
674
691
  generateFacts({ parent: "wrapper", items: [{ term: "System", description: "Linux" }, { term: "Seen", description: formatRelativeTime(host.lastSeen) }] });
692
+ generateField({ parent: "toolbar", type: "select", name: "org", label: "Organization", hideLabel: true, options }); // the label stays for screen readers, it is not drawn
675
693
  generateEmptyState({ parent: "wrapper", title: "No hosts yet", message: "Install the agent.", action: { text: "Add host", onclick: add } });
676
694
  generateLoading({ parent: "wrapper" }); // spinner + text, a live region
677
695
  generateStat({ parent: "wrapper", label: "CPU", value: "91 %", tone: "bad", note: "of 4 cores" }); // tone: "ok" | "warn" | "bad" (colour + a word for screen readers)
@@ -741,6 +759,7 @@ const grid = createWidgetGrid({
741
759
  onChange: (layout, reason) => localStorage.setItem("dashboard", JSON.stringify(layout)) // "move", "resize", "add", "remove", "settings", "undo", ...
742
760
  });
743
761
  grid.setLayout(JSON.parse(localStorage.getItem("dashboard"))); // plain, versioned JSON ({ version: 1, widgets: [...] })
762
+ const id = await grid.addWidgetWithSettings("clock"); // adds a widget and opens its settings: saved = one step "add", dismissed = nothing happened (null)
744
763
  ```
745
764
 
746
765
  - **Layout** is CSS grid. The columns, the row height, the gap and the place of every widget are CSS classes written into a constructed style sheet, so a strict
@@ -753,6 +772,9 @@ grid.setLayout(JSON.parse(localStorage.getItem("dashboard"))); // plain, ver
753
772
  - **Layouts** (`getLayout()` / `setLayout(json)`) are plain JSON and the application decides where they are stored. Loading is checked: a bad entry is skipped (reported in the result),
754
773
  duplicate ids are replaced, places are clamped and made free of overlaps, `__proto__`-style keys are dropped, and a type that is not registered is shown as a placeholder (its data is kept, nothing is executed).
755
774
  - **Performance**: a widget is rendered only when it is first seen, `resize(context, size)` is called throttled when its body changes size, and nothing re-renders while it is out of view.
775
+ - **Sizes**: `context.size` is the box of the body as it is NOW (also in `resize`), `context.contentSize` is what is left inside its padding: give a chart that.
776
+ - **Saving**: `changeDelay: 600` turns the many steps of a drag into one call of `onChange` (with the reason of the last step); `grid.flush()` calls it now (a button "save", leaving the page) and `destroy()` does it for you.
777
+ An application with ONE layout (no breakpoints) asks `getLayout({ breakpoint: "default" })` and gets `x`, `y`, `w`, `h` on every widget.
756
778
  - The grid maths (`placeItem`, `compact`, `findFreeSpot`, `normalize`, `collides`) is exported as well, for your own layouts.
757
779
 
758
780
  ### Code: highlighting, an editor and a diff
@@ -882,6 +904,26 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
882
904
 
883
905
  ## Releases
884
906
 
907
+ ### 2.7.1
908
+
909
+ - **Security fix in `isSafeUrl` / the sanitizer:** a link such as `/\evil.com` was accepted as a path of the same site, but browsers read a backslash in an http(s) URL as a slash, so it led to `evil.com` (a phishing or redirect link; no script ran). It is refused now, like `//host`.
910
+ - README: the section *Sanitizing HTML* says what the sanitizer does and that it is defense in depth: sanitize again on the server.
911
+ - New sanitizer regression cases (hostile markup, SVG/MathML, DOM clobbering, URL schemes) in the browser suite.
912
+
913
+ ### 2.7.0
914
+ (what moving Heimdall onto Athena UI 2.x showed was missing; each item removed a workaround of that application)
915
+ #### Added:
916
+ 1. `hideLabel` for `generateField` / form fields: the label stays for screen readers and the browser (also the legend of a group, the words of a switch) and is not drawn
917
+ 2. Widget grid: `addWidgetWithSettings(type, options)` (add and configure in one step: dismissed leaves no trace, no undo step and no call of `onChange`), `contentSize` next to `size` in the context of a widget, `changeDelay` and `flush()`
918
+ for the layout (one call after a drag), `getLayout({ breakpoint })` with flat `x`, `y`, `w`, `h`
919
+ 3. `generateThemePicker({ previewModes: "both" })`: the light and the dark picture of every theme
920
+ 4. `docs/migration-2.0.md` section 9: the generic class names that collide, the variable mapping for the pictures of a theme, tests
921
+ #### Fixed:
922
+ 1. A chart with a legend gets at least 48 px at the bottom, so the legend no longer overlaps the time labels (also when a smaller margin was asked for)
923
+ 2. `.athena-chart` does not leave a gap of a few pixels under the inline SVG (a widget scrolled by one pixel)
924
+ 3. A `resize` of a widget is told the size it has now (it was the size of the last render or update)
925
+ 4. The page header keeps its actions on the row of the title when the description is long (the description has a line length), and the actions stand on the bottom line of their row
926
+
885
927
  ### 2.6.1
886
928
  #### Fixed:
887
929
  1. **A form reported one keystroke in an autocomplete twice**: the combobox announces every change of its value itself (as a `change` event), and the form listened to `input` as well, so `onChange` of the field and of the form ran twice for each typed character. They run once now, and typing in a multiselect (a search, not a change of the value) reports nothing; choosing and removing a chip still report once. The page of an application that asked a server on every change asked it twice (found by the metrics page of Heimdall)
@@ -90,6 +90,23 @@ Odin moved with little work, and then replaced its own copies of the theme manag
90
90
  `el()` wrapper, its API client and its list loader.
91
91
  - **Smaller downloads**: import from the entry points (`athena-ui-js/table`, ...) and start with `athena-ui-js/app` instead of the root file, which loads every module.
92
92
 
93
+ ## 9. What Heimdall needed when it moved (a second real application, 2.6 to 2.7)
94
+
95
+ Heimdall replaced its chart library (uPlot), its log filter, its custom views and its own dialogs, forms and tables with Athena. What it found:
96
+
97
+ - **Generic class names collide.** Athena styles plain class names such as `.facts`, `.fact`, `.widget`, `.widget-body`, `.widget-header`, `.widget-title`, `.stat`, `.toast`, `.dialog`, `.empty-state`, `.loading-state`, `.page-header`,
98
+ `.page-title`, `.page-actions`, `.card`, `.badge`, `.alert`, `.tab`, `.field`, `.field-label`, `.menu`, `.dropdown`, `.sidebar`, `.chip`, `.stepper`, `.avatar`, `.spinner`, `.pagination`, `.choice`, `.switch`, `.combobox`,
99
+ `.chart-legend`, `.theme-picker`, `.theme-preview`, `.form-actions`, `.form-message`. If your application used one of them for something of its own (a `.facts` list, a `.widget` of a dashboard), its look changes:
100
+ rename yours (a prefix of your application is enough) or use the Athena part. The full list is the file `docs/styling.md` (`npm run docs`); search it for the names you use.
101
+ - **Rules of your own must not be unlayered if you want Athena to win, and the other way round**: Athena is in the layer `athena`, so any plain rule of yours beats it. That is the way to restyle, and also the way an old `.grid td` or `td` rule
102
+ leaks into an Athena table (add a rule for the Athena class, for example `.is-stacked .grid td`).
103
+ - **A theme preview needs the variables for the mode**: map your theme variables for `:root, [data-theme][data-mode]`, not only for `:root[data-theme]`, otherwise the pictures of a theme in the picker all look the same.
104
+ `generateThemePicker({ previewModes: "both" })` shows the light and the dark picture side by side.
105
+ - **Tests**: run the application's tests with `installDom` from `athena-ui-js/testing` instead of a copy of jsdom setup, and import Athena modules after it is installed.
106
+ - **Escape closes a dialog by the `cancel` event** of the native `<dialog>`; a test that sends a key must dispatch `cancel`.
107
+ - **New in 2.7.0 for what Heimdall had to write itself**: `hideLabel` for a field, `contentSize` and a right `size` on a resize of a widget, `addWidgetWithSettings`, `changeDelay` and `flush()` for the layout of a grid,
108
+ `getLayout({ breakpoint })`, room for a chart legend, no gap under a chart, and a page header that keeps the actions on the row of the title.
109
+
93
110
  ## Upgrade in five steps
94
111
 
95
112
  1. Replace `import AthenaUI from ...` and `window.` calls by named imports, or add the `classic.js` line.
package/docs/styling.md CHANGED
@@ -104,7 +104,7 @@ Dark colours: set `data-mode="dark"` on `<html>` (or let `createThemeManager` do
104
104
  | Table: resizable columns, virtual scrolling | `.athena-col-resizer` `.athena-table` `.athena-table-resizable` `.athena-table-scroll` `.athena-table-spacer` `.athena-table-virtual` `.resizing` | `--athena-accent` `--athena-border-width` `--athena-line` `--athena-row-height` `--row-height` |
105
105
  | Date range | `.daterange` `.daterange-part` | - |
106
106
  | Rich text editor | `.richtext` `.rt-bold` `.rt-button` `.rt-disabled` `.rt-editor` `.rt-empty` `.rt-italic` `.rt-separator` `.rt-source-view` `.rt-strike` `.rt-toolbar` `.rt-underline` `.submenu` | `--athena-accent` `--athena-accent-fg` `--athena-bg` `--athena-border-width` `--athena-fg` `--athena-hover` `--athena-line` `--athena-muted` `--athena-radius` `--athena-surface` |
107
- | Theme picker (generateThemePicker). The preview is drawn with the colours of the theme it shows. | `.theme-picker` `.theme-picker-description` `.theme-picker-group` `.theme-picker-option` `.theme-picker-options` `.theme-preview` `.theme-preview-bar` `.theme-preview-body` `.theme-preview-button` `.theme-preview-line` | `--athena-accent` `--athena-bg` `--athena-border-width` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-line` `--athena-muted` `--athena-radius` `--athena-space-1` `--athena-space-3` `--athena-space-4` |
107
+ | Theme picker (generateThemePicker). The preview is drawn with the colours of the theme it shows. | `.theme-picker` `.theme-picker-description` `.theme-picker-group` `.theme-picker-option` `.theme-picker-options` `.theme-preview` `.theme-preview-bar` `.theme-preview-body` `.theme-preview-both` `.theme-preview-button` `.theme-preview-half` `.theme-preview-line` | `--athena-accent` `--athena-bg` `--athena-border-width` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-line` `--athena-muted` `--athena-radius` `--athena-space-1` `--athena-space-3` `--athena-space-4` |
108
108
  | Tables with a data source and row actions | `.athena-button` `.athena-table` `.athena-table-actions` `.athena-table-error` `.athena-table-is-loading` `.athena-table-loading` `.athena-visually-hidden` | `--athena-danger` `--athena-muted` |
109
109
  | Tables: the stacked layout of the option `stack`: while the table is narrow every row is a block and the label of the column stands next to each value | `.athena-chart` `.athena-chart-sparkline` `.athena-table` `.athena-table-actions` `.athena-table-stackable` `.chart-area` `.chart-bar` `.chart-data` `.chart-hidden` `.chart-legend-item` `.chart-line` `.chart-point` `.chart-ring` `.chart-slice` `.chart-swatch` `.chart-tooltip` `.chart-tooltip-box` `.chart-tooltip-text` `.is-off` `.is-stacked` `.is-visible` `.s1` `.s2` `.s3` `.s4` `.s5` `.s6` `.s7` `.s8` | `--athena-bg` `--athena-border-width` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-line` `--athena-muted` `--series-1` `--series-2` `--series-3` `--series-4` `--series-5` `--series-6` `--series-7` `--series-8` |
110
110
  | Menu (generateMenu): a bar, or tabs at the bottom of the screen with sheets for the groups | `.athena-menu` `.athena-menu-list` `.has-active` `.is-active` `.menu-avatar` `.menu-control` `.menu-icon` `.menu-item` `.menu-item-end` `.menu-sheet` | `--athena-accent` `--athena-accent-fg` `--athena-bg` `--athena-border-width` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-hover` `--athena-line` `--athena-menu-active` `--athena-menu-bg` `--athena-menu-fg` `--athena-menu-hover` `--athena-radius` `--athena-shadow` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "athena-ui-js",
3
- "version": "2.6.1",
3
+ "version": "2.7.1",
4
4
  "description": "A small, dependency-free UI framework: forms, tables, charts, menus, dialogs, themes and a router, written as ES modules.",
5
5
  "type": "module",
6
6
  "main": "./src/athena-ui.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: 2.6.1
5
+ //Version: 2.7.1
6
6
 
7
7
  // The whole API as ES module exports. There are no side effects: importing this file does not touch the page, does not load a script and does not
8
8
  // put anything on globalThis. For pages that need globals use `athena-ui-js/classic`, and to download only what you use import from the entry points
@@ -6,7 +6,7 @@
6
6
  export const BORDERED_CLASS = "default-cointainer-bordered";
7
7
 
8
8
  export const defaults = Object.freeze({
9
- version: "2.6.1",
9
+ version: "2.7.1",
10
10
  container_class: "container",
11
11
  header_class: "header-container",
12
12
  header_menu_class: "header-menu menu",
@@ -1,65 +1,67 @@
1
- //sanitize 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
- // Allow-list HTML sanitizer for the rich text editor. Everything that is not listed is unwrapped
7
- // (its text stays), dangerous elements are removed with their content, and every attribute is dropped
8
- // except a checked `href` on links. The input is parsed in an inert document, so nothing runs
9
- // while it is being cleaned.
10
-
11
- const ALLOWED = new Set([
12
- "p", "br", "b", "strong", "i", "em", "u", "s", "strike", "del", "ul", "ol", "li",
13
- "h1", "h2", "h3", "h4", "blockquote", "code", "pre", "a", "hr", "sub", "sup"
14
- ]);
15
- const RENAMED = { div: "p", strike: "s", del: "s", b: "strong", i: "em" };
16
- const DROPPED = new Set(["script", "style", "iframe", "object", "embed", "template", "noscript", "svg", "math", "link", "meta", "title", "form", "textarea", "select", "button", "input", "head"]);
17
- const SAFE_URL = /^(?:https?:|mailto:|tel:|#|\/(?!\/)|\.{1,2}\/)/i;
18
-
19
- /** True for http(s), mailto, tel, anchors and relative paths. Rejects javascript:, data:, vbscript: and the like. */
20
- export function isSafeUrl(url) {
21
- // Browsers ignore control characters and spaces inside the scheme ("java\tscript:").
22
- const compact = String(url ?? "").replace(/[\u0000- \u007f-\u009f]/g, "");
23
- return compact !== "" && SAFE_URL.test(compact);
24
- }
25
-
26
- function clean(node, target, doc) {
27
- for (const child of [...node.childNodes]) {
28
- if (child.nodeType === 3) {
29
- target.append(doc.createTextNode(child.nodeValue));
30
- } else if (child.nodeType === 1) {
31
- const tag = child.tagName.toLowerCase();
32
- if (DROPPED.has(tag)) continue;
33
- const name = RENAMED[tag] ?? tag;
34
- if (!ALLOWED.has(name)) {
35
- clean(child, target, doc); // unwrap: keep the text, lose the element
36
- continue;
37
- }
38
- const copy = doc.createElement(name);
39
- if (name === "a") {
40
- const href = child.getAttribute("href");
41
- if (href && isSafeUrl(href)) {
42
- copy.setAttribute("href", href.trim());
43
- copy.setAttribute("rel", "noopener noreferrer");
44
- if (!href.trim().startsWith("#")) copy.setAttribute("target", "_blank");
45
- }
46
- }
47
- clean(child, copy, doc);
48
- target.append(copy);
49
- }
50
- }
51
- }
52
-
53
- /** Cleans HTML from the editor, the clipboard or the application. Returns the safe HTML string. */
54
- export function sanitizeHtml(html) {
55
- const parsed = new DOMParser().parseFromString(`<body>${html ?? ""}</body>`, "text/html");
56
- const out = parsed.implementation.createHTMLDocument("");
57
- clean(parsed.body, out.body, out);
58
- return out.body.innerHTML;
59
- }
60
-
61
- /** The text of an HTML string, without tags. */
62
- export function htmlToText(html) {
63
- const parsed = new DOMParser().parseFromString(`<body>${html ?? ""}</body>`, "text/html");
64
- return parsed.body.textContent ?? "";
65
- }
1
+ //sanitize 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
+ // Allow-list HTML sanitizer for the rich text editor. Everything that is not listed is unwrapped
7
+ // (its text stays), dangerous elements are removed with their content, and every attribute is dropped
8
+ // except a checked `href` on links. The input is parsed in an inert document, so nothing runs
9
+ // while it is being cleaned.
10
+
11
+ const ALLOWED = new Set([
12
+ "p", "br", "b", "strong", "i", "em", "u", "s", "strike", "del", "ul", "ol", "li",
13
+ "h1", "h2", "h3", "h4", "blockquote", "code", "pre", "a", "hr", "sub", "sup"
14
+ ]);
15
+ const RENAMED = { div: "p", strike: "s", del: "s", b: "strong", i: "em" };
16
+ const DROPPED = new Set(["script", "style", "iframe", "object", "embed", "template", "noscript", "svg", "math", "link", "meta", "title", "form", "textarea", "select", "button", "input", "head"]);
17
+ // A path starts with one slash that is not followed by another slash OR a backslash: a browser reads a backslash in an
18
+ // http(s) URL as a slash, so "/\evil.com" is "//evil.com" (another site), not a path of this one.
19
+ const SAFE_URL = /^(?:https?:|mailto:|tel:|#|\/(?![\/\\])|\.{1,2}\/)/i;
20
+
21
+ /** True for http(s), mailto, tel, anchors and relative paths. Rejects javascript:, data:, vbscript: and the like. */
22
+ export function isSafeUrl(url) {
23
+ // Browsers ignore control characters and spaces inside the scheme ("java\tscript:").
24
+ const compact = String(url ?? "").replace(/[\u0000- \u007f-\u009f]/g, "");
25
+ return compact !== "" && SAFE_URL.test(compact);
26
+ }
27
+
28
+ function clean(node, target, doc) {
29
+ for (const child of [...node.childNodes]) {
30
+ if (child.nodeType === 3) {
31
+ target.append(doc.createTextNode(child.nodeValue));
32
+ } else if (child.nodeType === 1) {
33
+ const tag = child.tagName.toLowerCase();
34
+ if (DROPPED.has(tag)) continue;
35
+ const name = RENAMED[tag] ?? tag;
36
+ if (!ALLOWED.has(name)) {
37
+ clean(child, target, doc); // unwrap: keep the text, lose the element
38
+ continue;
39
+ }
40
+ const copy = doc.createElement(name);
41
+ if (name === "a") {
42
+ const href = child.getAttribute("href");
43
+ if (href && isSafeUrl(href)) {
44
+ copy.setAttribute("href", href.trim());
45
+ copy.setAttribute("rel", "noopener noreferrer");
46
+ if (!href.trim().startsWith("#")) copy.setAttribute("target", "_blank");
47
+ }
48
+ }
49
+ clean(child, copy, doc);
50
+ target.append(copy);
51
+ }
52
+ }
53
+ }
54
+
55
+ /** Cleans HTML from the editor, the clipboard or the application. Returns the safe HTML string. */
56
+ export function sanitizeHtml(html) {
57
+ const parsed = new DOMParser().parseFromString(`<body>${html ?? ""}</body>`, "text/html");
58
+ const out = parsed.implementation.createHTMLDocument("");
59
+ clean(parsed.body, out.body, out);
60
+ return out.body.innerHTML;
61
+ }
62
+
63
+ /** The text of an HTML string, without tags. */
64
+ export function htmlToText(html) {
65
+ const parsed = new DOMParser().parseFromString(`<body>${html ?? ""}</body>`, "text/html");
66
+ return parsed.body.textContent ?? "";
67
+ }
@@ -12,6 +12,8 @@ import { getLocale, translate } from "../../core/i18n.js";
12
12
  const NS = "http://www.w3.org/2000/svg";
13
13
  const SERIES_COLORS = 8;
14
14
  const DEFAULT_MARGIN = { top: 40, right: 20, bottom: 50, left: 55 };
15
+ // The legend stands under the time labels: with less than this at the bottom they overlap (a smaller margin the application asked for is raised)
16
+ const LEGEND_BOTTOM = 48;
15
17
  const DOT_LIMIT = 80; // up to this many points in view every point is a dot with a tooltip; more: the tooltip follows the pointer
16
18
 
17
19
  const svgEl = (tag, attrs = {}, text) => {
@@ -597,7 +599,7 @@ function buildDataTable({ labels, series, times, title, type, format = formatNum
597
599
  * time in milliseconds, or the options of Intl.DateTimeFormat (default: `{ dateStyle: "medium", timeStyle: "medium" }`, for example "Nov 19, 2026, 6:15:09 PM")
598
600
  * @param {boolean} [options.points=true] line and area charts: false never draws the dots, however few the points are (the tooltip still follows the pointer and the keyboard)
599
601
  * @param {(value: number) => string} [options.tickFormat] how the numbers of the value axis are written, when they should not be written like the values (a chart of whole numbers has ticks of 0.2)
600
- * @param {{top?: number, right?: number, bottom?: number, left?: number}} [options.margin] room around the plot in px (default 40, 20, 50, 55): a chart without a title and a legend does not need the top
602
+ * @param {{top?: number, right?: number, bottom?: number, left?: number}} [options.margin] room around the plot in px (default 40, 20, 50, 55; with a legend the bottom is at least 48): a chart without a title and a legend does not need the top
601
603
  * @param {boolean} [options.responsive=false] the chart is as wide as its parent and follows it when it changes (`height` stays); `width` is only the first guess
602
604
  * @returns {(SVGElement & {element: SVGElement, update: (options?: object) => SVGElement, destroy: () => void,
603
605
  * zoom: (from: number, to: number) => void, resetZoom: () => void, getZoom: () => ({from: number, to: number}|null),
@@ -753,6 +755,7 @@ function buildChart(options = {}, hooks, { animate = false } = {}) {
753
755
  // The tooltip is created first, so the shapes can use it, and moved to the end afterwards, so it is drawn on top.
754
756
  const tooltip = createTooltip(svg, width);
755
757
  const margin = { ...DEFAULT_MARGIN, ...(options.margin ?? {}) };
758
+ if (!sparkline && type !== "pie" && type !== "donut" && (options.legend ?? series.length > 1)) margin.bottom = Math.max(margin.bottom, LEGEND_BOTTOM);
756
759
  const format = typeof options.format === "function" ? options.format : formatNumber;
757
760
  const tickFormat = typeof options.tickFormat === "function" ? options.tickFormat : format;
758
761
  const formatTime = makeTimeFormatter(options.timeFormat);
@@ -1,73 +1,78 @@
1
- //themePicker 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, uid } from "../../core/dom.js";
7
- import { translate } from "../../core/i18n.js";
8
-
9
- /**
10
- * Generates the appearance picker of an account page: a group of themes with a small preview of each, and a group of modes.
11
- * The preview is drawn with the colours of the theme itself: the stylesheet of a theme applies to any element that has the
12
- * attributes data-theme and data-mode, not only to <html>.
13
- *
14
- * @param {object} options
15
- * @param {string|Element} [options.parent]
16
- * @param {ReturnType<import("../../core/theme.js").createThemeManager>} options.manager
17
- * @param {string} [options.themeLabel] legend of the theme group (default: translated "Theme")
18
- * @param {string} [options.modeLabel] legend of the mode group (default: translated "Mode")
19
- * @param {string} [options.class]
20
- * @returns {{element: HTMLElement, update: Function, destroy: Function}}
21
- */
22
- export function generateThemePicker(options = {}) {
23
- const { manager } = options;
24
- if (!manager) throw new Error("Athena UI: generateThemePicker needs a manager from createThemeManager");
25
- const name = uid("appearance");
26
-
27
- const group = (legend, items, kind, preview) => {
28
- const set = el("fieldset", { class: `theme-picker-group theme-picker-${kind}` }, el("legend", { text: legend }));
29
- const list = el("div", { class: "theme-picker-options" });
30
- for (const item of items) {
31
- const input = el("input", { attrs: { type: "radio", name: `${name}-${kind}`, value: item.id } });
32
- input.addEventListener("change", () => {
33
- if (input.checked) (kind === "theme" ? manager.setTheme : manager.setMode)(item.id);
34
- });
35
- const label = el("label", { class: "theme-picker-option", attrs: { "data-id": item.id } }, input);
36
- if (preview) label.append(preview(item));
37
- label.append(el("span", { class: "theme-picker-name", text: item.name ?? item.id }));
38
- if (item.description) label.append(el("span", { class: "theme-picker-description", text: item.description }));
39
- list.append(label);
40
- }
41
- set.append(list);
42
- return set;
43
- };
44
-
45
- // A small page drawn with the colours of the theme, in the mode that is in use (the light one for "system" in a light browser).
46
- const preview = theme => el("span", {
47
- class: "theme-preview",
48
- attrs: { "data-theme": theme.id, "data-mode": manager.appearance().dark ? "dark" : "light", "aria-hidden": "true" }
49
- },
50
- el("span", { class: "theme-preview-bar" }),
51
- el("span", { class: "theme-preview-body" }, el("span", { class: "theme-preview-line" }), el("span", { class: "theme-preview-button" })));
52
-
53
- const element = el("div", { class: cx("theme-picker", options.class) });
54
- const render = () => {
55
- element.replaceChildren(
56
- group(options.themeLabel ?? translate("theme"), manager.themes, "theme", preview),
57
- group(options.modeLabel ?? translate("mode"), manager.modes, "mode", null)
58
- );
59
- sync(manager.appearance());
60
- };
61
- const sync = state => {
62
- for (const input of element.querySelectorAll("input")) {
63
- const kind = input.name.endsWith("-theme") ? "theme" : "mode";
64
- input.checked = input.value === state[kind];
65
- }
66
- // The previews follow dark / light
67
- for (const node of element.querySelectorAll(".theme-preview")) node.dataset.mode = state.dark ? "dark" : "light";
68
- };
69
- render();
70
- const stop = manager.onChange(sync);
71
- mount(options.parent, element);
72
- return asHandle({ element, update: () => { render(); }, destroy() { stop(); element.remove(); } });
73
- }
1
+ //themePicker 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, uid } from "../../core/dom.js";
7
+ import { translate } from "../../core/i18n.js";
8
+
9
+ /**
10
+ * Generates the appearance picker of an account page: a group of themes with a small preview of each, and a group of modes.
11
+ * The preview is drawn with the colours of the theme itself: the stylesheet of a theme applies to any element that has the
12
+ * attributes data-theme and data-mode, not only to <html>.
13
+ *
14
+ * @param {object} options
15
+ * @param {string|Element} [options.parent]
16
+ * @param {ReturnType<import("../../core/theme.js").createThemeManager>} options.manager
17
+ * @param {string} [options.themeLabel] legend of the theme group (default: translated "Theme")
18
+ * @param {string} [options.modeLabel] legend of the mode group (default: translated "Mode")
19
+ * @param {"current"|"both"} [options.previewModes="current"] "current": one picture, in the mode that is in use. "both": the light and the dark picture side by side, so a person sees what each mode of a theme looks like
20
+ * @param {string} [options.class]
21
+ * @returns {{element: HTMLElement, update: Function, destroy: Function}}
22
+ */
23
+ export function generateThemePicker(options = {}) {
24
+ const { manager } = options;
25
+ if (!manager) throw new Error("Athena UI: generateThemePicker needs a manager from createThemeManager");
26
+ const name = uid("appearance");
27
+
28
+ const group = (legend, items, kind, preview) => {
29
+ const set = el("fieldset", { class: `theme-picker-group theme-picker-${kind}` }, el("legend", { text: legend }));
30
+ const list = el("div", { class: "theme-picker-options" });
31
+ for (const item of items) {
32
+ const input = el("input", { attrs: { type: "radio", name: `${name}-${kind}`, value: item.id } });
33
+ input.addEventListener("change", () => {
34
+ if (input.checked) (kind === "theme" ? manager.setTheme : manager.setMode)(item.id);
35
+ });
36
+ const label = el("label", { class: "theme-picker-option", attrs: { "data-id": item.id } }, input);
37
+ if (preview) label.append(preview(item));
38
+ label.append(el("span", { class: "theme-picker-name", text: item.name ?? item.id }));
39
+ if (item.description) label.append(el("span", { class: "theme-picker-description", text: item.description }));
40
+ list.append(label);
41
+ }
42
+ set.append(list);
43
+ return set;
44
+ };
45
+
46
+ const page = (theme, mode, className) => el("span", { class: className, attrs: { "data-theme": theme.id, "data-mode": mode } },
47
+ el("span", { class: "theme-preview-bar" }),
48
+ el("span", { class: "theme-preview-body" }, el("span", { class: "theme-preview-line" }), el("span", { class: "theme-preview-button" })));
49
+ // A small page drawn with the colours of the theme, in the mode that is in use (the light one for "system" in a light browser), or in both modes.
50
+ const preview = theme => options.previewModes === "both" ? el("span", { class: "theme-preview theme-preview-both", attrs: { "aria-hidden": "true" } },
51
+ page(theme, "light", "theme-preview-half"), page(theme, "dark", "theme-preview-half")) : el("span", {
52
+ class: "theme-preview",
53
+ attrs: { "data-theme": theme.id, "data-mode": manager.appearance().dark ? "dark" : "light", "aria-hidden": "true" }
54
+ },
55
+ el("span", { class: "theme-preview-bar" }),
56
+ el("span", { class: "theme-preview-body" }, el("span", { class: "theme-preview-line" }), el("span", { class: "theme-preview-button" })));
57
+
58
+ const element = el("div", { class: cx("theme-picker", options.class) });
59
+ const render = () => {
60
+ element.replaceChildren(
61
+ group(options.themeLabel ?? translate("theme"), manager.themes, "theme", preview),
62
+ group(options.modeLabel ?? translate("mode"), manager.modes, "mode", null)
63
+ );
64
+ sync(manager.appearance());
65
+ };
66
+ const sync = state => {
67
+ for (const input of element.querySelectorAll("input")) {
68
+ const kind = input.name.endsWith("-theme") ? "theme" : "mode";
69
+ input.checked = input.value === state[kind];
70
+ }
71
+ // The previews follow dark / light
72
+ for (const node of element.querySelectorAll(".theme-preview:not(.theme-preview-both)")) node.dataset.mode = state.dark ? "dark" : "light";
73
+ };
74
+ render();
75
+ const stop = manager.onChange(sync);
76
+ mount(options.parent, element);
77
+ return asHandle({ element, update: () => { render(); }, destroy() { stop(); element.remove(); } });
78
+ }
@@ -105,6 +105,7 @@ function choiceList(wrapper, kind, name, choices, value) {
105
105
  * @param {object} [options.rules] validation rules, see validateValue. They can also be given directly
106
106
  * (required, email, minLength, ...)
107
107
  * @param {(value, field) => void} [options.onChange]
108
+ * @param {boolean} [options.hideLabel=false] the label is there for screen readers and the browser only (a select in a header, a compact filter): it is hidden visually, not removed
108
109
  * @param {() => object} [options.getValues] all form values (set by generateForm, used by `match`)
109
110
  * @returns {{element: HTMLElement, name: string, getValue: Function, setValue: Function, validate: Function,
110
111
  * setError: Function, focus: Function}}
@@ -134,7 +135,7 @@ export function generateField(options = {}) {
134
135
  let getValue;
135
136
  let setValue;
136
137
  let events = ["input", "change"];
137
- const container = grouped ? el("fieldset", { class: "field-group" }, el("legend", {}, caption ?? "")) : wrapper;
138
+ const container = grouped ? el("fieldset", { class: "field-group" }, el("legend", { class: options.hideLabel ? "athena-visually-hidden" : undefined }, caption ?? "")) : wrapper;
138
139
 
139
140
  if (type === "textarea") {
140
141
  const control = el("textarea", { id, attrs: { name, placeholder, rows: options.rows ?? 3 }, prop: { value: options.value ?? "" } });
@@ -226,11 +227,12 @@ export function generateField(options = {}) {
226
227
  const helpEl = help ? el("div", { class: "field-help", id: helpId, text: help }) : null;
227
228
  if (inline) {
228
229
  const track = type === "switch" ? el("span", { class: "switch-track", attrs: { "aria-hidden": "true" } }) : null;
230
+ if (options.hideLabel) caption?.classList.add("athena-visually-hidden"); // the control stays, its words are for screen readers
229
231
  wrapper.append(el("label", { class: cx("choice", type === "switch" && "switch"), attrs: { for: id } }, controls[0], track ?? "", caption ?? ""));
230
232
  } else if (grouped) {
231
233
  wrapper.append(container);
232
234
  } else {
233
- if (caption) wrapper.append(el("label", { class: "field-label", id: `${id}-label`, attrs: { for: id } }, caption));
235
+ if (caption) wrapper.append(el("label", { class: cx("field-label", options.hideLabel && "athena-visually-hidden"), id: `${id}-label`, attrs: { for: id } }, caption));
234
236
  wrapper.append(...(controlNodes ?? controls));
235
237
  }
236
238
  if (helpEl) wrapper.append(helpEl);