athena-ui-js 0.4.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +352 -11
  2. package/package.json +84 -60
  3. package/src/athena-ui.js +68 -1
  4. package/src/libs/config/config.js +15 -1
  5. package/src/libs/config/hooks.js +15 -3
  6. package/src/libs/core/combobox.js +179 -0
  7. package/src/libs/core/csv.js +37 -0
  8. package/src/libs/core/dateRange.js +50 -0
  9. package/src/libs/core/dom.js +57 -0
  10. package/src/libs/core/focus.js +49 -0
  11. package/src/libs/core/format.js +31 -0
  12. package/src/libs/core/i18n.js +160 -0
  13. package/src/libs/core/pagination.js +24 -0
  14. package/src/libs/core/sanitize.js +65 -0
  15. package/src/libs/core/tableMath.js +31 -0
  16. package/src/libs/core/validation.js +79 -0
  17. package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +81 -0
  18. package/src/libs/hephaestus/auth/session.js +68 -0
  19. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +187 -0
  20. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +201 -0
  21. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +126 -0
  22. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +138 -0
  23. package/src/libs/hephaestus/formGenerator/changePasswordFormGenerator.js +50 -0
  24. package/src/libs/hephaestus/formGenerator/formBuilder.js +379 -0
  25. package/src/libs/hephaestus/formGenerator/formUtils.js +66 -0
  26. package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +20 -6
  27. package/src/libs/hephaestus/formGenerator/lostPasswordFormGenerator.js +30 -0
  28. package/src/libs/hephaestus/formGenerator/registrationFormGenerator.js +54 -0
  29. package/src/libs/hephaestus/hephaestus.js +8 -1
  30. package/src/libs/hephaestus/inputGenerator/inputGenerator.js +299 -0
  31. package/src/libs/hephaestus/inputGenerator/richTextGenerator.js +222 -0
  32. package/src/libs/hephaestus/modalGenerator/modalGenerator.js +13 -2
  33. package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +388 -0
  34. package/src/libs/hephaestus/router/matchRoute.js +42 -0
  35. package/src/libs/hephaestus/router/router.js +102 -0
  36. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +457 -0
  37. package/src/res/themes/dark/style.css +31 -0
  38. package/src/res/themes/default/style.css +1388 -7
  39. package/src/res/themes/themes.js +6 -0
