athena-ui-js 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +228 -22
- package/package.json +9 -7
- package/src/athena-ui.js +33 -10
- package/src/libs/config/config.js +8 -1
- package/src/libs/core/controls.js +153 -0
- package/src/libs/core/dateRange.js +121 -0
- package/src/libs/core/dom.js +58 -8
- package/src/libs/{hephaestus/HTMLElementGenerator/src/HTMLElementGenerator.js → core/elementGenerator.js} +23 -21
- package/src/libs/{hephaestus/HTMLElementGenerator/src → core}/errors.js +7 -5
- package/src/libs/core/format.js +51 -0
- package/src/libs/core/hungarianControls.js +41 -0
- package/src/libs/core/i18n.js +64 -0
- package/src/libs/core/theme.js +131 -0
- package/src/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.js +4 -6
- package/src/libs/hephaestus/LayoutGenerator/footerContentGenerator.js +2 -4
- package/src/libs/hephaestus/LayoutGenerator/headerContentGenerator.js +12 -5
- package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +3 -3
- package/src/libs/hephaestus/MenuGenerator/menuGenerator.js +253 -0
- package/src/libs/hephaestus/auth/authState.js +58 -0
- package/src/libs/hephaestus/chartGenerator/chartGenerator.js +519 -87
- package/src/libs/hephaestus/componentGenerator/componentGenerator.js +121 -4
- package/src/libs/hephaestus/componentGenerator/themePicker.js +73 -0
- package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +88 -8
- package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +21 -0
- package/src/libs/hephaestus/formGenerator/authForms.js +130 -0
- package/src/libs/hephaestus/formGenerator/formUtils.js +10 -9
- package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +9 -9
- package/src/libs/hephaestus/hephaestus.js +7 -2
- package/src/libs/hephaestus/inputGenerator/inputGenerator.js +30 -1
- package/src/libs/hephaestus/modalGenerator/modalGenerator.js +17 -11
- package/src/libs/hephaestus/router/router.js +54 -5
- package/src/libs/hephaestus/tableGenerator/tableGenerator.js +290 -16
- package/src/libs/libs.js +3 -3
- package/src/res/themes/appearance.css +154 -0
- package/src/res/themes/default/style.css +609 -0
- package/src/theme-boot.js +25 -0
- package/src/libs/hephaestus/HTMLControlGenerator/LICENSE +0 -21
- package/src/libs/hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js +0 -5
- package/src/libs/hephaestus/HTMLElementGenerator/LICENSE +0 -21
package/src/libs/core/i18n.js
CHANGED
|
@@ -20,6 +20,38 @@ const messages = {
|
|
|
20
20
|
changePassword: "Change password",
|
|
21
21
|
rememberMe: "Remember me",
|
|
22
22
|
ok: "OK",
|
|
23
|
+
save: "Save",
|
|
24
|
+
"range.preset": "Range",
|
|
25
|
+
"range.custom": "Custom",
|
|
26
|
+
"range.last15m": "Last 15 minutes",
|
|
27
|
+
"range.last1h": "Last hour",
|
|
28
|
+
"range.last24h": "Last 24 hours",
|
|
29
|
+
"range.last7d": "Last 7 days",
|
|
30
|
+
"range.last30d": "Last 30 days",
|
|
31
|
+
copied: "Copied",
|
|
32
|
+
copyFailed: "Copying is not possible here.",
|
|
33
|
+
"tone.ok": "good",
|
|
34
|
+
"tone.warn": "warning",
|
|
35
|
+
"tone.bad": "critical",
|
|
36
|
+
"chart.zoomHint": "Chart plot. Plus and minus zoom, arrow keys move, 0 resets.",
|
|
37
|
+
"chart.resetZoom": "Reset zoom",
|
|
38
|
+
menu: "Main menu",
|
|
39
|
+
showAsTable: "Show as table",
|
|
40
|
+
series: "Series",
|
|
41
|
+
time: "Time",
|
|
42
|
+
"chart.bar": "Bar chart",
|
|
43
|
+
"chart.line": "Line chart",
|
|
44
|
+
"chart.area": "Area chart",
|
|
45
|
+
"chart.sparkline": "Trend",
|
|
46
|
+
"chart.pie": "Pie chart",
|
|
47
|
+
"chart.donut": "Donut chart",
|
|
48
|
+
actions: "Actions",
|
|
49
|
+
retry: "Retry",
|
|
50
|
+
loadMore: "Load more",
|
|
51
|
+
theme: "Theme",
|
|
52
|
+
mode: "Mode",
|
|
53
|
+
typeToConfirm: "Type {text} to confirm:",
|
|
54
|
+
textMismatch: "The text does not match.",
|
|
23
55
|
cancel: "Cancel",
|
|
24
56
|
close: "Close",
|
|
25
57
|
back: "Back",
|
|
@@ -85,6 +117,38 @@ const messages = {
|
|
|
85
117
|
changePassword: "Jelszó módosítása",
|
|
86
118
|
rememberMe: "Emlékezz rám",
|
|
87
119
|
ok: "OK",
|
|
120
|
+
save: "Mentés",
|
|
121
|
+
"range.preset": "Időszak",
|
|
122
|
+
"range.custom": "Egyéni",
|
|
123
|
+
"range.last15m": "Utolsó 15 perc",
|
|
124
|
+
"range.last1h": "Utolsó óra",
|
|
125
|
+
"range.last24h": "Utolsó 24 óra",
|
|
126
|
+
"range.last7d": "Utolsó 7 nap",
|
|
127
|
+
"range.last30d": "Utolsó 30 nap",
|
|
128
|
+
copied: "Másolva",
|
|
129
|
+
copyFailed: "A másolás itt nem lehetséges.",
|
|
130
|
+
"tone.ok": "rendben",
|
|
131
|
+
"tone.warn": "figyelmeztetés",
|
|
132
|
+
"tone.bad": "kritikus",
|
|
133
|
+
"chart.zoomHint": "A diagram területe. A plusz és a mínusz nagyít, a nyilak mozgatnak, a 0 visszaállít.",
|
|
134
|
+
"chart.resetZoom": "Nagyítás visszaállítása",
|
|
135
|
+
menu: "Főmenü",
|
|
136
|
+
showAsTable: "Megjelenítés táblázatként",
|
|
137
|
+
series: "Adatsor",
|
|
138
|
+
time: "Idő",
|
|
139
|
+
"chart.bar": "Oszlopdiagram",
|
|
140
|
+
"chart.line": "Vonaldiagram",
|
|
141
|
+
"chart.area": "Területdiagram",
|
|
142
|
+
"chart.sparkline": "Trend",
|
|
143
|
+
"chart.pie": "Kördiagram",
|
|
144
|
+
"chart.donut": "Fánkdiagram",
|
|
145
|
+
actions: "Műveletek",
|
|
146
|
+
retry: "Újra",
|
|
147
|
+
loadMore: "Továbbiak betöltése",
|
|
148
|
+
theme: "Téma",
|
|
149
|
+
mode: "Mód",
|
|
150
|
+
typeToConfirm: "A megerősítéshez írja be: {text}",
|
|
151
|
+
textMismatch: "A szöveg nem egyezik.",
|
|
88
152
|
cancel: "Mégse",
|
|
89
153
|
close: "Bezár",
|
|
90
154
|
back: "Vissza",
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
//theme manager 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
|
+
// The look of an application: a theme (a set of colours) and a mode (light, dark, or whatever the system uses).
|
|
7
|
+
// Both are a choice of the person at this browser. They are kept in localStorage and put on <html> as
|
|
8
|
+
// data-theme and data-mode, which is what the stylesheets read:
|
|
9
|
+
//
|
|
10
|
+
// <html data-theme="ocean" data-mode="dark">
|
|
11
|
+
//
|
|
12
|
+
// [data-theme="ocean"][data-mode="light"] { --athena-bg: #f4f9fb; ... }
|
|
13
|
+
// [data-theme="ocean"][data-mode="dark"] { --athena-bg: #0b1c24; ... }
|
|
14
|
+
//
|
|
15
|
+
// Nothing is sent to a server. theme-boot.js (a classic script of its own) sets the two attributes before the page is
|
|
16
|
+
// drawn, so the wrong colours never flash.
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_MODES = [
|
|
19
|
+
{ id: "system", name: "Like the system" },
|
|
20
|
+
{ id: "light", name: "Light" },
|
|
21
|
+
{ id: "dark", name: "Dark" }
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {object} options
|
|
26
|
+
* @param {{id: string, name?: string, description?: string}[]} options.themes the first one is the default
|
|
27
|
+
* @param {{id: string, name?: string}[]} [options.modes] default: system, light, dark. Ids "light" and "dark" are the ones that can be resolved
|
|
28
|
+
* @param {string} [options.storageKey="athena.appearance"] localStorage key (also give it to theme-boot.js)
|
|
29
|
+
* @param {string} [options.themeColorVariable] CSS variable whose value becomes <meta name="theme-color"> (the bar of a phone browser)
|
|
30
|
+
* @param {HTMLElement} [options.root] element that gets the attributes (default: <html>)
|
|
31
|
+
* @param {Storage} [options.storage] default: localStorage
|
|
32
|
+
* @returns {{themes, modes, appearance: () => object, setTheme: (id) => boolean, setMode: (id) => boolean,
|
|
33
|
+
* onChange: (listener) => Function, refresh: Function, destroy: Function}}
|
|
34
|
+
*/
|
|
35
|
+
export function createThemeManager(options = {}) {
|
|
36
|
+
const themes = options.themes ?? [];
|
|
37
|
+
if (!themes.length) throw new Error("Athena UI: createThemeManager needs at least one theme");
|
|
38
|
+
const modes = options.modes ?? DEFAULT_MODES;
|
|
39
|
+
const key = options.storageKey ?? "athena.appearance";
|
|
40
|
+
const root = options.root ?? document.documentElement;
|
|
41
|
+
const storage = options.storage ?? globalThis.localStorage;
|
|
42
|
+
const view = root.ownerDocument.defaultView ?? globalThis;
|
|
43
|
+
const listeners = new Set();
|
|
44
|
+
const systemDark = () => view.matchMedia?.("(prefers-color-scheme: dark)");
|
|
45
|
+
|
|
46
|
+
const read = () => {
|
|
47
|
+
try {
|
|
48
|
+
const saved = JSON.parse(storage?.getItem(key) || "{}");
|
|
49
|
+
return {
|
|
50
|
+
theme: themes.some(theme => theme.id === saved.theme) ? saved.theme : themes[0].id,
|
|
51
|
+
mode: modes.some(mode => mode.id === saved.mode) ? saved.mode : "system"
|
|
52
|
+
};
|
|
53
|
+
} catch {
|
|
54
|
+
return { theme: themes[0].id, mode: "system" };
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
let current = read();
|
|
59
|
+
const appearance = () => ({ ...current, dark: root.dataset.mode === "dark" });
|
|
60
|
+
|
|
61
|
+
function apply() {
|
|
62
|
+
const dark = current.mode === "dark" || (current.mode === "system" && Boolean(systemDark()?.matches));
|
|
63
|
+
root.dataset.theme = current.theme;
|
|
64
|
+
root.dataset.mode = dark ? "dark" : "light";
|
|
65
|
+
if (options.themeColorVariable) {
|
|
66
|
+
const doc = root.ownerDocument;
|
|
67
|
+
let meta = doc.querySelector('meta[name="theme-color"]');
|
|
68
|
+
if (!meta) {
|
|
69
|
+
meta = doc.createElement("meta");
|
|
70
|
+
meta.name = "theme-color";
|
|
71
|
+
doc.head.append(meta);
|
|
72
|
+
}
|
|
73
|
+
const color = view.getComputedStyle(root).getPropertyValue(options.themeColorVariable).trim();
|
|
74
|
+
if (color) meta.content = color;
|
|
75
|
+
}
|
|
76
|
+
listeners.forEach(listener => listener(appearance()));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function save(change) {
|
|
80
|
+
current = { ...current, ...change };
|
|
81
|
+
try {
|
|
82
|
+
storage?.setItem(key, JSON.stringify(current));
|
|
83
|
+
} catch {
|
|
84
|
+
// Not saved (private browsing, full storage), but it works until the page is closed
|
|
85
|
+
}
|
|
86
|
+
apply();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const onSystemChange = () => { if (current.mode === "system") apply(); };
|
|
90
|
+
const onStorage = event => {
|
|
91
|
+
if (event.key !== key) return; // another tab changed it
|
|
92
|
+
current = read();
|
|
93
|
+
apply();
|
|
94
|
+
};
|
|
95
|
+
const media = systemDark();
|
|
96
|
+
media?.addEventListener?.("change", onSystemChange);
|
|
97
|
+
view.addEventListener?.("storage", onStorage);
|
|
98
|
+
apply();
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
themes,
|
|
102
|
+
modes,
|
|
103
|
+
appearance,
|
|
104
|
+
/** Chooses a theme. Returns false (and changes nothing) for one that does not exist. */
|
|
105
|
+
setTheme(id) {
|
|
106
|
+
if (!themes.some(theme => theme.id === id)) return false;
|
|
107
|
+
save({ theme: id });
|
|
108
|
+
return true;
|
|
109
|
+
},
|
|
110
|
+
/** Chooses a mode. Returns false (and changes nothing) for one that does not exist. */
|
|
111
|
+
setMode(id) {
|
|
112
|
+
if (!modes.some(mode => mode.id === id)) return false;
|
|
113
|
+
save({ mode: id });
|
|
114
|
+
return true;
|
|
115
|
+
},
|
|
116
|
+
/** Called with { theme, mode, dark } now, and whenever the look changes. Returns a function that stops it. */
|
|
117
|
+
onChange(listener) {
|
|
118
|
+
listeners.add(listener);
|
|
119
|
+
listener(appearance());
|
|
120
|
+
return () => listeners.delete(listener);
|
|
121
|
+
},
|
|
122
|
+
/** The stylesheet may have loaded after the first call: read the colours (theme-color) again. */
|
|
123
|
+
refresh: apply,
|
|
124
|
+
/** Stops listening to the system and to other tabs. */
|
|
125
|
+
destroy() {
|
|
126
|
+
media?.removeEventListener?.("change", onSystemChange);
|
|
127
|
+
view.removeEventListener?.("storage", onStorage);
|
|
128
|
+
listeners.clear();
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
@@ -3,9 +3,7 @@
|
|
|
3
3
|
//LICENCE: MIT
|
|
4
4
|
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import { HTMLElementGenerator } from "../HTMLElementGenerator/src/HTMLElementGenerator.js";
|
|
6
|
+
import { HTMLElementGenerator } from "../../core/elementGenerator.js";
|
|
9
7
|
import config, { withBorder } from "../../config/config.js";
|
|
10
8
|
import { generateHeaderContent } from "./headerContentGenerator.js";
|
|
11
9
|
import { generateWrapperContent } from "./wrapperContentGenerator.js";
|
|
@@ -39,7 +37,7 @@ export function generateHeader() {
|
|
|
39
37
|
}
|
|
40
38
|
|
|
41
39
|
export function clearHeader() {
|
|
42
|
-
|
|
40
|
+
document.getElementById("header")?.replaceChildren();
|
|
43
41
|
}
|
|
44
42
|
|
|
45
43
|
/* WRAPPER ELEMENT GENERATION */
|
|
@@ -50,7 +48,7 @@ export function generateWrapper() {
|
|
|
50
48
|
}
|
|
51
49
|
|
|
52
50
|
export function clearWrapper() {
|
|
53
|
-
|
|
51
|
+
document.getElementById("wrapper")?.replaceChildren();
|
|
54
52
|
}
|
|
55
53
|
|
|
56
54
|
/* FOOTER ELEMENT GENERATION */
|
|
@@ -61,5 +59,5 @@ export function generateFooter() {
|
|
|
61
59
|
}
|
|
62
60
|
|
|
63
61
|
export function clearFooter() {
|
|
64
|
-
|
|
62
|
+
document.getElementById("footer")?.replaceChildren();
|
|
65
63
|
}
|
|
@@ -3,9 +3,7 @@
|
|
|
3
3
|
//LICENCE: MIT
|
|
4
4
|
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import { HTMLElementGenerator } from "../HTMLElementGenerator/src/HTMLElementGenerator.js";
|
|
6
|
+
import { HTMLElementGenerator } from "../../core/elementGenerator.js";
|
|
9
7
|
import config, { withBorder } from "../../config/config.js";
|
|
10
8
|
import { getMenuItems } from "../../config/hooks.js";
|
|
11
9
|
import { generateBasicMenu, defaultMenuItems } from "../MenuGenerator/basicMenuGenerator.js";
|
|
@@ -25,7 +23,7 @@ export function generateFooterMenu() {
|
|
|
25
23
|
}
|
|
26
24
|
|
|
27
25
|
export function clearFooterMenu() {
|
|
28
|
-
|
|
26
|
+
document.getElementById("footer_menu")?.replaceChildren();
|
|
29
27
|
}
|
|
30
28
|
|
|
31
29
|
export function generateFooterCopyrightText() {
|
|
@@ -3,12 +3,11 @@
|
|
|
3
3
|
//LICENCE: MIT
|
|
4
4
|
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import { HTMLElementGenerator } from "../HTMLElementGenerator/src/HTMLElementGenerator.js";
|
|
6
|
+
import { HTMLElementGenerator } from "../../core/elementGenerator.js";
|
|
9
7
|
import config, { withBorder } from "../../config/config.js";
|
|
10
8
|
import { getMenuItems } from "../../config/hooks.js";
|
|
11
9
|
import { generateBasicMenu, defaultMenuItems } from "../MenuGenerator/basicMenuGenerator.js";
|
|
10
|
+
import { generateMenu } from "../MenuGenerator/menuGenerator.js";
|
|
12
11
|
|
|
13
12
|
export function generateHeaderContent() {
|
|
14
13
|
generateContaninerForElements({ parent: "header", id: "header_logo_container", text: "" });
|
|
@@ -19,7 +18,15 @@ export function generateHeaderContent() {
|
|
|
19
18
|
generateHeaderMenu();
|
|
20
19
|
}
|
|
21
20
|
|
|
22
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Generates the menu of the header. Without options it is built from the global `menuItems` / nav callback, as before.
|
|
23
|
+
* With `options.items` it is a generateMenu (no globals): `generateHeaderMenu({ items, onNavigate, active, layout, followHash })`.
|
|
24
|
+
*/
|
|
25
|
+
export function generateHeaderMenu(options) {
|
|
26
|
+
if (options?.items) {
|
|
27
|
+
document.getElementById("header_menu_container")?.replaceChildren();
|
|
28
|
+
return generateMenu({ ...options, parent: "header_menu_container", id: options.id ?? "header_menu" });
|
|
29
|
+
}
|
|
23
30
|
generateBasicMenu({
|
|
24
31
|
parent: "header_menu_container",
|
|
25
32
|
menu_id: "header_menu",
|
|
@@ -29,7 +36,7 @@ export function generateHeaderMenu() {
|
|
|
29
36
|
}
|
|
30
37
|
|
|
31
38
|
export function clearHeaderMenu() {
|
|
32
|
-
|
|
39
|
+
document.getElementById("header_menu_container")?.replaceChildren();
|
|
33
40
|
}
|
|
34
41
|
|
|
35
42
|
export function generateHeaderTitle() {
|
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
//LICENCE: MIT
|
|
4
4
|
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
5
|
|
|
6
|
-
/* global HTMLControlGenerator */
|
|
7
6
|
|
|
8
|
-
import { HTMLElementGenerator } from "
|
|
7
|
+
import { HTMLElementGenerator } from "../../core/elementGenerator.js";
|
|
9
8
|
import { BORDERED_CLASS } from "../../config/config.js";
|
|
10
9
|
import { getNav } from "../../config/hooks.js";
|
|
11
10
|
import { el, uid } from "../../core/dom.js";
|
|
11
|
+
import { generateControl } from "../../core/controls.js";
|
|
12
12
|
|
|
13
13
|
// Placeholder items used when the application does not provide menuItems.
|
|
14
14
|
export function defaultMenuItems(menuId, count = 3) {
|
|
@@ -34,7 +34,7 @@ export function generateMenuWireFrame(options) {
|
|
|
34
34
|
const menuClass = [options.menu_class, options.bordered && BORDERED_CLASS, options.class]
|
|
35
35
|
.filter(Boolean)
|
|
36
36
|
.join(" ");
|
|
37
|
-
|
|
37
|
+
generateControl({
|
|
38
38
|
inputType: "ul",
|
|
39
39
|
parent: options.parent,
|
|
40
40
|
id: options.menu_id,
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
//menuGenerator 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 { translate } from "../../core/i18n.js";
|
|
8
|
+
import { isSafeUrl } from "../../core/sanitize.js";
|
|
9
|
+
import { initialsOf } from "../componentGenerator/componentGenerator.js";
|
|
10
|
+
|
|
11
|
+
const ENABLED = "[role=menuitem]:not([aria-disabled=true]):not(:disabled)";
|
|
12
|
+
|
|
13
|
+
/** The text of a badge: numbers above 99 become "99+", 0 / null / false / "" mean no badge. */
|
|
14
|
+
export function badgeText(value) {
|
|
15
|
+
if (value == null || value === false || value === 0 || value === "") return "";
|
|
16
|
+
return typeof value === "number" && value > 99 ? "99+" : String(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Generates a navigation menu. Items are real links (`href`) or buttons, so the keyboard and screen readers work without help:
|
|
21
|
+
* Tab reaches every item, Enter and Space use it, the arrow keys move inside a group, Esc closes it.
|
|
22
|
+
*
|
|
23
|
+
* @param {object} options
|
|
24
|
+
* @param {string|Element} [options.parent]
|
|
25
|
+
* @param {{id: string, label: string, icon?: string|Node, href?: string, disabled?: boolean, align?: "end",
|
|
26
|
+
* badge?: number|string|{text: (number|string), tone?: "info"|"ok"|"warn"|"bad"}, badgeLabel?: string,
|
|
27
|
+
* avatar?: {name: string, src?: string}, children?: object[]}[]} options.items
|
|
28
|
+
* `icon` is shown before the label (text, or a Node such as an SVG; it is hidden from screen readers).
|
|
29
|
+
* `badge` is a small count or word after the label (0, null and "" show nothing, numbers above 99 show "99+").
|
|
30
|
+
* `badgeLabel` is what a screen reader hears for it ("3 unread"); without it the badge text is read after the label.
|
|
31
|
+
* `avatar` shows the picture (or the initials) of a person: for the user menu, usually with `align: "end"` and children.
|
|
32
|
+
* An item with `children` opens a group; a child can have children too (a group inside a group, any depth).
|
|
33
|
+
* @param {(item: object, event: Event) => void} [options.onNavigate] called when a PERSON uses an item (click, Enter, Space).
|
|
34
|
+
* It is never called by select() or while the menu is built.
|
|
35
|
+
* @param {string} [options.active] id of the item that is the current page at the start
|
|
36
|
+
* @param {boolean} [options.followHash=false] the item whose `href` equals location.hash is the active one, and follows hashchange
|
|
37
|
+
* @param {"bar"|"bottom-tabs"|"responsive"} [options.layout="bar"] "bottom-tabs": a bar of tabs at the bottom of the screen,
|
|
38
|
+
* groups open as sheets above it. "responsive": a bar on wide screens, bottom tabs on a tablet or phone (max 700px).
|
|
39
|
+
* @param {string} [options.label] accessible name of the navigation
|
|
40
|
+
* @param {string} [options.id]
|
|
41
|
+
* @param {string} [options.class]
|
|
42
|
+
* @returns {{element: HTMLElement, select: (id: string|null) => void, getActive: () => string|null, setBadge: (id: string, badge) => void,
|
|
43
|
+
* close: Function, update: (changes?: {items?: object[]}) => object, destroy: Function}}
|
|
44
|
+
*/
|
|
45
|
+
export function generateMenu(options = {}) {
|
|
46
|
+
const layout = options.layout ?? "bar";
|
|
47
|
+
let items = options.items ?? [];
|
|
48
|
+
let active = null;
|
|
49
|
+
const nodes = new Map(); // id -> { item, control, li, parent (id) }
|
|
50
|
+
let openGroups = []; // from the outermost to the innermost: { toggle, sheet, depth }
|
|
51
|
+
|
|
52
|
+
const list = el("ul", { class: "athena-menu-list" });
|
|
53
|
+
const element = el("nav", {
|
|
54
|
+
id: options.id,
|
|
55
|
+
class: cx("athena-menu", `athena-menu-${layout}`, options.class),
|
|
56
|
+
attrs: { "aria-label": options.label ?? translate("menu") }
|
|
57
|
+
}, list);
|
|
58
|
+
const doc = element.ownerDocument;
|
|
59
|
+
const view = doc.defaultView;
|
|
60
|
+
|
|
61
|
+
const badgeNode = badge => {
|
|
62
|
+
const spec = badge != null && typeof badge === "object" ? badge : { text: badge };
|
|
63
|
+
const text = badgeText(spec.text);
|
|
64
|
+
return text ? el("span", { class: cx("menu-badge", spec.tone && `menu-badge-${spec.tone}`), text }) : null;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const content = item => {
|
|
68
|
+
const parts = [];
|
|
69
|
+
if (item.avatar) {
|
|
70
|
+
const avatar = el("span", { class: "menu-avatar", attrs: { "aria-hidden": "true" } });
|
|
71
|
+
if (item.avatar.src && isSafeUrl(item.avatar.src)) avatar.append(el("img", { attrs: { src: item.avatar.src, alt: "" } }));
|
|
72
|
+
else avatar.textContent = initialsOf(item.avatar.name);
|
|
73
|
+
parts.push(avatar);
|
|
74
|
+
}
|
|
75
|
+
if (item.icon) parts.push(setContent(el("span", { class: "menu-icon", attrs: { "aria-hidden": "true" } }), item.icon));
|
|
76
|
+
parts.push(el("span", { class: "menu-label", text: item.label }));
|
|
77
|
+
const badge = badgeNode(item.badge);
|
|
78
|
+
if (badge) parts.push(badge);
|
|
79
|
+
return parts;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// A link when there is an address, a button otherwise.
|
|
83
|
+
const control = (item, inGroup) => {
|
|
84
|
+
const attrs = { "data-id": item.id, role: inGroup ? "menuitem" : null };
|
|
85
|
+
const node = item.href && !item.children?.length
|
|
86
|
+
? el("a", { class: cx("menu-control", inGroup && "menu-sub-control"), attrs: { ...attrs, href: item.href } }, ...content(item))
|
|
87
|
+
: el("button", { class: cx("menu-control", inGroup && "menu-sub-control"), attrs: { ...attrs, type: "button", disabled: item.disabled } }, ...content(item));
|
|
88
|
+
if (item.disabled && node.tagName === "A") {
|
|
89
|
+
node.setAttribute("aria-disabled", "true");
|
|
90
|
+
node.removeAttribute("href");
|
|
91
|
+
}
|
|
92
|
+
if (item.badgeLabel) node.setAttribute("aria-label", `${item.label}, ${item.badgeLabel}`);
|
|
93
|
+
if (inGroup) node.tabIndex = -1;
|
|
94
|
+
return node;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/* ------------------GROUPS (any depth)------------------- */
|
|
98
|
+
|
|
99
|
+
function closeFrom(depth, restoreFocus = false) {
|
|
100
|
+
const closing = openGroups.filter(group => group.depth >= depth);
|
|
101
|
+
if (!closing.length) return;
|
|
102
|
+
for (const { toggle, sheet } of closing.reverse()) {
|
|
103
|
+
sheet.hidden = true;
|
|
104
|
+
toggle.setAttribute("aria-expanded", "false");
|
|
105
|
+
}
|
|
106
|
+
const outermost = closing.at(-1);
|
|
107
|
+
openGroups = openGroups.filter(group => group.depth < depth);
|
|
108
|
+
if (restoreFocus) outermost.toggle.focus();
|
|
109
|
+
if (!openGroups.length) doc.removeEventListener("pointerdown", onOutside);
|
|
110
|
+
}
|
|
111
|
+
const closeAll = (restoreFocus = false) => closeFrom(0, restoreFocus);
|
|
112
|
+
const onOutside = event => { if (!element.contains(event.target)) closeAll(); };
|
|
113
|
+
|
|
114
|
+
function openSheet(toggle, sheet, depth, focusFirst) {
|
|
115
|
+
closeFrom(depth); // siblings and everything deeper than this group close first
|
|
116
|
+
sheet.hidden = false;
|
|
117
|
+
toggle.setAttribute("aria-expanded", "true");
|
|
118
|
+
if (!openGroups.length) doc.addEventListener("pointerdown", onOutside);
|
|
119
|
+
openGroups.push({ toggle, sheet, depth });
|
|
120
|
+
if (focusFirst) sheet.querySelector(`:scope > li > ${ENABLED}`)?.focus();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Builds a group: the toggle (a button) and its sheet, which holds the children (which may be groups again).
|
|
124
|
+
function buildGroup(item, depth, toggle) {
|
|
125
|
+
const sheetId = uid("menu-sheet");
|
|
126
|
+
const sheet = el("ul", { id: sheetId, class: cx("menu-sheet", depth > 0 && "menu-sheet-nested"), attrs: { role: "menu", hidden: true, "aria-label": item.label } });
|
|
127
|
+
toggle.setAttribute("aria-haspopup", "menu");
|
|
128
|
+
toggle.setAttribute("aria-expanded", "false");
|
|
129
|
+
toggle.setAttribute("aria-controls", sheetId);
|
|
130
|
+
toggle.append(el("span", { class: "menu-caret", text: depth > 0 ? "▸" : "▾", attrs: { "aria-hidden": "true" } }));
|
|
131
|
+
toggle.addEventListener("click", () => (sheet.hidden ? openSheet(toggle, sheet, depth, depth > 0) : closeFrom(depth)));
|
|
132
|
+
toggle.addEventListener("keydown", event => {
|
|
133
|
+
const opens = depth === 0 ? ["ArrowDown", "ArrowUp"] : ["ArrowRight"];
|
|
134
|
+
if (opens.includes(event.key)) {
|
|
135
|
+
event.preventDefault();
|
|
136
|
+
event.stopPropagation();
|
|
137
|
+
openSheet(toggle, sheet, depth, true);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
for (const child of item.children) sheet.append(buildItem(child, depth + 1, item.id, "menuitem"));
|
|
141
|
+
sheet.addEventListener("keydown", event => {
|
|
142
|
+
// Only the innermost sheet reacts: the event comes from an item that is a direct child of this sheet
|
|
143
|
+
if (event.target.closest(".menu-sheet") !== sheet) return;
|
|
144
|
+
const entries = [...sheet.querySelectorAll(`:scope > li > ${ENABLED}`)];
|
|
145
|
+
const index = entries.indexOf(doc.activeElement);
|
|
146
|
+
if (event.key === "ArrowDown") entries[(index + 1) % entries.length]?.focus();
|
|
147
|
+
else if (event.key === "ArrowUp") entries[(index - 1 + entries.length) % entries.length]?.focus();
|
|
148
|
+
else if (event.key === "Home") entries[0]?.focus();
|
|
149
|
+
else if (event.key === "End") entries.at(-1)?.focus();
|
|
150
|
+
else if (event.key === "Escape" || (event.key === "ArrowLeft" && depth > 0)) closeFrom(depth, true);
|
|
151
|
+
else if (event.key === "Tab") closeAll();
|
|
152
|
+
else return;
|
|
153
|
+
if (event.key !== "Tab") {
|
|
154
|
+
event.preventDefault();
|
|
155
|
+
event.stopPropagation();
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
return sheet;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function buildItem(item, depth, parentId, role) {
|
|
162
|
+
const li = el("li", { class: cx("menu-item", depth === 0 && item.align === "end" && "menu-item-end", item.children?.length && "has-submenu"), attrs: { role: role === "menuitem" ? "none" : null } });
|
|
163
|
+
const node = control(item, depth > 0);
|
|
164
|
+
nodes.set(item.id, { item, control: node, li, parent: parentId });
|
|
165
|
+
if (item.children?.length) {
|
|
166
|
+
li.append(node, buildGroup(item, depth, node));
|
|
167
|
+
} else {
|
|
168
|
+
node.addEventListener("click", event => {
|
|
169
|
+
if (item.disabled) return;
|
|
170
|
+
if (depth > 0) closeAll(true);
|
|
171
|
+
options.onNavigate?.(item, event);
|
|
172
|
+
});
|
|
173
|
+
li.append(node);
|
|
174
|
+
}
|
|
175
|
+
return li;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function build() {
|
|
179
|
+
closeAll();
|
|
180
|
+
list.replaceChildren();
|
|
181
|
+
nodes.clear();
|
|
182
|
+
for (const item of items) list.append(buildItem(item, 0, null, null));
|
|
183
|
+
// Arrow keys move along the top level, like a toolbar (Tab still reaches every item).
|
|
184
|
+
list.onkeydown = event => {
|
|
185
|
+
if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") return;
|
|
186
|
+
if (event.target.closest(".menu-sheet")) return;
|
|
187
|
+
const tops = [...list.querySelectorAll(":scope > li > .menu-control:not(:disabled)")];
|
|
188
|
+
const index = tops.indexOf(event.target);
|
|
189
|
+
if (index < 0) return;
|
|
190
|
+
event.preventDefault();
|
|
191
|
+
tops[(index + (event.key === "ArrowRight" ? 1 : -1) + tops.length) % tops.length].focus();
|
|
192
|
+
};
|
|
193
|
+
select(active);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Marks the current page: class is-active and aria-current="page" on the item (and has-active on every group around it). Does not call onNavigate. */
|
|
197
|
+
function select(id) {
|
|
198
|
+
active = id ?? null;
|
|
199
|
+
for (const { control: node, li } of nodes.values()) {
|
|
200
|
+
node.classList.remove("is-active");
|
|
201
|
+
node.removeAttribute("aria-current");
|
|
202
|
+
li.classList.remove("has-active");
|
|
203
|
+
}
|
|
204
|
+
const found = nodes.get(active);
|
|
205
|
+
if (!found) return;
|
|
206
|
+
found.control.classList.add("is-active");
|
|
207
|
+
found.control.setAttribute("aria-current", "page");
|
|
208
|
+
for (let parent = found.parent; parent; parent = nodes.get(parent)?.parent) nodes.get(parent)?.li.classList.add("has-active");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Changes the badge of an item (a number, text, { text, tone }, or 0 / null to remove it) without building the menu again. */
|
|
212
|
+
function setBadge(id, badge) {
|
|
213
|
+
const found = nodes.get(id);
|
|
214
|
+
if (!found) return;
|
|
215
|
+
found.item.badge = badge;
|
|
216
|
+
found.control.querySelector(".menu-badge")?.remove();
|
|
217
|
+
const node = badgeNode(badge);
|
|
218
|
+
if (node) found.control.querySelector(".menu-caret") ? found.control.querySelector(".menu-caret").before(node) : found.control.append(node);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const fromHash = () => {
|
|
222
|
+
const hash = view.location.hash;
|
|
223
|
+
const match = [...nodes.values()].find(({ item }) => item.href && item.href === hash);
|
|
224
|
+
if (match) select(match.item.id);
|
|
225
|
+
};
|
|
226
|
+
if (options.followHash) view.addEventListener("hashchange", fromHash);
|
|
227
|
+
|
|
228
|
+
active = options.active ?? null;
|
|
229
|
+
build();
|
|
230
|
+
if (options.followHash) fromHash();
|
|
231
|
+
mount(options.parent, element);
|
|
232
|
+
|
|
233
|
+
return asHandle({
|
|
234
|
+
element,
|
|
235
|
+
select,
|
|
236
|
+
setBadge,
|
|
237
|
+
getActive: () => active,
|
|
238
|
+
close: closeAll,
|
|
239
|
+
update(changes = {}) {
|
|
240
|
+
if (changes.items) {
|
|
241
|
+
items = changes.items;
|
|
242
|
+
build();
|
|
243
|
+
if (options.followHash) fromHash();
|
|
244
|
+
}
|
|
245
|
+
return this;
|
|
246
|
+
},
|
|
247
|
+
destroy() {
|
|
248
|
+
closeAll();
|
|
249
|
+
view.removeEventListener("hashchange", fromHash);
|
|
250
|
+
element.remove();
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
//authState 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
|
+
/**
|
|
7
|
+
* Who is signed in, kept in memory only. Nothing is written to a cookie or to the storage, so a script (an injected one too) cannot read
|
|
8
|
+
* a credential from here: the real session is a cookie that only the server can read (HttpOnly). This object is the UI's copy of the
|
|
9
|
+
* answer to "who am I", for menus, route guards and the page. The server decides what a person may do.
|
|
10
|
+
*
|
|
11
|
+
* After a reload the state is empty until restore() has asked the server.
|
|
12
|
+
*
|
|
13
|
+
* @param {object} [options]
|
|
14
|
+
* @param {() => Promise<(object|null)>} [options.restore] asks the server who is signed in (for example GET /api/me with the cookie):
|
|
15
|
+
* resolves with the user object, or with null / throws when nobody is
|
|
16
|
+
* @returns {{signIn: (user: object) => void, signOut: () => void, restore: () => Promise<object|null>, isSignedIn: () => boolean,
|
|
17
|
+
* getUser: () => (object|null), hasRole: (role: string) => boolean, onChange: (listener: Function) => Function,
|
|
18
|
+
* routerRules: (paths?: object) => object}}
|
|
19
|
+
*/
|
|
20
|
+
export function createAuthState(options = {}) {
|
|
21
|
+
let user = null;
|
|
22
|
+
const listeners = new Set();
|
|
23
|
+
const notify = () => listeners.forEach(listener => listener(user));
|
|
24
|
+
const set = next => {
|
|
25
|
+
const changed = (next === null) !== (user === null) || JSON.stringify(next) !== JSON.stringify(user);
|
|
26
|
+
user = next;
|
|
27
|
+
if (changed) notify();
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const state = {
|
|
31
|
+
/** The server accepted the sign in: remember who it is (the user object comes from the server's answer). */
|
|
32
|
+
signIn(next) { set(next ?? {}); },
|
|
33
|
+
/** Forget the person. (End the session on the server too: this only clears the UI.) */
|
|
34
|
+
signOut() { set(null); },
|
|
35
|
+
/** Asks the server who is signed in. Resolves with the user, or null. Never throws. */
|
|
36
|
+
async restore() {
|
|
37
|
+
try {
|
|
38
|
+
const found = await options.restore?.();
|
|
39
|
+
set(found ?? null);
|
|
40
|
+
} catch {
|
|
41
|
+
set(null);
|
|
42
|
+
}
|
|
43
|
+
return user;
|
|
44
|
+
},
|
|
45
|
+
isSignedIn: () => user !== null,
|
|
46
|
+
getUser: () => user,
|
|
47
|
+
/** True when the user has the role (user.roles is a list, or user.role a single role). */
|
|
48
|
+
hasRole: role => Boolean(user && (user.roles?.includes?.(role) || user.role === role)),
|
|
49
|
+
/** Called with the user (or null) when somebody signs in or out. Returns a function that stops it. */
|
|
50
|
+
onChange(listener) {
|
|
51
|
+
listeners.add(listener);
|
|
52
|
+
return () => listeners.delete(listener);
|
|
53
|
+
},
|
|
54
|
+
/** The \`auth\` option of createRouter: createRouter({ auth: auth.routerRules({ loginPath: "/signin" }) }). */
|
|
55
|
+
routerRules: (paths = {}) => ({ isSignedIn: state.isSignedIn, hasRole: state.hasRole, ...paths })
|
|
56
|
+
};
|
|
57
|
+
return state;
|
|
58
|
+
}
|