athena-ui-js 0.4.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +352 -11
  2. package/package.json +84 -60
  3. package/src/athena-ui.js +68 -1
  4. package/src/libs/config/config.js +15 -1
  5. package/src/libs/config/hooks.js +15 -3
  6. package/src/libs/core/combobox.js +179 -0
  7. package/src/libs/core/csv.js +37 -0
  8. package/src/libs/core/dateRange.js +50 -0
  9. package/src/libs/core/dom.js +57 -0
  10. package/src/libs/core/focus.js +49 -0
  11. package/src/libs/core/format.js +31 -0
  12. package/src/libs/core/i18n.js +160 -0
  13. package/src/libs/core/pagination.js +24 -0
  14. package/src/libs/core/sanitize.js +65 -0
  15. package/src/libs/core/tableMath.js +31 -0
  16. package/src/libs/core/validation.js +79 -0
  17. package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +81 -0
  18. package/src/libs/hephaestus/auth/session.js +68 -0
  19. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +187 -0
  20. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +201 -0
  21. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +126 -0
  22. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +138 -0
  23. package/src/libs/hephaestus/formGenerator/changePasswordFormGenerator.js +50 -0
  24. package/src/libs/hephaestus/formGenerator/formBuilder.js +379 -0
  25. package/src/libs/hephaestus/formGenerator/formUtils.js +66 -0
  26. package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +20 -6
  27. package/src/libs/hephaestus/formGenerator/lostPasswordFormGenerator.js +30 -0
  28. package/src/libs/hephaestus/formGenerator/registrationFormGenerator.js +54 -0
  29. package/src/libs/hephaestus/hephaestus.js +8 -1
  30. package/src/libs/hephaestus/inputGenerator/inputGenerator.js +299 -0
  31. package/src/libs/hephaestus/inputGenerator/richTextGenerator.js +222 -0
  32. package/src/libs/hephaestus/modalGenerator/modalGenerator.js +13 -2
  33. package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +388 -0
  34. package/src/libs/hephaestus/router/matchRoute.js +42 -0
  35. package/src/libs/hephaestus/router/router.js +102 -0
  36. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +457 -0
  37. package/src/res/themes/dark/style.css +31 -0
  38. package/src/res/themes/default/style.css +1388 -7
  39. package/src/res/themes/themes.js +6 -0