@@ -0,0 +1,160 @@
1
+ //i18n 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
+ // Every text generated by Athena UI goes through translate(), so an application can switch
7
+ // the language with setLocale() or override single texts with addMessages().
8
+
9
+ const messages = {
10
+ en: {
11
+ username: "Username",
12
+ password: "Password",
13
+ email: "Email",
14
+ confirmPassword: "Confirm password",
15
+ currentPassword: "Current password",
16
+ newPassword: "New password",
17
+ login: "Login",
18
+ register: "Register",
19
+ resetPassword: "Reset password",
20
+ changePassword: "Change password",
21
+ rememberMe: "Remember me",
22
+ ok: "OK",
23
+ cancel: "Cancel",
24
+ close: "Close",
25
+ back: "Back",
26
+ next: "Next",
27
+ finish: "Finish",
28
+ previous: "Prev",
29
+ page: "Page {page} / {pages}",
30
+ filter: "Filter...",
31
+ noData: "No data",
32
+ loading: "Loading...",
33
+ selectAll: "Select all",
34
+ search: "Search...",
35
+ noResults: "No results",
36
+ dropFiles: "Drop files here or click to browse",
37
+ "validation.required": "This field is required.",
38
+ "validation.email": "Enter a valid email address.",
39
+ "validation.minLength": "Enter at least {min} characters.",
40
+ "validation.maxLength": "Enter at most {max} characters.",
41
+ "validation.pattern": "The value has an invalid format.",
42
+ "validation.min": "The value must be at least {min}.",
43
+ "validation.max": "The value must be at most {max}.",
44
+ "validation.match": "The values do not match.",
45
+ "validation.invalid": "The value is invalid.",
46
+ "validation.fileSize": "{name} is larger than {max}.",
47
+ "validation.url": "Enter a valid address (https://, mailto: or tel:).",
48
+ "validation.dateRange": "The end date must not be before the start date.",
49
+ "validation.dateMin": "The date must be {min} or later.",
50
+ "validation.dateMax": "The date must be {max} or earlier.",
51
+ "session.loggedOut": "You have been logged out.",
52
+ dateFrom: "From",
53
+ dateTo: "To",
54
+ resizeColumn: "Resize column",
55
+ more: "More",
56
+ "rt.toolbar": "Text formatting",
57
+ "rt.bold": "Bold",
58
+ "rt.italic": "Italic",
59
+ "rt.underline": "Underline",
60
+ "rt.strike": "Strikethrough",
61
+ "rt.heading2": "Heading 2",
62
+ "rt.heading3": "Heading 3",
63
+ "rt.quote": "Quote",
64
+ "rt.bulletList": "Bulleted list",
65
+ "rt.numberList": "Numbered list",
66
+ "rt.link": "Link",
67
+ "rt.unlink": "Remove link",
68
+ "rt.clear": "Clear formatting",
69
+ "rt.undo": "Undo",
70
+ "rt.redo": "Redo",
71
+ "rt.linkPrompt": "Link address"
72
+ },
73
+ hu: {
74
+ username: "Felhasználónév",
75
+ password: "Jelszó",
76
+ email: "E-mail",
77
+ confirmPassword: "Jelszó megerősítése",
78
+ currentPassword: "Jelenlegi jelszó",
79
+ newPassword: "Új jelszó",
80
+ login: "Belépés",
81
+ register: "Regisztráció",
82
+ resetPassword: "Jelszó visszaállítása",
83
+ changePassword: "Jelszó módosítása",
84
+ rememberMe: "Emlékezz rám",
85
+ ok: "OK",
86
+ cancel: "Mégse",
87
+ close: "Bezár",
88
+ back: "Vissza",
89
+ next: "Tovább",
90
+ finish: "Befejezés",
91
+ previous: "Előző",
92
+ page: "{page}. oldal / {pages}",
93
+ filter: "Szűrés...",
94
+ noData: "Nincs adat",
95
+ loading: "Betöltés...",
96
+ selectAll: "Összes kijelölése",
97
+ search: "Keresés...",
98
+ noResults: "Nincs találat",
99
+ dropFiles: "Húzza ide a fájlokat vagy kattintson a tallózáshoz",
100
+ "validation.required": "A mező kitöltése kötelező.",
101
+ "validation.email": "Adjon meg érvényes e-mail címet.",
102
+ "validation.minLength": "Legalább {min} karakter szükséges.",
103
+ "validation.maxLength": "Legfeljebb {max} karakter adható meg.",
104
+ "validation.pattern": "Az érték formátuma érvénytelen.",
105
+ "validation.min": "Az érték legalább {min} legyen.",
106
+ "validation.max": "Az érték legfeljebb {max} lehet.",
107
+ "validation.match": "Az értékek nem egyeznek.",
108
+ "validation.invalid": "Érvénytelen érték.",
109
+ "validation.fileSize": "{name} mérete meghaladja a {max} értéket.",
110
+ "validation.url": "Adjon meg érvényes címet (https://, mailto: vagy tel:).",
111
+ "validation.dateRange": "A záró dátum nem lehet korábbi a kezdő dátumnál.",
112
+ "validation.dateMin": "A dátum legkorábban {min} lehet.",
113
+ "validation.dateMax": "A dátum legkésőbb {max} lehet.",
114
+ "session.loggedOut": "Kijelentkezett.",
115
+ dateFrom: "Ettől",
116
+ dateTo: "Eddig",
117
+ resizeColumn: "Oszlop átméretezése",
118
+ more: "Továbbiak",
119
+ "rt.toolbar": "Szövegformázás",
120
+ "rt.bold": "Félkövér",
121
+ "rt.italic": "Dőlt",
122
+ "rt.underline": "Aláhúzott",
123
+ "rt.strike": "Áthúzott",
124
+ "rt.heading2": "2. szintű cím",
125
+ "rt.heading3": "3. szintű cím",
126
+ "rt.quote": "Idézet",
127
+ "rt.bulletList": "Felsorolás",
128
+ "rt.numberList": "Számozott lista",
129
+ "rt.link": "Hivatkozás",
130
+ "rt.unlink": "Hivatkozás törlése",
131
+ "rt.clear": "Formázás törlése",
132
+ "rt.undo": "Visszavonás",
133
+ "rt.redo": "Újra",
134
+ "rt.linkPrompt": "Hivatkozás címe"
135
+ }
136
+ };
137
+
138
+ let locale = "en";
139
+
140
+ export function setLocale(newLocale) {
141
+ locale = newLocale;
142
+ }
143
+
144
+ export function getLocale() {
145
+ return locale;
146
+ }
147
+
148
+ // Adds or overrides texts of a locale: addMessages("de", { login: "Anmelden" })
149
+ export function addMessages(forLocale, texts) {
150
+ messages[forLocale] = { ...messages[forLocale], ...texts };
151
+ }
152
+
153
+ /**
154
+ * Looks a text up in the current locale, then in its base language ("hu-HU" -> "hu"), then in English.
155
+ * Unknown keys are returned as they are. {name} placeholders are replaced from params.
156
+ */
157
+ export function translate(key, params = {}) {
158
+ const text = messages[locale]?.[key] ?? messages[locale.split("-")[0]]?.[key] ?? messages.en[key] ?? key;
159
+ return text.replace(/\{(\w+)\}/g, (match, name) => params[name] ?? match);
160
+ }
@@ -0,0 +1,24 @@
1
+ //pagination helper 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
+ * Page buttons to show: first and last page, the current page with its neighbours, "…" for the gaps.
8
+ * pageRange(5, 10, 1) -> [1, "…", 4, 5, 6, "…", 10]
9
+ */
10
+ export function pageRange(page, pages, siblings = 1) {
11
+ const wanted = new Set([1, pages]);
12
+ for (let p = page - siblings; p <= page + siblings; p++) {
13
+ if (p >= 1 && p <= pages) wanted.add(p);
14
+ }
15
+ const sorted = [...wanted].sort((a, b) => a - b);
16
+ const result = [];
17
+ sorted.forEach((p, i) => {
18
+ const previous = sorted[i - 1];
19
+ if (previous !== undefined && p - previous === 2) result.push(previous + 1);
20
+ else if (previous !== undefined && p - previous > 2) result.push("…");
21
+ result.push(p);
22
+ });
23
+ return result;
24
+ }
@@ -0,0 +1,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
+ 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
+ }
@@ -0,0 +1,31 @@
1
+ //tableMath 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
+ * Which rows of a long list have to be in the DOM for the current scroll position.
8
+ * The rows before and after the window are replaced by spacers of `offsetTop` / `offsetBottom` pixels,
9
+ * so the scroll bar keeps the size of the whole list.
10
+ *
11
+ * @param {object} options
12
+ * @param {number} options.scrollTop
13
+ * @param {number} options.viewportHeight
14
+ * @param {number} options.rowHeight
15
+ * @param {number} options.total number of rows
16
+ * @param {number} [options.overscan=5] extra rows above and below, so fast scrolling does not show gaps
17
+ * @returns {{start: number, end: number, offsetTop: number, offsetBottom: number}} rows start..end-1 are rendered
18
+ */
19
+ export function virtualWindow({ scrollTop, viewportHeight, rowHeight, total, overscan = 5 }) {
20
+ if (total <= 0 || rowHeight <= 0) return { start: 0, end: 0, offsetTop: 0, offsetBottom: 0 };
21
+ const first = Math.floor(Math.max(scrollTop, 0) / rowHeight);
22
+ const last = Math.ceil((Math.max(scrollTop, 0) + viewportHeight) / rowHeight);
23
+ const start = Math.min(Math.max(first - overscan, 0), total - 1);
24
+ const end = Math.min(Math.max(last + overscan, start + 1), total);
25
+ return { start, end, offsetTop: start * rowHeight, offsetBottom: (total - end) * rowHeight };
26
+ }
27
+
28
+ // Keeps a column width between the minimum and the maximum.
29
+ export function clampWidth(width, min = 40, max = 1200) {
30
+ return Math.min(Math.max(Math.round(width), min), Math.max(min, max));
31
+ }
@@ -0,0 +1,79 @@
1
+ //validation 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 { translate } from "./i18n.js";
7
+
8
+ export const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
9
+
10
+ const isEmpty = value => value == null || value === false || value === "" || (Array.isArray(value) && !value.length);
11
+
12
+ /**
13
+ * Validates one value. Returns the (translated) error text, or "" when the value is valid.
14
+ * Empty values only fail `required`, so optional fields can stay empty.
15
+ *
16
+ * @param {*} value a string, boolean (checkbox) or array (multiple choice)
17
+ * @param {object} [rules]
18
+ * @param {boolean} [rules.required]
19
+ * @param {boolean} [rules.email]
20
+ * @param {number} [rules.minLength]
21
+ * @param {number} [rules.maxLength]
22
+ * @param {RegExp|string} [rules.pattern]
23
+ * @param {number} [rules.min] numeric minimum
24
+ * @param {number} [rules.max] numeric maximum
25
+ * @param {string} [rules.match] name of another field that has to hold the same value
26
+ * @param {(value, values) => (string|boolean|undefined)} [rules.validate] custom rule: a string is the error
27
+ * text, false is a generic error, anything else is valid
28
+ * @param {object} [values] all values of the form, for `match` and `validate`
29
+ */
30
+ export function validateValue(value, rules = {}, values = {}) {
31
+ if (isEmpty(value)) return rules.required ? translate("validation.required") : "";
32
+ const text = String(value);
33
+ if (rules.email && !EMAIL_PATTERN.test(text)) return translate("validation.email");
34
+ if (rules.minLength != null && text.length < rules.minLength) return translate("validation.minLength", { min: rules.minLength });
35
+ if (rules.maxLength != null && text.length > rules.maxLength) return translate("validation.maxLength", { max: rules.maxLength });
36
+ if (rules.pattern != null && !new RegExp(rules.pattern).test(text)) return translate("validation.pattern");
37
+ if (rules.min != null && Number(value) < rules.min) return translate("validation.min", { min: rules.min });
38
+ if (rules.max != null && Number(value) > rules.max) return translate("validation.max", { max: rules.max });
39
+ if (rules.match != null && value !== values[rules.match]) return translate("validation.match");
40
+ if (rules.validate) {
41
+ const result = rules.validate(value, values);
42
+ if (typeof result === "string") return result;
43
+ if (result === false) return translate("validation.invalid");
44
+ }
45
+ return "";
46
+ }
47
+
48
+ /**
49
+ * Checks a date range given as ISO dates ("2026-01-31"; they compare correctly as text).
50
+ * Returns the (translated) error text, or "" when the range is valid. Empty dates are not an error.
51
+ *
52
+ * @param {string} from
53
+ * @param {string} to
54
+ * @param {{min?: string, max?: string}} [limits]
55
+ */
56
+ export function validateDateRange(from, to, { min, max } = {}) {
57
+ if (from && to && to < from) return translate("validation.dateRange");
58
+ for (const date of [from, to]) {
59
+ if (date && min && date < min) return translate("validation.dateMin", { min });
60
+ if (date && max && date > max) return translate("validation.dateMax", { max });
61
+ }
62
+ return "";
63
+ }
64
+
65
+ /**
66
+ * Validates a whole form.
67
+ *
68
+ * @param {Object<string, object>} ruleSet rules by field name
69
+ * @param {Object<string, *>} values
70
+ * @returns {Object<string, string>} error text by field name, only for invalid fields
71
+ */
72
+ export function validateAll(ruleSet, values) {
73
+ const errors = {};
74
+ for (const [name, rules] of Object.entries(ruleSet)) {
75
+ const error = validateValue(values[name], rules, values);
76
+ if (error) errors[name] = error;
77
+ }
78
+ return errors;
79
+ }
@@ -8,6 +8,7 @@
8
8
  import { HTMLElementGenerator } from "../HTMLElementGenerator/src/HTMLElementGenerator.js";
