athena-ui-js 2.4.0 → 2.5.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.
- package/README.md +32 -2
- package/docs/styling.md +1 -1
- package/package.json +4 -1
- package/src/athena-ui.js +1 -1
- package/src/libs/config/config.js +1 -1
- package/src/libs/core/i18n.js +2 -0
- package/src/libs/hephaestus/chartGenerator/chartGenerator.js +70 -28
- package/src/libs/hephaestus/codeGenerator/codeEditor.js +1037 -0
- package/src/libs/hephaestus/codeGenerator/codeGenerator.js +286 -0
- package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +5 -2
- package/src/libs/hephaestus/formGenerator/formBuilder.js +86 -5
- package/src/libs/hephaestus/tableGenerator/tableGenerator.js +5 -1
- package/src/libs/hephaestus/widgetGrid/widgetGrid.js +870 -0
- package/src/res/themes/default/style.css +4 -0
- package/types/athena-ui.d.ts +103 -103
- package/types/code.d.ts +4 -4
- package/types/libs/config/config.d.ts +3 -3
- package/types/libs/core/codeDiff.d.ts +32 -32
- package/types/libs/core/codeLanguages.d.ts +58 -58
- package/types/libs/hephaestus/chartGenerator/chartGenerator.d.ts +117 -95
- package/types/libs/hephaestus/codeGenerator/codeEditor.d.ts +60 -60
- package/types/libs/hephaestus/codeGenerator/codeGenerator.d.ts +99 -99
- package/types/libs/hephaestus/dialogGenerator/dialogGenerator.d.ts +122 -120
- package/types/libs/hephaestus/formGenerator/authForms.d.ts +130 -122
- package/types/libs/hephaestus/formGenerator/formBuilder.d.ts +128 -113
- package/types/libs/hephaestus/tableGenerator/tableGenerator.d.ts +129 -123
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
//Code display of Athena UI: highlightCode (a <pre><code> with tokens), generateCodeBlock (label, copy button) and createDiffView.
|
|
2
|
+
//Everything is built with el(): text stays text, nothing is parsed as markup.
|
|
3
|
+
//LICENCE: MIT
|
|
4
|
+
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
|
+
|
|
6
|
+
import { asHandle, cx, el, resolveElement } from "../../core/dom.js";
|
|
7
|
+
import { translate } from "../../core/i18n.js";
|
|
8
|
+
import { getLanguage, tokenize } from "../../core/codeLanguages.js";
|
|
9
|
+
import { diffLines, hunksOf, splitLines } from "../../core/codeDiff.js";
|
|
10
|
+
|
|
11
|
+
/* ------------------TOKENS TO LINES------------------- */
|
|
12
|
+
|
|
13
|
+
/** Splits tokens at the line breaks: an array (one entry per line) of arrays of { type, text }. */
|
|
14
|
+
export function tokensToLines(tokens) {
|
|
15
|
+
const lines = [[]];
|
|
16
|
+
for (const token of tokens) {
|
|
17
|
+
const parts = token.text.split("\n");
|
|
18
|
+
parts.forEach((part, index) => {
|
|
19
|
+
if (index > 0) lines.push([]);
|
|
20
|
+
if (part) lines.at(-1).push({ type: token.type, text: part });
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
return lines;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The nodes of one line: text nodes and <span class="tok-..."> (a span has one class and one text node). */
|
|
27
|
+
export function lineNodes(tokens) {
|
|
28
|
+
return tokens.map(token => (token.type ? el("span", { class: `tok-${token.type}` }, token.text) : document.createTextNode(token.text)));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** "3", 3 or "5-8" (and a list of them) to a Set of line numbers. */
|
|
32
|
+
function lineSet(spec) {
|
|
33
|
+
const set = new Set();
|
|
34
|
+
for (const item of [].concat(spec ?? [])) {
|
|
35
|
+
const range = /^(\d+)\s*-\s*(\d+)$/.exec(String(item));
|
|
36
|
+
if (range) for (let n = Number(range[1]); n <= Math.min(Number(range[2]), Number(range[1]) + 100000); n++) set.add(n);
|
|
37
|
+
else if (Number.isInteger(Number(item))) set.add(Number(item));
|
|
38
|
+
}
|
|
39
|
+
return set;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const digitsOf = count => Math.min(7, Math.max(1, String(count).length));
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Writes the highlighted lines of a text into a <code> element (replacing what is there). The editor uses it too.
|
|
46
|
+
*
|
|
47
|
+
* @param {HTMLElement} code
|
|
48
|
+
* @param {string} text
|
|
49
|
+
* @param {string|object} [language] a name or alias ("js"), or a language object; unknown: plain text
|
|
50
|
+
* @param {object} [options]
|
|
51
|
+
* @param {Array<number|string>} [options.highlightLines] line numbers (1-based) or ranges ("5-8") that get a background
|
|
52
|
+
* @returns {number} the number of lines
|
|
53
|
+
*/
|
|
54
|
+
export function renderCode(code, text, language, { highlightLines } = {}) {
|
|
55
|
+
const marked = lineSet(highlightLines);
|
|
56
|
+
const lines = tokensToLines(tokenize(text, language));
|
|
57
|
+
const fragment = document.createDocumentFragment();
|
|
58
|
+
lines.forEach((tokens, index) => {
|
|
59
|
+
const line = el("span", { class: cx("code-line", marked.has(index + 1) && "is-highlighted") });
|
|
60
|
+
line.append(...lineNodes(tokens));
|
|
61
|
+
fragment.append(line);
|
|
62
|
+
});
|
|
63
|
+
code.replaceChildren(fragment);
|
|
64
|
+
return lines.length;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Highlights read-only code: a `<pre class="athena-code"><code>` element.
|
|
69
|
+
*
|
|
70
|
+
* @param {string} text
|
|
71
|
+
* @param {string|object} [language] "js", "ts", "json", "html", "css", "sql", "sh", "yaml", "c#", "python" or a language you registered
|
|
72
|
+
* @param {object} [options]
|
|
73
|
+
* @param {boolean} [options.lineNumbers=false]
|
|
74
|
+
* @param {Array<number|string>} [options.highlightLines]
|
|
75
|
+
* @param {boolean} [options.wrap=false] long lines wrap instead of scrolling
|
|
76
|
+
* @param {string} [options.label] accessible name of the code
|
|
77
|
+
* @returns {HTMLPreElement}
|
|
78
|
+
*/
|
|
79
|
+
export function highlightCode(text, language, { lineNumbers = false, highlightLines, wrap = false, label } = {}) {
|
|
80
|
+
const found = getLanguage(language);
|
|
81
|
+
const code = el("code", { class: found ? `language-${found.name}` : "" });
|
|
82
|
+
const count = renderCode(code, text, language, { highlightLines });
|
|
83
|
+
return el("pre", {
|
|
84
|
+
class: cx("athena-code", lineNumbers && "has-line-numbers", lineNumbers && `code-digits-${digitsOf(count)}`, wrap && "code-wrap"),
|
|
85
|
+
attrs: { tabindex: "0", ...(label ? { "aria-label": label, role: "region" } : {}) }
|
|
86
|
+
}, code);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/* ------------------CODE BLOCK------------------- */
|
|
90
|
+
|
|
91
|
+
async function copyText(text) {
|
|
92
|
+
try {
|
|
93
|
+
await navigator.clipboard.writeText(text);
|
|
94
|
+
return true;
|
|
95
|
+
} catch {
|
|
96
|
+
const area = el("textarea", { class: "athena-visually-hidden", attrs: { "aria-hidden": "true", tabindex: "-1", readonly: "" } });
|
|
97
|
+
area.value = text;
|
|
98
|
+
document.body.append(area);
|
|
99
|
+
area.select();
|
|
100
|
+
let done = false;
|
|
101
|
+
try {
|
|
102
|
+
done = document.execCommand("copy");
|
|
103
|
+
} catch {
|
|
104
|
+
done = false;
|
|
105
|
+
}
|
|
106
|
+
area.remove();
|
|
107
|
+
return done;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A code block: a label with the language, a copy button and the highlighted code.
|
|
113
|
+
*
|
|
114
|
+
* @param {object} options
|
|
115
|
+
* @param {string|HTMLElement} [options.parent]
|
|
116
|
+
* @param {string} options.code
|
|
117
|
+
* @param {string|object} [options.language]
|
|
118
|
+
* @param {string} [options.title] shown in the header instead of the language
|
|
119
|
+
* @param {boolean} [options.lineNumbers=false]
|
|
120
|
+
* @param {Array<number|string>} [options.highlightLines]
|
|
121
|
+
* @param {boolean} [options.copy=true] the copy button
|
|
122
|
+
* @param {boolean} [options.wrap=false]
|
|
123
|
+
* @param {string} [options.id]
|
|
124
|
+
* @returns {{element: HTMLElement, getCode: () => string, setCode: (code: string, language?: string|object) => void, copy: () => Promise<boolean>, destroy: Function}}
|
|
125
|
+
*/
|
|
126
|
+
export function generateCodeBlock({ parent, code = "", language, title, lineNumbers = false, highlightLines, copy = true, wrap = false, id } = {}) {
|
|
127
|
+
let text = String(code);
|
|
128
|
+
let current = language;
|
|
129
|
+
const label = () => title ?? getLanguage(current)?.label ?? getLanguage(current)?.name ?? "";
|
|
130
|
+
const status = el("span", { class: "athena-visually-hidden", attrs: { role: "status" } });
|
|
131
|
+
const name = el("span", { class: "code-block-language" }, label());
|
|
132
|
+
const header = el("figcaption", { class: "code-block-header" }, name);
|
|
133
|
+
const figure = el("figure", { class: "code-block", attrs: id ? { id } : {} }, header);
|
|
134
|
+
let pre = null;
|
|
135
|
+
let timer = 0;
|
|
136
|
+
|
|
137
|
+
const draw = () => {
|
|
138
|
+
const next = highlightCode(text, current, { lineNumbers, highlightLines, wrap, label: label() || undefined });
|
|
139
|
+
if (pre) pre.replaceWith(next);
|
|
140
|
+
else figure.append(next);
|
|
141
|
+
pre = next;
|
|
142
|
+
name.textContent = label();
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const doCopy = async () => {
|
|
146
|
+
const done = await copyText(text);
|
|
147
|
+
status.textContent = translate(done ? "code.copied" : "code.copyFailed");
|
|
148
|
+
if (button) {
|
|
149
|
+
button.textContent = translate(done ? "code.copied" : "code.copyFailed");
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
timer = setTimeout(() => { button.textContent = translate("code.copy"); status.textContent = ""; }, 1800);
|
|
152
|
+
}
|
|
153
|
+
return done;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
let button = null;
|
|
157
|
+
if (copy) {
|
|
158
|
+
button = el("button", { class: "code-block-copy", attrs: { type: "button" } }, translate("code.copy"));
|
|
159
|
+
button.addEventListener("click", doCopy);
|
|
160
|
+
header.append(button);
|
|
161
|
+
}
|
|
162
|
+
figure.append(status);
|
|
163
|
+
draw();
|
|
164
|
+
resolveElement(parent)?.append(figure);
|
|
165
|
+
|
|
166
|
+
return asHandle({
|
|
167
|
+
element: figure,
|
|
168
|
+
getCode: () => text,
|
|
169
|
+
setCode(next, nextLanguage) {
|
|
170
|
+
text = String(next ?? "");
|
|
171
|
+
if (nextLanguage !== undefined) current = nextLanguage;
|
|
172
|
+
draw();
|
|
173
|
+
},
|
|
174
|
+
copy: doCopy,
|
|
175
|
+
destroy() {
|
|
176
|
+
clearTimeout(timer);
|
|
177
|
+
figure.remove();
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/* ------------------DIFF VIEW------------------- */
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A view of the difference between two texts, with highlighted code on both sides.
|
|
186
|
+
*
|
|
187
|
+
* @param {object} options
|
|
188
|
+
* @param {string|HTMLElement} [options.parent]
|
|
189
|
+
* @param {string} [options.original]
|
|
190
|
+
* @param {string} [options.modified]
|
|
191
|
+
* @param {string|object} [options.language]
|
|
192
|
+
* @param {"unified"|"split"} [options.mode="unified"]
|
|
193
|
+
* @param {number} [options.context=3] unchanged lines kept around a change (Infinity: all of them); a button shows the rest
|
|
194
|
+
* @param {string} [options.originalLabel]
|
|
195
|
+
* @param {string} [options.modifiedLabel]
|
|
196
|
+
* @returns {{element: HTMLElement, setTexts: (original: string, modified: string) => void, setMode: (mode: string) => void, getStats: () => {added: number, removed: number}}}
|
|
197
|
+
*/
|
|
198
|
+
export function createDiffView({ parent, original = "", modified = "", language, mode = "unified", context = 3, originalLabel, modifiedLabel } = {}) {
|
|
199
|
+
const root = el("div", { class: "code-diff", attrs: { role: "group", "aria-label": translate("code.diff") } });
|
|
200
|
+
let texts = [String(original), String(modified)];
|
|
201
|
+
let view = mode === "split" ? "split" : "unified";
|
|
202
|
+
let expanded = false;
|
|
203
|
+
let stats = { added: 0, removed: 0 };
|
|
204
|
+
|
|
205
|
+
const mark = (symbol, word) => el("span", { class: "code-diff-mark" }, el("span", { class: "athena-visually-hidden" }, `${word} `), el("span", { attrs: { "aria-hidden": "true" } }, symbol));
|
|
206
|
+
|
|
207
|
+
const cell = (kind, tokens, symbol, word, number) => {
|
|
208
|
+
const line = el("span", { class: "code-line" });
|
|
209
|
+
if (tokens) line.append(...lineNodes(tokens));
|
|
210
|
+
return el("span", { class: cx("code-diff-cell", `is-${kind}`) },
|
|
211
|
+
el("span", { class: "code-diff-number", attrs: { "aria-hidden": "true" } }, number ?? ""), symbol ? mark(symbol, word) : el("span", { class: "code-diff-mark" }), line);
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
function draw() {
|
|
215
|
+
const oldLines = splitLines(texts[0]);
|
|
216
|
+
const newLines = splitLines(texts[1]);
|
|
217
|
+
const oldTokens = tokensToLines(tokenize(oldLines.join("\n"), language));
|
|
218
|
+
const newTokens = tokensToLines(tokenize(newLines.join("\n"), language));
|
|
219
|
+
const ops = diffLines(oldLines, newLines);
|
|
220
|
+
stats = { added: ops.filter(op => op.type === "add").length, removed: ops.filter(op => op.type === "remove").length };
|
|
221
|
+
const hunks = hunksOf(ops, expanded ? Infinity : context);
|
|
222
|
+
const body = el("div", { class: cx("code-diff-body", `is-${view}`) });
|
|
223
|
+
const header = el("div", { class: "code-diff-header" }, el("span", { class: "code-diff-stat is-removed" }, `−${stats.removed}`), el("span", { class: "code-diff-stat is-added" }, `+${stats.added}`));
|
|
224
|
+
if (view === "split") header.append(el("span", { class: "code-diff-side" }, originalLabel ?? translate("code.original")), el("span", { class: "code-diff-side" }, modifiedLabel ?? translate("code.modified")));
|
|
225
|
+
const tail = oldLines.length - hunks.reduce((sum, hunk) => sum + hunk.skippedBefore + hunk.ops.filter(op => op.type !== "add").length, 0);
|
|
226
|
+
|
|
227
|
+
const skipRow = count => {
|
|
228
|
+
const button = el("button", { class: "code-diff-skip", attrs: { type: "button" } }, translate("code.unchanged", { count }));
|
|
229
|
+
button.addEventListener("click", () => { expanded = true; draw(); });
|
|
230
|
+
return el("div", { class: "code-diff-row is-skip" }, button);
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
for (const hunk of hunks) {
|
|
234
|
+
if (hunk.skippedBefore) body.append(skipRow(hunk.skippedBefore));
|
|
235
|
+
const pending = { removed: [], added: [] };
|
|
236
|
+
const flush = () => {
|
|
237
|
+
if (view === "split") {
|
|
238
|
+
const rows = Math.max(pending.removed.length, pending.added.length);
|
|
239
|
+
for (let i = 0; i < rows; i++) {
|
|
240
|
+
const left = pending.removed[i];
|
|
241
|
+
const right = pending.added[i];
|
|
242
|
+
body.append(el("div", { class: "code-diff-row" },
|
|
243
|
+
left !== undefined ? cell("removed", oldTokens[left], "−", translate("code.removed"), left + 1) : cell("empty"),
|
|
244
|
+
right !== undefined ? cell("added", newTokens[right], "+", translate("code.added"), right + 1) : cell("empty")));
|
|
245
|
+
}
|
|
246
|
+
} else {
|
|
247
|
+
for (const index of pending.removed) body.append(el("div", { class: "code-diff-row" }, cell("removed", oldTokens[index], "−", translate("code.removed"), index + 1)));
|
|
248
|
+
for (const index of pending.added) body.append(el("div", { class: "code-diff-row" }, cell("added", newTokens[index], "+", translate("code.added"), index + 1)));
|
|
249
|
+
}
|
|
250
|
+
pending.removed = [];
|
|
251
|
+
pending.added = [];
|
|
252
|
+
};
|
|
253
|
+
for (const op of hunk.ops) {
|
|
254
|
+
if (op.type === "remove") pending.removed.push(op.a);
|
|
255
|
+
else if (op.type === "add") pending.added.push(op.b);
|
|
256
|
+
else {
|
|
257
|
+
flush();
|
|
258
|
+
body.append(el("div", { class: "code-diff-row" },
|
|
259
|
+
cell("equal", oldTokens[op.a], null, "", op.a + 1), ...(view === "split" ? [cell("equal", newTokens[op.b], null, "", op.b + 1)] : [])));
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
flush();
|
|
263
|
+
}
|
|
264
|
+
if (tail > 0 && hunks.length) body.append(skipRow(tail));
|
|
265
|
+
if (!hunks.length) body.append(el("p", { class: "code-diff-empty" }, translate("code.noChanges")));
|
|
266
|
+
root.replaceChildren(header, el("pre", { class: cx("athena-code", "code-diff-code"), attrs: { tabindex: "0" } }, el("code", {}, body)));
|
|
267
|
+
root.dataset.mode = view;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
draw();
|
|
271
|
+
resolveElement(parent)?.append(root);
|
|
272
|
+
return asHandle({
|
|
273
|
+
element: root,
|
|
274
|
+
setTexts(a, b) {
|
|
275
|
+
texts = [String(a ?? ""), String(b ?? "")];
|
|
276
|
+
expanded = false;
|
|
277
|
+
draw();
|
|
278
|
+
},
|
|
279
|
+
setMode(next) {
|
|
280
|
+
view = next === "split" ? "split" : "unified";
|
|
281
|
+
draw();
|
|
282
|
+
},
|
|
283
|
+
getStats: () => ({ ...stats })
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
@@ -153,11 +153,12 @@ export function showConfirm({ title, message, confirmText = translate("ok"), can
|
|
|
153
153
|
* @param {string} [options.cancelText]
|
|
154
154
|
* @param {boolean} [options.danger=false] red submit button
|
|
155
155
|
* @param {"small"|"medium"|"large"|"full"} [options.size]
|
|
156
|
+
* @param {boolean} [options.nested=false] a field called "soa.host" is `values.soa.host` (see generateForm, which also explains `show`, `label`, `send`, `trim` and `empty` of a field)
|
|
156
157
|
* @param {(values: object, form: object) => (void|Promise)} options.onSubmit
|
|
157
158
|
* @param {(form: object) => void} [options.onReady] called with the form once it is built
|
|
158
159
|
* @returns {Promise<boolean> & {element: HTMLElement, form: object, close: Function}} resolves with true when it was saved, false when dismissed
|
|
159
160
|
*/
|
|
160
|
-
export function showFormDialog({ title, intro, content, fields, submitText = translate("save"), cancelText = translate("cancel"), danger = false, size, onSubmit, onReady } = {}) {
|
|
161
|
+
export function showFormDialog({ title, intro, content, fields, submitText = translate("save"), cancelText = translate("cancel"), danger = false, size, nested = false, onSubmit, onReady } = {}) {
|
|
161
162
|
let saved = false;
|
|
162
163
|
let dialog = null;
|
|
163
164
|
const body = el("div", { class: "dialog-form" });
|
|
@@ -166,6 +167,7 @@ export function showFormDialog({ title, intro, content, fields, submitText = tra
|
|
|
166
167
|
const form = generateForm({
|
|
167
168
|
parent: body,
|
|
168
169
|
fields,
|
|
170
|
+
nested,
|
|
169
171
|
submitText,
|
|
170
172
|
onSubmit: async (values, f) => {
|
|
171
173
|
await onSubmit?.(values, f);
|
|
@@ -182,7 +184,8 @@ export function showFormDialog({ title, intro, content, fields, submitText = tra
|
|
|
182
184
|
form.submitButton.element.classList.add("button-danger");
|
|
183
185
|
}
|
|
184
186
|
dialog = showDialog({ title, content: body, buttons: [], size });
|
|
185
|
-
|
|
187
|
+
// The first control that is there to be used (a field that is not shown, or disabled, is not)
|
|
188
|
+
const first = [...form.element.querySelectorAll("input:not([disabled]):not([type=hidden]), select:not([disabled]), textarea:not([disabled])")].find(control => !control.closest("[hidden]"));
|
|
186
189
|
first?.focus();
|
|
187
190
|
return Object.assign(dialog.then(() => saved), { element: dialog.element, backdrop: dialog.backdrop, form, close: dialog.close });
|
|
188
191
|
}
|
|
@@ -263,6 +263,10 @@ export function generateField(options = {}) {
|
|
|
263
263
|
focus() {
|
|
264
264
|
controls[0]?.focus();
|
|
265
265
|
},
|
|
266
|
+
/** Changes the text of the label (the star of a required field stays). */
|
|
267
|
+
setLabel(text) {
|
|
268
|
+
if (caption?.firstChild?.nodeType === Node.TEXT_NODE) caption.firstChild.nodeValue = text;
|
|
269
|
+
},
|
|
266
270
|
resetState() {
|
|
267
271
|
touched = false;
|
|
268
272
|
field.setError("");
|
|
@@ -294,21 +298,79 @@ export function generateField(options = {}) {
|
|
|
294
298
|
* @param {(values: object, form: object) => (void|Promise)} [options.onSubmit] called with the values when every
|
|
295
299
|
* field is valid. A returned promise keeps the submit button busy; a rejection is shown as form message.
|
|
296
300
|
* @param {(values: object, field: object) => void} [options.onChange]
|
|
297
|
-
* @
|
|
298
|
-
*
|
|
301
|
+
* @param {boolean} [options.nested=false] a field called "soa.host" is the key `host` of the object `soa` in the values
|
|
302
|
+
*
|
|
303
|
+
* Field definitions can also have these, which only generateForm reads:
|
|
304
|
+
* - `show: (values) => boolean`: the field is shown while it returns true. A field that is not shown is not validated and not in the values.
|
|
305
|
+
* - `label: (values) => string`: a label that follows the other fields (`values` are the raw values of every field)
|
|
306
|
+
* - `send: false`: the field is validated but not in the values (the second field of "type the password again")
|
|
307
|
+
* - `trim: true`: a text value is trimmed
|
|
308
|
+
* - `empty: "omit"|"null"|"empty"`: what an empty value (an empty text, a number that is not a number) becomes: left out, null, or "".
|
|
309
|
+
* Without it the value stays as it is.
|
|
310
|
+
*
|
|
311
|
+
* A rejection of `onSubmit` with a `details` object ({ "soa.host": "Not a name" }) puts the messages at their fields; what has no field, and the message
|
|
312
|
+
* of the error when no field shows one, go to the message of the form.
|
|
313
|
+
* @returns {{element: HTMLFormElement, fields: Object<string, object>, getValues: Function, getRawValues: Function, setValues: Function,
|
|
314
|
+
* setErrors: Function, validate: Function, reset: Function, setMessage: Function, arrange: Function, submitButton: object}}
|
|
299
315
|
*/
|
|
300
316
|
export function generateForm(options = {}) {
|
|
301
317
|
const element = el("form", { id: options.id, class: cx("athena-form", options.class), attrs: { novalidate: true } });
|
|
302
318
|
const fields = {};
|
|
303
|
-
const
|
|
319
|
+
const definitions = {};
|
|
320
|
+
const shown = {}; // name -> is the field shown (a field without `show` always is)
|
|
321
|
+
// What every field holds, the way it is (the fields read it for `match`, and `show` and `label` get it)
|
|
322
|
+
const getRawValues = () => Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, field.getValue()]));
|
|
323
|
+
|
|
324
|
+
// The values of the form: only the fields that are shown and sent, trimmed and emptied as their definitions say, nested when asked
|
|
325
|
+
const getValues = () => {
|
|
326
|
+
const values = {};
|
|
327
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
328
|
+
const definition = definitions[name];
|
|
329
|
+
if (shown[name] === false || definition.send === false) continue;
|
|
330
|
+
let value = field.getValue();
|
|
331
|
+
if (typeof value === "string" && definition.trim) value = value.trim();
|
|
332
|
+
if (value === "" || value === undefined || Number.isNaN(value)) {
|
|
333
|
+
if (definition.empty === "omit") continue;
|
|
334
|
+
if (definition.empty === "null") value = null;
|
|
335
|
+
else if (definition.empty === "empty") value = "";
|
|
336
|
+
}
|
|
337
|
+
if (!options.nested) {
|
|
338
|
+
values[name] = value;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
const keys = name.split(".");
|
|
342
|
+
const last = keys.pop();
|
|
343
|
+
let node = values;
|
|
344
|
+
for (const key of keys) node = node[key] ??= {};
|
|
345
|
+
node[last] = value;
|
|
346
|
+
}
|
|
347
|
+
return values;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
// Shows and hides the fields that have `show`, and writes the labels that are functions
|
|
351
|
+
const arrange = () => {
|
|
352
|
+
const raw = getRawValues();
|
|
353
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
354
|
+
const definition = definitions[name];
|
|
355
|
+
if (definition.show) {
|
|
356
|
+
shown[name] = Boolean(definition.show(raw));
|
|
357
|
+
field.element.hidden = !shown[name];
|
|
358
|
+
}
|
|
359
|
+
if (typeof definition.label === "function") field.setLabel(definition.label(raw));
|
|
360
|
+
}
|
|
361
|
+
};
|
|
304
362
|
|
|
305
363
|
for (const definition of options.fields ?? []) {
|
|
364
|
+
definitions[definition.name] = definition;
|
|
365
|
+
shown[definition.name] = true;
|
|
306
366
|
const field = generateField({
|
|
307
367
|
...definition,
|
|
368
|
+
label: typeof definition.label === "function" ? definition.label({}) : definition.label,
|
|
308
369
|
parent: element,
|
|
309
|
-
getValues,
|
|
370
|
+
getValues: getRawValues,
|
|
310
371
|
onChange: (value, source) => {
|
|
311
372
|
definition.onChange?.(value, source);
|
|
373
|
+
arrange();
|
|
312
374
|
options.onChange?.(getValues(), source);
|
|
313
375
|
}
|
|
314
376
|
});
|
|
@@ -326,6 +388,8 @@ export function generateForm(options = {}) {
|
|
|
326
388
|
element,
|
|
327
389
|
fields,
|
|
328
390
|
getValues,
|
|
391
|
+
getRawValues,
|
|
392
|
+
arrange,
|
|
329
393
|
submitButton,
|
|
330
394
|
setValues(values) {
|
|
331
395
|
for (const [name, value] of Object.entries(values)) fields[name]?.setValue(value);
|
|
@@ -343,6 +407,7 @@ export function generateForm(options = {}) {
|
|
|
343
407
|
validate() {
|
|
344
408
|
const errors = {};
|
|
345
409
|
for (const [name, field] of Object.entries(fields)) {
|
|
410
|
+
if (shown[name] === false) continue;
|
|
346
411
|
const error = field.validate();
|
|
347
412
|
if (error) errors[name] = error;
|
|
348
413
|
}
|
|
@@ -359,7 +424,9 @@ export function generateForm(options = {}) {
|
|
|
359
424
|
element.addEventListener("reset", () => queueMicrotask(() => {
|
|
360
425
|
Object.values(fields).forEach(field => field.resetState());
|
|
361
426
|
form.setMessage("");
|
|
427
|
+
arrange();
|
|
362
428
|
}));
|
|
429
|
+
arrange();
|
|
363
430
|
element.addEventListener("submit", async event => {
|
|
364
431
|
event.preventDefault();
|
|
365
432
|
form.setMessage("");
|
|
@@ -368,7 +435,21 @@ export function generateForm(options = {}) {
|
|
|
368
435
|
submitButton.setLoading(true);
|
|
369
436
|
await options.onSubmit?.(getValues(), form);
|
|
370
437
|
} catch (error) {
|
|
371
|
-
|
|
438
|
+
const details = error?.details && typeof error.details === "object" ? error.details : null;
|
|
439
|
+
if (!details) form.setMessage(error?.message ?? String(error));
|
|
440
|
+
else {
|
|
441
|
+
// The messages at their fields; what has no field, and the error itself when no field shows anything, in the message of the form
|
|
442
|
+
const rest = [];
|
|
443
|
+
let marked = false;
|
|
444
|
+
for (const [name, text] of Object.entries(details)) {
|
|
445
|
+
if (fields[name] && shown[name] !== false) {
|
|
446
|
+
fields[name].setError(String(text));
|
|
447
|
+
marked = true;
|
|
448
|
+
} else rest.push(String(text));
|
|
449
|
+
}
|
|
450
|
+
const text = [marked && !rest.length ? "" : error.message, ...rest].filter(Boolean).join(": ");
|
|
451
|
+
form.setMessage(text || translate("form.checkFields"));
|
|
452
|
+
}
|
|
372
453
|
} finally {
|
|
373
454
|
submitButton.setLoading(false);
|
|
374
455
|
}
|
|
@@ -34,7 +34,10 @@ const compare = (a, b) =>
|
|
|
34
34
|
* @param {string} [options.id] id of the table wrapper (default: "table")
|
|
35
35
|
* @param {string} [options.class] extra CSS class of the table
|
|
36
36
|
* @param {string} [options.caption]
|
|
37
|
-
* @param {{key: string, label?: string, width?: number, sortable?: boolean, editable?: boolean,
|
|
37
|
+
* @param {{key: string, label?: string, width?: number, sortable?: boolean, editable?: boolean, align?: "left"|"center"|"right", title?: boolean,
|
|
38
|
+
* format?: (value, row) => string, render?: (row: object, value) => (string|Node)}[]} options.columns
|
|
39
|
+
* `format` writes the text of a cell; `render` builds its content instead (a badge, a link, buttons: an element, or text). Every cell carries its column
|
|
40
|
+
* label in `data-label`, so a stylesheet can show a row as a block on a narrow screen, with the label next to the value.
|
|
38
41
|
* @param {object[]} [options.rows] row objects, read by column key
|
|
39
42
|
* @param {boolean} [options.sortable=true] click on a header sorts by it
|
|
40
43
|
* @param {boolean} [options.filter=false] show a text filter above the table
|
|
@@ -411,6 +414,7 @@ export function generateTable(options = {}) {
|
|
|
411
414
|
const value = row[col.key];
|
|
412
415
|
const content = col.render ? col.render(row, value) : (col.format ? col.format(value, row) : (value ?? ""));
|
|
413
416
|
const td = el("td");
|
|
417
|
+
td.dataset.label = col.label ?? col.key;
|
|
414
418
|
if (content instanceof Node) td.append(content);
|
|
415
419
|
else {
|
|
416
420
|
td.textContent = content;
|