athena-ui-js 1.1.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.
Files changed (45) hide show
  1. package/README.md +273 -23
  2. package/package.json +11 -7
  3. package/src/athena-ui.js +33 -10
  4. package/src/libs/config/config.js +8 -1
  5. package/src/libs/core/combobox.js +1 -1
  6. package/src/libs/core/controls.js +153 -0
  7. package/src/libs/core/dateRange.js +121 -0
  8. package/src/libs/core/dom.js +88 -11
  9. package/src/libs/{hephaestus/HTMLElementGenerator/src/HTMLElementGenerator.js → core/elementGenerator.js} +23 -21
  10. package/src/libs/{hephaestus/HTMLElementGenerator/src → core}/errors.js +7 -5
  11. package/src/libs/core/format.js +51 -0
  12. package/src/libs/core/hungarianControls.js +41 -0
  13. package/src/libs/core/i18n.js +64 -0
  14. package/src/libs/core/theme.js +131 -0
  15. package/src/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.js +4 -6
  16. package/src/libs/hephaestus/LayoutGenerator/footerContentGenerator.js +2 -4
  17. package/src/libs/hephaestus/LayoutGenerator/headerContentGenerator.js +12 -5
  18. package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +3 -3
  19. package/src/libs/hephaestus/MenuGenerator/menuGenerator.js +253 -0
  20. package/src/libs/hephaestus/auth/authState.js +58 -0
  21. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +530 -65
  22. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +124 -6
  23. package/src/libs/hephaestus/componentGenerator/themePicker.js +73 -0
  24. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +100 -13
  25. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +23 -2
  26. package/src/libs/hephaestus/formGenerator/authForms.js +130 -0
  27. package/src/libs/hephaestus/formGenerator/formBuilder.js +5 -5
  28. package/src/libs/hephaestus/formGenerator/formUtils.js +10 -9
  29. package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +9 -9
  30. package/src/libs/hephaestus/hephaestus.js +7 -2
  31. package/src/libs/hephaestus/inputGenerator/dropZoneGenerator.js +2 -2
  32. package/src/libs/hephaestus/inputGenerator/inputGenerator.js +37 -8
  33. package/src/libs/hephaestus/inputGenerator/richTextGenerator.js +2 -2
  34. package/src/libs/hephaestus/modalGenerator/modalGenerator.js +17 -11
  35. package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +20 -11
  36. package/src/libs/hephaestus/router/router.js +56 -6
  37. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +368 -29
  38. package/src/libs/libs.js +3 -3
  39. package/src/res/themes/appearance.css +154 -0
  40. package/src/res/themes/default/style.css +649 -2
  41. package/src/testing.js +71 -0
  42. package/src/theme-boot.js +25 -0
  43. package/src/libs/hephaestus/HTMLControlGenerator/LICENSE +0 -21
  44. package/src/libs/hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js +0 -5
  45. package/src/libs/hephaestus/HTMLElementGenerator/LICENSE +0 -21
@@ -3,11 +3,11 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- /* global $, CryptoJS, HTMLControlGenerator */
7
6
 
8
- import { HTMLElementGenerator } from "../HTMLElementGenerator/src/HTMLElementGenerator.js";
7
+ import { HTMLElementGenerator } from "../../core/elementGenerator.js";
9
8
  import config from "../../config/config.js";
10
9
  import { translate } from "../../core/i18n.js";
10
+ import { generateControl } from "../../core/controls.js";
11
11
 
12
12
  export { EMAIL_PATTERN } from "../../core/validation.js";
13
13
 
