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
@@ -4,6 +4,9 @@
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
6
  import { asHandle, cx, el, mount, resolveElement, setContent, uid } from "../../core/dom.js";
7
+ import { generateBreadcrumbs } from "../navigationGenerator/navigationGenerator.js";
8
+ import { generateSpinner } from "../feedbackGenerator/feedbackGenerator.js";
9
+ import { translate } from "../../core/i18n.js";
7
10
 
8
11
  /**
9
12
  * Generates a link. External links open in a new tab and get `rel="noopener noreferrer"`.
@@ -143,10 +146,14 @@ export function generateAvatar(options = {}) {
143
146
  * @param {string|number} options.value
144
147
  * @param {number} [options.delta] change in percent, shown with an arrow
145
148
  * @param {boolean} [options.invertDelta] a falling value is good news (costs, errors)
146
- * @returns {{element: HTMLElement, setValue: Function}}
149
+ * @param {"ok"|"warn"|"bad"} [options.tone] colours the tile (the class is-ok / is-warn / is-bad) and adds the word to the screen reader text
150
+ * @param {string} [options.note] small text under the value ("of 120 hosts", "updated 2 min ago")
151
+ * @returns {{element: HTMLElement, setValue: Function, setNote: Function, setTone: Function}}
147
152
  */
148
153
  export function generateStat(options = {}) {
149
- const value = el("div", { class: "stat-value", text: String(options.value ?? "") });
154
+ const valueText = document.createTextNode(String(options.value ?? ""));
155
+ const toneWord = el("span", { class: "athena-visually-hidden" });
156
+ const value = el("div", { class: "stat-value" }, valueText, toneWord);
150
157
  const element = el("div", { id: options.id, class: cx("stat", options.class) }, el("div", { class: "stat-label", text: options.label }), value);
151
158
  if (options.delta != null) {
152
159
  const good = options.invertDelta ? options.delta < 0 : options.delta > 0;
@@ -154,9 +161,25 @@ export function generateStat(options = {}) {
154
161
  const arrow = options.delta > 0 ? "▲" : options.delta < 0 ? "▼" : "■";
155
162
  element.append(el("div", { class: cx("stat-delta", `stat-${kind}`), text: `${arrow} ${Math.abs(options.delta)}%` }));
156
163
  }
164
+ const note = el("div", { class: "stat-note" });
165
+ value.after(note);
166
+ const setValue = text => { valueText.data = String(text); };
167
+ const setNote = text => { note.textContent = text ?? ""; note.hidden = !text; };
168
+ const setTone = tone => {
169
+ for (const name of ["ok", "warn", "bad"]) element.classList.toggle(`is-${name}`, name === tone);
170
+ toneWord.textContent = tone ? ` (${translate(`tone.${tone}`)})` : "";
171
+ };
172
+ setNote(options.note);
173
+ setTone(options.tone);
157
174
  mount(options.parent, element);
158
- const setValue = text => { value.textContent = String(text); };
159
- return asHandle({ element, setValue, update: ({ value: text } = {}) => { if (text != null) setValue(text); } });
175
+ return asHandle({
176
+ element, setValue, setNote, setTone,
177
+ update: ({ value: text, note: noteText, tone } = {}) => {
178
+ if (text != null) setValue(text);
179
+ if (noteText !== undefined) setNote(noteText);
180
+ if (tone !== undefined) setTone(tone);
181
+ }
182
+ });
160
183
  }
161
184
 
162
185
  /**
@@ -200,3 +223,97 @@ export function generateTooltip(target, text) {
200
223
  host.append(tip);
201
224
  return tip;
202
225
  }
226
+
227
+ /* ------------------PAGE PARTS------------------- */
228
+
229
+ /**
230
+ * The top of a page: breadcrumbs, the title (a heading), a description and the actions of the page.
231
+ *
232
+ * @param {object} options
233
+ * @param {string|Element} [options.parent]
234
+ * @param {string} options.title
235
+ * @param {string} [options.description]
236
+ * @param {{label: string, href?: string, onclick?: Function}[]} [options.breadcrumbs] see generateBreadcrumbs
237
+ * @param {(Node|string)[]|Node} [options.actions] buttons, shown at the end of the header
238
+ * @param {1|2|3} [options.level=1] heading level
239
+ * @returns {{element: HTMLElement, setTitle: Function, setDescription: Function, actions: HTMLElement}}
240
+ */
241
+ export function generatePageHeader(options = {}) {
242
+ const title = el(`h${options.level ?? 1}`, { class: "page-title", text: options.title });
243
+ const description = el("p", { class: "page-description", text: options.description ?? "" });
244
+ description.hidden = !options.description;
245
+ const actions = setContent(el("div", { class: "page-actions" }), options.actions);
246
+ const heading = el("div", { class: "page-heading" }, title, description);
247
+ const element = el("header", { id: options.id, class: cx("page-header", options.class) });
248
+ if (options.breadcrumbs?.length) generateBreadcrumbs({ parent: element, items: options.breadcrumbs });
249
+ element.append(el("div", { class: "page-header-row" }, heading, actions));
250
+ mount(options.parent, element);
251
+ return asHandle({
252
+ element, actions,
253
+ setTitle: text => { title.textContent = text; },
254
+ setDescription: text => { description.textContent = text ?? ""; description.hidden = !text; }
255
+ });
256
+ }
257
+
258
+ /**
259
+ * A list of facts: a term and its description, in pairs (a <dl>).
260
+ *
261
+ * @param {object} options
262
+ * @param {string|Element} [options.parent]
263
+ * @param {{term: string, description: (string|number|Node|Array), title?: string}[]} options.items text is inserted as text
264
+ * @param {boolean} [options.inline=false] terms and descriptions side by side
265
+ * @returns {{element: HTMLElement, setItems: Function}}
266
+ */
267
+ export function generateFacts(options = {}) {
268
+ const element = el("dl", { id: options.id, class: cx("facts", options.inline && "facts-inline", options.class) });
269
+ const setItems = items => {
270
+ element.replaceChildren();
271
+ for (const item of items ?? []) {
272
+ const group = el("div", { class: "fact" }, el("dt", { text: item.term }), setContent(el("dd", { attrs: { title: item.title } }), item.description));
273
+ element.append(group);
274
+ }
275
+ };
276
+ setItems(options.items);
277
+ mount(options.parent, element);
278
+ return asHandle({ element, setItems, update: ({ items } = {}) => { if (items) setItems(items); } });
279
+ }
280
+
281
+ /**
282
+ * What a list shows when there is nothing in it: a title, a short explanation and what to do about it.
283
+ *
284
+ * @param {object} options
285
+ * @param {string|Element} [options.parent]
286
+ * @param {string} options.title
287
+ * @param {string} [options.message]
288
+ * @param {string|Node} [options.icon] decorative
289
+ * @param {{text: string, onclick: Function, variant?: string}} [options.action] a button
290
+ */
291
+ export function generateEmptyState(options = {}) {
292
+ const element = el("div", { id: options.id, class: cx("empty-state", options.class) });
293
+ if (options.icon) element.append(setContent(el("div", { class: "empty-icon", attrs: { "aria-hidden": "true" } }), options.icon));
294
+ element.append(el("p", { class: "empty-title", text: options.title }));
295
+ if (options.message) element.append(el("p", { class: "empty-message", text: options.message }));
296
+ if (options.action) {
297
+ const button = el("button", { class: `athena-button button-${options.action.variant ?? "primary"}`, text: options.action.text, attrs: { type: "button" } });
298
+ button.addEventListener("click", event => options.action.onclick?.(event));
299
+ element.append(button);
300
+ }
301
+ mount(options.parent, element);
302
+ return asHandle({ element });
303
+ }
304
+
305
+ /**
306
+ * A placeholder while something loads: a spinner and a text (a live region, so a screen reader says it).
307
+ *
308
+ * @param {object} [options]
309
+ * @param {string|Element} [options.parent]
310
+ * @param {string} [options.text] default: the translated "Loading..."
311
+ */
312
+ export function generateLoading(options = {}) {
313
+ const text = options.text ?? translate("loading");
314
+ const element = el("div", { id: options.id, class: cx("loading-state", options.class), attrs: { role: "status", "aria-live": "polite" } });
315
+ generateSpinner({ parent: element, label: text });
316
+ element.append(el("span", { class: "loading-text", text }));
317
+ mount(options.parent, element);
318
+ return asHandle({ element });
319
+ }
@@ -0,0 +1,73 @@
1
+ //themePicker for Athena UI
2
+ //Author: Csaba Tóth https://github.com/csabatibortoth/
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ import { asHandle, cx, el, mount, uid } from "../../core/dom.js";
7
+ import { translate } from "../../core/i18n.js";
8
+
9
+ /**
10
+ * Generates the appearance picker of an account page: a group of themes with a small preview of each, and a group of modes.
11
+ * The preview is drawn with the colours of the theme itself: the stylesheet of a theme applies to any element that has the
12
+ * attributes data-theme and data-mode, not only to <html>.
13
+ *
14
+ * @param {object} options
15
+ * @param {string|Element} [options.parent]
16
+ * @param {ReturnType<import("../../core/theme.js").createThemeManager>} options.manager
17
+ * @param {string} [options.themeLabel] legend of the theme group (default: translated "Theme")
18
+ * @param {string} [options.modeLabel] legend of the mode group (default: translated "Mode")
19
+ * @param {string} [options.class]
20
+ * @returns {{element: HTMLElement, update: Function, destroy: Function}}
21
+ */
22
+ export function generateThemePicker(options = {}) {
23
+ const { manager } = options;
24
+ if (!manager) throw new Error("Athena UI: generateThemePicker needs a manager from createThemeManager");
25
+ const name = uid("appearance");
26
+
27
+ const group = (legend, items, kind, preview) => {
28
+ const set = el("fieldset", { class: `theme-picker-group theme-picker-${kind}` }, el("legend", { text: legend }));
29
+ const list = el("div", { class: "theme-picker-options" });
30
+ for (const item of items) {
31
+ const input = el("input", { attrs: { type: "radio", name: `${name}-${kind}`, value: item.id } });
32
+ input.addEventListener("change", () => {
33
+ if (input.checked) (kind === "theme" ? manager.setTheme : manager.setMode)(item.id);
34
+ });
35
+ const label = el("label", { class: "theme-picker-option", attrs: { "data-id": item.id } }, input);
36
+ if (preview) label.append(preview(item));
37
+ label.append(el("span", { class: "theme-picker-name", text: item.name ?? item.id }));
38
+ if (item.description) label.append(el("span", { class: "theme-picker-description", text: item.description }));
39
+ list.append(label);
40
+ }
41
+ set.append(list);
42
+ return set;
43
+ };
44
+
45
+ // A small page drawn with the colours of the theme, in the mode that is in use (the light one for "system" in a light browser).
46
+ const preview = theme => el("span", {
47
+ class: "theme-preview",
48
+ attrs: { "data-theme": theme.id, "data-mode": manager.appearance().dark ? "dark" : "light", "aria-hidden": "true" }
49
+ },
50
+ el("span", { class: "theme-preview-bar" }),
51
+ el("span", { class: "theme-preview-body" }, el("span", { class: "theme-preview-line" }), el("span", { class: "theme-preview-button" })));
52
+
53
+ const element = el("div", { class: cx("theme-picker", options.class) });
54
+ const render = () => {
55
+ element.replaceChildren(
56
+ group(options.themeLabel ?? translate("theme"), manager.themes, "theme", preview),
57
+ group(options.modeLabel ?? translate("mode"), manager.modes, "mode", null)
58
+ );
59
+ sync(manager.appearance());
60
+ };
61
+ const sync = state => {
62
+ for (const input of element.querySelectorAll("input")) {
63
+ const kind = input.name.endsWith("-theme") ? "theme" : "mode";
64
+ input.checked = input.value === state[kind];
65
+ }
66
+ // The previews follow dark / light
67
+ for (const node of element.querySelectorAll(".theme-preview")) node.dataset.mode = state.dark ? "dark" : "light";
68
+ };
69
+ render();
70
+ const stop = manager.onChange(sync);
71
+ mount(options.parent, element);
72
+ return asHandle({ element, update: () => { render(); }, destroy() { stop(); element.remove(); } });
73
+ }
@@ -4,9 +4,8 @@
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
6
  import { cx, el, setContent, uid } from "../../core/dom.js";
7
- import { trapFocus } from "../../core/focus.js";
8
7
  import { translate } from "../../core/i18n.js";
9
- import { generateButton } from "../formGenerator/formBuilder.js";
8
+ import { generateButton, generateForm } from "../formGenerator/formBuilder.js";
10
9
 
11
10
  /**
12
11
  * Opens a dialog and resolves with the value of the button that was used,
@@ -20,7 +19,7 @@ import { generateButton } from "../formGenerator/formBuilder.js";
20
19
  * @param {(value) => (boolean|Promise<boolean>)} [options.beforeClose] return false to keep the dialog open
21
20
  * @param {"small"|"medium"|"large"|"full"} [options.size="medium"] width of the dialog (360 / 480 / 720 px / the whole window)
22
21
  * @param {string} [options.class] extra CSS class(es) of the dialog element
23
- * @returns {Promise<*> & {element: HTMLElement, backdrop: HTMLElement, close: (value?) => Promise<void>}}
22
+ * @returns {Promise<*> & {element: HTMLDialogElement, backdrop: HTMLDialogElement, close: (value?) => Promise<void>}}
24
23
  * resolves with the pressed button's value; the promise also carries the handle of the open dialog
25
24
  */
26
25
  export function showDialog(options = {}) {
@@ -30,15 +29,16 @@ export function showDialog(options = {}) {
30
29
  const titleId = uid("dialog-title");
31
30
  const body = setContent(el("div", { class: "dialog-body" }), content);
32
31
  const footer = el("div", { class: "dialog-footer" });
33
- const dialog = el("div", {
34
- class: cx("modal-content dialog", options.size && `dialog-${options.size}`, options.class),
35
- attrs: { role: "dialog", "aria-modal": "true", "aria-labelledby": title ? titleId : null }
36
- });
37
- if (title) dialog.append(el("h2", { class: "dialog-title", id: titleId, text: title }));
38
- dialog.append(body, footer);
39
- const backdrop = el("div", { class: "modal dialog-backdrop" }, dialog);
32
+ // A native <dialog>, opened with showModal(): the browser traps the focus, closes it with Esc, puts it above everything (the top layer),
33
+ // makes the page behind it inert, draws the backdrop (::backdrop) and gives the focus back. No inline style is needed.
34
+ const inner = el("div", { class: "dialog-inner" });
35
+ const dialog = el("dialog", {
36
+ class: cx("dialog", options.size && `dialog-${options.size}`, options.class),
37
+ attrs: { "aria-labelledby": title ? titleId : null }
38
+ }, inner);
39
+ if (title) inner.append(el("h2", { class: "dialog-title", id: titleId, text: title }));
40
+ inner.append(body, footer);
40
41
 
41
- let release = () => {};
42
42
  let closing = false;
43
43
  const close = async value => {
44
44
  if (closing) return;
@@ -47,19 +47,25 @@ export function showDialog(options = {}) {
47
47
  closing = false;
48
48
  return;
49
49
  }
50
- release();
51
- backdrop.remove();
50
+ if (dialog.open) dialog.close();
51
+ dialog.remove();
52
52
  resolve(value);
53
53
  };
54
54
 
55
+ // Esc: the browser asks (cancel); a dialog that cannot be dismissed stays, and beforeClose can still say no
56
+ dialog.addEventListener("cancel", event => {
57
+ event.preventDefault();
58
+ if (dismissible) close(null);
59
+ });
55
60
  if (dismissible) {
56
- dialog.prepend(el("button", {
61
+ inner.prepend(el("button", {
57
62
  class: "dialog-close",
58
63
  text: "×",
59
64
  attrs: { type: "button", "aria-label": translate("close") },
60
65
  on: { click: () => close(null) }
61
66
  }));
62
- backdrop.addEventListener("mousedown", event => { if (event.target === backdrop) close(null); });
67
+ // A click on the backdrop lands on the dialog element itself (its content fills it up to the edge)
68
+ dialog.addEventListener("mousedown", event => { if (event.target === dialog) close(null); });
63
69
  }
64
70
  for (const spec of buttons) {
65
71
  const { element } = generateButton({
@@ -71,10 +77,12 @@ export function showDialog(options = {}) {
71
77
  if (spec.autofocus) element.dataset.autofocus = "true";
72
78
  }
73
79
 
74
- document.body.append(backdrop);
75
- release = trapFocus(dialog, { onEscape: dismissible ? () => close(null) : undefined });
80
+ document.body.append(dialog);
81
+ // Without showModal (an old browser, or jsdom without athena-ui-js/testing) it is opened as a plain, non-modal dialog.
82
+ if (typeof dialog.showModal === "function") dialog.showModal();
83
+ else dialog.setAttribute("open", "");
76
84
  dialog.querySelector("[data-autofocus]")?.focus();
77
- handle = { element: dialog, backdrop, close: value => close(value ?? null) };
85
+ handle = { element: dialog, backdrop: dialog, close: value => close(value ?? null) };
78
86
  });
79
87
  // The executor above runs synchronously, so the handle exists here.
80
88
  return Object.assign(promise, handle);
@@ -85,17 +93,97 @@ export async function alertDialog(message, { title, okText = translate("ok") } =
85
93
  await showDialog({ title, content: message, buttons: [{ text: okText, value: true, autofocus: true }] });
86
94
  }
87
95
 
88
- /** Question with confirm and cancel buttons. Resolves with true / false. */
89
- export async function confirmDialog(message, { title, confirmText = translate("ok"), cancelText = translate("cancel"), danger = false } = {}) {
90
- const result = await showDialog({
96
+ /** Question with confirm and cancel buttons. Resolves with true / false. See showConfirm for `typeToConfirm`. */
97
+ export function confirmDialog(message, options = {}) {
98
+ return showConfirm({ ...options, message });
99
+ }
100
+
101
+ /**
102
+ * Asks for a confirmation. Resolves with true when confirmed, false when cancelled or dismissed.
103
+ *
104
+ * @param {object} options
105
+ * @param {string} [options.title]
106
+ * @param {string|Node|Array} options.message
107
+ * @param {string} [options.confirmText]
108
+ * @param {string} [options.cancelText]
109
+ * @param {boolean} [options.danger=false] red confirm button
110
+ * @param {string} [options.typeToConfirm] the person has to type exactly this text before the dialog confirms
111
+ * (for things that cannot be undone: the name of what is deleted)
112
+ * @param {"small"|"medium"|"large"|"full"} [options.size]
113
+ * @returns {Promise<boolean> & {element: HTMLElement, close: Function}}
114
+ */
115
+ export function showConfirm({ title, message, confirmText = translate("ok"), cancelText = translate("cancel"), danger = false, typeToConfirm, size } = {}) {
116
+ let input = null;
117
+ const error = el("div", { class: "field-error", attrs: { role: "alert" } });
118
+ const content = [message];
119
+ if (typeToConfirm) {
120
+ input = el("input", { class: "confirm-input", attrs: { type: "text", autocomplete: "off", "aria-label": typeToConfirm, "data-autofocus": "true" } });
121
+ content.push(el("p", { class: "confirm-prompt", text: translate("typeToConfirm", { text: typeToConfirm }) }), input, error);
122
+ }
123
+ const dialog = showDialog({
91
124
  title,
92
- content: message,
125
+ content,
126
+ size,
93
127
  buttons: [
94
128
  { text: cancelText, value: false, variant: "secondary" },
95
- { text: confirmText, value: true, variant: danger ? "danger" : "primary", autofocus: true }
96
- ]
129
+ { text: confirmText, value: true, variant: danger ? "danger" : "primary", autofocus: !typeToConfirm }
130
+ ],
131
+ beforeClose: value => {
132
+ if (value !== true || !typeToConfirm || input.value === typeToConfirm) return true;
133
+ error.textContent = translate("textMismatch");
134
+ input.focus();
135
+ return false;
136
+ }
137
+ });
138
+ return Object.assign(dialog.then(result => result === true), { element: dialog.element, backdrop: dialog.backdrop, close: dialog.close });
139
+ }
140
+
141
+ /**
142
+ * A dialog that holds a form (see generateForm): validation, Enter submits, the button shows a spinner while it saves.
143
+ * `onSubmit(values, form)` saves. When it throws (or rejects) the message is shown in the dialog and the dialog stays open;
144
+ * `form.setErrors({ field: "message" })` marks single fields, for example with errors of the server. When it returns, the dialog closes.
145
+ *
146
+ * @param {object} options
147
+ * @param {string} [options.title]
148
+ * @param {string} [options.intro] text above the fields
149
+ * @param {string|Node|Array} [options.content] nodes above the fields
150
+ * @param {object[]} options.fields field definitions, see generateField
151
+ * @param {string} [options.submitText]
152
+ * @param {string} [options.cancelText]
153
+ * @param {boolean} [options.danger=false] red submit button
154
+ * @param {"small"|"medium"|"large"|"full"} [options.size]
155
+ * @param {(values: object, form: object) => (void|Promise)} options.onSubmit
156
+ * @param {(form: object) => void} [options.onReady] called with the form once it is built
157
+ * @returns {Promise<boolean> & {element: HTMLElement, form: object, close: Function}} resolves with true when it was saved, false when dismissed
158
+ */
159
+ export function showFormDialog({ title, intro, content, fields, submitText = translate("save"), cancelText = translate("cancel"), danger = false, size, onSubmit, onReady } = {}) {
160
+ let saved = false;
161
+ let dialog = null;
162
+ const body = el("div", { class: "dialog-form" });
163
+ if (intro) body.append(el("p", { class: "dialog-intro", text: intro }));
164
+ setContent(body, content);
165
+ const form = generateForm({
166
+ parent: body,
167
+ fields,
168
+ submitText,
169
+ onSubmit: async (values, f) => {
170
+ await onSubmit?.(values, f);
171
+ saved = true;
172
+ dialog.close(true);
173
+ }
97
174
  });
98
- return result === true;
175
+ onReady?.(form);
176
+ form.element.querySelector(".form-actions").append(
177
+ generateButton({ text: cancelText, variant: "secondary", onclick: () => dialog.close(null) }).element
178
+ );
179
+ if (danger) {
180
+ form.submitButton.element.classList.remove("button-primary");
181
+ form.submitButton.element.classList.add("button-danger");
182
+ }
183
+ dialog = showDialog({ title, content: body, buttons: [], size });
184
+ const first = form.element.querySelector("input:not([disabled]):not([type=hidden]), select, textarea");
185
+ first?.focus();
186
+ return Object.assign(dialog.then(() => saved), { element: dialog.element, backdrop: dialog.backdrop, form, close: dialog.close });
99
187
  }
100
188
 
101
189
  /**
@@ -80,6 +80,27 @@ export function generateAlert(options = {}) {
80
80
  return mount(options.parent, alert);
81
81
  }
82
82
 
83
+ /**
84
+ * Copies text to the clipboard and says so in a toast. Resolves with true when it worked (it needs a secure page and a click or key
85
+ * press of the person), false otherwise (a toast with the error is shown).
86
+ *
87
+ * @param {string} text
88
+ * @param {object} [options]
89
+ * @param {string} [options.message] text of the toast (default: the translated "Copied")
90
+ * @param {boolean} [options.toast=true] false copies silently
91
+ * @returns {Promise<boolean>}
92
+ */
93
+ export async function copyToClipboard(text, { message = translate("copied"), toast = true } = {}) {
94
+ try {
95
+ await navigator.clipboard.writeText(String(text));
96
+ if (toast) showToast({ message, type: "success" });
97
+ return true;
98
+ } catch {
99
+ if (toast) showToast({ message: translate("copyFailed"), type: "error" });
100
+ return false;
101
+ }
102
+ }
103
+
83
104
  /**
84
105
  * Generates a loading spinner.
85
106
  *
@@ -0,0 +1,130 @@
1
+ //authForms 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 "../../core/i18n.js";
7
+ import { generateForm } from "./formBuilder.js";
8
+
9
+ // Real <form> elements with the autocomplete tokens that password managers look for (username, current-password, new-password,
10
+ // email), so saving and filling passwords works and Enter submits. The password is sent as it is: hashing it in the browser
11
+ // only turns the hash into the password. Use HTTPS, and let the server hash it (argon2, scrypt, bcrypt).
12
+ //
13
+ // onSubmit is asynchronous. When it throws (or rejects) the message is shown in the form and the person can try again; an error
14
+ // that carries `fields` ({ username: "Already taken" }) marks those fields as well.
15
+
16
+ function build(options, { fields, submitText }) {
17
+ return generateForm({
18
+ parent: options.parent,
19
+ id: options.id,
20
+ class: options.class,
21
+ fields,
22
+ submitText: options.submitText ?? submitText,
23
+ onSubmit: async (values, form) => {
24
+ try {
25
+ await options.onSubmit?.(values, form);
26
+ } catch (error) {
27
+ if (error?.fields) form.setErrors(error.fields);
28
+ throw error;
29
+ }
30
+ }
31
+ });
32
+ }
33
+
34
+ /**
35
+ * A sign in form: username (or email), password, and optionally "Remember me".
36
+ *
37
+ * @param {object} options
38
+ * @param {string|Element} [options.parent]
39
+ * @param {(values: {username: string, password: string, remember?: boolean}, form: object) => (void|Promise)} options.onSubmit
40
+ * @param {boolean} [options.remember=false] shows "Remember me"
41
+ * @param {"username"|"email"} [options.identifier="username"] what the first field asks for
42
+ * @param {string} [options.submitText]
43
+ */
44
+ export function generateSignInForm(options = {}) {
45
+ const email = options.identifier === "email";
46
+ const fields = [
47
+ { name: "username", label: translate(email ? "email" : "username"), type: email ? "email" : "text", autocomplete: "username", required: true },
48
+ { name: "password", label: translate("password"), type: "password", autocomplete: "current-password", required: true }
49
+ ];
50
+ if (options.remember) fields.push({ name: "remember", label: translate("rememberMe"), type: "checkbox" });
51
+ return build(options, { fields, submitText: translate("login") });
52
+ }
53
+
54
+ /**
55
+ * A registration form: username, email, password and its confirmation.
56
+ *
57
+ * @param {object} options
58
+ * @param {string|Element} [options.parent]
59
+ * @param {(values: {username: string, email: string, password: string}, form: object) => (void|Promise)} options.onSubmit
60
+ * the confirmation is checked here and not sent
61
+ * @param {number} [options.passwordMinLength=8]
62
+ * @param {boolean} [options.username=true] false leaves the username out (sign in with the email)
63
+ * @param {string} [options.submitText]
64
+ */
65
+ export function generateSignUpForm(options = {}) {
66
+ const fields = [];
67
+ if (options.username !== false) fields.push({ name: "username", label: translate("username"), autocomplete: "username", required: true });
68
+ fields.push(
69
+ { name: "email", label: translate("email"), type: "email", autocomplete: "email", required: true },
70
+ { name: "password", label: translate("password"), type: "password", autocomplete: "new-password", required: true, minLength: options.passwordMinLength ?? 8 },
71
+ { name: "confirmPassword", label: translate("confirmPassword"), type: "password", autocomplete: "new-password", required: true, match: "password" }
72
+ );
73
+ return build({
74
+ ...options,
75
+ onSubmit: (values, form) => {
76
+ const { confirmPassword, ...rest } = values;
77
+ void confirmPassword;
78
+ return options.onSubmit?.(rest, form);
79
+ }
80
+ }, { fields, submitText: translate("register") });
81
+ }
82
+
83
+ /**
84
+ * Asks for the email address to send a reset link to.
85
+ *
86
+ * @param {object} options
87
+ * @param {string|Element} [options.parent]
88
+ * @param {(values: {email: string}, form: object) => (void|Promise)} options.onSubmit
89
+ */
90
+ export function generatePasswordResetForm(options = {}) {
91
+ return build(options, {
92
+ fields: [{ name: "email", label: translate("email"), type: "email", autocomplete: "email", required: true }],
93
+ submitText: translate("resetPassword")
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Change of the password of the person who is signed in: the current one, the new one and its confirmation.
99
+ *
100
+ * @param {object} options
101
+ * @param {string|Element} [options.parent]
102
+ * @param {(values: {currentPassword: string, newPassword: string}, form: object) => (void|Promise)} options.onSubmit
103
+ * @param {number} [options.passwordMinLength=8]
104
+ * @param {string} [options.username] when given, a hidden username field helps the password manager to update the right entry
105
+ */
106
+ export function generatePasswordChangeForm(options = {}) {
107
+ const fields = [
108
+ { name: "currentPassword", label: translate("currentPassword"), type: "password", autocomplete: "current-password", required: true },
109
+ { name: "newPassword", label: translate("newPassword"), type: "password", autocomplete: "new-password", required: true, minLength: options.passwordMinLength ?? 8 },
110
+ { name: "confirmPassword", label: translate("confirmPassword"), type: "password", autocomplete: "new-password", required: true, match: "newPassword" }
111
+ ];
112
+ const form = build({
113
+ ...options,
114
+ onSubmit: (values, f) => {
115
+ const { confirmPassword, ...rest } = values;
116
+ void confirmPassword;
117
+ return options.onSubmit?.(rest, f);
118
+ }
119
+ }, { fields, submitText: translate("changePassword") });
120
+ if (options.username) {
121
+ const hidden = document.createElement("input");
122
+ hidden.type = "text";
123
+ hidden.name = "username";
124
+ hidden.value = options.username;
125
+ hidden.autocomplete = "username";
126
+ hidden.hidden = true;
127
+ form.element.prepend(hidden);
128
+ }
129
+ return form;
130
+ }
@@ -7,15 +7,15 @@ import config from "../../config/config.js";
7
7
  import { getChangePassword } 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 = "changePasswordForm";
13
13
 
14
- // Reads the form. Both passwords are SHA-256 hashed when enable_encrypt_password is set.
14
+ // Reads the form. The passwords are returned as typed: send them over HTTPS and hash them on the server.
15
15
  export function getChangePasswordFormData() {
16
16
  return {
17
- currentPassword: hashPassword(readControl(FORM_ID, "current")),
18
- newPassword: hashPassword(readControl(FORM_ID, "new"))
17
+ currentPassword: readControl(FORM_ID, "current"),
18
+ newPassword: readControl(FORM_ID, "new")
19
19
  };
20
20
  }
21
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,16 +51,13 @@ 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
- }
63
-
64
- export function hashPassword(password) {
65
- return config.enable_encrypt_password ? CryptoJS.SHA256(password).toString() : password;
62
+ return document.getElementById(`${formId}-${name}-control`)?.value ?? "";
66
63
  }