athena-ui-js 2.4.1 → 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 +10 -2
- package/docs/styling.md +123 -123
- package/package.json +1 -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/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/res/themes/default/style.css +4 -0
- package/types/libs/config/config.d.ts +3 -3
- package/types/libs/hephaestus/chartGenerator/chartGenerator.d.ts +117 -95
- 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
|
@@ -11,7 +11,7 @@ import { getLocale, translate } from "../../core/i18n.js";
|
|
|
11
11
|
|
|
12
12
|
const NS = "http://www.w3.org/2000/svg";
|
|
13
13
|
const SERIES_COLORS = 8;
|
|
14
|
-
const
|
|
14
|
+
const DEFAULT_MARGIN = { top: 40, right: 20, bottom: 50, left: 55 };
|
|
15
15
|
const DOT_LIMIT = 80; // up to this many points in view every point is a dot with a tooltip; more: the tooltip follows the pointer
|
|
16
16
|
|
|
17
17
|
const svgEl = (tag, attrs = {}, text) => {
|
|
@@ -91,6 +91,7 @@ export function decimate(indices, values, buckets) {
|
|
|
91
91
|
/* ------------------PARTS------------------- */
|
|
92
92
|
|
|
93
93
|
function addLegend(svg, entries, width, height, ctx) {
|
|
94
|
+
const MARGIN = ctx.margin;
|
|
94
95
|
let x = MARGIN.left;
|
|
95
96
|
const y = height - 12;
|
|
96
97
|
entries.forEach(({ name, props, series }) => {
|
|
@@ -160,7 +161,7 @@ function addTip(ctx, node, x, y, lines) {
|
|
|
160
161
|
}
|
|
161
162
|
|
|
162
163
|
// Draws the value grid and the y axis for the range [min, min + scale.span].
|
|
163
|
-
function addValueAxis(svg, { min, scale, width, height }) {
|
|
164
|
+
function addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format = formatNumber }) {
|
|
164
165
|
const plotW = width - MARGIN.left - MARGIN.right;
|
|
165
166
|
const plotH = height - MARGIN.top - MARGIN.bottom;
|
|
166
167
|
const y = value => MARGIN.top + plotH - ((value - min) / scale.span) * plotH;
|
|
@@ -168,7 +169,7 @@ function addValueAxis(svg, { min, scale, width, height }) {
|
|
|
168
169
|
for (let i = 0; i <= ticks; i++) {
|
|
169
170
|
const v = min + i * scale.step;
|
|
170
171
|
svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left + plotW, y1: y(v), y2: y(v), class: "chart-grid" }));
|
|
171
|
-
svg.append(svgEl("text", { x: MARGIN.left - 8, y: y(v) + 4, "text-anchor": "end", class: "chart-tick" },
|
|
172
|
+
svg.append(svgEl("text", { x: MARGIN.left - 8, y: y(v) + 4, "text-anchor": "end", class: "chart-tick" }, format(v)));
|
|
172
173
|
}
|
|
173
174
|
svg.append(svgEl("line", { x1: MARGIN.left, x2: MARGIN.left, y1: MARGIN.top, y2: MARGIN.top + plotH, class: "chart-axis" }));
|
|
174
175
|
// The category axis sits at zero when the range includes it, so negative bars hang below it.
|
|
@@ -190,9 +191,10 @@ function valueRange(values, zero = true) {
|
|
|
190
191
|
/* ------------------DRAWERS------------------- */
|
|
191
192
|
|
|
192
193
|
function drawBar(svg, ctx) {
|
|
193
|
-
const { labels, series, width, height } = ctx;
|
|
194
|
+
const { labels, series, width, height, format } = ctx;
|
|
195
|
+
const MARGIN = ctx.margin;
|
|
194
196
|
const { min, scale } = valueRange(series.flatMap(s => s.data));
|
|
195
|
-
const { y, plotW, plotH } = addValueAxis(svg, { min, scale, width, height });
|
|
197
|
+
const { y, plotW, plotH } = addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format: ctx.tickFormat });
|
|
196
198
|
const band = plotW / Math.max(labels.length, 1);
|
|
197
199
|
labels.forEach((label, i) => svg.append(svgEl("text",
|
|
198
200
|
{ x: MARGIN.left + band * (i + 0.5), y: MARGIN.top + plotH + 18, "text-anchor": "middle", class: "chart-tick" }, label)));
|
|
@@ -206,19 +208,21 @@ function drawBar(svg, ctx) {
|
|
|
206
208
|
"data-series": si, ...seriesProps(s, si)
|
|
207
209
|
});
|
|
208
210
|
bar.setAttribute("class", `chart-bar ${bar.getAttribute("class") ?? ""}`.trim());
|
|
209
|
-
addTip(ctx, bar, x + barWidth / 2, top, [`${s.name ?? ""} ${labels[i] ?? ""}`.trim(),
|
|
211
|
+
addTip(ctx, bar, x + barWidth / 2, top, [`${s.name ?? ""} ${labels[i] ?? ""}`.trim(), format(value)]);
|
|
210
212
|
svg.append(bar);
|
|
211
213
|
}));
|
|
212
214
|
}
|
|
213
215
|
|
|
214
216
|
// Line and area charts, with a category or a time axis, zoom (a range of the x axis) and long series (no dots, a pointer tooltip).
|
|
215
217
|
function drawLine(svg, ctx) {
|
|
216
|
-
const { labels, series, width, height, times, area, options, zoom } = ctx;
|
|
218
|
+
const { labels, series, width, height, times, area, options, zoom, format } = ctx;
|
|
219
|
+
const MARGIN = ctx.margin;
|
|
217
220
|
const plotW = width - MARGIN.left - MARGIN.right;
|
|
218
221
|
const plotH = height - MARGIN.top - MARGIN.bottom;
|
|
219
222
|
const count = Math.max(...series.map(s => s.data.length));
|
|
220
223
|
const position = i => (times ? times[i] : i); // x position of point i in the units of the axis
|
|
221
|
-
|
|
224
|
+
// The range of the x axis: what the data covers, or the one asked for (a window of the last hour that is only half measured)
|
|
225
|
+
const full = times ? (options.timeRange && options.timeRange.to > options.timeRange.from ? { from: toTime(options.timeRange.from), to: toTime(options.timeRange.to) } : { from: Math.min(...times.slice(0, count)), to: Math.max(...times.slice(0, count)) }) : { from: -0.5, to: count - 0.5 };
|
|
222
226
|
const view = zoom ? { from: Math.max(zoom.from, full.from), to: Math.min(zoom.to, full.to) } : full;
|
|
223
227
|
if (!(view.to > view.from)) Object.assign(view, full);
|
|
224
228
|
const x = p => MARGIN.left + ((p - view.from) / (view.to - view.from || 1)) * plotW;
|
|
@@ -234,7 +238,7 @@ function drawLine(svg, ctx) {
|
|
|
234
238
|
});
|
|
235
239
|
const zeroBased = area || options.zero !== false;
|
|
236
240
|
const { min, scale } = valueRange(series.flatMap((s, si) => visible[si].map(i => s.data[i])), zeroBased);
|
|
237
|
-
const { y, baseline } = addValueAxis(svg, { min, scale, width, height });
|
|
241
|
+
const { y, baseline } = addValueAxis(svg, { min, scale, width, height, margin: MARGIN, format: ctx.tickFormat });
|
|
238
242
|
|
|
239
243
|
// x axis
|
|
240
244
|
if (times) {
|
|
@@ -264,22 +268,33 @@ function drawLine(svg, ctx) {
|
|
|
264
268
|
const inside = visible[si];
|
|
265
269
|
const lo = inside.length ? inside[0] : 0;
|
|
266
270
|
const hi = inside.length ? inside.at(-1) : -1;
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
+
// Without `gaps` a missing value is skipped and the line goes on; with it the line breaks there, and a point on its own is a dot
|
|
272
|
+
const runs = [];
|
|
273
|
+
let run = [];
|
|
274
|
+
for (let i = Math.max(lo - 1, 0); i <= Math.min(hi + 1, s.data.length - 1); i++) {
|
|
275
|
+
if (Number.isFinite(s.data[i])) run.push(i);
|
|
276
|
+
else if (options.gaps) {
|
|
277
|
+
if (run.length) runs.push(run);
|
|
278
|
+
run = [];
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (run.length) runs.push(run);
|
|
271
282
|
const group = svgEl("g", { "data-series": si, ...seriesProps(s, si) });
|
|
272
283
|
const clipped = svgEl("g", { "clip-path": `url(#${clipId})` });
|
|
273
|
-
|
|
274
|
-
const
|
|
275
|
-
|
|
284
|
+
for (const members of runs) {
|
|
285
|
+
const points = decimate(members, s.data, Math.floor(plotW)).map(i => [x(position(i)), y(s.data[i])]);
|
|
286
|
+
if (area && points.length) {
|
|
287
|
+
const outline = [`M${points[0][0]},${baseline}`, ...points.map(p => `L${p.join(",")}`), `L${points.at(-1)[0]},${baseline}`, "Z"];
|
|
288
|
+
clipped.append(svgEl("path", { d: outline.join(" "), class: "chart-area" }));
|
|
289
|
+
}
|
|
290
|
+
if (points.length === 1 && options.gaps) clipped.append(svgEl("circle", { cx: points[0][0], cy: points[0][1], r: 2.5, class: "chart-point chart-lone-point" }));
|
|
291
|
+
else clipped.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none", pathLength: 1 }));
|
|
276
292
|
}
|
|
277
|
-
clipped.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none", pathLength: 1 }));
|
|
278
293
|
group.append(clipped);
|
|
279
294
|
if (dotted) {
|
|
280
295
|
for (const i of inside) {
|
|
281
296
|
const dot = svgEl("circle", { cx: x(position(i)), cy: y(s.data[i]), r: 4, class: "chart-point" });
|
|
282
|
-
addTip(ctx, dot, x(position(i)), y(s.data[i]), [`${s.name ?? ""} ${when(i)}`.trim(),
|
|
297
|
+
addTip(ctx, dot, x(position(i)), y(s.data[i]), [`${s.name ?? ""} ${when(i)}`.trim(), format(s.data[i])]);
|
|
283
298
|
group.append(dot);
|
|
284
299
|
}
|
|
285
300
|
}
|
|
@@ -321,7 +336,7 @@ function drawLine(svg, ctx) {
|
|
|
321
336
|
marker.setAttribute("x1", px);
|
|
322
337
|
marker.setAttribute("x2", px);
|
|
323
338
|
marker.removeAttribute("display");
|
|
324
|
-
const lines = [when(index), ...series.map(s => (Number.isFinite(s.data[index]) ? `${s.name ? `${s.name}: ` : ""}${
|
|
339
|
+
const lines = [when(index), ...series.map(s => (Number.isFinite(s.data[index]) ? `${s.name ? `${s.name}: ` : ""}${format(s.data[index])}` : null)).filter(Boolean)];
|
|
325
340
|
const top = Math.min(...series.map(s => (Number.isFinite(s.data[index]) ? y(s.data[index]) : Infinity)));
|
|
326
341
|
ctx.tooltip.show(px, Number.isFinite(top) ? top : MARGIN.top, lines);
|
|
327
342
|
};
|
|
@@ -396,7 +411,7 @@ function drawLine(svg, ctx) {
|
|
|
396
411
|
|
|
397
412
|
// A small line without axes, legend or title: for a table cell or a stat tile. Its tooltips still work.
|
|
398
413
|
function drawSparkline(svg, ctx) {
|
|
399
|
-
const { series, width, height } = ctx;
|
|
414
|
+
const { series, width, height, format } = ctx;
|
|
400
415
|
const s = series[0];
|
|
401
416
|
const values = s.data.filter(Number.isFinite);
|
|
402
417
|
const min = Math.min(...values);
|
|
@@ -410,14 +425,15 @@ function drawSparkline(svg, ctx) {
|
|
|
410
425
|
const last = points.at(-1);
|
|
411
426
|
if (last) {
|
|
412
427
|
const dot = svgEl("circle", { cx: last[0], cy: last[1], r: 2.5, class: "chart-point" });
|
|
413
|
-
addTip(ctx, dot, last[0], last[1], [
|
|
428
|
+
addTip(ctx, dot, last[0], last[1], [format(values.at(-1))]);
|
|
414
429
|
group.append(dot);
|
|
415
430
|
}
|
|
416
431
|
svg.append(group);
|
|
417
432
|
}
|
|
418
433
|
|
|
419
434
|
function drawPie(svg, ctx) {
|
|
420
|
-
const { labels, series, width, height, donut } = ctx;
|
|
435
|
+
const { labels, series, width, height, donut, format } = ctx;
|
|
436
|
+
const MARGIN = ctx.margin;
|
|
421
437
|
const data = series[0].data.map(v => Math.max(0, v));
|
|
422
438
|
const total = data.reduce((a, b) => a + b, 0);
|
|
423
439
|
const cx = width / 2;
|
|
@@ -447,7 +463,7 @@ function drawPie(svg, ctx) {
|
|
|
447
463
|
slice.setAttribute("data-series", i);
|
|
448
464
|
const mid = start + sweep / 2;
|
|
449
465
|
const [tx, ty] = point(r * (donut ? (1 + 0.55) / 2 : 0.6), mid).split(",").map(Number);
|
|
450
|
-
addTip(ctx, slice, tx, ty, [labels[i] ?? "", `${
|
|
466
|
+
addTip(ctx, slice, tx, ty, [labels[i] ?? "", `${format(value)} (${Math.round(value / total * 100)}%)`]);
|
|
451
467
|
svg.append(slice);
|
|
452
468
|
start += sweep;
|
|
453
469
|
});
|
|
@@ -467,7 +483,7 @@ const DRAWERS = {
|
|
|
467
483
|
/* ------------------TABLE OF VALUES------------------- */
|
|
468
484
|
|
|
469
485
|
// The same numbers as a table, for screen readers and for people who want to read them off or copy them.
|
|
470
|
-
function buildDataTable({ labels, series, times, title, type }) {
|
|
486
|
+
function buildDataTable({ labels, series, times, title, type, format = formatNumber }) {
|
|
471
487
|
const details = document.createElement("details");
|
|
472
488
|
details.className = "chart-data";
|
|
473
489
|
const summary = document.createElement("summary");
|
|
@@ -493,7 +509,7 @@ function buildDataTable({ labels, series, times, title, type }) {
|
|
|
493
509
|
head.scope = "row";
|
|
494
510
|
head.textContent = times ? when.format(times[i]) : (labels[i] ?? "");
|
|
495
511
|
row.append(head);
|
|
496
|
-
for (const s of shown) row.insertCell().textContent = s.data[i] == null ? "" :
|
|
512
|
+
for (const s of shown) row.insertCell().textContent = s.data[i] == null ? "" : format(s.data[i]);
|
|
497
513
|
}
|
|
498
514
|
details.append(summary, table);
|
|
499
515
|
return details;
|
|
@@ -526,6 +542,14 @@ function buildDataTable({ labels, series, times, title, type }) {
|
|
|
526
542
|
* @param {number[]} [options.hiddenSeries] the series (or slices) that are hidden at the start; a person hides and shows them with the legend, and a redraw keeps that
|
|
527
543
|
* @param {boolean} [options.animate=true] the first drawing animates: bars grow, a line is drawn, slices pop in (not when it is redrawn, and not under reduced motion)
|
|
528
544
|
* @param {boolean} [options.interactive=true] line and area charts: false leaves out the pointer layer (tooltip that follows the pointer, zoom)
|
|
545
|
+
* @param {boolean} [options.gaps=false] line and area charts: a missing value (null, NaN, undefined) breaks the line, and a point on its own is a dot;
|
|
546
|
+
* without it the line goes on from the value before to the one after
|
|
547
|
+
* @param {{from: (number|Date|string), to: (number|Date|string)}} [options.timeRange] line and area charts with `times`: the range of the time axis, when it is not the one
|
|
548
|
+
* the data covers (the last hour, of which only the last quarter has been measured)
|
|
549
|
+
* @param {(value: number) => string} [options.format] how a value is written: on the axis, in the tooltips and in the table of values (default: whole numbers, otherwise two decimals)
|
|
550
|
+
* @param {(value: number) => string} [options.tickFormat] how the numbers of the value axis are written, when they should not be written like the values (a chart of whole numbers has ticks of 0.2)
|
|
551
|
+
* @param {{top?: number, right?: number, bottom?: number, left?: number}} [options.margin] room around the plot in px (default 40, 20, 50, 55): a chart without a title and a legend does not need the top
|
|
552
|
+
* @param {boolean} [options.responsive=false] the chart is as wide as its parent and follows it when it changes (`height` stays); `width` is only the first guess
|
|
529
553
|
* @returns {(SVGElement & {element: SVGElement, update: (options?: object) => SVGElement, destroy: () => void,
|
|
530
554
|
* zoom: (from: number, to: number) => void, resetZoom: () => void, getZoom: () => ({from: number, to: number}|null),
|
|
531
555
|
* push: (point: {x?: (number|Date|string), label?: string, values: (number|number[])}, config?: {maxPoints?: number}) => void,
|
|
@@ -540,6 +564,7 @@ export function generateChart(options = {}) {
|
|
|
540
564
|
if (options.labels) state.used.labels = [...options.labels];
|
|
541
565
|
if (options.times) state.used.times = [...options.times];
|
|
542
566
|
const hidden = new Set(options.hiddenSeries ?? []);
|
|
567
|
+
let resizing = null;
|
|
543
568
|
// Only the first drawing animates (bars grow, the line is drawn, slices pop in): a redraw while streaming or zooming must not start it again
|
|
544
569
|
let firstDrawing = options.animate !== false;
|
|
545
570
|
const hooks = {
|
|
@@ -582,6 +607,7 @@ export function generateChart(options = {}) {
|
|
|
582
607
|
return handle.redraw();
|
|
583
608
|
},
|
|
584
609
|
destroy() {
|
|
610
|
+
resizing?.disconnect();
|
|
585
611
|
state.current.svg.remove();
|
|
586
612
|
state.current.table?.remove();
|
|
587
613
|
},
|
|
@@ -626,13 +652,26 @@ export function generateChart(options = {}) {
|
|
|
626
652
|
dataTable: { get: () => state.current.table ?? null, configurable: true }
|
|
627
653
|
});
|
|
628
654
|
|
|
655
|
+
const host = resolveElement(options.parent ?? "wrapper") ?? document.body;
|
|
656
|
+
if (options.responsive && host.clientWidth >= 120) state.used.width = Math.floor(host.clientWidth);
|
|
629
657
|
const built = buildChart(state.used, hooks, { animate: firstDrawing });
|
|
630
658
|
firstDrawing = false;
|
|
631
659
|
if (!built) return null;
|
|
632
660
|
state.current = built;
|
|
633
|
-
const host = resolveElement(options.parent ?? "wrapper") ?? document.body;
|
|
634
661
|
host.append(built.svg);
|
|
635
662
|
if (built.table) built.svg.after(built.table);
|
|
663
|
+
if (options.responsive && typeof ResizeObserver === "function") {
|
|
664
|
+
// The chart is as wide as its parent (the height stays): redrawn once per frame when the parent changes its width
|
|
665
|
+
let frame = 0;
|
|
666
|
+
resizing = new ResizeObserver(() => {
|
|
667
|
+
cancelAnimationFrame(frame);
|
|
668
|
+
frame = requestAnimationFrame(() => {
|
|
669
|
+
const width = Math.floor(host.clientWidth);
|
|
670
|
+
if (width >= 120 && width !== state.used.width) handle.update({ width });
|
|
671
|
+
});
|
|
672
|
+
});
|
|
673
|
+
resizing.observe(host);
|
|
674
|
+
}
|
|
636
675
|
return attach(built.svg);
|
|
637
676
|
}
|
|
638
677
|
|
|
@@ -664,7 +703,10 @@ function buildChart(options = {}, hooks, { animate = false } = {}) {
|
|
|
664
703
|
|
|
665
704
|
// The tooltip is created first, so the shapes can use it, and moved to the end afterwards, so it is drawn on top.
|
|
666
705
|
const tooltip = createTooltip(svg, width);
|
|
667
|
-
const
|
|
706
|
+
const margin = { ...DEFAULT_MARGIN, ...(options.margin ?? {}) };
|
|
707
|
+
const format = typeof options.format === "function" ? options.format : formatNumber;
|
|
708
|
+
const tickFormat = typeof options.tickFormat === "function" ? options.tickFormat : format;
|
|
709
|
+
const ctx = { labels, series, width, height, times, options, tooltip, hooks, zoom: options.zoomRange ?? null, margin, format, tickFormat };
|
|
668
710
|
const pieLegend = draw(svg, ctx);
|
|
669
711
|
if (!sparkline && (options.legend ?? (Boolean(pieLegend) || series.length > 1))) {
|
|
670
712
|
addLegend(svg, pieLegend ?? series.map((s, i) => ({ name: s.name ?? `${translate("series")} ${i + 1}`, props: seriesProps(s, i), series: i })), width, height, ctx);
|
|
@@ -676,5 +718,5 @@ function buildChart(options = {}, hooks, { animate = false } = {}) {
|
|
|
676
718
|
entry?.setAttribute("aria-pressed", "false");
|
|
677
719
|
entry?.classList.add("is-off");
|
|
678
720
|
}
|
|
679
|
-
return { svg, table: options.table ? buildDataTable({ labels, series, times, title, type }) : null };
|
|
721
|
+
return { svg, table: options.table ? buildDataTable({ labels, series, times, title, type, format }) : null };
|
|
680
722
|
}
|
|
@@ -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;
|
|
@@ -2380,6 +2380,10 @@ dialog.dialog[open]::backdrop {
|
|
|
2380
2380
|
widget (wg-x-1, wg-y-1, wg-w-3, wg-h-2), written into a constructed style sheet: no style attribute, so a strict Content-Security-Policy is fine.
|
|
2381
2381
|
The controls of the edit mode (handle, buttons, resize edges) exist in every widget and are shown only in .is-editable. */
|
|
2382
2382
|
|
|
2383
|
+
.field[hidden] {
|
|
2384
|
+
display: none;
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2383
2387
|
.athena-widget-grid {
|
|
2384
2388
|
display: grid;
|
|
2385
2389
|
position: relative;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export function applyConfig(...sources: any[]): {
|
|
2
|
-
version: "2.
|
|
2
|
+
version: "2.5.0";
|
|
3
3
|
container_class: "container";
|
|
4
4
|
header_class: "header-container";
|
|
5
5
|
header_menu_class: "header-menu menu";
|
|
@@ -32,7 +32,7 @@ export function applyConfig(...sources: any[]): {
|
|
|
32
32
|
export function withBorder(className: any): any;
|
|
33
33
|
export const BORDERED_CLASS: "default-cointainer-bordered";
|
|
34
34
|
export const defaults: Readonly<{
|
|
35
|
-
version: "2.
|
|
35
|
+
version: "2.5.0";
|
|
36
36
|
container_class: "container";
|
|
37
37
|
header_class: "header-container";
|
|
38
38
|
header_menu_class: "header-menu menu";
|
|
@@ -64,7 +64,7 @@ export const defaults: Readonly<{
|
|
|
64
64
|
}>;
|
|
65
65
|
export default config;
|
|
66
66
|
declare namespace config {
|
|
67
|
-
let version: "2.
|
|
67
|
+
let version: "2.5.0";
|
|
68
68
|
let container_class: "container";
|
|
69
69
|
let header_class: "header-container";
|
|
70
70
|
let header_menu_class: "header-menu menu";
|