@@ -25,11 +25,11 @@ export function generateRow(formId, name) {
25
25
  export function generateField(formId, name, label, inputType) {
26
26
  const row = generateRow(formId, name);
27
27
  HTMLElementGenerator({ elementType: "span", parent: row, id: `${row}-label`, class: "container", text: `${translate(label)}: ` });
28
- HTMLControlGenerator({ inputType, parent: row, id: `${row}-control`, class: "text-filed-class" });
28
+ generateControl({ inputType, parent: row, id: `${row}-control`, class: "text-filed-class" });
29
29
  }
30
30
 
31
31
  export function generateButton(formId, name, text, onclick) {
32
- HTMLControlGenerator({
32
+ generateControl({
33
33
  inputType: "button",
34
34
  parent: generateRow(formId, name),
35
35
  text,
@@ -51,14 +51,15 @@ export function generateMessage(formId) {
51
51
  }
52
52
 
53
53
  export function showMessage(formId, text, isError = true) {
54
- $(`#${formId}-message`)
55
- .text(text)
56
- .toggleClass("form-message-error", isError)
57
- .toggleClass("form-message-success", !isError);
54
+ const node = document.getElementById(`${formId}-message`);
55
+ if (!node) return;
56
+ node.textContent = text;
57
+ node.classList.toggle("form-message-error", isError);
58
+ node.classList.toggle("form-message-success", !isError);
58
59
  }
59
60
 
60
61
  export function readControl(formId, name) {
61
- return $(`#${formId}-${name}-control`).val() ?? "";
62
+ return document.getElementById(`${formId}-${name}-control`)?.value ?? "";
62
63
  }
63
64
 
64
65
  export function hashPassword(password) {
@@ -3,12 +3,12 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- /* global $, CryptoJS, HTMLControlGenerator */
7
6
 
8
- import { HTMLElementGenerator } from "../HTMLElementGenerator/src/HTMLElementGenerator.js";
7
+ import { HTMLElementGenerator } from "../../core/elementGenerator.js";
9
8
  import config from "../../config/config.js";
10
9
  import { getLogin } from "../../config/hooks.js";
11
10
  import { translate } from "../../core/i18n.js";
11
+ import { generateControl } from "../../core/controls.js";
12
12
 
13
13
  const FORM_ID = "loginForm";
14
14
 
@@ -33,7 +33,7 @@ function generateField(name, label, inputType) {
33
33
  class: "container",
34
34
  text: `${translate(label)}: `
35
35
  });
36
- HTMLControlGenerator({
36
+ generateControl({
37
37
  inputType,
38
38
  parent: row,
39
39
  id: `${row}-control`,
@@ -44,12 +44,12 @@ function generateField(name, label, inputType) {
44
44
  // Reads the form. The password is SHA-256 hashed when enable_encrypt_password is set.
45
45
  // `remember` is included when the login_remember_me setting shows the checkbox.
46
46
  export function getLoginFormData() {
47
- const username = $(`#${FORM_ID}-username-control`).val();
48
- let password = $(`#${FORM_ID}-password-control`).val();
47
+ const username = document.getElementById(`${FORM_ID}-username-control`)?.value;
48
+ let password = document.getElementById(`${FORM_ID}-password-control`)?.value;
49
49
  if (config.enable_encrypt_password) password = CryptoJS.SHA256(password).toString();
50
50
  const data = { username, password };
51
- const remember = $(`#${FORM_ID}-remember-control`);
52
- if (remember.length) data.remember = remember.prop("checked");
51
+ const remember = document.getElementById(`${FORM_ID}-remember-control`);
52
+ if (remember) data.remember = remember.checked;
53
53
  return data;
54
54
  }
55
55
 
@@ -85,12 +85,12 @@ export function generatePasswordElements() {
85
85
  export function generateRememberElement() {
86
86
  if (!config.login_remember_me) return;
87
87
  const row = generateRow("remember");
88
- HTMLControlGenerator({ inputType: "checkbox", parent: row, id: `${row}-control` });
88
+ generateControl({ inputType: "checkbox", parent: row, id: `${row}-control` });
89
89
  HTMLElementGenerator({ elementType: "span", parent: row, id: `${row}-label`, text: translate("rememberMe") });
90
90
  }
91
91
 
92
92
  export function generateSubmitElement() {
93
- HTMLControlGenerator({
93
+ generateControl({
94
94
  inputType: "button",
95
95
  parent: generateRow("submit"),
96
96
  text: translate("login"),
@@ -28,8 +28,13 @@ export function loadScript(src) {
28
28
  return loadedScripts.get(src);
29
29
  }
30
30
 
31
- export function loadLibs(extraScripts = []) {
32
- return Promise.all([...libs.map(lib => lib.src), ...extraScripts].map(loadScript));
31
+ /**
32
+ * Loads the classic scripts that are still needed: only crypto-js, and only when the deprecated enable_encrypt_password is on.
33
+ * Athena UI has no other classic script, and does not need jQuery.
34
+ */
35
+ export function loadLibs(extraScripts = [], { crypto = false } = {}) {
36
+ const wanted = libs.filter(lib => (lib.needs === "crypto" ? crypto : true));
37
+ return Promise.all([...wanted.map(lib => lib.src), ...extraScripts].map(loadScript));
33
38
  }
34
39
 
35
40
  // Accepts { id } of a registered theme or a custom { href }. Falls back to the default theme.
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { cx, el, mount, setContent, uid } from "../../core/dom.js";
6
+ import { asHandle, cx, el, mount, setContent, uid } from "../../core/dom.js";
7
7
  import { formatBytes, matchesAccept } from "../../core/format.js";
8
8
  import { translate } from "../../core/i18n.js";
9
9
 
@@ -114,5 +114,5 @@ export function createDropZone(options = {}) {
114
114
  export function generateDropZone(options = {}) {
115
115
  const zone = createDropZone(options);
116
116
  mount(options.parent, zone.element);
117
- return zone;
117
+ return asHandle(zone);
118
118
  }
@@ -4,8 +4,8 @@
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
6
  import { createCombobox } from "../../core/combobox.js";
7
- import { createDateRange } from "../../core/dateRange.js";
8
- import { cx, el, mount, setContent, uid } from "../../core/dom.js";
7
+ import { createDateRange, createDateTimeRange } from "../../core/dateRange.js";
8
+ import { asHandle, cx, el, mount, setContent, uid } from "../../core/dom.js";
9
9
  import { formatBytes, matchesAccept } from "../../core/format.js";
10
10
  import { translate } from "../../core/i18n.js";
11
11
  import { generateButton } from "../formGenerator/formBuilder.js";
@@ -46,7 +46,7 @@ function wrapCombobox(options, mode) {
46
46
  if (options.label) wrapper.append(el("label", { class: "field-label", text: options.label, attrs: { for: id } }));
47
47
  wrapper.append(combo.element);
48
48
  mount(options.parent, wrapper);
49
- return combo;
49
+ return asHandle(combo, { also: wrapper });
50
50
  }
51
51
 
52
52
  /* ------------------DATE RANGE------------------- */
@@ -73,7 +73,36 @@ export function generateDateRange(options = {}) {
73
73
  wrapper.append(range.element, error);
74
74
  range.element.addEventListener("change", () => { error.textContent = range.validate(); });
75
75
  mount(options.parent, wrapper);
76
- return range;
76
+ return asHandle(range, { also: wrapper });
77
+ }
78
+
79
+ /**
80
+ * Generates a from / to range with date AND time (datetime-local inputs), and a list of presets: last 15 minutes, hour,
81
+ * 24 hours, 7 days, 30 days, or "Custom". For log filters, charts and reports that need times, not whole days.
82
+ * A preset moves with the clock: getRange() measures it from now when it is called.
83
+ *
84
+ * @param {object} options
85
+ * @param {string|Element} [options.parent]
86
+ * @param {string} [options.label]
87
+ * @param {string} [options.from] initial start, "2026-01-31T08:00"
88
+ * @param {string} [options.to] initial end
89
+ * @param {string} [options.preset] id of the preset to start with ("15m", "1h", "24h", "7d", "30d")
90
+ * @param {{id: string, label?: string, labelKey?: string, minutes: number}[]} [options.presets] your own list
91
+ * @param {boolean} [options.seconds=false]
92
+ * @param {string} [options.min]
93
+ * @param {string} [options.max]
94
+ * @param {(value: {from: string, to: string, preset: string}) => void} [options.onChange]
95
+ * @returns {{element: HTMLElement, getValue: Function, getRange: () => ({from: Date|null, to: Date|null}), setValue: Function, validate: () => string}}
96
+ */
97
+ export function generateDateTimeRange(options = {}) {
98
+ const range = createDateTimeRange(options);
99
+ const wrapper = el("div", { class: "field" });
100
+ const error = el("div", { class: "field-error", attrs: { role: "alert" } });
101
+ if (options.label) wrapper.append(el("span", { class: "field-label", text: options.label }));
102
+ wrapper.append(range.element, error);
103
+ range.element.addEventListener("change", () => { error.textContent = range.validate(); });
104
+ mount(options.parent, wrapper);
105
+ return asHandle(range, { also: wrapper });
77
106
  }
78
107
 
79
108
  /* ------------------FILE UPLOAD------------------- */
@@ -196,13 +225,13 @@ export function generateFileUpload(options = {}) {
196
225
  }
197
226
 
198
227
  mount(options.parent, element);
199
- return {
228
+ return asHandle({
200
229
  element,
201
230
  getFiles: () => entries.map(entry => entry.file),
202
231
  upload,
203
232
  clear: () => entries.slice().forEach(remove),
204
233
  add
205
- };
234
+ });
206
235
  }
207
236
 
208
237
  /* ------------------STEPPER (wizard)------------------- */
@@ -273,12 +302,12 @@ export function generateStepper(options = {}) {
273
302
 
274
303
  mount(options.parent, element);
275
304
  if (steps.length) show(0);
276
- return {
305
+ return asHandle({
277
306
  element,
278
307
  next,
279
308
  back,
280
309
  // Going back is always possible, going forward only one step at a time through next().
281
310
  goTo: index => { if (index >= 0 && index < current) show(index); },
282
311
  getCurrent: () => current
283
- };
312
+ });
284
313
  }
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { cx, el, mount, uid } from "../../core/dom.js";
6
+ import { asHandle, cx, el, mount, uid } from "../../core/dom.js";
7
7
  import { translate } from "../../core/i18n.js";
8
8
  import { htmlToText, isSafeUrl, sanitizeHtml } from "../../core/sanitize.js";
9
9
 
@@ -244,7 +244,7 @@ export function generateRichText(options = {}) {
244
244
  }
245
245
  wrapper.append(rich.element);
246
246
  mount(options.parent, wrapper);
247
- return rich;
247
+ return asHandle(rich, { also: wrapper });
248
248
  }
249
249
 
250
250
  /**
@@ -3,8 +3,6 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- /* global $ */
7
-
8
6
  import { trapFocus } from "../../core/focus.js";
9
7
 
10
8
  const DEFAULT_MODAL_ID = "myModal";
@@ -13,21 +11,29 @@ const DEFAULT_MODAL_ID = "myModal";
13
11
  const releases = new Map();
14
12
 
15
13
  export function openModal(id = DEFAULT_MODAL_ID) {
16
- const modal = $(`#${id}`);
17
- modal.css("display", "block").attr({ role: "dialog", "aria-modal": "true" });
18
- if (modal[0] && !releases.has(id)) {
19
- releases.set(id, trapFocus(modal[0], { onEscape: () => closeModal(id) }));
20
- }
14
+ const modal = document.getElementById(id);
15
+ if (!modal) return;
16
+ modal.classList.add("is-open");
17
+ modal.style.display = "block";
18
+ modal.setAttribute("role", "dialog");
19
+ modal.setAttribute("aria-modal", "true");
20
+ if (!releases.has(id)) releases.set(id, trapFocus(modal, { onEscape: () => closeModal(id) }));
21
21
  }
22
22
 
23
23
  export function closeModal(id = DEFAULT_MODAL_ID) {
24
- $(`#${id}`).css("display", "none");
24
+ const modal = document.getElementById(id);
25
+ if (modal) {
26
+ modal.classList.remove("is-open");
27
+ modal.style.display = "none";
28
+ }
25
29
  releases.get(id)?.();
26
30
  releases.delete(id);
27
31
  }
28
32
 
29
33
  // One delegated handler serves every close button (x), including modals added later.
30
- $(document).on("click.athenaModal", ".close", function () {
31
- const modal = $(this).closest(".modal");
32
- closeModal(modal.length ? modal.attr("id") : DEFAULT_MODAL_ID);
34
+ // One delegated handler serves every close button (x), including modals added later.
35
+ document.addEventListener("click", event => {
36
+ const button = event.target.closest?.(".close");
37
+ if (!button) return;
38
+ closeModal(button.closest(".modal")?.id || DEFAULT_MODAL_ID);
33
39
  });
@@ -3,7 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import { cx, el, mount, setContent, uid } from "../../core/dom.js";
6
+ import { asHandle, cx, el, mount, setContent, uid } from "../../core/dom.js";
7
7
  import { translate } from "../../core/i18n.js";
8
8
  import { pageRange } from "../../core/pagination.js";
9
9
 
@@ -85,7 +85,7 @@ export function generateTabs(options = {}) {
85
85
 
86
86
  mount(options.parent, element);
87
87
  select(options.active ?? tabs.find(tab => !tab.disabled)?.id);
88
- return { element, select, getActive: () => active };
88
+ return asHandle({ element, select, getActive: () => active });
89
89
  }
90
90
 
91
91
  /* ------------------BREADCRUMBS------------------- */
@@ -169,7 +169,7 @@ export function generatePagination(options = {}) {
169
169
 
170
170
  render();
171
171
  mount(options.parent, element);
172
- return {
172
+ return asHandle({
173
173
  element,
174
174
  getPage: () => page,
175
175
  setPage: go,
@@ -177,7 +177,7 @@ export function generatePagination(options = {}) {
177
177
  total = value;
178
178
  render();
179
179
  }
180
- };
180
+ });
181
181
  }
182
182
 
183
183
  /* ------------------ACCORDION------------------- */
@@ -226,7 +226,7 @@ export function generateAccordion(options = {}) {
226
226
  (options.items ?? []).forEach((item, index) => { if (item.open) toggle(index, true); });
227
227
 
228
228
  mount(options.parent, element);
229
- return { element, toggle };
229
+ return asHandle({ element, toggle });
230
230
  }
231
231
 
232
232
  /* ------------------DROPDOWN------------------- */
@@ -236,7 +236,11 @@ export function generateAccordion(options = {}) {
236
236
  *
237
237
  * @param {object} options
238
238
  * @param {string|Element} [options.parent]
239
- * @param {string} options.label button text
239
+ * @param {string} [options.label] button text (leave it out for an icon-only button, and give `ariaLabel`)
240
+ * @param {string|Node} [options.icon] shown before the label, text or a Node (e.g. an SVG); hidden from screen readers
241
+ * @param {string} [options.ariaLabel] accessible name, needed when there is no label
242
+ * @param {boolean} [options.caret=false] show a small arrow after the label
243
+ * @param {string} [options.toggleClass] extra CSS class(es) of the toggle button
240
244
  * @param {{label?: string, onclick?: Function, href?: string, disabled?: boolean, divider?: boolean}[]} options.items
241
245
  * @param {"left"|"right"} [options.align="left"]
242
246
  * @returns {{element: HTMLElement, open: Function, close: Function}}
@@ -245,10 +249,15 @@ export function generateDropdown(options = {}) {
245
249
  const menuId = uid("dropdown");
246
250
  const menu = el("div", { class: cx("dropdown-menu", options.align === "right" && "dropdown-right"), id: menuId, attrs: { role: "menu", hidden: true } });
247
251
  const button = el("button", {
248
- class: "athena-button button-secondary dropdown-toggle",
249
- text: options.label,
250
- attrs: { type: "button", "aria-haspopup": "menu", "aria-expanded": "false", "aria-controls": menuId }
252
+ class: cx("athena-button button-secondary dropdown-toggle", options.icon && !options.label && "dropdown-icon-only", options.toggleClass),
253
+ attrs: {
254
+ type: "button", "aria-haspopup": "menu", "aria-expanded": "false", "aria-controls": menuId,
255
+ "aria-label": options.ariaLabel
256
+ }
251
257
  });
258
+ if (options.icon) button.append(setContent(el("span", { class: "dropdown-icon", attrs: { "aria-hidden": "true" } }), options.icon));
259
+ if (options.label) button.append(document.createTextNode(options.label));
260
+ if (options.caret) button.append(el("span", { class: "dropdown-caret", text: "▾", attrs: { "aria-hidden": "true" } }));
252
261
  const element = el("div", { id: options.id, class: cx("dropdown", options.class) }, button, menu);
253
262
 
254
263
  const enabledItems = () => [...menu.querySelectorAll("[role=menuitem]:not([disabled])")];
@@ -305,7 +314,7 @@ export function generateDropdown(options = {}) {
305
314
  });
306
315
 
307
316
  mount(options.parent, element);
308
- return { element, open, close };
317
+ return asHandle({ element, open, close });
309
318
  }
310
319
 
311
320
  /* ------------------SIDEBAR------------------- */
@@ -384,5 +393,5 @@ export function generateSidebar(options = {}) {
384
393
 
385
394
  mount(options.parent, element);
386
395
  if (options.active) select(options.active);
387
- return { element, select, toggle };
396
+ return asHandle({ element, select, toggle });
388
397
  }
@@ -3,6 +3,7 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
+ import { resolveElement } from "../../core/dom.js";
6
7
  import { matchRoute, normalizePath, parseQuery } from "./matchRoute.js";
7
8
 
8
9
  /**
@@ -17,12 +18,33 @@ import { matchRoute, normalizePath, parseQuery } from "./matchRoute.js";
17
18
  * @param {(context) => void} [options.notFound] called when no route matches
18
19
  * @param {(context) => (boolean|string|void|Promise)} [options.beforeEach] guard: return false to cancel,
19
20
  * or a path to redirect to (login redirect)
20
- * @param {(context) => void} [options.afterEach]
21
+ * @param {(context) => void} [options.afterEach] same as onShown
22
+ * @param {(context, route) => void} [options.onRender] called after the outlet was emptied, before the page function runs
23
+ * @param {(context, route) => void} [options.onShown] called after the page function finished (and it was not replaced by a newer
24
+ * navigation): the place to set the title, move the focus to the content, scroll to the top
25
+ * @param {boolean} [options.focusContent=false] after a page is shown the outlet gets the focus (it is made focusable for that), so a
26
+ * screen reader starts reading the new page and the keyboard continues there
27
+ * @param {boolean} [options.scrollTop=false] scroll to the top after a page is shown
28
+ * @param {object} [options.auth] sign-in rules for routes, see the route options below
29
+ * @param {() => boolean} [options.auth.isSignedIn]
30
+ * @param {(role: string) => boolean} [options.auth.hasRole]
31
+ * @param {string} [options.auth.loginPath="/login"] where `auth: true` routes send a visitor who is not signed in (with `?next=<path>`)
32
+ * @param {string} [options.auth.homePath="/"] where `guestOnly` routes send a signed-in person
33
+ * @param {string} [options.auth.forbiddenPath] where a person without the role goes (default: homePath)
21
34
  * @param {string} [options.titlePrefix] document title is `${titlePrefix}${route.title}`
22
- * @returns {{start: Function, stop: Function, navigate: Function, current: Function, href: Function}}
35
+ *
36
+ * A route is a page function, or an object: `{ handler, title, auth: true, guestOnly: true, roles: ["admin"], guard(context) }`.
37
+ * `auth`, `guestOnly` and `roles` are checked with options.auth; `guard` is a function that gets the same context and returns
38
+ * false (stay where you are), a path (redirect) or anything else (go on); it runs after the rules.
39
+ * @returns {{start: Function, stop: Function, navigate: Function, current: Function, href: Function,
40
+ * onChange: (listener: (context) => void) => Function}}
41
+ * `onChange(listener)` is called with the context after every page that is shown (menus and breadcrumbs follow the router
42
+ * with it) and returns a function that stops it.
23
43
  */
24
44
  export function createRouter(options = {}) {
25
45
  const { routes = {}, outlet = "wrapper", mode = "hash", notFound, beforeEach, afterEach, titlePrefix = "" } = options;
46
+ const rules = { loginPath: "/login", homePath: "/", ...options.auth };
47
+ const listeners = new Set();
26
48
  const entries = Object.entries(routes).map(([pattern, route]) => [pattern, typeof route === "function" ? { handler: route } : route]);
27
49
  let currentContext = null;
28
50
  let renderToken = 0;
@@ -32,6 +54,16 @@ export function createRouter(options = {}) {
32
54
  ? location.hash.replace(/^#/, "") || "/"
33
55
  : location.pathname + location.search;
34
56
 
57
+ // The rules of a route and its own guard. Returns false, a path to redirect to, or undefined.
58
+ async function checkRoute(route, context) {
59
+ const signedIn = Boolean(rules.isSignedIn?.());
60
+ if (route.guestOnly && signedIn) return rules.homePath;
61
+ if (route.auth && !signedIn) return `${rules.loginPath}?next=${encodeURIComponent(context.path)}`;
62
+ if (route.roles?.length && !route.roles.some(role => rules.hasRole?.(role))) return rules.forbiddenPath ?? rules.homePath;
63
+ const result = await route.guard?.(context);
64
+ return result === false || typeof result === "string" ? result : undefined;
65
+ }
66
+
35
67
  async function render(raw, depth = 0) {
36
68
  const token = ++renderToken;
37
69
  const path = normalizePath(raw);
@@ -46,23 +78,37 @@ export function createRouter(options = {}) {
46
78
  }
47
79
  const context = { path, params: matched?.params ?? {}, query };
48
80
 
49
- const guard = await beforeEach?.(context);
50
- if (token !== renderToken || guard === false) return;
81
+ let guard = await beforeEach?.(context);
82
+ if (token !== renderToken) return;
83
+ if (guard !== false && typeof guard !== "string" && matched) {
84
+ guard = await checkRoute(matched.route, context);
85
+ if (token !== renderToken) return;
86
+ }
87
+ if (guard === false) return;
51
88
  if (typeof guard === "string" && depth < 5) {
52
89
  navigate(guard, { replace: true });
53
90
  return;
54
91
  }
55
92
 
56
- const host = document.getElementById(outlet);
93
+ const host = resolveElement(outlet);
57
94
  host?.replaceChildren();
58
95
  currentContext = context;
96
+ options.onRender?.(context, matched?.route);
59
97
  if (!matched) {
60
98
  notFound?.(context);
61
99
  } else {
62
100
  if (matched.route.title) document.title = titlePrefix + matched.route.title;
63
101
  await matched.route.handler(context);
64
102
  }
65
- if (token === renderToken) afterEach?.(context);
103
+ if (token !== renderToken) return;
104
+ if (options.focusContent && host) {
105
+ if (!host.hasAttribute("tabindex")) host.setAttribute("tabindex", "-1");
106
+ host.focus({ preventScroll: true });
107
+ }
108
+ if (options.scrollTop) window.scrollTo(0, 0);
109
+ options.onShown?.(context, matched?.route);
110
+ afterEach?.(context);
111
+ listeners.forEach(listener => listener(context));
66
112
  }
67
113
 
68
114
  const onChange = () => render(readLocation());
@@ -96,6 +142,10 @@ export function createRouter(options = {}) {
96
142
  },
97
143
  navigate,
98
144
  current: () => currentContext,
145
+ onChange(listener) {
146
+ listeners.add(listener);
147
+ return () => listeners.delete(listener);
148
+ },
99
149
  // Value for an anchor's href.
100
150
  href: path => mode === "hash" ? `#${path}` : path
101
151
  };