@@ -0,0 +1,187 @@
1
+ //chartGenerator 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
+ // Dependency free SVG charts: bar, line, pie and donut.
7
+
8
+ const NS = "http://www.w3.org/2000/svg";
9
+ const PALETTE = ["#4e79a7", "#f28e2b", "#e15759", "#76b7b2", "#59a14f", "#edc948", "#b07aa1", "#ff9da7", "#9c755f", "#bab0ac"];
10
+ const MARGIN = { top: 40, right: 20, bottom: 50, left: 55 };
11
+
12
+ const svgEl = (tag, attrs = {}, text) => {
13
+ const node = document.createElementNS(NS, tag);
14
+ for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value);
15
+ if (text != null) node.textContent = text;
16
+ return node;
17
+ };
18
+
19
+ const colorOf = (series, index) => series.color ?? PALETTE[index % PALETTE.length];
20
+ const formatNumber = n => Number.isInteger(n) ? String(n) : String(+n.toFixed(2));
21
+
22
+ // Rounded axis maximum and tick step, so ticks land on readable numbers.
23
+ function niceScale(span, ticks = 5) {
24
+ if (span <= 0) return { span: 1, step: 1 / ticks };
25
+ const rough = span / ticks;
26
+ const magnitude = 10 ** Math.floor(Math.log10(rough));
27
+ const step = [1, 2, 5, 10].map(m => m * magnitude).find(s => s >= rough);
28
+ return { span: step * Math.ceil(span / step - 1e-9), step };
29
+ }
30
+
31
+ function addLegend(svg, entries, width, height) {
32
+ let x = MARGIN.left;
33
+ const y = height - 12;
34
+ for (const { name, color } of entries) {
35
+ svg.append(svgEl("rect", { x, y: y - 9, width: 10, height: 10, fill: color }));
36
+ svg.append(svgEl("text", { x: x + 14, y, class: "chart-legend" }, name));
37
+ x += 14 + name.length * 7 + 14;
38
+ if (x > width) break;
39
+ }
40
+ }
41
+
42
+ // Draws grid, ticks and axes for the value range [min, min + scale.span].
43
+ function addAxes(svg, { labels, min, scale, width, height }) {
44
+ const plotW = width - MARGIN.left - MARGIN.right;
45
+ const plotH = height - MARGIN.top - MARGIN.bottom;
46
+ const y = value => MARGIN.top + plotH - ((value - min) / scale.span) * plotH;
47
+ const ticks = Math.round(scale.span / scale.step);
48
+ for (let i = 0; i <= ticks; i++) {
49
+ const v = min + i * scale.step;
50
+ svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: y(v), y2: y(v), class: "chart-grid" }));
51
+ svg.append(svgEl("text", { x: MARGIN.left - 8, y: y(v) + 4, "text-anchor": "end", class: "chart-tick" }, formatNumber(v)));
52
+ }
53
+ const band = plotW / Math.max(labels.length, 1);
54
+ labels.forEach((label, i) => svg.append(svgEl("text",
55
+ { x: MARGIN.left + band * (i + 0.5), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, label)));
56
+ svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left, y1: MARGIN.top, y2: MARGIN.top + plotH, class: "chart-axis" }));
57
+ // The category axis sits at zero when the range includes it, so negative bars hang below it.
58
+ const baseline = y(Math.min(Math.max(0, min), min + scale.span));
59
+ svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: baseline, y2: baseline, class: "chart-axis" }));
60
+ return { band, y };
61
+ }
62
+
63
+ function valueRange(series) {
64
+ const values = series.flatMap(s => s.data);
65
+ const min = Math.min(0, ...values);
66
+ const scale = niceScale(Math.max(0, ...values) - min);
67
+ return { min, scale };
68
+ }
69
+
70
+ function drawBar(svg, { labels, series, width, height }) {
71
+ const { min, scale } = valueRange(series);
72
+ const { band, y } = addAxes(svg, { labels, min, scale, width, height });
73
+ const groupWidth = band * 0.8;
74
+ const barWidth = groupWidth / series.length;
75
+ series.forEach((s, si) => s.data.forEach((value, i) => {
76
+ const x = MARGIN.left + band * i + (band - groupWidth) / 2 + barWidth * si;
77
+ const top = Math.min(y(value), y(0));
78
+ const bar = svgEl("rect", {
79
+ x, y: top, width: Math.max(barWidth - 2, 1), height: Math.abs(y(0) - y(value)),
80
+ fill: colorOf(s, si), class: "chart-bar"
81
+ });
82
+ bar.append(svgEl("title", {}, `${s.name ?? ""} ${labels[i] ?? ""}: ${formatNumber(value)}`.trim()));
83
+ svg.append(bar);
84
+ }));
85
+ }
86
+
87
+ function drawLine(svg, { labels, series, width, height }) {
88
+ const { min, scale } = valueRange(series);
89
+ const { band, y } = addAxes(svg, { labels, min, scale, width, height });
90
+ series.forEach((s, si) => {
91
+ const color = colorOf(s, si);
92
+ const points = s.data.map((v, i) => [MARGIN.left + band * (i + 0.5), y(v)]);
93
+ svg.append(svgEl("polyline", {
94
+ points: points.map(p => p.join(",")).join(" "), fill: "none", stroke: color, "stroke-width": 2, class: "chart-line"
95
+ }));
96
+ points.forEach(([cx, cy], i) => {
97
+ const dot = svgEl("circle", { cx, cy, r: 4, fill: color, class: "chart-point" });
98
+ dot.append(svgEl("title", {}, `${s.name ?? ""} ${labels[i] ?? ""}: ${formatNumber(s.data[i])}`.trim()));
99
+ svg.append(dot);
100
+ });
101
+ });
102
+ }
103
+
104
+ function drawPie(svg, { labels, series, width, height, donut }) {
105
+ const data = series[0].data.map(v => Math.max(0, v));
106
+ const total = data.reduce((a, b) => a + b, 0);
107
+ const cx = width / 2;
108
+ const cy = MARGIN.top + (height - MARGIN.top - MARGIN.bottom) / 2;
109
+ const r = Math.min(width - MARGIN.left - MARGIN.right, height - MARGIN.top - MARGIN.bottom) / 2;
110
+ const inner = donut ? r * 0.55 : 0;
111
+ const point = (radius, angle) => [cx + radius * Math.cos(angle), cy + radius * Math.sin(angle)].join(",");
112
+ let start = -Math.PI / 2;
113
+ data.forEach((value, i) => {
114
+ if (!total || !value) return;
115
+ const sweep = (value / total) * Math.PI * 2;
116
+ const color = PALETTE[i % PALETTE.length];
117
+ let slice;
118
+ if (sweep >= Math.PI * 2 - 1e-6) {
119
+ // A single full slice cannot be drawn as an arc.
120
+ slice = donut
121
+ ? svgEl("circle", { cx, cy, r: (r + inner) / 2, fill: "none", stroke: color, "stroke-width": r - inner })
122
+ : svgEl("circle", { cx, cy, r, fill: color });
123
+ } else {
124
+ const end = start + sweep;
125
+ const large = sweep > Math.PI ? 1 : 0;
126
+ const d = donut
127
+ ? `M${point(r, start)} A${r},${r} 0 ${large} 1 ${point(r, end)} L${point(inner, end)} A${inner},${inner} 0 ${large} 0 ${point(inner, start)} Z`
128
+ : `M${cx},${cy} L${point(r, start)} A${r},${r} 0 ${large} 1 ${point(r, end)} Z`;
129
+ slice = svgEl("path", { d, fill: color, stroke: "#fff" });
130
+ }
131
+ slice.setAttribute("class", "chart-slice");
132
+ slice.append(svgEl("title", {}, `${labels[i] ?? ""}: ${formatNumber(value)} (${Math.round(value / total * 100)}%)`));
133
+ svg.append(slice);
134
+ start += sweep;
135
+ });
136
+ // The legend of a pie lists the slices, not the series.
137
+ return labels.map((name, i) => ({ name, color: PALETTE[i % PALETTE.length] }));
138
+ }
139
+
140
+ const DRAWERS = {
141
+ bar: drawBar,
142
+ line: drawLine,
143
+ pie: drawPie,
144
+ donut: (svg, o) => drawPie(svg, { ...o, donut: true })
145
+ };
146
+
147
+ /**
148
+ * Draws a chart as inline SVG and appends it to its parent.
149
+ *
150
+ * @param {object} options
151
+ * @param {"bar"|"line"|"pie"|"donut"} [options.type="bar"]
152
+ * @param {string} [options.parent] id of the parent element, defaults to "wrapper"
153
+ * @param {string} [options.id] id of the svg element
154
+ * @param {string} [options.title]
155
+ * @param {string[]} [options.labels] category labels
156
+ * @param {{name?: string, data: number[], color?: string}[]} options.series pie / donut use the first series only
157
+ * @param {number} [options.width=600]
158
+ * @param {number} [options.height=360]
159
+ * @param {boolean} [options.legend] default: shown for several series, and for pie / donut
160
+ * @returns {SVGElement|null} null when the options are invalid
161
+ */
162
+ export function generateChart(options = {}) {
163
+ const { type = "bar", parent = "wrapper", id, title, width = 600, height = 360 } = options;
164
+ const draw = DRAWERS[type];
165
+ const series = (options.series ?? []).filter(s => Array.isArray(s?.data) && s.data.length);
166
+ if (!draw || !series.length) {
167
+ console.error("Athena UI: generateChart needs a valid type and at least one series with data", options);
168
+ return null;
169
+ }
170
+ const labels = (options.labels ?? []).map(String);
171
+ const count = Math.max(...series.map(s => s.data.length));
172
+ while (labels.length < count) labels.push(String(labels.length + 1));
173
+
174
+ const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class: "athena-chart", role: "img" });
175
+ if (id) svg.id = id;
176
+ if (title) {
177
+ svg.setAttribute("aria-label", title);
178
+ svg.append(svgEl("text", { x: width / 2, y: 24, "text-anchor": "middle", class: "chart-title" }, title));
179
+ }
180
+
181
+ const pieLegend = draw(svg, { labels, series, width, height });
182
+ if (options.legend ?? (Boolean(pieLegend) || series.length > 1)) {
183
+ addLegend(svg, pieLegend ?? series.map((s, i) => ({ name: s.name ?? `Series ${i + 1}`, color: colorOf(s, i) })), width, height);
184
+ }
185
+ (document.getElementById(parent) ?? document.body).append(svg);
186
+ return svg;
187
+ }
@@ -0,0 +1,201 @@
1
+ //componentGenerator 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 { cx, el, mount, setContent, uid } from "../../core/dom.js";
7
+
8
+ /**
9
+ * Generates a link. External links open in a new tab and get `rel="noopener noreferrer"`.
10
+ * With `onclick` and no `href` it behaves as an in-page action.
11
+ *
12
+ * @param {object} options
13
+ * @param {string|Element} [options.parent]
14
+ * @param {string} options.text
15
+ * @param {string} [options.href]
16
+ * @param {boolean} [options.external]
17
+ * @param {(event: Event) => void} [options.onclick]
18
+ * @returns {HTMLAnchorElement}
19
+ */
20
+ export function generateLink(options = {}) {
21
+ const link = el("a", {
22
+ id: options.id,
23
+ class: cx("athena-link", options.class),
24
+ text: options.text,
25
+ attrs: {
26
+ href: options.href ?? "#",
27
+ target: options.external ? "_blank" : null,
28
+ rel: options.external ? "noopener noreferrer" : null
29
+ }
30
+ });
31
+ link.addEventListener("click", event => {
32
+ if (options.onclick) {
33
+ if (!options.href) event.preventDefault();
34
+ options.onclick(event);
35
+ } else if (!options.href) {
36
+ event.preventDefault();
37
+ }
38
+ });
39
+ return mount(options.parent, link);
40
+ }
41
+
42
+ /**
43
+ * Generates a section with an optional heading. Returns the section, fill it through `content`
44
+ * or append to it.
45
+ *
46
+ * @param {object} options
47
+ * @param {string|Element} [options.parent]
48
+ * @param {string} [options.title]
49
+ * @param {number} [options.level=2] heading level 1..6
50
+ * @param {string|Node|Array|Function} [options.content]
51
+ * @returns {HTMLElement}
52
+ */
53
+ export function generateSection(options = {}) {
54
+ const section = el("section", { id: options.id, class: cx("athena-section", options.class) });
55
+ if (options.title) {
56
+ const id = uid("section");
57
+ section.setAttribute("aria-labelledby", id);
58
+ section.append(el(`h${Math.min(Math.max(options.level ?? 2, 1), 6)}`, { id, text: options.title }));
59
+ }
60
+ setContent(section, options.content);
61
+ return mount(options.parent, section);
62
+ }
63
+
64
+ /**
65
+ * Generates a card.
66
+ *
67
+ * @param {object} options
68
+ * @param {string|Element} [options.parent]
69
+ * @param {string} [options.title]
70
+ * @param {string} [options.image] image URL shown on top
71
+ * @param {string} [options.imageAlt]
72
+ * @param {string|Node|Array|Function} [options.content]
73
+ * @param {string|Node|Array|Function} [options.footer]
74
+ * @returns {{element: HTMLElement, body: HTMLElement}} append to `body` to add more content
75
+ */
76
+ export function generateCard(options = {}) {
77
+ const body = setContent(el("div", { class: "card-body" }), options.content);
78
+ const card = el("div", { id: options.id, class: cx("card", options.class) });
79
+ if (options.image) card.append(el("img", { class: "card-image", attrs: { src: options.image, alt: options.imageAlt ?? "" } }));
80
+ if (options.title) body.prepend(el("h3", { class: "card-title", text: options.title }));
81
+ card.append(body);
82
+ if (options.footer) card.append(setContent(el("div", { class: "card-footer" }), options.footer));
83
+ mount(options.parent, card);
84
+ return { element: card, body };
85
+ }
86
+
87
+ /**
88
+ * Generates a small label.
89
+ *
90
+ * @param {object} options
91
+ * @param {string|Element} [options.parent]
92
+ * @param {string} options.text
93
+ * @param {"neutral"|"info"|"success"|"warning"|"error"} [options.variant="neutral"]
94
+ * @param {boolean} [options.pill]
95
+ * @returns {HTMLElement}
96
+ */
97
+ export function generateBadge(options = {}) {
98
+ return mount(options.parent, el("span", {
99
+ id: options.id,
100
+ class: cx("badge", `badge-${options.variant ?? "neutral"}`, options.pill && "badge-pill", options.class),
101
+ text: options.text
102
+ }));
103
+ }
104
+
105
+ // Up to two initials of a name: "Ada Lovelace" -> "AL"
106
+ export function initialsOf(name = "") {
107
+ return name.trim().split(/\s+/).filter(Boolean).slice(0, 2).map(word => [...word][0].toUpperCase()).join("");
108
+ }
109
+
110
+ /**
111
+ * Generates an avatar: the image, or the initials of the name when there is no (working) image.
112
+ *
113
+ * @param {object} options
114
+ * @param {string|Element} [options.parent]
115
+ * @param {string} [options.name]
116
+ * @param {string} [options.src]
117
+ * @param {"small"|"large"} [options.size]
118
+ * @returns {HTMLElement}
119
+ */
120
+ export function generateAvatar(options = {}) {
121
+ const avatar = el("span", {
122
+ id: options.id,
123
+ class: cx("avatar", options.size && `avatar-${options.size}`, options.class),
124
+ attrs: { role: "img", "aria-label": options.name ?? "avatar" }
125
+ });
126
+ const showInitials = () => avatar.replaceChildren(el("span", { text: initialsOf(options.name), attrs: { "aria-hidden": "true" } }));
127
+ if (options.src) {
128
+ const image = el("img", { attrs: { src: options.src, alt: "" } });
129
+ image.addEventListener("error", showInitials);
130
+ avatar.append(image);
131
+ } else {
132
+ showInitials();
133
+ }
134
+ return mount(options.parent, avatar);
135
+ }
136
+
137
+ /**
138
+ * Generates a KPI tile: a label, a big value and an optional change.
139
+ *
140
+ * @param {object} options
141
+ * @param {string|Element} [options.parent]
142
+ * @param {string} options.label
143
+ * @param {string|number} options.value
144
+ * @param {number} [options.delta] change in percent, shown with an arrow
145
+ * @param {boolean} [options.invertDelta] a falling value is good news (costs, errors)
146
+ * @returns {{element: HTMLElement, setValue: Function}}
147
+ */
148
+ export function generateStat(options = {}) {
149
+ const value = el("div", { class: "stat-value", text: String(options.value ?? "") });
150
+ const element = el("div", { id: options.id, class: cx("stat", options.class) }, el("div", { class: "stat-label", text: options.label }), value);
151
+ if (options.delta != null) {
152
+ const good = options.invertDelta ? options.delta < 0 : options.delta > 0;
153
+ const kind = options.delta === 0 ? "neutral" : good ? "good" : "bad";
154
+ const arrow = options.delta > 0 ? "▲" : options.delta < 0 ? "▼" : "■";
155
+ element.append(el("div", { class: cx("stat-delta", `stat-${kind}`), text: `${arrow} ${Math.abs(options.delta)}%` }));
156
+ }
157
+ mount(options.parent, element);
158
+ return { element, setValue: text => { value.textContent = String(text); } };
159
+ }
160
+
161
+ /**
162
+ * Generates a responsive grid. The columns collapse to one on small screens.
163
+ *
164
+ * @param {object} options
165
+ * @param {string|Element} [options.parent]
166
+ * @param {number} [options.columns=3]
167
+ * @param {string} [options.gap] any CSS length
168
+ * @returns {HTMLElement} append the cells to it
169
+ */
170
+ export function generateGrid(options = {}) {
171
+ const grid = el("div", { id: options.id, class: cx("athena-grid", options.class) });
172
+ grid.style.setProperty("--grid-columns", String(options.columns ?? 3));
173
+ if (options.gap) grid.style.setProperty("--grid-gap", options.gap);
174
+ return mount(options.parent, grid);
175
+ }
176
+
177
+ /**
178
+ * Adds a tooltip to an element. It shows on hover and on keyboard focus.
179
+ *
180
+ * @param {Element|string} target element or id
181
+ * @param {string} text
182
+ */
183
+ export function generateTooltip(target, text) {
184
+ const node = typeof target === "string" ? document.getElementById(target) : target;
185
+ if (!node) return null;
186
+ const id = uid("tooltip");
187
+ const tip = el("span", { class: "tooltip-text", id, text, attrs: { role: "tooltip" } });
188
+ // Inputs and images cannot hold the tooltip text, so they get a wrapper.
189
+ let host = node;
190
+ if (node.matches("input,img,select,textarea")) {
191
+ host = el("span", { class: "tooltip-wrap" });
192
+ node.replaceWith(host);
193
+ host.append(node);
194
+ } else if (!node.matches("a[href],button") && !node.hasAttribute("tabindex")) {
195
+ node.tabIndex = 0;
196
+ }
197
+ host.classList.add("has-tooltip");
198
+ node.setAttribute("aria-describedby", id);
199
+ host.append(tip);
200
+ return tip;
201
+ }
@@ -0,0 +1,126 @@
1
+ //dialogGenerator 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 { el, setContent, uid } from "../../core/dom.js";
7
+ import { trapFocus } from "../../core/focus.js";
8
+ import { translate } from "../../core/i18n.js";
9
+ import { generateButton } from "../formGenerator/formBuilder.js";
10
+
11
+ /**
12
+ * Opens a dialog and resolves with the value of the button that was used,
13
+ * or with `null` when it was dismissed (Esc, the close button, a click on the backdrop).
14
+ *
15
+ * @param {object} options
16
+ * @param {string} [options.title]
17
+ * @param {string|Node|Array} [options.content] text is inserted as text, never as HTML
18
+ * @param {{text: string, value?: *, variant?: string, autofocus?: boolean}[]} [options.buttons]
19
+ * @param {boolean} [options.dismissible=true]
20
+ * @param {(value) => (boolean|Promise<boolean>)} [options.beforeClose] return false to keep the dialog open
21
+ * @returns {Promise<*>} resolves with the pressed button's value
22
+ */
23
+ export function showDialog(options = {}) {
24
+ const { title, content, buttons = [{ text: translate("ok"), value: true }], dismissible = true } = options;
25
+ return new Promise(resolve => {
26
+ const titleId = uid("dialog-title");
27
+ const body = setContent(el("div", { class: "dialog-body" }), content);
28
+ const footer = el("div", { class: "dialog-footer" });
29
+ const dialog = el("div", {
30
+ class: "modal-content dialog",
31
+ attrs: { role: "dialog", "aria-modal": "true", "aria-labelledby": title ? titleId : null }
32
+ });
33
+ if (title) dialog.append(el("h2", { class: "dialog-title", id: titleId, text: title }));
34
+ dialog.append(body, footer);
35
+ const backdrop = el("div", { class: "modal dialog-backdrop", attrs: { style: "display: block" } }, dialog);
36
+
37
+ let release = () => {};
38
+ let closing = false;
39
+ const close = async value => {
40
+ if (closing) return;
41
+ closing = true;
42
+ if (options.beforeClose && (await options.beforeClose(value)) === false) {
43
+ closing = false;
44
+ return;
45
+ }
46
+ release();
47
+ backdrop.remove();
48
+ resolve(value);
49
+ };
50
+
51
+ if (dismissible) {
52
+ dialog.prepend(el("button", {
53
+ class: "dialog-close",
54
+ text: "×",
55
+ attrs: { type: "button", "aria-label": translate("close") },
56
+ on: { click: () => close(null) }
57
+ }));
58
+ backdrop.addEventListener("mousedown", event => { if (event.target === backdrop) close(null); });
59
+ }
60
+ for (const spec of buttons) {
61
+ const { element } = generateButton({
62
+ parent: footer,
63
+ text: spec.text,
64
+ variant: spec.variant ?? "primary",
65
+ onclick: () => close("value" in spec ? spec.value : spec.text)
66
+ });
67
+ if (spec.autofocus) element.dataset.autofocus = "true";
68
+ }
69
+
70
+ document.body.append(backdrop);
71
+ release = trapFocus(dialog, { onEscape: dismissible ? () => close(null) : undefined });
72
+ dialog.querySelector("[data-autofocus]")?.focus();
73
+ });
74
+ }
75
+
76
+ /** Message with an OK button. Resolves when it is closed. */
77
+ export async function alertDialog(message, { title, okText = translate("ok") } = {}) {
78
+ await showDialog({ title, content: message, buttons: [{ text: okText, value: true, autofocus: true }] });
79
+ }
80
+
81
+ /** Question with confirm and cancel buttons. Resolves with true / false. */
82
+ export async function confirmDialog(message, { title, confirmText = translate("ok"), cancelText = translate("cancel"), danger = false } = {}) {
83
+ const result = await showDialog({
84
+ title,
85
+ content: message,
86
+ buttons: [
87
+ { text: cancelText, value: false, variant: "secondary" },
88
+ { text: confirmText, value: true, variant: danger ? "danger" : "primary", autofocus: true }
89
+ ]
90
+ });
91
+ return result === true;
92
+ }
93
+
94
+ /**
95
+ * Asks for a text value. Resolves with the entered text, or null when cancelled.
96
+ *
97
+ * @param {string} message
98
+ * @param {object} [options]
99
+ * @param {string} [options.title]
100
+ * @param {string} [options.value] initial value
101
+ * @param {string} [options.placeholder]
102
+ * @param {string} [options.type="text"] input type
103
+ * @param {(value: string) => string} [options.validate] returns an error text, or "" when valid
104
+ */
105
+ export function promptDialog(message, { title, value = "", placeholder, type = "text", validate, okText = translate("ok"), cancelText = translate("cancel") } = {}) {
106
+ const input = el("input", { attrs: { type, placeholder, "data-autofocus": "true" }, prop: { value } });
107
+ const error = el("div", { class: "field-error", attrs: { role: "alert" } });
108
+ const label = el("label", { class: "field-label", text: message });
109
+ const submit = () => {
110
+ const text = validate?.(input.value) ?? "";
111
+ error.textContent = text;
112
+ return !text;
113
+ };
114
+ input.addEventListener("keydown", event => {
115
+ if (event.key === "Enter") input.closest(".dialog").querySelector(".dialog-footer button:last-child").click();
116
+ });
117
+ return showDialog({
118
+ title,
119
+ content: [label, input, error],
120
+ buttons: [
121
+ { text: cancelText, value: null, variant: "secondary" },
122
+ { text: okText, value: "__ok__", autofocus: false }
123
+ ],
124
+ beforeClose: result => result !== "__ok__" || submit()
125
+ }).then(result => result === "__ok__" ? input.value : null);
126
+ }
@@ -0,0 +1,138 @@
1
+ //feedbackGenerator 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 { cx, el, mount, setContent } from "../../core/dom.js";
7
+ import { translate } from "../../core/i18n.js";
8
+
9
+ const TOAST_CONTAINER_ID = "athena-toasts";
10
+ const URGENT_TYPES = new Set(["error", "warning"]);
11
+
12
+ function closeButton(onclick) {
13
+ return el("button", {
14
+ class: "alert-close",
15
+ text: "×",
16
+ attrs: { type: "button", "aria-label": translate("close") },
17
+ on: { click: onclick }
18
+ });
19
+ }
20
+
21
+ /**
22
+ * Shows a toast notification in the corner of the page.
23
+ *
24
+ * @param {object|string} options a message, or an options object
25
+ * @param {string} options.message
26
+ * @param {string} [options.title]
27
+ * @param {"info"|"success"|"warning"|"error"} [options.type="info"]
28
+ * @param {number} [options.duration=4000] ms before it disappears, 0 keeps it until it is closed
29
+ * @returns {{close: Function}}
30
+ */
31
+ export function showToast(options) {
32
+ const { message, title, type = "info", duration = 4000 } = typeof options === "string" ? { message: options } : options;
33
+ let container = document.getElementById(TOAST_CONTAINER_ID);
34
+ if (!container) {
35
+ container = el("div", { id: TOAST_CONTAINER_ID, class: "toast-container" });
36
+ document.body.append(container);
37
+ }
38
+ let timer;
39
+ const close = () => {
40
+ clearTimeout(timer);
41
+ toast.remove();
42
+ };
43
+ const toast = el("div", {
44
+ class: cx("toast", `alert-${type}`),
45
+ attrs: { role: URGENT_TYPES.has(type) ? "alert" : "status" }
46
+ }, el("div", { class: "alert-body" }, title ? el("strong", { text: title }) : "", el("div", { text: message })), closeButton(close));
47
+ container.append(toast);
48
+ if (duration > 0) {
49
+ timer = setTimeout(close, duration);
50
+ // Do not hide a toast the user is reading.
51
+ toast.addEventListener("mouseenter", () => clearTimeout(timer));
52
+ toast.addEventListener("mouseleave", () => { timer = setTimeout(close, duration); });
53
+ }
54
+ return { close };
55
+ }
56
+
57
+ /**
58
+ * Generates an inline alert box.
59
+ *
60
+ * @param {object} options
61
+ * @param {string|Element} [options.parent]
62
+ * @param {string} [options.id]
63
+ * @param {string|Node} options.message
64
+ * @param {string} [options.title]
65
+ * @param {"info"|"success"|"warning"|"error"} [options.type="info"]
66
+ * @param {boolean} [options.dismissible]
67
+ * @returns {HTMLElement}
68
+ */
69
+ export function generateAlert(options = {}) {
70
+ const { type = "info", title, message, dismissible } = options;
71
+ const body = el("div", { class: "alert-body" });
72
+ if (title) body.append(el("strong", { text: title }));
73
+ body.append(setContent(el("div"), message));
74
+ const alert = el("div", {
75
+ id: options.id,
76
+ class: cx("alert", `alert-${type}`, options.class),
77
+ attrs: { role: URGENT_TYPES.has(type) ? "alert" : "status" }
78
+ }, body);
79
+ if (dismissible) alert.append(closeButton(() => alert.remove()));
80
+ return mount(options.parent, alert);
81
+ }
82
+
83
+ /**
84
+ * Generates a loading spinner.
85
+ *
86
+ * @param {object} [options]
87
+ * @param {string|Element} [options.parent]
88
+ * @param {string} [options.id]
89
+ * @param {"small"|"large"} [options.size]
90
+ * @param {string} [options.label] accessible text, defaults to the translated "Loading..."
91
+ * @returns {HTMLElement}
92
+ */
93
+ export function generateSpinner(options = {}) {
94
+ return mount(options.parent, el("span", {
95
+ id: options.id,
96
+ class: cx("spinner", options.size && `spinner-${options.size}`, options.class),
97
+ attrs: { role: "status", "aria-label": options.label ?? translate("loading") }
98
+ }));
99
+ }
100
+
101
+ /**
102
+ * Generates a progress bar. Without a value it is indeterminate.
103
+ *
104
+ * @param {object} [options]
105
+ * @param {string|Element} [options.parent]
106
+ * @param {string} [options.id]
107
+ * @param {number} [options.value] 0..max
108
+ * @param {number} [options.max=100]
109
+ * @param {string} [options.label] text shown above the bar
110
+ * @param {"info"|"success"|"warning"|"error"} [options.type]
111
+ * @returns {{element: HTMLElement, setValue: (value: number) => void}}
112
+ */
113
+ export function generateProgress(options = {}) {
114
+ const max = options.max ?? 100;
115
+ const fill = el("div", { class: "progress-fill" });
116
+ const bar = el("div", {
117
+ class: "progress-bar",
118
+ attrs: { role: "progressbar", "aria-valuemin": 0, "aria-valuemax": max, "aria-label": options.label ?? null }
119
+ }, fill);
120
+ const element = el("div", { id: options.id, class: cx("progress", options.type && `progress-${options.type}`, options.class) },
121
+ options.label ? el("div", { class: "progress-label", text: options.label }) : "", bar);
122
+
123
+ const setValue = value => {
124
+ const indeterminate = value == null;
125
+ element.classList.toggle("progress-indeterminate", indeterminate);
126
+ if (indeterminate) {
127
+ bar.removeAttribute("aria-valuenow");
128
+ fill.style.width = "";
129
+ } else {
130
+ const clamped = Math.min(Math.max(value, 0), max);
131
+ bar.setAttribute("aria-valuenow", clamped);
132
+ fill.style.width = `${(clamped / max) * 100}%`;
133
+ }
134
+ };
135
+ setValue(options.value);
136
+ mount(options.parent, element);
137
+ return { element, setValue };
138
+ }