athena-ui-js 1.2.0 → 2.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 (148) hide show
  1. package/README.md +312 -60
  2. package/docs/migration-2.0.md +83 -0
  3. package/docs/styling.md +86 -0
  4. package/package.json +109 -24
  5. package/src/athena-ui.js +61 -81
  6. package/src/chart.js +6 -0
  7. package/src/classic.js +11 -0
  8. package/src/components.js +6 -0
  9. package/src/controls.js +8 -0
  10. package/src/csv.js +6 -0
  11. package/src/dialog.js +7 -0
  12. package/src/dom.js +6 -0
  13. package/src/feedback.js +6 -0
  14. package/src/format.js +6 -0
  15. package/src/forms.js +7 -0
  16. package/src/i18n.js +6 -0
  17. package/src/inputs.js +9 -0
  18. package/src/libs/config/config.js +1 -2
  19. package/src/libs/core/controls.js +145 -0
  20. package/src/libs/core/cookies.js +55 -0
  21. package/src/libs/core/dateRange.js +121 -0
  22. package/src/libs/core/dom.js +58 -8
  23. package/src/libs/{hephaestus/HTMLElementGenerator/src/HTMLElementGenerator.js → core/elementGenerator.js} +23 -21
  24. package/src/libs/{hephaestus/HTMLElementGenerator/src → core}/errors.js +7 -5
  25. package/src/libs/core/format.js +51 -0
  26. package/src/libs/core/hungarianControls.js +41 -0
  27. package/src/libs/core/i18n.js +104 -6
  28. package/src/libs/core/theme.js +131 -0
  29. package/src/libs/core/validation.js +2 -2
  30. package/src/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.js +13 -7
  31. package/src/libs/hephaestus/LayoutGenerator/footerContentGenerator.js +2 -4
  32. package/src/libs/hephaestus/LayoutGenerator/headerContentGenerator.js +12 -5
  33. package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +3 -3
  34. package/src/libs/hephaestus/MenuGenerator/menuGenerator.js +265 -0
  35. package/src/libs/hephaestus/auth/authState.js +58 -0
  36. package/src/libs/hephaestus/auth/session.js +1 -1
  37. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +519 -87
  38. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +121 -4
  39. package/src/libs/hephaestus/componentGenerator/themePicker.js +73 -0
  40. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +113 -25
  41. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +21 -0
  42. package/src/libs/hephaestus/formGenerator/authForms.js +130 -0
  43. package/src/libs/hephaestus/formGenerator/changePasswordFormGenerator.js +4 -4
  44. package/src/libs/hephaestus/formGenerator/formUtils.js +10 -13
  45. package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +10 -11
  46. package/src/libs/hephaestus/formGenerator/registrationFormGenerator.js +3 -3
  47. package/src/libs/hephaestus/hephaestus.js +0 -5
  48. package/src/libs/hephaestus/inputGenerator/dropZoneGenerator.js +1 -1
  49. package/src/libs/hephaestus/inputGenerator/inputGenerator.js +30 -1
  50. package/src/libs/hephaestus/modalGenerator/modalGenerator.js +25 -12
  51. package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +20 -24
  52. package/src/libs/hephaestus/router/router.js +54 -5
  53. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +290 -16
  54. package/src/menu.js +6 -0
  55. package/src/navigation.js +6 -0
  56. package/src/res/themes/appearance.css +154 -0
  57. package/src/res/themes/default/style.css +688 -82
  58. package/src/res/themes/tokens.css +96 -0
  59. package/src/router.js +6 -0
  60. package/src/sanitize.js +6 -0
  61. package/src/session.js +8 -0
  62. package/src/table.js +6 -0
  63. package/src/testing.js +11 -1
  64. package/src/theme-boot.js +25 -0
  65. package/src/theme.js +7 -0
  66. package/src/validation.js +6 -0
  67. package/types/athena-ui.d.ts +96 -0
  68. package/types/chart.d.ts +1 -0
  69. package/types/classic.d.ts +1 -0
  70. package/types/components.d.ts +1 -0
  71. package/types/controls.d.ts +3 -0
  72. package/types/csv.d.ts +1 -0
  73. package/types/dialog.d.ts +2 -0
  74. package/types/dom.d.ts +1 -0
  75. package/types/feedback.d.ts +1 -0
  76. package/types/format.d.ts +1 -0
  77. package/types/forms.d.ts +2 -0
  78. package/types/i18n.d.ts +1 -0
  79. package/types/inputs.d.ts +4 -0
  80. package/types/libs/config/config.d.ts +96 -0
  81. package/types/libs/config/hooks.d.ts +8 -0
  82. package/types/libs/core/combobox.d.ts +10 -0
  83. package/types/libs/core/controls.d.ts +28 -0
  84. package/types/libs/core/cookies.d.ts +27 -0
  85. package/types/libs/core/csv.d.ts +12 -0
  86. package/types/libs/core/dateRange.d.ts +72 -0
  87. package/types/libs/core/dom.d.ts +65 -0
  88. package/types/libs/core/elementGenerator.d.ts +30 -0
  89. package/types/libs/core/errors.d.ts +29 -0
  90. package/types/libs/core/focus.d.ts +6 -0
  91. package/types/libs/core/format.d.ts +21 -0
  92. package/types/libs/core/hungarianControls.d.ts +2 -0
  93. package/types/libs/core/i18n.d.ts +17 -0
  94. package/types/libs/core/pagination.d.ts +5 -0
  95. package/types/libs/core/sanitize.d.ts +6 -0
  96. package/types/libs/core/tableMath.d.ts +26 -0
  97. package/types/libs/core/theme.d.ts +39 -0
  98. package/types/libs/core/validation.d.ts +56 -0
  99. package/types/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.d.ts +10 -0
  100. package/types/libs/hephaestus/LayoutGenerator/footerContentGenerator.d.ts +4 -0
  101. package/types/libs/hephaestus/LayoutGenerator/headerContentGenerator.d.ts +20 -0
  102. package/types/libs/hephaestus/LayoutGenerator/wrapperContentGenerator.d.ts +1 -0
  103. package/types/libs/hephaestus/MenuGenerator/basicMenuGenerator.d.ts +14 -0
  104. package/types/libs/hephaestus/MenuGenerator/menuGenerator.d.ts +65 -0
  105. package/types/libs/hephaestus/auth/authState.d.ts +26 -0
  106. package/types/libs/hephaestus/auth/session.d.ts +26 -0
  107. package/types/libs/hephaestus/chartGenerator/chartGenerator.d.ts +91 -0
  108. package/types/libs/hephaestus/componentGenerator/componentGenerator.d.ts +222 -0
  109. package/types/libs/hephaestus/componentGenerator/themePicker.d.ts +24 -0
  110. package/types/libs/hephaestus/dialogGenerator/dialogGenerator.d.ts +120 -0
  111. package/types/libs/hephaestus/feedbackGenerator/feedbackGenerator.d.ts +86 -0
  112. package/types/libs/hephaestus/formGenerator/authForms.d.ts +122 -0
  113. package/types/libs/hephaestus/formGenerator/changePasswordFormGenerator.d.ts +6 -0
  114. package/types/libs/hephaestus/formGenerator/formBuilder.d.ts +113 -0
  115. package/types/libs/hephaestus/formGenerator/formUtils.d.ts +8 -0
  116. package/types/libs/hephaestus/formGenerator/loginFormGenerator.d.ts +11 -0
  117. package/types/libs/hephaestus/formGenerator/lostPasswordFormGenerator.d.ts +4 -0
  118. package/types/libs/hephaestus/formGenerator/registrationFormGenerator.d.ts +7 -0
  119. package/types/libs/hephaestus/hephaestus.d.ts +3 -0
  120. package/types/libs/hephaestus/inputGenerator/dropZoneGenerator.d.ts +48 -0
  121. package/types/libs/hephaestus/inputGenerator/inputGenerator.d.ts +185 -0
  122. package/types/libs/hephaestus/inputGenerator/richTextGenerator.d.ts +49 -0
  123. package/types/libs/hephaestus/modalGenerator/modalGenerator.d.ts +2 -0
  124. package/types/libs/hephaestus/navigationGenerator/navigationGenerator.d.ts +150 -0
  125. package/types/libs/hephaestus/router/matchRoute.d.ts +12 -0
  126. package/types/libs/hephaestus/router/router.d.ts +67 -0
  127. package/types/libs/hephaestus/tableGenerator/tableGenerator.d.ts +120 -0
  128. package/types/menu.d.ts +1 -0
  129. package/types/navigation.d.ts +1 -0
  130. package/types/res/themes/themes.d.ts +7 -0
  131. package/types/router.d.ts +1 -0
  132. package/types/sanitize.d.ts +1 -0
  133. package/types/session.d.ts +3 -0
  134. package/types/table.d.ts +1 -0
  135. package/types/testing.d.ts +27 -0
  136. package/types/theme-boot.d.ts +0 -0
  137. package/types/theme.d.ts +2 -0
  138. package/types/validation.d.ts +1 -0
  139. package/src/libs/crypto-js/LICENSE +0 -24
  140. package/src/libs/crypto-js/crypto-js.js +0 -6657
  141. package/src/libs/hephaestus/HTMLControlGenerator/LICENSE +0 -21
  142. package/src/libs/hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js +0 -5
  143. package/src/libs/hephaestus/HTMLElementGenerator/LICENSE +0 -21
  144. package/src/libs/js-cookie/LICENSE +0 -21
  145. package/src/libs/js-cookie/src/api.mjs +0 -103
  146. package/src/libs/js-cookie/src/assign.mjs +0 -10
  147. package/src/libs/js-cookie/src/converter.mjs +0 -14
  148. package/src/libs/libs.js +0 -13