9
9
  import { BORDERED_CLASS } from "../../config/config.js";
10
10
  import { getNav } from "../../config/hooks.js";
11
+ import { el, uid } from "../../core/dom.js";
11
12
 
12
13
  // Placeholder items used when the application does not provide menuItems.
13
14
  export function defaultMenuItems(menuId, count = 3) {
@@ -19,6 +20,11 @@ export function defaultMenuItems(menuId, count = 3) {
19
20
  }));
20
21
  }
21
22
 
23
+ /**
24
+ * Generates a menu. An item with `children: [{ inner_text, disabled? }]` opens a submenu on click, Enter, Space
25
+ * or the Down arrow. Esc, a click outside, or choosing an entry closes it. Choosing an entry calls the
26
+ * nav callback with its `inner_text`, like a top level item.
27
+ */
22
28
  export function generateBasicMenu(options) {
23
29
  generateMenuWireFrame(options);
24
30
  addMenuItemToWireFrame(options);
@@ -41,6 +47,10 @@ export function addMenuItemToWireFrame(options) {
41
47
  options.items.forEach((item, index) => {
42
48
  // Without a parent id HTMLElementGenerator would append the label to the body.
43
49
  if (!item.id) return;
50
+ if (item.children?.length) {
51
+ addSubmenu(item, `${options.menu_id}-item-${index}`);
52
+ return;
53
+ }
44
54
  HTMLElementGenerator({
45
55
  parent: item.id,
46
56
  id: `${options.menu_id}-item-${index}`,
@@ -50,3 +60,74 @@ export function addMenuItemToWireFrame(options) {
50
60
  });
51
61
  });
52
62
  }
63
+
64
+ function addSubmenu(item, labelId) {
65
+ const host = document.getElementById(item.id);
66
+ if (!host) return;
67
+ const listId = uid("submenu");
68
+ const label = el("span", {
69
+ id: labelId,
70
+ class: "menu-parent",
71
+ text: item.inner_text,
72
+ attrs: { role: "button", tabindex: "0", "aria-haspopup": "menu", "aria-expanded": "false", "aria-controls": listId }
73
+ });
74
+ const list = el("ul", { id: listId, class: "submenu", attrs: { role: "menu", hidden: true } });
75
+ host.classList.add("has-submenu");
76
+
77
+ const entries = item.children.map(child => {
78
+ const entry = el("li", {
79
+ class: "submenu-item",
80
+ text: child.inner_text,
81
+ attrs: { role: "menuitem", tabindex: "-1", "aria-disabled": child.disabled ? "true" : null }
82
+ });
83
+ if (!child.disabled) {
84
+ entry.addEventListener("click", () => {
85
+ close(true);
86
+ getNav()?.(child.inner_text);
87
+ });
88
+ }
89
+ list.append(entry);
90
+ return entry;
91
+ });
92
+ const enabled = () => entries.filter(entry => entry.getAttribute("aria-disabled") !== "true");
93
+
94
+ const onOutside = event => { if (!host.contains(event.target)) close(); };
95
+ function open(focusFirst = false) {
96
+ list.hidden = false;
97
+ label.setAttribute("aria-expanded", "true");
98
+ document.addEventListener("pointerdown", onOutside);
99
+ if (focusFirst) enabled()[0]?.focus();
100
+ }
101
+ function close(restoreFocus = false) {
102
+ list.hidden = true;
103
+ label.setAttribute("aria-expanded", "false");
104
+ document.removeEventListener("pointerdown", onOutside);
105
+ if (restoreFocus === true) label.focus();
106
+ }
107
+
108
+ label.addEventListener("click", () => (list.hidden ? open() : close()));
109
+ label.addEventListener("keydown", event => {
110
+ if (event.key === "Enter" || event.key === " " || event.key === "ArrowDown") {
111
+ event.preventDefault();
112
+ if (list.hidden) open(true);
113
+ else enabled()[0]?.focus();
114
+ } else if (event.key === "Escape") {
115
+ close();
116
+ }
117
+ });
118
+ list.addEventListener("keydown", event => {
119
+ const items = enabled();
120
+ const index = items.indexOf(document.activeElement);
121
+ if (event.key === "ArrowDown") items[(index + 1) % items.length]?.focus();
122
+ else if (event.key === "ArrowUp") items[(index - 1 + items.length) % items.length]?.focus();
123
+ else if (event.key === "Home") items[0]?.focus();
124
+ else if (event.key === "End") items[items.length - 1]?.focus();
125
+ else if (event.key === "Escape") close(true);
126
+ else if (event.key === "Enter" || event.key === " ") document.activeElement.click();
127
+ else if (event.key === "Tab") close();
128
+ else return;
129
+ if (event.key !== "Tab") event.preventDefault();
130
+ });
131
+
132
+ host.append(label, list);
133
+ }
@@ -0,0 +1,68 @@
1
+ //session 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 config from "../../config/config.js";
7
+ import Cookies from "../../js-cookie/src/api.mjs";
8
+
9
+ // The session is kept in a cookie, so the page knows after a reload who is logged in.
10
+ // A cookie written from script can be read by any script of the page: keep only what the UI needs
11
+ // (a name, roles, a short lived token) and let the server enforce the real authorization. A server
12
+ // set `HttpOnly` session cookie is the safer place for the actual credentials.
13
+
14
+ const listeners = new Set();
15
+
16
+ function notify() {
17
+ const session = getSession();
18
+ listeners.forEach(listener => listener(session));
19
+ }
20
+
21
+ /**
22
+ * Stores the session after a successful login.
23
+ *
24
+ * @param {object} session
25
+ * @param {*} [session.user] anything JSON serializable: name, roles, ...
26
+ * @param {string} [session.token]
27
+ * @param {boolean} [session.remember=false] keep the session after the browser closes
28
+ * @param {number} [session.days] lifetime of a remembered session (default: the `session_days` setting)
29
+ */
30
+ export function setSession({ user, token, remember = false, days = config.session_days } = {}) {
31
+ Cookies.set(config.session_cookie, JSON.stringify({ user, token, at: Date.now() }), {
32
+ expires: remember ? days : undefined,
33
+ sameSite: "strict",
34
+ secure: location.protocol === "https:"
35
+ });
36
+ notify();
37
+ }
38
+
39
+ /** The stored session ({ user, token, at }), or null when nobody is logged in. */
40
+ export function getSession() {
41
+ const raw = Cookies.get(config.session_cookie);
42
+ if (!raw) return null;
43
+ try {
44
+ return JSON.parse(raw);
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ export function isLoggedIn() {
51
+ return getSession() !== null;
52
+ }
53
+
54
+ /** Ends the session. */
55
+ export function logout() {
56
+ Cookies.remove(config.session_cookie, { sameSite: "strict", secure: location.protocol === "https:" });
57
+ notify();
58
+ }
59
+
60
+ /**
61
+ * Calls the listener with the session (or null) whenever somebody logs in or out.
62
+ *
63
+ * @returns {() => void} unsubscribe function
64
+ */
65
+ export function onSessionChange(listener) {
66
+ listeners.add(listener);
67
+ return () => listeners.delete(listener);
68
+ }