athena-ui-js 2.5.1 → 2.6.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.
@@ -1,460 +1,470 @@
1
- //formBuilder 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 { createCombobox } from "../../core/combobox.js";
7
- import { createDateRange } from "../../core/dateRange.js";
8
- import { asHandle, cx, el, mount, uid } from "../../core/dom.js";
9
- import { translate } from "../../core/i18n.js";
10
- import { validateDateRange, validateValue } from "../../core/validation.js";
11
- import { createRichText, createWysiwyg } from "../inputGenerator/richTextGenerator.js";
12
-
13
- const INPUT_TYPES = new Set([
14
- "text", "password", "email", "number", "date", "datetime-local", "time", "month", "week",
15
- "url", "tel", "search", "color", "range", "file", "hidden"
16
- ]);
17
- const RULE_KEYS = ["required", "email", "minLength", "maxLength", "pattern", "min", "max", "match", "validate"];
18
-
19
- /* ------------------BUTTON------------------- */
20
-
21
- /**
22
- * Generates a button.
23
- *
24
- * @param {object} options
25
- * @param {string|Element} [options.parent] id or element, defaults to the body
26
- * @param {string} [options.id]
27
- * @param {string} [options.text]
28
- * @param {"primary"|"secondary"|"danger"|"link"} [options.variant="primary"]
29
- * @param {"button"|"submit"|"reset"} [options.type="button"]
30
- * @param {"small"|"large"} [options.size]
31
- * @param {boolean} [options.disabled]
32
- * @param {boolean} [options.loading] shows a spinner and blocks clicks
33
- * @param {(event: Event) => void} [options.onclick]
34
- * @returns {{element: HTMLButtonElement, setLoading: Function, setDisabled: Function, setText: Function}}
35
- */
36
- export function generateButton(options = {}) {
37
- const { variant = "primary", type = "button", size, onclick } = options;
38
- let disabled = Boolean(options.disabled);
39
- let loading = false;
40
- const label = el("span", { class: "button-text", text: options.text ?? "" });
41
- const element = el("button", {
42
- id: options.id,
43
- class: cx("athena-button", `button-${variant}`, size && `button-${size}`, options.class),
44
- attrs: { type }
45
- }, label);
46
- if (onclick) element.addEventListener("click", event => { if (!loading) onclick(event); });
47
-
48
- const sync = () => {
49
- element.disabled = disabled || loading;
50
- element.toggleAttribute("aria-busy", loading);
51
- element.classList.toggle("button-loading", loading);
52
- element.querySelector(".spinner")?.remove();
53
- if (loading) element.prepend(el("span", { class: "spinner spinner-small", attrs: { "aria-hidden": "true" } }));
54
- };
55
- sync();
56
- if (options.loading) {
57
- loading = true;
58
- sync();
59
- }
60
- mount(options.parent, element);
61
- return asHandle({
62
- element,
63
- setLoading(value) {
64
- loading = Boolean(value);
65
- sync();
66
- },
67
- setDisabled(value) {
68
- disabled = Boolean(value);
69
- sync();
70
- },
71
- setText(text) {
72
- label.textContent = text;
73
- }
74
- });
75
- }
76
-
77
- /* ------------------FIELD------------------- */
78
-
79
- function choiceList(wrapper, kind, name, choices, value) {
80
- const inputs = choices.map(choice => {
81
- const item = typeof choice === "object" ? choice : { value: choice, text: choice };
82
- const input = el("input", {
83
- attrs: { type: kind, name, value: item.value, disabled: item.disabled },
84
- prop: { checked: kind === "radio" ? item.value === value : Array.isArray(value) && value.includes(item.value) }
85
- });
86
- wrapper.append(el("label", { class: "choice" }, input, el("span", { text: item.text ?? item.value })));
87
- return input;
88
- });
89
- return inputs;
90
- }
91
-
92
- /**
93
- * Generates one labelled form field with help text and an error line.
94
- *
95
- * @param {object} options
96
- * @param {string} options.name key of the field in the form values
97
- * @param {"text"|"password"|"email"|"number"|"date"|"datetime-local"|"time"|"url"|"tel"|"search"|"color"|"range"|"file"|"hidden"|"textarea"|"select"|"checkbox"|"switch"|"radio"|"checkboxes"|"autocomplete"|"multiselect"|"daterange"|"richtext"|"wysiwyg"} [options.type="text"]
98
- * @param {string} [options.label]
99
- * @param {string} [options.help] help text under the control
100
- * @param {*} [options.value] initial value (boolean for checkbox / switch, array for checkboxes / multiple select)
101
- * @param {(string|{value: string, text?: string, disabled?: boolean})[]} [options.options] choices of select / radio / checkboxes
102
- * @param {boolean} [options.multiple] select / file: allow several values
103
- * @param {string} [options.placeholder]
104
- * @param {number} [options.rows] textarea rows
105
- * @param {object} [options.rules] validation rules, see validateValue. They can also be given directly
106
- * (required, email, minLength, ...)
107
- * @param {(value, field) => void} [options.onChange]
108
- * @param {() => object} [options.getValues] all form values (set by generateForm, used by `match`)
109
- * @returns {{element: HTMLElement, name: string, getValue: Function, setValue: Function, validate: Function,
110
- * setError: Function, focus: Function}}
111
- */
112
- export function generateField(options = {}) {
113
- const { name, type = "text", label, help, placeholder, onChange } = options;
114
- const rules = { ...Object.fromEntries(RULE_KEYS.filter(key => options[key] != null).map(key => [key, options[key]])), ...options.rules };
115
- if (type === "email") rules.email = true;
116
- // min / max of a date range are dates, not the numeric rules
117
- if (type === "daterange") {
118
- delete rules.min;
119
- delete rules.max;
120
- }
121
- const id = options.id ?? uid("field");
122
- const helpId = `${id}-help`;
123
- const errorId = `${id}-error`;
124
- const choiceName = uid("choice");
125
-
126
- const wrapper = el("div", { class: cx("field", `field-${type}`, options.class), attrs: { "data-name": name } });
127
- const grouped = type === "radio" || type === "checkboxes";
128
- const inline = type === "checkbox" || type === "switch";
129
- const caption = label == null ? null : el("span", { class: "field-label-text", text: label });
130
- if (caption && rules.required) caption.append(el("span", { class: "field-required", text: " *", attrs: { "aria-hidden": "true" } }));
131
-
132
- let controls;
133
- let controlNodes;
134
- let getValue;
135
- let setValue;
136
- const events = ["input", "change"];
137
- const container = grouped ? el("fieldset", { class: "field-group" }, el("legend", {}, caption ?? "")) : wrapper;
138
-
139
- if (type === "textarea") {
140
- const control = el("textarea", { id, attrs: { name, placeholder, rows: options.rows ?? 3 }, prop: { value: options.value ?? "" } });
141
- controls = [control];
142
- getValue = () => control.value;
143
- setValue = value => { control.value = value ?? ""; };
144
- } else if (type === "select") {
145
- const control = el("select", { id, attrs: { name, multiple: options.multiple } });
146
- if (placeholder && !options.multiple) control.append(el("option", { text: placeholder, attrs: { value: "" } }));
147
- for (const choice of options.options ?? []) {
148
- const item = typeof choice === "object" ? choice : { value: choice, text: choice };
149
- control.append(el("option", { text: item.text ?? item.value, attrs: { value: item.value, disabled: item.disabled } }));
150
- }
151
- controls = [control];
152
- getValue = () => options.multiple ? [...control.selectedOptions].map(o => o.value) : control.value;
153
- setValue = value => {
154
- const wanted = [].concat(value ?? "");
155
- [...control.options].forEach(o => { o.selected = wanted.includes(o.value); });
156
- };
157
- setValue(options.value);
158
- } else if (inline) {
159
- const control = el("input", { id, attrs: { type: "checkbox", name, role: type === "switch" ? "switch" : null }, prop: { checked: Boolean(options.value) } });
160
- controls = [control];
161
- getValue = () => control.checked;
162
- setValue = value => { control.checked = Boolean(value); };
163
- } else if (grouped) {
164
- const kind = type === "radio" ? "radio" : "checkbox";
165
- const list = el("div", { class: "choices" });
166
- controls = choiceList(list, kind, choiceName, options.options ?? [], options.value);
167
- container.append(list);
168
- getValue = () => kind === "radio"
169
- ? (controls.find(input => input.checked)?.value ?? "")
170
- : controls.filter(input => input.checked).map(input => input.value);
171
- setValue = value => controls.forEach(input => {
172
- input.checked = kind === "radio" ? input.value === value : [].concat(value ?? []).includes(input.value);
173
- });
174
- } else if (type === "autocomplete" || type === "multiselect") {
175
- const combo = createCombobox({
176
- id, name, placeholder, options: options.options, multiple: type === "multiselect",
177
- minChars: options.minChars, strict: options.strict, value: options.value, disabled: options.disabled
178
- });
179
- controls = [combo.input];
180
- controlNodes = [combo.element];
181
- getValue = combo.getValue;
182
- setValue = combo.setValue;
183
- } else if (type === "daterange") {
184
- const range = createDateRange({ id, name, value: options.value, min: options.min, max: options.max, disabled: options.disabled });
185
- controls = range.inputs;
186
- controlNodes = [range.element];
187
- getValue = range.getValue;
188
- setValue = range.setValue;
189
- } else if (type === "richtext" || type === "wysiwyg") {
190
- const rich = (type === "wysiwyg" ? createWysiwyg : createRichText)({
191
- id, value: options.value, placeholder, minHeight: options.minHeight, toolbar: options.toolbar, disabled: options.disabled
192
- });
193
- rich.editor.setAttribute("aria-labelledby", `${id}-label`);
194
- controls = [rich.editor];
195
- controlNodes = [rich.element];
196
- getValue = rich.getValue;
197
- setValue = rich.setValue;
198
- } else if (INPUT_TYPES.has(type)) {
199
- const control = el("input", { id, attrs: { type, name, placeholder, multiple: options.multiple, accept: options.accept, min: options.min, max: options.max, step: options.step, autocomplete: options.autocomplete } });
200
- if (type !== "file" && options.value != null) control.value = options.value;
201
- controls = [control];
202
- if (type === "file") {
203
- getValue = () => [...control.files];
204
- setValue = () => {};
205
- } else if (type === "number" || type === "range") {
206
- getValue = () => control.value === "" ? "" : control.valueAsNumber;
207
- setValue = value => { control.value = value ?? ""; };
208
- } else {
209
- getValue = () => control.value;
210
- setValue = value => { control.value = value ?? ""; };
211
- }
212
- } else {
213
- throw new Error(`Athena UI: unknown field type "${type}"`);
214
- }
215
-
216
- for (const control of controls) {
217
- control.disabled = Boolean(options.disabled);
218
- if (!grouped) control.id = control.id || id;
219
- }
220
-
221
- // Markup: label above the control, a checkbox / switch label wraps its control.
222
- const errorEl = el("div", { class: "field-error", id: errorId, attrs: { role: "alert" } });
223
- const helpEl = help ? el("div", { class: "field-help", id: helpId, text: help }) : null;
224
- if (inline) {
225
- const track = type === "switch" ? el("span", { class: "switch-track", attrs: { "aria-hidden": "true" } }) : null;
226
- wrapper.append(el("label", { class: cx("choice", type === "switch" && "switch"), attrs: { for: id } }, controls[0], track ?? "", caption ?? ""));
227
- } else if (grouped) {
228
- wrapper.append(container);
229
- } else {
230
- if (caption) wrapper.append(el("label", { class: "field-label", id: `${id}-label`, attrs: { for: id } }, caption));
231
- wrapper.append(...(controlNodes ?? controls));
232
- }
233
- if (helpEl) wrapper.append(helpEl);
234
- wrapper.append(errorEl);
235
- for (const control of controls) control.setAttribute("aria-describedby", [helpEl && helpId, errorId].filter(Boolean).join(" "));
236
- if (rules.required && type !== "checkbox") controls.forEach(control => control.setAttribute("aria-required", "true"));
237
- mount(options.parent, wrapper);
238
-
239
- let touched = false;
240
- const field = {
241
- element: wrapper,
242
- name,
243
- getValue,
244
- setValue(value) {
245
- setValue(value);
246
- field.setError("");
247
- },
248
- setError(message) {
249
- errorEl.textContent = message;
250
- wrapper.classList.toggle("field-invalid", Boolean(message));
251
- controls.forEach(control => control.setAttribute("aria-invalid", message ? "true" : "false"));
252
- },
253
- validate() {
254
- const values = options.getValues?.() ?? { [name]: getValue() };
255
- const value = getValue();
256
- // A date range counts as filled when both dates are given.
257
- const filled = type === "daterange" && !(value.from && value.to) ? "" : value;
258
- let error = validateValue(filled, rules, values);
259
- if (!error && type === "daterange") error = validateDateRange(value.from, value.to, { min: options.min, max: options.max });
260
- field.setError(error);
261
- return error;
262
- },
263
- focus() {
264
- controls[0]?.focus();
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
- },
270
- resetState() {
271
- touched = false;
272
- field.setError("");
273
- }
274
- };
275
-
276
- // Validate when the user leaves the field, then live on every change.
277
- controls.forEach(control => {
278
- control.addEventListener("blur", () => { touched = true; field.validate(); });
279
- events.forEach(event => control.addEventListener(event, () => {
280
- if (touched) field.validate();
281
- if (event === "change" || event === "input") onChange?.(getValue(), field);
282
- }));
283
- });
284
- return asHandle(field);
285
- }
286
-
287
- /* ------------------FORM------------------- */
288
-
289
- /**
290
- * Generates a form from a list of field definitions.
291
- *
292
- * @param {object} options
293
- * @param {string|Element} [options.parent]
294
- * @param {string} [options.id]
295
- * @param {object[]} options.fields field definitions, see generateField
296
- * @param {string} [options.submitText]
297
- * @param {string|false} [options.resetText] adds a reset button when set
298
- * @param {(values: object, form: object) => (void|Promise)} [options.onSubmit] called with the values when every
299
- * field is valid. A returned promise keeps the submit button busy; a rejection is shown as form message.
300
- * @param {(values: object, field: object) => void} [options.onChange]
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}}
315
- */
316
- export function generateForm(options = {}) {
317
- const element = el("form", { id: options.id, class: cx("athena-form", options.class), attrs: { novalidate: true } });
318
- const fields = {};
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
- };
362
-
363
- for (const definition of options.fields ?? []) {
364
- definitions[definition.name] = definition;
365
- shown[definition.name] = true;
366
- const field = generateField({
367
- ...definition,
368
- label: typeof definition.label === "function" ? definition.label({}) : definition.label,
369
- parent: element,
370
- getValues: getRawValues,
371
- onChange: (value, source) => {
372
- definition.onChange?.(value, source);
373
- arrange();
374
- options.onChange?.(getValues(), source);
375
- }
376
- });
377
- fields[definition.name] = field;
378
- }
379
-
380
- const message = el("div", { class: "form-message", attrs: { role: "status" } });
381
- element.append(message);
382
- const actions = el("div", { class: "form-actions" });
383
- element.append(actions);
384
- const submitButton = generateButton({ parent: actions, text: options.submitText ?? translate("ok"), type: "submit" });
385
- if (options.resetText) generateButton({ parent: actions, text: options.resetText, type: "reset", variant: "secondary" });
386
-
387
- const form = {
388
- element,
389
- fields,
390
- getValues,
391
- getRawValues,
392
- arrange,
393
- submitButton,
394
- setValues(values) {
395
- for (const [name, value] of Object.entries(values)) fields[name]?.setValue(value);
396
- },
397
- // Shows server side errors: { username: "Already taken" }
398
- setErrors(errors) {
399
- for (const [name, text] of Object.entries(errors)) fields[name]?.setError(text);
400
- },
401
- setMessage(text, isError = true) {
402
- message.textContent = text;
403
- message.classList.toggle("form-message-error", isError && Boolean(text));
404
- message.classList.toggle("form-message-success", !isError && Boolean(text));
405
- },
406
- // Validates every field, focuses the first invalid one. Returns the errors by field name.
407
- validate() {
408
- const errors = {};
409
- for (const [name, field] of Object.entries(fields)) {
410
- if (shown[name] === false) continue;
411
- const error = field.validate();
412
- if (error) errors[name] = error;
413
- }
414
- fields[Object.keys(errors)[0]]?.focus();
415
- return errors;
416
- },
417
- reset() {
418
- element.reset();
419
- Object.values(fields).forEach(field => field.resetState());
420
- form.setMessage("");
421
- }
422
- };
423
-
424
- element.addEventListener("reset", () => queueMicrotask(() => {
425
- Object.values(fields).forEach(field => field.resetState());
426
- form.setMessage("");
427
- arrange();
428
- }));
429
- arrange();
430
- element.addEventListener("submit", async event => {
431
- event.preventDefault();
432
- form.setMessage("");
433
- if (Object.keys(form.validate()).length) return;
434
- try {
435
- submitButton.setLoading(true);
436
- await options.onSubmit?.(getValues(), form);
437
- } catch (error) {
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
- }
453
- } finally {
454
- submitButton.setLoading(false);
455
- }
456
- });
457
-
458
- mount(options.parent, element);
459
- return asHandle(form);
460
- }
1
+ //formBuilder 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 { createCombobox } from "../../core/combobox.js";
7
+ import { createDateRange } from "../../core/dateRange.js";
8
+ import { asHandle, cx, el, mount, uid } from "../../core/dom.js";
9
+ import { translate } from "../../core/i18n.js";
10
+ import { validateDateRange, validateValue } from "../../core/validation.js";
11
+ import { createRichText, createWysiwyg } from "../inputGenerator/richTextGenerator.js";
12
+
13
+ const INPUT_TYPES = new Set([
14
+ "text", "password", "email", "number", "date", "datetime-local", "time", "month", "week",
15
+ "url", "tel", "search", "color", "range", "file", "hidden"
16
+ ]);
17
+ const RULE_KEYS = ["required", "email", "minLength", "maxLength", "pattern", "min", "max", "match", "validate"];
18
+
19
+ /* ------------------BUTTON------------------- */
20
+
21
+ /**
22
+ * Generates a button.
23
+ *
24
+ * @param {object} options
25
+ * @param {string|Element} [options.parent] id or element, defaults to the body
26
+ * @param {string} [options.id]
27
+ * @param {string} [options.text]
28
+ * @param {"primary"|"secondary"|"danger"|"link"} [options.variant="primary"]
29
+ * @param {"button"|"submit"|"reset"} [options.type="button"]
30
+ * @param {"small"|"large"} [options.size]
31
+ * @param {boolean} [options.disabled]
32
+ * @param {boolean} [options.loading] shows a spinner and blocks clicks
33
+ * @param {(event: Event) => void} [options.onclick]
34
+ * @returns {{element: HTMLButtonElement, setLoading: Function, setDisabled: Function, setText: Function}}
35
+ */
36
+ export function generateButton(options = {}) {
37
+ const { variant = "primary", type = "button", size, onclick } = options;
38
+ let disabled = Boolean(options.disabled);
39
+ let loading = false;
40
+ const label = el("span", { class: "button-text", text: options.text ?? "" });
41
+ const element = el("button", {
42
+ id: options.id,
43
+ class: cx("athena-button", `button-${variant}`, size && `button-${size}`, options.class),
44
+ attrs: { type }
45
+ }, label);
46
+ if (onclick) element.addEventListener("click", event => { if (!loading) onclick(event); });
47
+
48
+ const sync = () => {
49
+ element.disabled = disabled || loading;
50
+ element.toggleAttribute("aria-busy", loading);
51
+ element.classList.toggle("button-loading", loading);
52
+ element.querySelector(".spinner")?.remove();
53
+ if (loading) element.prepend(el("span", { class: "spinner spinner-small", attrs: { "aria-hidden": "true" } }));
54
+ };
55
+ sync();
56
+ if (options.loading) {
57
+ loading = true;
58
+ sync();
59
+ }
60
+ mount(options.parent, element);
61
+ return asHandle({
62
+ element,
63
+ setLoading(value) {
64
+ loading = Boolean(value);
65
+ sync();
66
+ },
67
+ setDisabled(value) {
68
+ disabled = Boolean(value);
69
+ sync();
70
+ },
71
+ setText(text) {
72
+ label.textContent = text;
73
+ }
74
+ });
75
+ }
76
+
77
+ /* ------------------FIELD------------------- */
78
+
79
+ function choiceList(wrapper, kind, name, choices, value) {
80
+ const inputs = choices.map(choice => {
81
+ const item = typeof choice === "object" ? choice : { value: choice, text: choice };
82
+ const input = el("input", {
83
+ attrs: { type: kind, name, value: item.value, disabled: item.disabled },
84
+ prop: { checked: kind === "radio" ? item.value === value : Array.isArray(value) && value.includes(item.value) }
85
+ });
86
+ wrapper.append(el("label", { class: "choice" }, input, el("span", { text: item.text ?? item.value })));
87
+ return input;
88
+ });
89
+ return inputs;
90
+ }
91
+
92
+ /**
93
+ * Generates one labelled form field with help text and an error line.
94
+ *
95
+ * @param {object} options
96
+ * @param {string} options.name key of the field in the form values
97
+ * @param {"text"|"password"|"email"|"number"|"date"|"datetime-local"|"time"|"url"|"tel"|"search"|"color"|"range"|"file"|"hidden"|"textarea"|"select"|"checkbox"|"switch"|"radio"|"checkboxes"|"autocomplete"|"multiselect"|"daterange"|"richtext"|"wysiwyg"} [options.type="text"]
98
+ * @param {string} [options.label]
99
+ * @param {string} [options.help] help text under the control
100
+ * @param {*} [options.value] initial value (boolean for checkbox / switch, array for checkboxes / multiple select)
101
+ * @param {(string|{value: string, text?: string, disabled?: boolean})[]} [options.options] choices of select / radio / checkboxes
102
+ * @param {boolean} [options.multiple] select / file: allow several values
103
+ * @param {string} [options.placeholder]
104
+ * @param {number} [options.rows] textarea rows
105
+ * @param {object} [options.rules] validation rules, see validateValue. They can also be given directly
106
+ * (required, email, minLength, ...)
107
+ * @param {(value, field) => void} [options.onChange]
108
+ * @param {() => object} [options.getValues] all form values (set by generateForm, used by `match`)
109
+ * @returns {{element: HTMLElement, name: string, getValue: Function, setValue: Function, validate: Function,
110
+ * setError: Function, focus: Function}}
111
+ */
112
+ export function generateField(options = {}) {
113
+ const { name, type = "text", label, help, placeholder, onChange } = options;
114
+ const rules = { ...Object.fromEntries(RULE_KEYS.filter(key => options[key] != null).map(key => [key, options[key]])), ...options.rules };
115
+ if (type === "email") rules.email = true;
116
+ // min / max of a date range are dates, not the numeric rules
117
+ if (type === "daterange") {
118
+ delete rules.min;
119
+ delete rules.max;
120
+ }
121
+ const id = options.id ?? uid("field");
122
+ const helpId = `${id}-help`;
123
+ const errorId = `${id}-error`;
124
+ const choiceName = uid("choice");
125
+
126
+ const wrapper = el("div", { class: cx("field", `field-${type}`, options.class), attrs: { "data-name": name } });
127
+ const grouped = type === "radio" || type === "checkboxes";
128
+ const inline = type === "checkbox" || type === "switch";
129
+ const caption = label == null ? null : el("span", { class: "field-label-text", text: label });
130
+ if (caption && rules.required) caption.append(el("span", { class: "field-required", text: " *", attrs: { "aria-hidden": "true" } }));
131
+
132
+ let controls;
133
+ let controlNodes;
134
+ let getValue;
135
+ let setValue;
136
+ const events = ["input", "change"];
137
+ const container = grouped ? el("fieldset", { class: "field-group" }, el("legend", {}, caption ?? "")) : wrapper;
138
+
139
+ if (type === "textarea") {
140
+ const control = el("textarea", { id, attrs: { name, placeholder, rows: options.rows ?? 3 }, prop: { value: options.value ?? "" } });
141
+ controls = [control];
142
+ getValue = () => control.value;
143
+ setValue = value => { control.value = value ?? ""; };
144
+ } else if (type === "select") {
145
+ const control = el("select", { id, attrs: { name, multiple: options.multiple } });
146
+ if (placeholder && !options.multiple) control.append(el("option", { text: placeholder, attrs: { value: "" } }));
147
+ for (const choice of options.options ?? []) {
148
+ const item = typeof choice === "object" ? choice : { value: choice, text: choice };
149
+ control.append(el("option", { text: item.text ?? item.value, attrs: { value: item.value, disabled: item.disabled } }));
150
+ }
151
+ controls = [control];
152
+ getValue = () => options.multiple ? [...control.selectedOptions].map(o => o.value) : control.value;
153
+ setValue = value => {
154
+ const wanted = [].concat(value ?? "");
155
+ [...control.options].forEach(o => { o.selected = wanted.includes(o.value); });
156
+ };
157
+ setValue(options.value);
158
+ } else if (inline) {
159
+ const control = el("input", { id, attrs: { type: "checkbox", name, role: type === "switch" ? "switch" : null }, prop: { checked: Boolean(options.value) } });
160
+ controls = [control];
161
+ getValue = () => control.checked;
162
+ setValue = value => { control.checked = Boolean(value); };
163
+ } else if (grouped) {
164
+ const kind = type === "radio" ? "radio" : "checkbox";
165
+ const list = el("div", { class: "choices" });
166
+ controls = choiceList(list, kind, choiceName, options.options ?? [], options.value);
167
+ container.append(list);
168
+ getValue = () => kind === "radio"
169
+ ? (controls.find(input => input.checked)?.value ?? "")
170
+ : controls.filter(input => input.checked).map(input => input.value);
171
+ setValue = value => controls.forEach(input => {
172
+ input.checked = kind === "radio" ? input.value === value : [].concat(value ?? []).includes(input.value);
173
+ });
174
+ } else if (type === "autocomplete" || type === "multiselect") {
175
+ const combo = createCombobox({
176
+ id, name, placeholder, options: options.options, multiple: type === "multiselect",
177
+ minChars: options.minChars, strict: options.strict, value: options.value, disabled: options.disabled
178
+ });
179
+ controls = [combo.input];
180
+ controlNodes = [combo.element];
181
+ getValue = combo.getValue;
182
+ setValue = combo.setValue;
183
+ } else if (type === "daterange") {
184
+ const range = createDateRange({ id, name, value: options.value, min: options.min, max: options.max, disabled: options.disabled });
185
+ controls = range.inputs;
186
+ controlNodes = [range.element];
187
+ getValue = range.getValue;
188
+ setValue = range.setValue;
189
+ } else if (type === "richtext" || type === "wysiwyg") {
190
+ const rich = (type === "wysiwyg" ? createWysiwyg : createRichText)({
191
+ id, value: options.value, placeholder, minHeight: options.minHeight, toolbar: options.toolbar, disabled: options.disabled
192
+ });
193
+ rich.editor.setAttribute("aria-labelledby", `${id}-label`);
194
+ controls = [rich.editor];
195
+ controlNodes = [rich.element];
196
+ getValue = rich.getValue;
197
+ setValue = rich.setValue;
198
+ } else if (INPUT_TYPES.has(type)) {
199
+ const control = el("input", { id, attrs: { type, name, placeholder, multiple: options.multiple, accept: options.accept, min: options.min, max: options.max, step: options.step, autocomplete: options.autocomplete } });
200
+ if (type !== "file" && options.value != null) control.value = options.value;
201
+ controls = [control];
202
+ if (type === "file") {
203
+ getValue = () => [...control.files];
204
+ setValue = () => {};
205
+ } else if (type === "number" || type === "range") {
206
+ getValue = () => control.value === "" ? "" : control.valueAsNumber;
207
+ setValue = value => { control.value = value ?? ""; };
208
+ } else {
209
+ getValue = () => control.value;
210
+ setValue = value => { control.value = value ?? ""; };
211
+ }
212
+ } else {
213
+ throw new Error(`Athena UI: unknown field type "${type}"`);
214
+ }
215
+
216
+ for (const control of controls) {
217
+ control.disabled = Boolean(options.disabled);
218
+ if (!grouped) control.id = control.id || id;
219
+ }
220
+
221
+ // Markup: label above the control, a checkbox / switch label wraps its control.
222
+ const errorEl = el("div", { class: "field-error", id: errorId, attrs: { role: "alert" } });
223
+ const helpEl = help ? el("div", { class: "field-help", id: helpId, text: help }) : null;
224
+ if (inline) {
225
+ const track = type === "switch" ? el("span", { class: "switch-track", attrs: { "aria-hidden": "true" } }) : null;
226
+ wrapper.append(el("label", { class: cx("choice", type === "switch" && "switch"), attrs: { for: id } }, controls[0], track ?? "", caption ?? ""));
227
+ } else if (grouped) {
228
+ wrapper.append(container);
229
+ } else {
230
+ if (caption) wrapper.append(el("label", { class: "field-label", id: `${id}-label`, attrs: { for: id } }, caption));
231
+ wrapper.append(...(controlNodes ?? controls));
232
+ }
233
+ if (helpEl) wrapper.append(helpEl);
234
+ wrapper.append(errorEl);
235
+ for (const control of controls) control.setAttribute("aria-describedby", [helpEl && helpId, errorId].filter(Boolean).join(" "));
236
+ if (rules.required && type !== "checkbox") controls.forEach(control => control.setAttribute("aria-required", "true"));
237
+ mount(options.parent, wrapper);
238
+
239
+ let touched = false;
240
+ const field = {
241
+ element: wrapper,
242
+ name,
243
+ getValue,
244
+ setValue(value) {
245
+ setValue(value);
246
+ field.setError("");
247
+ },
248
+ setError(message) {
249
+ errorEl.textContent = message;
250
+ wrapper.classList.toggle("field-invalid", Boolean(message));
251
+ controls.forEach(control => control.setAttribute("aria-invalid", message ? "true" : "false"));
252
+ },
253
+ validate() {
254
+ const values = options.getValues?.() ?? { [name]: getValue() };
255
+ const value = getValue();
256
+ // A date range counts as filled when both dates are given.
257
+ const filled = type === "daterange" && !(value.from && value.to) ? "" : value;
258
+ let error = validateValue(filled, rules, values);
259
+ if (!error && type === "daterange") error = validateDateRange(value.from, value.to, { min: options.min, max: options.max });
260
+ field.setError(error);
261
+ return error;
262
+ },
263
+ focus() {
264
+ controls[0]?.focus();
265
+ },
266
+ /** Changes the text of the label (the star of a required field stays). */
267
+ setLabel(text) {
268
+ if (!caption) return;
269
+ text = text == null ? "" : String(text);
270
+ if (caption.firstChild?.nodeType === Node.TEXT_NODE) caption.firstChild.nodeValue = text;
271
+ else caption.prepend(document.createTextNode(text)); // an empty label has no text node yet
272
+ },
273
+ resetState() {
274
+ touched = false;
275
+ field.setError("");
276
+ }
277
+ };
278
+
279
+ // Validate when the user leaves the field, then live on every change.
280
+ controls.forEach(control => {
281
+ control.addEventListener("blur", () => { touched = true; field.validate(); });
282
+ events.forEach(event => control.addEventListener(event, () => {
283
+ if (touched) field.validate();
284
+ if (event === "change" || event === "input") onChange?.(getValue(), field);
285
+ }));
286
+ });
287
+ return asHandle(field);
288
+ }
289
+
290
+ /* ------------------FORM------------------- */
291
+
292
+ /**
293
+ * Generates a form from a list of field definitions.
294
+ *
295
+ * @param {object} options
296
+ * @param {string|Element} [options.parent]
297
+ * @param {string} [options.id]
298
+ * @param {object[]} options.fields field definitions, see generateField
299
+ * @param {string} [options.submitText]
300
+ * @param {string|false} [options.resetText] adds a reset button when set
301
+ * @param {(values: object, form: object) => (void|Promise)} [options.onSubmit] called with the values when every
302
+ * field is valid. A returned promise keeps the submit button busy; a rejection is shown as form message.
303
+ * @param {(values: object, field: object) => void} [options.onChange]
304
+ * @param {boolean} [options.nested=false] a field called "soa.host" is the key `host` of the object `soa` in the values
305
+ *
306
+ * Field definitions can also have these, which only generateForm reads:
307
+ * - `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.
308
+ * - `label: (values) => string`: a label that follows the other fields (`values` are the raw values of every field)
309
+ * - `send: false`: the field is validated but not in the values (the second field of "type the password again")
310
+ * - `trim: true`: a text value is trimmed
311
+ * - `empty: "omit"|"null"|"empty"`: what an empty value (an empty text, a number that is not a number) becomes: left out, null, or "".
312
+ * Without it the value stays as it is.
313
+ *
314
+ * 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
315
+ * of the error when no field shows one, go to the message of the form.
316
+ * @returns {{element: HTMLFormElement, fields: Object<string, object>, getValues: Function, getRawValues: Function, setValues: Function,
317
+ * setErrors: Function, validate: Function, reset: Function, setMessage: Function, arrange: Function, submitButton: object}}
318
+ */
319
+ export function generateForm(options = {}) {
320
+ const element = el("form", { id: options.id, class: cx("athena-form", options.class), attrs: { novalidate: true } });
321
+ const fields = {};
322
+ const definitions = {};
323
+ const shown = {}; // name -> is the field shown (a field without `show` always is)
324
+ // What every field holds, the way it is (the fields read it for `match`, and `show` and `label` get it)
325
+ const getRawValues = () => Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, field.getValue()]));
326
+
327
+ // The values of the form: only the fields that are shown and sent, trimmed and emptied as their definitions say, nested when asked
328
+ const getValues = () => {
329
+ const values = {};
330
+ for (const [name, field] of Object.entries(fields)) {
331
+ const definition = definitions[name];
332
+ if (shown[name] === false || definition.send === false) continue;
333
+ let value = field.getValue();
334
+ if (typeof value === "string" && definition.trim) value = value.trim();
335
+ if (value === "" || value === undefined || Number.isNaN(value)) {
336
+ if (definition.empty === "omit") continue;
337
+ if (definition.empty === "null") value = null;
338
+ else if (definition.empty === "empty") value = "";
339
+ }
340
+ if (!options.nested) {
341
+ values[name] = value;
342
+ continue;
343
+ }
344
+ const keys = name.split(".");
345
+ const last = keys.pop();
346
+ let node = values;
347
+ for (const key of keys) node = node[key] ??= {};
348
+ node[last] = value;
349
+ }
350
+ return values;
351
+ };
352
+
353
+ // Shows and hides the fields that have `show`, and writes the labels that are functions
354
+ const arrange = () => {
355
+ const raw = getRawValues();
356
+ for (const [name, field] of Object.entries(fields)) {
357
+ const definition = definitions[name];
358
+ if (definition.show) {
359
+ shown[name] = Boolean(definition.show(raw));
360
+ field.element.hidden = !shown[name];
361
+ }
362
+ if (typeof definition.label === "function") field.setLabel(definition.label(raw));
363
+ }
364
+ };
365
+
366
+ for (const definition of options.fields ?? []) {
367
+ definitions[definition.name] = definition;
368
+ shown[definition.name] = true;
369
+ const field = generateField({
370
+ ...definition,
371
+ // A label that is a function always gets its caption, even when the first answer is empty: arrange() writes the text
372
+ label: typeof definition.label === "function" ? definition.label({}) ?? "" : definition.label,
373
+ parent: element,
374
+ getValues: getRawValues,
375
+ onChange: (value, source) => {
376
+ definition.onChange?.(value, source);
377
+ arrange();
378
+ options.onChange?.(getValues(), source);
379
+ }
380
+ });
381
+ fields[definition.name] = field;
382
+ }
383
+
384
+ const message = el("div", { class: "form-message", attrs: { role: "status" } });
385
+ element.append(message);
386
+ const actions = el("div", { class: "form-actions" });
387
+ element.append(actions);
388
+ const submitButton = generateButton({ parent: actions, text: options.submitText ?? translate("ok"), type: "submit" });
389
+ if (options.resetText) generateButton({ parent: actions, text: options.resetText, type: "reset", variant: "secondary" });
390
+
391
+ const form = {
392
+ element,
393
+ fields,
394
+ getValues,
395
+ getRawValues,
396
+ arrange,
397
+ submitButton,
398
+ // With `nested`, { soa: { host: "x" } } sets the field "soa.host" (the shape getValues() returns); { "soa.host": "x" } works as well
399
+ setValues(values, prefix = "") {
400
+ for (const [name, value] of Object.entries(values ?? {})) {
401
+ const path = prefix + name;
402
+ if (fields[path]) fields[path].setValue(value);
403
+ else if (options.nested && value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date)) form.setValues(value, path + ".");
404
+ }
405
+ arrange();
406
+ },
407
+ // Shows server side errors: { username: "Already taken" }
408
+ setErrors(errors) {
409
+ for (const [name, text] of Object.entries(errors)) fields[name]?.setError(text);
410
+ },
411
+ setMessage(text, isError = true) {
412
+ message.textContent = text;
413
+ message.classList.toggle("form-message-error", isError && Boolean(text));
414
+ message.classList.toggle("form-message-success", !isError && Boolean(text));
415
+ },
416
+ // Validates every field, focuses the first invalid one. Returns the errors by field name.
417
+ validate() {
418
+ const errors = {};
419
+ for (const [name, field] of Object.entries(fields)) {
420
+ if (shown[name] === false) continue;
421
+ const error = field.validate();
422
+ if (error) errors[name] = error;
423
+ }
424
+ fields[Object.keys(errors)[0]]?.focus();
425
+ return errors;
426
+ },
427
+ reset() {
428
+ element.reset();
429
+ Object.values(fields).forEach(field => field.resetState());
430
+ form.setMessage("");
431
+ }
432
+ };
433
+
434
+ element.addEventListener("reset", () => queueMicrotask(() => {
435
+ Object.values(fields).forEach(field => field.resetState());
436
+ form.setMessage("");
437
+ arrange();
438
+ }));
439
+ arrange();
440
+ element.addEventListener("submit", async event => {
441
+ event.preventDefault();
442
+ form.setMessage("");
443
+ if (Object.keys(form.validate()).length) return;
444
+ try {
445
+ submitButton.setLoading(true);
446
+ await options.onSubmit?.(getValues(), form);
447
+ } catch (error) {
448
+ const details = error?.details && typeof error.details === "object" ? error.details : null;
449
+ if (!details) form.setMessage(error?.message ?? String(error));
450
+ else {
451
+ // The messages at their fields; what has no field, and the error itself when no field shows anything, in the message of the form
452
+ const rest = [];
453
+ let marked = false;
454
+ for (const [name, text] of Object.entries(details)) {
455
+ if (fields[name] && shown[name] !== false) {
456
+ fields[name].setError(String(text));
457
+ marked = true;
458
+ } else rest.push(String(text));
459
+ }
460
+ const text = [marked && !rest.length ? "" : error.message, ...rest].filter(Boolean).join(": ");
461
+ form.setMessage(text || translate("form.checkFields"));
462
+ }
463
+ } finally {
464
+ submitButton.setLoading(false);
465
+ }
466
+ });
467
+
468
+ mount(options.parent, element);
469
+ return asHandle(form);
470
+ }