@@ -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`,
@@ -41,15 +41,14 @@ function generateField(name, label, inputType) {
41
41
  });
42
42
  }
43
43
 
44
- // Reads the form. The password is SHA-256 hashed when enable_encrypt_password is set.
44
+ // Reads the form. The password is returned as typed: send it over HTTPS and hash it on the server.
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();
49
- if (config.enable_encrypt_password) password = CryptoJS.SHA256(password).toString();
47
+ const username = document.getElementById(`${FORM_ID}-username-control`)?.value;
48
+ const password = document.getElementById(`${FORM_ID}-password-control`)?.value;
50
49
  const data = { username, password };
51
- const remember = $(`#${FORM_ID}-remember-control`);
52
- if (remember.length) data.remember = remember.prop("checked");
50
+ const remember = document.getElementById(`${FORM_ID}-remember-control`);
51
+ if (remember) data.remember = remember.checked;
53
52
  return data;
54
53
  }
55
54
 
@@ -85,12 +84,12 @@ export function generatePasswordElements() {
85
84
  export function generateRememberElement() {
86
85
  if (!config.login_remember_me) return;
87
86
  const row = generateRow("remember");
88
- HTMLControlGenerator({ inputType: "checkbox", parent: row, id: `${row}-control` });
87
+ generateControl({ inputType: "checkbox", parent: row, id: `${row}-control` });
89
88
  HTMLElementGenerator({ elementType: "span", parent: row, id: `${row}-label`, text: translate("rememberMe") });
90
89
  }
91
90
 
92
91
  export function generateSubmitElement() {
93
- HTMLControlGenerator({
92
+ generateControl({
94
93
  inputType: "button",
95
94
  parent: generateRow("submit"),
96
95
  text: translate("login"),
@@ -7,16 +7,16 @@ import config from "../../config/config.js";
7
7
  import { getRegister } from "../../config/hooks.js";
8
8
  import { translate } from "../../core/i18n.js";
9
9
  import { validateAll } from "../../core/validation.js";
10
- import { generateButton, generateField, generateFormDiv, generateMessage, hashPassword, readControl, showMessage } from "./formUtils.js";
10
+ import { generateButton, generateField, generateFormDiv, generateMessage, readControl, showMessage } from "./formUtils.js";
11
11
 
12
12
  const FORM_ID = "registrationForm";
13
13
 
14
- // Reads the form. The password is SHA-256 hashed when enable_encrypt_password is set.
14
+ // Reads the form. The password is returned as typed: send it over HTTPS and hash it on the server.
15
15
  export function getRegistrationFormData() {
16
16
  return {
17
17
  username: readControl(FORM_ID, "username"),
18
18
  email: readControl(FORM_ID, "email"),
19
- password: hashPassword(readControl(FORM_ID, "password"))
19
+ password: readControl(FORM_ID, "password")
20
20
  };
21
21
  }
22
22
 
@@ -3,7 +3,6 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
- import libs from "../libs.js";
7
6
  import themes from "../../res/themes/themes.js";
8
7
 
9
8
  const loadedScripts = new Map();
@@ -28,10 +27,6 @@ export function loadScript(src) {
28
27
  return loadedScripts.get(src);
29
28
  }
30
29
 
31
- export function loadLibs(extraScripts = []) {
32
- return Promise.all([...libs.map(lib => lib.src), ...extraScripts].map(loadScript));
33
- }
34
-
35
30
  // Accepts { id } of a registered theme or a custom { href }. Falls back to the default theme.
36
31
  export function resolveTheme(selected) {
37
32
  if (selected?.href) return selected;
@@ -57,7 +57,7 @@ export function createDropZone(options = {}) {
57
57
  for (const file of list) {
58
58
  if (!matchesAccept(file, accept)) rejected.push({ file, reason: `${translate("validation.pattern")} (${file.name})` });
59
59
  else if (maxSize != null && file.size > maxSize) rejected.push({ file, reason: translate("validation.fileSize", { name: file.name, max: formatBytes(maxSize) }) });
60
- else if (maxFiles != null && valid.length >= maxFiles) rejected.push({ file, reason: translate("validation.maxFiles", { max: maxFiles }) });
60
+ else if (maxFiles != null && valid.length >= maxFiles) rejected.push({ file, reason: translate("validation.maxFiles", { max: maxFiles, count: maxFiles }) });
61
61
  else valid.push(file);
62
62
  }
63
63
  if (valid.length) options.onDrop?.(valid);
@@ -4,7 +4,7 @@
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";
7
+ import { createDateRange, createDateTimeRange } from "../../core/dateRange.js";
8
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";
@@ -76,6 +76,35 @@ export function generateDateRange(options = {}) {
76
76
  return asHandle(range, { also: wrapper });
77
77
  }
78
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 });
106
+ }
107
+
79
108
  /* ------------------FILE UPLOAD------------------- */
80
109
 
81
110
  /**
@@ -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,36 @@ 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
+ installCloseHandler();
17
+ modal.classList.add("is-open");
18
+ modal.style.display = "block";
19
+ modal.setAttribute("role", "dialog");
20
+ modal.setAttribute("aria-modal", "true");
21
+ if (!releases.has(id)) releases.set(id, trapFocus(modal, { onEscape: () => closeModal(id) }));
21
22
  }
22
23
 
23
24
  export function closeModal(id = DEFAULT_MODAL_ID) {
24
- $(`#${id}`).css("display", "none");
25
+ const modal = document.getElementById(id);
26
+ if (modal) {
27
+ modal.classList.remove("is-open");
28
+ modal.style.display = "none";
29
+ }
25
30
  releases.get(id)?.();
26
31
  releases.delete(id);
27
32
  }
28
33
 
29
34
  // 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);
33
- });
35
+ // One delegated handler serves every close button (x), including modals added later. It is installed when the first modal is opened,
36
+ // so importing this file has no side effect.
37
+ let closeHandlerInstalled = false;
38
+ function installCloseHandler() {
39
+ if (closeHandlerInstalled) return;
40
+ closeHandlerInstalled = true;
41
+ document.addEventListener("click", event => {
42
+ const button = event.target.closest?.(".close");
43
+ if (!button) return;
44
+ closeModal(button.closest(".modal")?.id || DEFAULT_MODAL_ID);
45
+ });
46
+ }
@@ -193,37 +193,33 @@ export function generatePagination(options = {}) {
193
193
  */
194
194
  export function generateAccordion(options = {}) {
195
195
  const element = el("div", { id: options.id, class: cx("accordion", options.class) });
196
+ const group = options.multiple ? null : uid("accordion-group"); // details elements with the same name open one at a time
196
197
  const sections = [];
197
198
 
198
- function toggle(index, open) {
199
- const section = sections[index];
200
- const willOpen = open ?? section.button.getAttribute("aria-expanded") !== "true";
201
- if (willOpen && !options.multiple) sections.forEach((other, i) => i !== index && setOpen(other, false));
202
- setOpen(section, willOpen);
203
- }
204
- function setOpen(section, open) {
205
- section.button.setAttribute("aria-expanded", String(open));
206
- section.panel.hidden = !open;
207
- section.item.classList.toggle("accordion-open", open);
199
+ // The browser does the rest (the keyboard, aria-expanded, find in page). The name attribute closes the others where it is supported;
200
+ // this does it in the browsers that do not know it yet.
201
+ function onToggle(section) {
202
+ if (!section.item.open || options.multiple) return;
203
+ for (const other of sections) if (other !== section && other.item.open) other.item.open = false;
208
204
  }
209
205
 
210
- (options.items ?? []).forEach((item, index) => {
211
- const base = uid("accordion");
212
- const button = el("button", {
213
- class: "accordion-header",
214
- id: `${base}-header`,
215
- attrs: { type: "button", "aria-controls": `${base}-panel` },
216
- on: { click: () => toggle(index) }
217
- }, el("span", { text: item.title }), el("span", { class: "accordion-icon", attrs: { "aria-hidden": "true" } }));
218
- const panel = el("div", { class: "accordion-panel", id: `${base}-panel`, attrs: { role: "region", "aria-labelledby": button.id } });
206
+ (options.items ?? []).forEach(item => {
207
+ const summary = el("summary", { class: "accordion-header" }, el("span", { text: item.title }), el("span", { class: "accordion-icon", attrs: { "aria-hidden": "true" } }));
208
+ const panel = el("div", { class: "accordion-panel" });
219
209
  setContent(panel, item.content);
220
- const wrapper = el("div", { class: "accordion-item" }, el("h3", { class: "accordion-title" }, button), panel);
221
- const section = { item: wrapper, button, panel };
210
+ const details = el("details", { class: "accordion-item", attrs: { name: group, open: item.open ? true : null } }, summary, panel);
211
+ const section = { item: details, summary, panel };
212
+ details.addEventListener("toggle", () => onToggle(section));
222
213
  sections.push(section);
223
- element.append(wrapper);
224
- setOpen(section, false);
214
+ element.append(details);
225
215
  });
226
- (options.items ?? []).forEach((item, index) => { if (item.open) toggle(index, true); });
216
+ // With several items marked open and one at a time, the first one wins
217
+ if (!options.multiple) sections.filter(section => section.item.open).slice(1).forEach(section => { section.item.open = false; });
218
+
219
+ function toggle(index, open) {
220
+ const section = sections[index];
221
+ if (section) section.item.open = open ?? !section.item.open;
222
+ }
227
223
 
228
224
  mount(options.parent, element);
229
225
  return asHandle({ element, toggle });
@@ -18,12 +18,33 @@ import { matchRoute, normalizePath, parseQuery } from "./matchRoute.js";
18
18
  * @param {(context) => void} [options.notFound] called when no route matches
19
19
  * @param {(context) => (boolean|string|void|Promise)} [options.beforeEach] guard: return false to cancel,
20
20
  * or a path to redirect to (login redirect)
21
- * @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)
22
34
  * @param {string} [options.titlePrefix] document title is `${titlePrefix}${route.title}`
23
- * @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.
24
43
  */
25
44
  export function createRouter(options = {}) {
26
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();
27
48
  const entries = Object.entries(routes).map(([pattern, route]) => [pattern, typeof route === "function" ? { handler: route } : route]);
28
49
  let currentContext = null;
29
50
  let renderToken = 0;
@@ -33,6 +54,16 @@ export function createRouter(options = {}) {
33
54
  ? location.hash.replace(/^#/, "") || "/"
34
55
  : location.pathname + location.search;
35
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
+
36
67
  async function render(raw, depth = 0) {
37
68
  const token = ++renderToken;
38
69
  const path = normalizePath(raw);
@@ -47,8 +78,13 @@ export function createRouter(options = {}) {
47
78
  }
48
79
  const context = { path, params: matched?.params ?? {}, query };
49
80
 
50
- const guard = await beforeEach?.(context);
51
- 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;
52
88
  if (typeof guard === "string" && depth < 5) {
53
89
  navigate(guard, { replace: true });
54
90
  return;
@@ -57,13 +93,22 @@ export function createRouter(options = {}) {
57
93
  const host = resolveElement(outlet);
58
94
  host?.replaceChildren();
59
95
  currentContext = context;
96
+ options.onRender?.(context, matched?.route);
60
97
  if (!matched) {
61
98
  notFound?.(context);
62
99
  } else {
63
100
  if (matched.route.title) document.title = titlePrefix + matched.route.title;
64
101
  await matched.route.handler(context);
65
102
  }
66
- 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));
67
112
  }
68
113
 
69
114
  const onChange = () => render(readLocation());
@@ -97,6 +142,10 @@ export function createRouter(options = {}) {
97
142
  },
98
143
  navigate,
99
144
  current: () => currentContext,
145
+ onChange(listener) {
146
+ listeners.add(listener);
147
+ return () => listeners.delete(listener);
148
+ },
100
149
  // Value for an anchor's href.
101
150
  href: path => mode === "hash" ? `#${path}` : path
102
151
  };