athena-ui-js 2.6.0 → 2.7.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,870 +1,943 @@
1
- //Widget grid of Athena UI: a dashboard of widgets that can be added, configured, moved, resized, locked, saved and loaded.
2
- //Layout is CSS grid. The place of a widget is a few CSS classes (no inline style), the maths is in core/gridLayout.js.
3
- //LICENCE: MIT
4
- //Repository: https://github.com/csabatibortoth/athena-ui
5
-
6
- import { animate, prefersReducedMotion } from "../../core/motion.js";
7
- import { asHandle, el, resolveElement, uid } from "../../core/dom.js";
8
- import { translate } from "../../core/i18n.js";
9
- import { showFormDialog } from "../dialogGenerator/dialogGenerator.js";
10
- import { clampItem, compact, findFreeSpot, normalize, placeItem } from "../../core/gridLayout.js";
11
-
12
- /* ------------------REGISTRY------------------- */
13
-
14
- const registry = new Map();
15
-
16
- /**
17
- * Registers a type of widget, so grids can create it, load it from a saved layout and show its settings.
18
- *
19
- * @param {string} type name of the type, for example "stat" (it is saved in layouts)
20
- * @param {object} definition
21
- * @param {(context: WidgetContext) => (void|Function|{update?: Function, destroy?: Function})} definition.render builds the widget into `context.element`;
22
- * it may return a function (called when the widget goes away) or an object with `update(context)` and `destroy(context)`
23
- * @param {(context: WidgetContext) => void} [definition.update] called (throttled) when the config or the title changed; without it the widget is rendered again
24
- * @param {(context: WidgetContext, size: {width: number, height: number}) => void} [definition.resize] called (throttled) when the body changes its size
25
- * @param {(context: WidgetContext) => void} [definition.destroy] called when the widget is removed or the grid is destroyed
26
- * @param {object[]|((widget: object) => object[])} [definition.configForm] field definitions (see generateField) of the settings dialog; the field `name` is the key in the config
27
- * @param {object} [definition.defaultConfig] config of a new widget
28
- * @param {string} [definition.title] title of a new widget
29
- * @param {{w: number, h: number}} [definition.defaultSize={w: 3, h: 2}] size in grid cells
30
- * @param {{w?: number, h?: number}} [definition.minSize]
31
- * @param {{w?: number, h?: number}} [definition.maxSize]
32
- *
33
- * @typedef {object} WidgetContext
34
- * @property {string} id
35
- * @property {string} type
36
- * @property {HTMLElement} element the body of the widget: build into it
37
- * @property {object} config the current config (read it again in update())
38
- * @property {string} title
39
- * @property {{width: number, height: number}} size
40
- * @property {(title: string) => void} setTitle
41
- */
42
- export function registerWidget(type, definition) {
43
- if (typeof type !== "string" || !/^[\w.:-]{1,100}$/.test(type)) throw new TypeError("Athena UI: a widget type is a short name of letters, digits and . _ : -");
44
- if (typeof definition?.render !== "function") throw new TypeError(`Athena UI: the widget type "${type}" needs a render function`);
45
- registry.set(type, definition);
46
- }
47
-
48
- /** Forgets a widget type. Widgets of it that are in grids stay and are shown as unknown. */
49
- export function unregisterWidget(type) {
50
- return registry.delete(type);
51
- }
52
-
53
- /** The names of the registered widget types. */
54
- export function getWidgetTypes() {
55
- return [...registry.keys()];
56
- }
57
-
58
- /* ------------------CLASSES FOR PLACES------------------- */
59
-
60
- // A place is a few classes whose rules are written into one constructed style sheet of the document (or shadow root): the strict
61
- // Content-Security-Policy that forbids the style attribute allows it, and the browser lays the grid out.
62
- const sheets = new WeakMap();
63
- function classSheet(root) {
64
- if (!sheets.has(root)) {
65
- const usable = typeof CSSStyleSheet === "function" && Array.isArray(root.adoptedStyleSheets) && typeof CSSStyleSheet.prototype.replaceSync === "function";
66
- const sheet = usable ? new CSSStyleSheet() : null;
67
- if (sheet) root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
68
- sheets.set(root, { sheet, rules: new Map() });
69
- }
70
- return sheets.get(root);
71
- }
72
-
73
- /** Gives the class of one declaration (and writes its rule the first time); returns "" without constructed style sheets. */
74
- function useClass(root, name, css) {
75
- const state = classSheet(root);
76
- if (!state.sheet) return "";
77
- if (!state.rules.has(name)) {
78
- state.rules.set(name, `.${name} { ${css} }`);
79
- state.sheet.replaceSync(`@layer athena {\n${[...state.rules.values()].join("\n")}\n}`);
80
- }
81
- return name;
82
- }
83
-
84
- const PLACE_CLASSES = [["x", "wg-x", n => `grid-column-start: ${n + 1}`], ["y", "wg-y", n => `grid-row-start: ${n + 1}`], ["w", "wg-w", n => `grid-column-end: span ${n}`], ["h", "wg-h", n => `grid-row-end: span ${n}`]];
85
-
86
- /** Puts a node on a place. With CSSOM as the fallback where there are no constructed style sheets (still no style attribute in the markup). */
87
- function setPlace(root, node, place) {
88
- const classes = [];
89
- for (const [key, prefix, css] of PLACE_CLASSES) {
90
- const name = useClass(root, `${prefix}-${place[key]}`, css(place[key]));
91
- if (name) classes.push(name);
92
- }
93
- if (classes.length) {
94
- for (const old of node.dataset.placeClasses?.split(" ").filter(Boolean) ?? []) if (!classes.includes(old)) node.classList.remove(old);
95
- node.classList.add(...classes);
96
- node.dataset.placeClasses = classes.join(" ");
97
- } else {
98
- node.style.gridColumn = `${place.x + 1} / span ${place.w}`;
99
- node.style.gridRow = `${place.y + 1} / span ${place.h}`;
100
- }
101
- }
102
-
103
- /* ------------------HELPERS------------------- */
104
-
105
- const wholeNumber = (value, min, max, fallback) => (Number.isFinite(value) ? Math.min(Math.max(Math.round(value), min), max) : fallback);
106
- const plain = value => {
107
- // a JSON copy without the keys that change prototypes
108
- const text = JSON.stringify(value ?? {});
109
- if (text.length > 200000) throw new RangeError("Athena UI: the config of a widget is too large");
110
- return JSON.parse(text, (key, item) => (key === "__proto__" || key === "constructor" || key === "prototype" ? undefined : item));
111
- };
112
- const isPlainObject = value => value !== null && typeof value === "object" && !Array.isArray(value);
113
- const SAFE_ID = /^[\w.:-]{1,100}$/;
114
- const LAYOUT_VERSION = 1;
115
-
116
- /* ------------------THE GRID------------------- */
117
-
118
- /**
119
- * A grid of widgets.
120
- *
121
- * @param {object} options
122
- * @param {string|HTMLElement} options.element the container
123
- * @param {number} [options.columns=12] columns when there are no breakpoints
124
- * @param {number} [options.rowHeight=80] height of a row in px
125
- * @param {number} [options.gap=12] gap between widgets in px
126
- * @param {Record<string, {minWidth?: number, columns: number}>} [options.breakpoints] layouts by the width of the container, for example
127
- * `{ large: { minWidth: 900, columns: 12 }, small: { minWidth: 0, columns: 4 } }`. A breakpoint without a layout of its own is derived from the widest one.
128
- * @param {object[]} [options.widgets] first widgets: `{ type, title?, config?, x?, y?, w?, h?, locked?, id? }`
129
- * @param {object} [options.layout] a saved layout (getLayout()), used instead of `widgets`
130
- * @param {boolean} [options.editable=false] edit mode: move, resize, settings, duplicate, remove
131
- * @param {boolean} [options.compact=true] widgets fall upwards when there is room (false: they stay where they are put)
132
- * @param {boolean} [options.animate=true] widgets slide to their new places (never under reduced motion)
133
- * @param {string} [options.label] accessible name of the dashboard
134
- * @param {number} [options.maxWidgets=200]
135
- * @param {(layout: object, reason: string) => void} [options.onChange] called after a change made by the person or by add/remove/...: "move", "resize", "add", "remove", "duplicate", "settings", "lock", "undo", "redo"
136
- * @returns the handle: { element, addWidget, removeWidget, duplicateWidget, configureWidget, updateWidget, getWidget, getWidgets, lockWidget, setEditable, isEditable,
137
- * getLayout, setLayout, undo, redo, canUndo, canRedo, getBreakpoint, destroy }
138
- */
139
- export function createWidgetGrid(options = {}) {
140
- const element = resolveElement(options.element);
141
- if (!element) throw new TypeError("Athena UI: createWidgetGrid needs an element");
142
- const root = element.getRootNode?.() ?? document;
143
- const rowHeight = wholeNumber(options.rowHeight, 20, 1000, 80);
144
- const gap = wholeNumber(options.gap, 0, 100, 12);
145
- const compactItems = options.compact !== false;
146
- const animateMoves = options.animate !== false;
147
- const maxWidgets = wholeNumber(options.maxWidgets, 1, 2000, 200);
148
- const breakpoints = Object.entries(options.breakpoints ?? { default: { minWidth: 0, columns: options.columns ?? 12 } })
149
- .map(([name, value]) => ({ name, minWidth: wholeNumber(value.minWidth, 0, 100000, 0), columns: wholeNumber(value.columns, 1, 48, 12) }))
150
- .sort((a, b) => b.minWidth - a.minWidth);
151
- if (!breakpoints.length) throw new TypeError("Athena UI: createWidgetGrid needs at least one breakpoint");
152
-
153
- /** @type {Map<string, any>} */
154
- const widgets = new Map();
155
- let breakpoint = breakpoints[0];
156
- let editable = false;
157
- let gesture = null;
158
- let destroyed = false;
159
- let starting = true; // the first widgets are not a change
160
- const timers = new Set();
161
-
162
- const live = el("div", { class: "athena-visually-hidden", attrs: { role: "status", "aria-live": "polite" } });
163
- element.after(live);
164
- element.classList.add("athena-widget-grid");
165
- if (options.label) element.setAttribute("aria-label", options.label);
166
- element.setAttribute("role", "group");
167
- const announce = text => {
168
- live.textContent = "";
169
- live.textContent = text;
170
- };
171
-
172
- const intersection = typeof IntersectionObserver === "function" ? new IntersectionObserver(entries => {
173
- for (const entry of entries) {
174
- const widget = widgets.get(entry.target.dataset.widgetId);
175
- if (!widget) continue;
176
- widget.visible = entry.isIntersecting;
177
- if (widget.visible) showWidget(widget);
178
- }
179
- }) : null;
180
- const resizing = typeof ResizeObserver === "function" ? new ResizeObserver(entries => {
181
- for (const entry of entries) {
182
- const node = entry.target;
183
- if (node === element) {
184
- const next = pickBreakpoint();
185
- if (next !== breakpoint) switchBreakpoint(next);
186
- continue;
187
- }
188
- const widget = widgets.get(node.closest(".widget")?.dataset.widgetId);
189
- if (widget) later(widget, "resizeTimer", () => widget.rendered && widget.def?.resize?.(widget.context, widget.context.size), 100);
190
- }
191
- }) : null;
192
-
193
- function later(owner, key, fn, ms) {
194
- clearTimeout(owner[key]);
195
- owner[key] = setTimeout(() => {
196
- timers.delete(owner[key]);
197
- if (!destroyed) fn();
198
- }, ms);
199
- timers.add(owner[key]);
200
- }
201
-
202
- /* ---- breakpoints and layouts ---- */
203
-
204
- function pickBreakpoint() {
205
- const width = element.clientWidth;
206
- if (!width) return breakpoint;
207
- return breakpoints.find(entry => width >= entry.minWidth) ?? breakpoints.at(-1);
208
- }
209
-
210
- const limitsOf = widget => ({ min: widget.def?.minSize, max: widget.def?.maxSize });
211
-
212
- /** The items of one breakpoint, in the form of gridLayout.js. */
213
- function itemsOf(bp) {
214
- return [...widgets.values()].filter(widget => widget.places[bp.name]).map(widget => ({ id: widget.id, locked: widget.locked, ...widget.places[bp.name] }));
215
- }
216
-
217
- function store(bp, items) {
218
- for (const item of items) {
219
- const widget = widgets.get(item.id);
220
- if (widget) widget.places[bp.name] = { x: item.x, y: item.y, w: item.w, h: item.h };
221
- }
222
- }
223
-
224
- /** Widgets without a place at this breakpoint get one, derived from the widest breakpoint that has them. */
225
- function ensurePlaces(bp) {
226
- const missing = [...widgets.values()].filter(widget => !widget.places[bp.name]);
227
- if (!missing.length) return;
228
- const source = breakpoints.find(entry => entry !== bp && missing.every(widget => widget.places[entry.name])) ?? breakpoints.find(entry => entry !== bp && missing.some(widget => widget.places[entry.name]));
229
- const items = itemsOf(bp);
230
- const reading = missing.map(widget => ({ id: widget.id, ...(widget.places[source?.name] ?? { x: 0, y: 1e6, w: 3, h: 2 }) })).sort((a, b) => a.y - b.y || a.x - b.x);
231
- for (const item of reading) {
232
- const widget = widgets.get(item.id);
233
- const size = clampItem(item, bp.columns, limitsOf(widget));
234
- const spot = findFreeSpot(items, size.w, size.h, bp.columns);
235
- const placed = { id: item.id, locked: widget.locked, ...spot, w: size.w, h: size.h };
236
- items.push(placed);
237
- widget.places[bp.name] = { x: placed.x, y: placed.y, w: placed.w, h: placed.h };
238
- }
239
- }
240
-
241
- function applyContainerClasses() {
242
- for (const old of [...element.classList].filter(name => /^wg-(cols|rh|gap)-/.test(name))) element.classList.remove(old);
243
- const names = [
244
- useClass(root, `wg-cols-${breakpoint.columns}`, `grid-template-columns: repeat(${breakpoint.columns}, minmax(0, 1fr))`),
245
- useClass(root, `wg-rh-${rowHeight}`, `grid-auto-rows: ${rowHeight}px`),
246
- useClass(root, `wg-gap-${gap}`, `gap: ${gap}px`)
247
- ].filter(Boolean);
248
- if (names.length) element.classList.add(...names);
249
- else {
250
- element.style.gridTemplateColumns = `repeat(${breakpoint.columns}, minmax(0, 1fr))`;
251
- element.style.gridAutoRows = `${rowHeight}px`;
252
- element.style.gap = `${gap}px`;
253
- }
254
- }
255
-
256
- /** Puts every node on its place; the nodes that moved slide there (FLIP). */
257
- function applyPlaces({ slide = animateMoves, except } = {}) {
258
- const nodes = [...widgets.values()].map(widget => widget.node);
259
- const sliding = slide && !prefersReducedMotion() && nodes.length <= 60;
260
- const before = sliding ? new Map(nodes.map(node => [node, node.getBoundingClientRect()])) : null;
261
- for (const widget of widgets.values()) if (widget.places[breakpoint.name]) setPlace(root, widget.node, widget.places[breakpoint.name]);
262
- if (!before) return;
263
- for (const node of nodes) {
264
- if (node === except) continue;
265
- const was = before.get(node);
266
- const now = node.getBoundingClientRect();
267
- const dx = was.left - now.left;
268
- const dy = was.top - now.top;
269
- if (Math.abs(dx) > 1 || Math.abs(dy) > 1) animate(node, [{ translate: `${dx}px ${dy}px` }, { translate: "0 0" }], { duration: 160 });
270
- }
271
- }
272
-
273
- function switchBreakpoint(next) {
274
- cancelGesture();
275
- breakpoint = next;
276
- ensurePlaces(next);
277
- applyContainerClasses();
278
- applyPlaces({ slide: false });
279
- }
280
-
281
- /** Keeps the DOM order equal to the order of reading, so Tab goes through the widgets as the eye does. */
282
- function orderDom() {
283
- const order = [...widgets.values()].filter(widget => widget.places[breakpoint.name]).sort((a, b) => a.places[breakpoint.name].y - b.places[breakpoint.name].y || a.places[breakpoint.name].x - b.places[breakpoint.name].x);
284
- const current = [...element.children].filter(node => node.classList.contains("widget"));
285
- if (order.every((widget, index) => current[index] === widget.node)) return;
286
- const focused = element.contains(document.activeElement) ? document.activeElement : null;
287
- for (const widget of order) element.append(widget.node);
288
- focused?.focus?.({ preventScroll: true });
289
- }
290
-
291
- /* ---- the widget ---- */
292
-
293
- function buildNode(widget) {
294
- const titleId = uid("widget-title");
295
- const handle = el("button", { class: "widget-handle", attrs: { type: "button", "aria-describedby": titleId } }, "⠿");
296
- const title = el("h3", { class: "widget-title", attrs: { id: titleId } });
297
- const settings = el("button", { class: "widget-action", attrs: { type: "button", "data-action": "settings" } }, "⚙");
298
- const copy = el("button", { class: "widget-action", attrs: { type: "button", "data-action": "duplicate" } }, "⧉");
299
- const remove = el("button", { class: "widget-action", attrs: { type: "button", "data-action": "remove" } }, "✕");
300
- const body = el("div", { class: "widget-body" });
301
- const node = el("section", { class: "widget", attrs: { "data-widget-id": widget.id, "data-widget-type": widget.type, "aria-labelledby": titleId } },
302
- el("header", { class: "widget-header" }, handle, title, el("div", { class: "widget-actions" }, settings, copy, remove)), body);
303
- for (const dir of ["n", "s", "e", "w", "ne", "nw", "se", "sw"]) node.append(el("span", { class: `widget-resize widget-resize-${dir}`, attrs: { "data-dir": dir } }));
304
- widget.node = node;
305
- widget.parts = { handle, title, settings, copy, remove, body };
306
- widget.context = {
307
- id: widget.id,
308
- type: widget.type,
309
- element: body,
310
- get config() { return widget.config; },
311
- get title() { return widget.title; },
312
- size: { width: 0, height: 0 },
313
- setTitle: text => setTitle(widget, text)
314
- };
315
- labelNode(widget);
316
- node.classList.toggle("is-locked", widget.locked);
317
- resizing?.observe(body);
318
- if (intersection) intersection.observe(node);
319
- else {
320
- widget.visible = true;
321
- queueMicrotask(() => !destroyed && showWidget(widget));
322
- }
323
- }
324
-
325
- function labelNode(widget) {
326
- const { handle, title, settings, copy, remove } = widget.parts;
327
- title.textContent = widget.title;
328
- const params = { title: widget.title };
329
- handle.setAttribute("aria-label", translate("widget.move", params));
330
- settings.setAttribute("aria-label", translate("widget.settings", params));
331
- copy.setAttribute("aria-label", translate("widget.duplicate", params));
332
- remove.setAttribute("aria-label", translate("widget.remove", params));
333
- for (const part of [settings, copy, remove, handle]) part.title = part.getAttribute("aria-label");
334
- widget.node.querySelectorAll(".widget-resize").forEach(handleNode => handleNode.setAttribute("aria-hidden", "true"));
335
- }
336
-
337
- function setTitle(widget, text) {
338
- widget.title = String(text ?? "").slice(0, 200);
339
- labelNode(widget);
340
- }
341
-
342
- /** Renders the widget when it is visible for the first time, or brings it up to date when it changed while it was not. */
343
- function showWidget(widget) {
344
- if (destroyed || !widget.visible) return;
345
- if (!widget.rendered) renderWidget(widget);
346
- else if (widget.dirty) updateNow(widget);
347
- }
348
-
349
- function renderWidget(widget) {
350
- widget.rendered = true;
351
- widget.dirty = false;
352
- widget.def = registry.get(widget.type);
353
- widget.parts.body.replaceChildren();
354
- widget.node.classList.remove("is-unknown", "is-failed");
355
- const rect = widget.parts.body.getBoundingClientRect();
356
- widget.context.size = { width: Math.round(rect.width), height: Math.round(rect.height) };
357
- if (!widget.def) {
358
- widget.node.classList.add("is-unknown");
359
- widget.parts.body.append(el("p", { class: "widget-note", text: translate("widget.unknown", { type: widget.type }) }));
360
- return;
361
- }
362
- try {
363
- const result = widget.def.render(widget.context);
364
- widget.instance = typeof result === "function" ? { destroy: result } : (result ?? {});
365
- } catch (error) {
366
- console.error(`Athena UI: the widget "${widget.type}" failed to render`, error);
367
- widget.node.classList.add("is-failed");
368
- widget.parts.body.replaceChildren(el("p", { class: "widget-note", text: translate("widget.failed") }));
369
- }
370
- }
371
-
372
- function disposeWidget(widget) {
373
- try {
374
- widget.instance?.destroy?.(widget.context);
375
- if (widget.rendered && widget.def?.destroy && !widget.instance?.destroy) widget.def.destroy(widget.context);
376
- } catch (error) {
377
- console.error(`Athena UI: the widget "${widget.type}" failed to clean up`, error);
378
- }
379
- widget.instance = null;
380
- widget.rendered = false;
381
- }
382
-
383
- function updateNow(widget) {
384
- widget.dirty = false;
385
- const size = widget.parts.body.getBoundingClientRect();
386
- widget.context.size = { width: Math.round(size.width), height: Math.round(size.height) };
387
- const update = widget.instance?.update ?? widget.def?.update;
388
- if (!update) {
389
- disposeWidget(widget);
390
- renderWidget(widget);
391
- return;
392
- }
393
- try {
394
- update.call(widget.instance, widget.context);
395
- } catch (error) {
396
- console.error(`Athena UI: the widget "${widget.type}" failed to update`, error);
397
- }
398
- }
399
-
400
- function createWidget(data) {
401
- const widget = {
402
- id: data.id, type: data.type, title: data.title, config: data.config, locked: Boolean(data.locked), places: data.places ?? {},
403
- node: null, parts: null, context: null, def: registry.get(data.type), instance: null, rendered: false, visible: false, dirty: false
404
- };
405
- widgets.set(widget.id, widget);
406
- buildNode(widget);
407
- element.append(widget.node);
408
- return widget;
409
- }
410
-
411
- function removeNode(widget) {
412
- clearTimeout(widget.updateTimer);
413
- clearTimeout(widget.resizeTimer);
414
- disposeWidget(widget);
415
- intersection?.unobserve(widget.node);
416
- resizing?.unobserve(widget.parts.body);
417
- widget.node.remove();
418
- widgets.delete(widget.id);
419
- }
420
-
421
- /* ---- layout JSON ---- */
422
-
423
- /** The layout as plain, versioned JSON: where it is stored is up to the application. */
424
- function getLayout() {
425
- const items = itemsOf(breakpoint);
426
- const order = new Map(items.sort((a, b) => a.y - b.y || a.x - b.x).map((item, index) => [item.id, index]));
427
- return {
428
- version: LAYOUT_VERSION,
429
- widgets: [...widgets.values()].sort((a, b) => (order.get(a.id) ?? 1e9) - (order.get(b.id) ?? 1e9)).map(widget => ({
430
- id: widget.id, type: widget.type, title: widget.title, config: plain(widget.config), locked: widget.locked,
431
- layouts: Object.fromEntries(Object.entries(widget.places).map(([name, place]) => [name, { ...place }]))
432
- }))
433
- };
434
- }
435
-
436
- /** Checks one entry of a layout; returns the clean widget or a string with the reason. */
437
- function checkEntry(entry, seen) {
438
- if (!isPlainObject(entry)) return "not an object";
439
- if (typeof entry.type !== "string" || !SAFE_ID.test(entry.type)) return "bad type";
440
- let config;
441
- try {
442
- config = isPlainObject(entry.config) ? plain(entry.config) : {};
443
- } catch {
444
- return "bad config";
445
- }
446
- const places = {};
447
- for (const bp of breakpoints) {
448
- const place = entry.layouts?.[bp.name] ?? (breakpoints.length === 1 ? entry : null);
449
- if (!isPlainObject(place) || ![place.x, place.y, place.w, place.h].every(Number.isFinite)) continue;
450
- places[bp.name] = { x: wholeNumber(place.x, 0, 10000, 0), y: wholeNumber(place.y, 0, 100000, 0), w: wholeNumber(place.w, 1, 48, 1), h: wholeNumber(place.h, 1, 1000, 1) };
451
- }
452
- let id = typeof entry.id === "string" && SAFE_ID.test(entry.id) && !seen.has(entry.id) ? entry.id : null;
453
- while (!id || seen.has(id)) id = uid("widget");
454
- seen.add(id);
455
- const def = registry.get(entry.type);
456
- return { id, type: entry.type, title: typeof entry.title === "string" ? entry.title.slice(0, 200) : (def?.title ?? entry.type), config, locked: entry.locked === true, places };
457
- }
458
-
459
- /**
460
- * Replaces everything by a saved layout. An entry that is not valid is skipped; a type that is not registered is shown as a placeholder (its data is kept).
461
- * @returns {{loaded: number, skipped: {index: number, reason: string}[]}}
462
- */
463
- function setLayout(layout, { reset = true } = {}) {
464
- if (!isPlainObject(layout) || layout.version !== LAYOUT_VERSION || !Array.isArray(layout.widgets)) throw new TypeError(`Athena UI: a layout is { version: ${LAYOUT_VERSION}, widgets: [...] }`);
465
- cancelGesture();
466
- const seen = new Set();
467
- const skipped = [];
468
- const clean = [];
469
- layout.widgets.forEach((entry, index) => {
470
- if (clean.length >= maxWidgets) return skipped.push({ index, reason: "too many widgets" });
471
- const result = checkEntry(entry, seen);
472
- if (typeof result === "string") skipped.push({ index, reason: result });
473
- else clean.push(result);
474
- });
475
- const keep = new Map(clean.map(item => [item.id, item]));
476
- for (const widget of [...widgets.values()]) if (!keep.has(widget.id) || widget.type !== keep.get(widget.id).type) removeNode(widget);
477
- for (const item of clean) {
478
- const widget = widgets.get(item.id);
479
- if (!widget) {
480
- createWidget(item);
481
- continue;
482
- }
483
- const changed = JSON.stringify(widget.config) !== JSON.stringify(item.config) || widget.title !== item.title;
484
- Object.assign(widget, { config: item.config, locked: item.locked, places: item.places });
485
- widget.node.classList.toggle("is-locked", item.locked);
486
- if (widget.title !== item.title) setTitle(widget, item.title);
487
- if (changed) markChanged(widget);
488
- }
489
- // validate the places of every breakpoint: inside the columns, no overlaps
490
- for (const bp of breakpoints) {
491
- const items = itemsOf(bp);
492
- if (items.length) store(bp, normalizeKeeping(items, bp));
493
- }
494
- ensurePlaces(breakpoint);
495
- applyContainerClasses();
496
- applyPlaces({ slide: false });
497
- orderDom();
498
- if (reset) {
499
- snapshots.length = 0;
500
- snapshots.push(JSON.stringify(getLayout()));
501
- position = 0;
502
- }
503
- for (const skip of skipped) console.warn(`Athena UI: widget ${skip.index} of the layout was skipped (${skip.reason})`);
504
- return { loaded: clean.length, skipped };
505
- }
506
-
507
- function normalizeKeeping(items, bp) {
508
- return normalize(items, bp.columns, item => limitsOf(widgets.get(item.id)));
509
- }
510
-
511
- function markChanged(widget) {
512
- widget.dirty = true;
513
- if (widget.visible && widget.rendered) later(widget, "updateTimer", () => updateNow(widget), 100);
514
- }
515
-
516
- /* ---- snapshots ---- */
517
-
518
- const snapshots = [];
519
- let position = -1;
520
-
521
- function commit(reason) {
522
- const snapshot = JSON.stringify(getLayout());
523
- if (snapshot === snapshots[position]) return;
524
- snapshots.length = position + 1;
525
- snapshots.push(snapshot);
526
- if (snapshots.length > 100) snapshots.shift();
527
- position = snapshots.length - 1;
528
- if (!starting) options.onChange?.(getLayout(), reason);
529
- }
530
-
531
- function travel(step, reason) {
532
- const next = position + step;
533
- if (next < 0 || next >= snapshots.length) return false;
534
- position = next;
535
- setLayout(JSON.parse(snapshots[position]), { reset: false });
536
- options.onChange?.(getLayout(), reason);
537
- return true;
538
- }
539
-
540
- /* ---- add, remove, change ---- */
541
-
542
- function addWidget(type, { id, title, config, x, y, w, h, locked } = {}) {
543
- const def = registry.get(type);
544
- if (!def) throw new TypeError(`Athena UI: the widget type "${type}" is not registered`);
545
- if (widgets.size >= maxWidgets) throw new RangeError(`Athena UI: a grid holds at most ${maxWidgets} widgets`);
546
- const widgetId = typeof id === "string" && SAFE_ID.test(id) && !widgets.has(id) ? id : uid("widget");
547
- const size = clampItem({ x: 0, y: 0, w: w ?? def.defaultSize?.w ?? 3, h: h ?? def.defaultSize?.h ?? 2 }, breakpoint.columns, { min: def.minSize, max: def.maxSize });
548
- const items = itemsOf(breakpoint);
549
- const spot = Number.isFinite(x) && Number.isFinite(y) ? { x, y } : findFreeSpot(items, size.w, size.h, breakpoint.columns);
550
- const widget = createWidget({ id: widgetId, type, title: String(title ?? def.title ?? type).slice(0, 200), config: plain({ ...def.defaultConfig, ...config }), locked, places: {} });
551
- widget.places[breakpoint.name] = { ...clampItem({ ...size, ...spot }, breakpoint.columns, { min: def.minSize, max: def.maxSize }) };
552
- const placed = placeItem([...items, { id: widgetId, ...widget.places[breakpoint.name] }], widgetId, {}, breakpoint.columns, { limits: limitsOf(widget), compactItems });
553
- if (placed) store(breakpoint, placed);
554
- for (const bp of breakpoints) if (bp !== breakpoint) delete widget.places[bp.name];
555
- for (const bp of breakpoints) if (bp !== breakpoint && itemsOf(bp).length) ensurePlaces(bp);
556
- applyPlaces();
557
- orderDom();
558
- commit("add");
559
- announce(translate("widget.added", { title: widget.title }));
560
- return widgetId;
561
- }
562
-
563
- function removeWidget(id) {
564
- const widget = widgets.get(id);
565
- if (!widget) return false;
566
- const title = widget.title;
567
- removeNode(widget);
568
- for (const bp of breakpoints) {
569
- const items = itemsOf(bp);
570
- if (items.length && compactItems) store(bp, compact(items));
571
- }
572
- applyPlaces();
573
- commit("remove");
574
- announce(translate("widget.removed", { title }));
575
- return true;
576
- }
577
-
578
- function duplicateWidget(id) {
579
- const widget = widgets.get(id);
580
- if (!widget) return null;
581
- const place = widget.places[breakpoint.name];
582
- return addWidget(widget.type, { title: translate("widget.copy", { title: widget.title }), config: plain(widget.config), w: place.w, h: place.h });
583
- }
584
-
585
- function lockWidget(id, locked = true) {
586
- const widget = widgets.get(id);
587
- if (!widget) return false;
588
- widget.locked = Boolean(locked);
589
- widget.node.classList.toggle("is-locked", widget.locked);
590
- commit("lock");
591
- return true;
592
- }
593
-
594
- /** Changes the title and / or the config (merged) from code, for example with new data. It is not an undo step. */
595
- function updateWidget(id, { title, config } = {}) {
596
- const widget = widgets.get(id);
597
- if (!widget) return false;
598
- if (title !== undefined) setTitle(widget, title);
599
- if (config !== undefined) widget.config = plain({ ...widget.config, ...config });
600
- markChanged(widget);
601
- return true;
602
- }
603
-
604
- function configureWidget(id) {
605
- const widget = widgets.get(id);
606
- if (!widget) return null;
607
- const form = typeof widget.def?.configForm === "function" ? widget.def.configForm(widget) : (widget.def?.configForm ?? []);
608
- const fields = [
609
- { name: "widgetTitle", label: translate("widget.titleLabel"), type: "text", value: widget.title, required: true },
610
- ...form.map(field => ({ ...field, value: widget.config[field.name] ?? field.value }))
611
- ];
612
- return showFormDialog({
613
- title: translate("widget.settingsTitle"), fields, size: "small",
614
- onSubmit(values) {
615
- const { widgetTitle, ...config } = values;
616
- setTitle(widget, widgetTitle || widget.title);
617
- widget.config = plain({ ...widget.config, ...config });
618
- markChanged(widget);
619
- commit("settings");
620
- }
621
- });
622
- }
623
-
624
- /* ---- moving and resizing: pointer ---- */
625
-
626
- function metrics() {
627
- const rect = element.getBoundingClientRect();
628
- const cell = (rect.width - gap * (breakpoint.columns - 1)) / breakpoint.columns;
629
- return { strideX: cell + gap, strideY: rowHeight + gap };
630
- }
631
-
632
- function cancelGesture() {
633
- if (!gesture) return;
634
- const current = gesture;
635
- gesture = null;
636
- current.stop?.();
637
- store(breakpoint, current.base);
638
- current.widget.node.classList.remove("is-dragging");
639
- applyPlaces({ slide: false });
640
- }
641
-
642
- /** One try of a gesture: the base layout with the item in the new place; shows it when it is possible. */
643
- function tryPlace(current, place) {
644
- const widget = current.widget;
645
- const next = placeItem(current.base, widget.id, place, breakpoint.columns, { limits: limitsOf(widget), compactItems });
646
- if (!next) return false;
647
- const changed = JSON.stringify(next) !== JSON.stringify(current.shown);
648
- current.shown = next;
649
- if (changed) {
650
- store(breakpoint, next);
651
- applyPlaces({ except: current.pointer ? widget.node : undefined });
652
- }
653
- return changed;
654
- }
655
-
656
- function finishGesture(current, reason) {
657
- gesture = null;
658
- current.widget.node.classList.remove("is-dragging");
659
- orderDom();
660
- if (JSON.stringify(current.shown ?? current.base) !== JSON.stringify(current.base)) commit(reason);
661
- }
662
-
663
- function startPointer(event) {
664
- if (!editable || gesture || event.button !== 0) return;
665
- const resize = event.target.closest(".widget-resize");
666
- const grab = event.target.closest(".widget-handle");
667
- if (!resize && !grab) return;
668
- const node = event.target.closest(".widget");
669
- const widget = node && widgets.get(node.dataset.widgetId);
670
- if (!widget || widget.locked) return;
671
- event.preventDefault();
672
- const base = itemsOf(breakpoint);
673
- const start = widget.places[breakpoint.name];
674
- const { strideX, strideY } = metrics();
675
- const dir = resize?.dataset.dir ?? "";
676
- const target = resize ?? grab;
677
- const limits = limitsOf(widget);
678
- const current = { widget, base, shown: base, pointer: true, reason: dir ? "resize" : "move" };
679
- gesture = current;
680
- node.classList.add("is-dragging");
681
- try {
682
- target.setPointerCapture(event.pointerId);
683
- } catch {
684
- // no active pointer (a synthetic event): the handle still gets the events that are sent to it
685
- }
686
- const move = moveEvent => {
687
- const dx = Math.round((moveEvent.clientX - event.clientX) / strideX);
688
- const dy = Math.round((moveEvent.clientY - event.clientY) / strideY);
689
- if (!dir) return tryPlace(current, { x: start.x + dx, y: start.y + dy });
690
- const place = {};
691
- const minW = Math.max(1, limits.min?.w ?? 1);
692
- const minH = Math.max(1, limits.min?.h ?? 1);
693
- const maxW = Math.min(limits.max?.w ?? breakpoint.columns, breakpoint.columns);
694
- const maxH = limits.max?.h ?? Infinity;
695
- if (dir.includes("e")) place.w = Math.min(Math.max(start.w + dx, minW), maxW);
696
- if (dir.includes("w")) {
697
- place.w = Math.min(Math.max(start.w - dx, minW), maxW);
698
- place.x = start.x + start.w - place.w;
699
- }
700
- if (dir.includes("s")) place.h = Math.min(Math.max(start.h + dy, minH), maxH);
701
- if (dir.includes("n")) {
702
- place.h = Math.min(Math.max(start.h - dy, minH), maxH);
703
- place.y = Math.max(start.y + start.h - place.h, 0);
704
- place.h = start.y + start.h - place.y;
705
- }
706
- return tryPlace(current, place);
707
- };
708
- const end = () => {
709
- target.removeEventListener("pointermove", move);
710
- target.removeEventListener("pointerup", up);
711
- target.removeEventListener("pointercancel", cancel);
712
- target.removeEventListener("lostpointercapture", up);
713
- };
714
- const up = () => {
715
- end();
716
- if (gesture === current) finishGesture(current, current.reason);
717
- };
718
- const cancel = () => {
719
- end();
720
- if (gesture === current) cancelGesture();
721
- };
722
- current.stop = end;
723
- target.addEventListener("pointermove", move);
724
- target.addEventListener("pointerup", up);
725
- target.addEventListener("pointercancel", cancel);
726
- target.addEventListener("lostpointercapture", up);
727
- }
728
-
729
- /* ---- moving and resizing: keyboard ---- */
730
-
731
- const describe = widget => {
732
- const place = widget.places[breakpoint.name];
733
- return translate("widget.position", { x: place.x + 1, y: place.y + 1, w: place.w, h: place.h });
734
- };
735
-
736
- function dropKeyboard(current, keep) {
737
- if (gesture !== current) return;
738
- if (!keep) {
739
- cancelGesture();
740
- announce(translate("widget.cancelled"));
741
- } else {
742
- finishGesture(current, current.reason);
743
- announce(translate("widget.dropped", { title: current.widget.title }) + " " + describe(current.widget));
744
- }
745
- current.widget.parts.handle.removeAttribute("aria-pressed");
746
- }
747
-
748
- function keyHandle(event) {
749
- const handle = event.target.closest(".widget-handle");
750
- if (!handle || !editable) return;
751
- const node = handle.closest(".widget");
752
- const widget = widgets.get(node.dataset.widgetId);
753
- if (!widget || widget.locked) return;
754
- const picked = gesture?.widget === widget && gesture.keyboard;
755
- const pick = event.key === " " || event.key === "Enter";
756
- if (event.type === "keyup") {
757
- if (event.key === " ") event.preventDefault(); // Space must not click the button
758
- return;
759
- }
760
- if (!picked) {
761
- if (!pick || gesture) return;
762
- event.preventDefault();
763
- gesture = { widget, base: itemsOf(breakpoint), shown: itemsOf(breakpoint), keyboard: true, reason: "move" };
764
- node.classList.add("is-dragging");
765
- handle.setAttribute("aria-pressed", "true");
766
- announce(translate("widget.pickedUp", { title: widget.title }) + " " + describe(widget));
767
- return;
768
- }
769
- const arrows = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
770
- if (arrows) {
771
- event.preventDefault();
772
- const place = widget.places[breakpoint.name];
773
- const next = event.shiftKey ? { w: place.w + arrows[0], h: place.h + arrows[1] } : { x: place.x + arrows[0], y: place.y + arrows[1] };
774
- gesture.reason = event.shiftKey ? "resize" : gesture.reason;
775
- if (event.shiftKey && (arrows[0] < 0 || arrows[1] < 0) && (place.w + arrows[0] < 1 || place.h + arrows[1] < 1)) return announce(translate("widget.blocked"));
776
- const before = JSON.stringify(widget.places[breakpoint.name]);
777
- const placed = placeItem(itemsOf(breakpoint), widget.id, next, breakpoint.columns, { limits: limitsOf(widget), compactItems });
778
- if (placed) {
779
- store(breakpoint, placed);
780
- gesture.shown = placed;
781
- applyPlaces();
782
- }
783
- announce(placed && JSON.stringify(widget.places[breakpoint.name]) !== before ? describe(widget) : translate("widget.blocked"));
784
- } else if (pick) {
785
- event.preventDefault();
786
- dropKeyboard(gesture, true);
787
- } else if (event.key === "Escape") {
788
- event.preventDefault();
789
- event.stopPropagation();
790
- dropKeyboard(gesture, false);
791
- }
792
- }
793
-
794
- function blurHandle(event) {
795
- if (gesture?.keyboard && event.target.closest?.(".widget-handle")) dropKeyboard(gesture, true);
796
- }
797
-
798
- function clickAction(event) {
799
- const button = event.target.closest(".widget-action");
800
- if (!button || !editable) return;
801
- const id = button.closest(".widget")?.dataset.widgetId;
802
- const action = button.dataset.action;
803
- if (action === "settings") configureWidget(id);
804
- else if (action === "duplicate") duplicateWidget(id);
805
- else if (action === "remove") removeWidget(id);
806
- }
807
-
808
- element.addEventListener("pointerdown", startPointer);
809
- element.addEventListener("keydown", keyHandle);
810
- element.addEventListener("keyup", keyHandle);
811
- element.addEventListener("focusout", blurHandle);
812
- element.addEventListener("click", clickAction);
813
-
814
- /* ---- start ---- */
815
-
816
- function setEditable(flag = true) {
817
- editable = Boolean(flag);
818
- if (!editable) cancelGesture();
819
- element.classList.toggle("is-editable", editable);
820
- }
821
-
822
- breakpoint = pickBreakpoint();
823
- applyContainerClasses();
824
- if (options.layout) setLayout(options.layout);
825
- else {
826
- for (const entry of options.widgets ?? []) {
827
- const def = registry.get(entry.type);
828
- if (!def) {
829
- console.warn(`Athena UI: the widget type "${entry.type}" is not registered`);
830
- continue;
831
- }
832
- addWidget(entry.type, entry);
833
- }
834
- snapshots.length = 0;
835
- snapshots.push(JSON.stringify(getLayout()));
836
- position = 0;
837
- }
838
- setEditable(options.editable);
839
- resizing?.observe(element);
840
- starting = false;
841
-
842
- return asHandle({
843
- element,
844
- addWidget, removeWidget, duplicateWidget, configureWidget, updateWidget, lockWidget,
845
- getWidget: id => (widgets.has(id) ? { id, type: widgets.get(id).type, title: widgets.get(id).title, config: plain(widgets.get(id).config), locked: widgets.get(id).locked, element: widgets.get(id).node } : null),
846
- getWidgets: () => [...widgets.keys()],
847
- setEditable, isEditable: () => editable,
848
- getLayout, setLayout,
849
- undo: () => travel(-1, "undo"), redo: () => travel(1, "redo"),
850
- canUndo: () => position > 0, canRedo: () => position < snapshots.length - 1,
851
- getBreakpoint: () => breakpoint.name,
852
- destroy() {
853
- if (destroyed) return;
854
- destroyed = true;
855
- cancelGesture();
856
- for (const timer of timers) clearTimeout(timer);
857
- for (const widget of [...widgets.values()]) removeNode(widget);
858
- intersection?.disconnect();
859
- resizing?.disconnect();
860
- element.removeEventListener("pointerdown", startPointer);
861
- element.removeEventListener("keydown", keyHandle);
862
- element.removeEventListener("keyup", keyHandle);
863
- element.removeEventListener("focusout", blurHandle);
864
- element.removeEventListener("click", clickAction);
865
- element.classList.remove("athena-widget-grid", "is-editable");
866
- for (const name of [...element.classList].filter(name => /^wg-/.test(name))) element.classList.remove(name);
867
- live.remove();
868
- }
869
- });
870
- }
1
+ //Widget grid of Athena UI: a dashboard of widgets that can be added, configured, moved, resized, locked, saved and loaded.
2
+ //Layout is CSS grid. The place of a widget is a few CSS classes (no inline style), the maths is in core/gridLayout.js.
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ import { animate, prefersReducedMotion } from "../../core/motion.js";
7
+ import { asHandle, el, resolveElement, uid } from "../../core/dom.js";
8
+ import { translate } from "../../core/i18n.js";
9
+ import { showFormDialog } from "../dialogGenerator/dialogGenerator.js";
10
+ import { clampItem, compact, findFreeSpot, normalize, placeItem } from "../../core/gridLayout.js";
11
+
12
+ /* ------------------REGISTRY------------------- */
13
+
14
+ const registry = new Map();
15
+
16
+ /**
17
+ * Registers a type of widget, so grids can create it, load it from a saved layout and show its settings.
18
+ *
19
+ * @param {string} type name of the type, for example "stat" (it is saved in layouts)
20
+ * @param {object} definition
21
+ * @param {(context: WidgetContext) => (void|Function|{update?: Function, destroy?: Function})} definition.render builds the widget into `context.element`;
22
+ * it may return a function (called when the widget goes away) or an object with `update(context)` and `destroy(context)`
23
+ * @param {(context: WidgetContext) => void} [definition.update] called (throttled) when the config or the title changed; without it the widget is rendered again
24
+ * @param {(context: WidgetContext, size: {width: number, height: number}) => void} [definition.resize] called (throttled) when the body changes its size
25
+ * @param {(context: WidgetContext) => void} [definition.destroy] called when the widget is removed or the grid is destroyed
26
+ * @param {object[]|((widget: object) => object[])} [definition.configForm] field definitions (see generateField) of the settings dialog; the field `name` is the key in the config
27
+ * @param {object} [definition.defaultConfig] config of a new widget
28
+ * @param {string} [definition.title] title of a new widget
29
+ * @param {{w: number, h: number}} [definition.defaultSize={w: 3, h: 2}] size in grid cells
30
+ * @param {{w?: number, h?: number}} [definition.minSize]
31
+ * @param {{w?: number, h?: number}} [definition.maxSize]
32
+ *
33
+ * @typedef {object} WidgetContext
34
+ * @property {string} id
35
+ * @property {string} type
36
+ * @property {HTMLElement} element the body of the widget: build into it
37
+ * @property {object} config the current config (read it again in update())
38
+ * @property {string} title
39
+ * @property {{width: number, height: number}} size the box of the body, as it is now
40
+ * @property {{width: number, height: number}} contentSize what is left inside the padding of the body: the room a chart or a table has
41
+ * @property {(title: string) => void} setTitle
42
+ */
43
+ export function registerWidget(type, definition) {
44
+ if (typeof type !== "string" || !/^[\w.:-]{1,100}$/.test(type)) throw new TypeError("Athena UI: a widget type is a short name of letters, digits and . _ : -");
45
+ if (typeof definition?.render !== "function") throw new TypeError(`Athena UI: the widget type "${type}" needs a render function`);
46
+ registry.set(type, definition);
47
+ }
48
+
49
+ /** Forgets a widget type. Widgets of it that are in grids stay and are shown as unknown. */
50
+ export function unregisterWidget(type) {
51
+ return registry.delete(type);
52
+ }
53
+
54
+ /** The names of the registered widget types. */
55
+ export function getWidgetTypes() {
56
+ return [...registry.keys()];
57
+ }
58
+
59
+ /* ------------------CLASSES FOR PLACES------------------- */
60
+
61
+ // A place is a few classes whose rules are written into one constructed style sheet of the document (or shadow root): the strict
62
+ // Content-Security-Policy that forbids the style attribute allows it, and the browser lays the grid out.
63
+ const sheets = new WeakMap();
64
+ function classSheet(root) {
65
+ if (!sheets.has(root)) {
66
+ const usable = typeof CSSStyleSheet === "function" && Array.isArray(root.adoptedStyleSheets) && typeof CSSStyleSheet.prototype.replaceSync === "function";
67
+ const sheet = usable ? new CSSStyleSheet() : null;
68
+ if (sheet) root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
69
+ sheets.set(root, { sheet, rules: new Map() });
70
+ }
71
+ return sheets.get(root);
72
+ }
73
+
74
+ /** Gives the class of one declaration (and writes its rule the first time); returns "" without constructed style sheets. */
75
+ function useClass(root, name, css) {
76
+ const state = classSheet(root);
77
+ if (!state.sheet) return "";
78
+ if (!state.rules.has(name)) {
79
+ state.rules.set(name, `.${name} { ${css} }`);
80
+ state.sheet.replaceSync(`@layer athena {\n${[...state.rules.values()].join("\n")}\n}`);
81
+ }
82
+ return name;
83
+ }
84
+
85
+ const PLACE_CLASSES = [["x", "wg-x", n => `grid-column-start: ${n + 1}`], ["y", "wg-y", n => `grid-row-start: ${n + 1}`], ["w", "wg-w", n => `grid-column-end: span ${n}`], ["h", "wg-h", n => `grid-row-end: span ${n}`]];
86
+
87
+ /** Puts a node on a place. With CSSOM as the fallback where there are no constructed style sheets (still no style attribute in the markup). */
88
+ function setPlace(root, node, place) {
89
+ const classes = [];
90
+ for (const [key, prefix, css] of PLACE_CLASSES) {
91
+ const name = useClass(root, `${prefix}-${place[key]}`, css(place[key]));
92
+ if (name) classes.push(name);
93
+ }
94
+ if (classes.length) {
95
+ for (const old of node.dataset.placeClasses?.split(" ").filter(Boolean) ?? []) if (!classes.includes(old)) node.classList.remove(old);
96
+ node.classList.add(...classes);
97
+ node.dataset.placeClasses = classes.join(" ");
98
+ } else {
99
+ node.style.gridColumn = `${place.x + 1} / span ${place.w}`;
100
+ node.style.gridRow = `${place.y + 1} / span ${place.h}`;
101
+ }
102
+ }
103
+
104
+ /* ------------------HELPERS------------------- */
105
+
106
+ const wholeNumber = (value, min, max, fallback) => (Number.isFinite(value) ? Math.min(Math.max(Math.round(value), min), max) : fallback);
107
+ const plain = value => {
108
+ // a JSON copy without the keys that change prototypes
109
+ const text = JSON.stringify(value ?? {});
110
+ if (text.length > 200000) throw new RangeError("Athena UI: the config of a widget is too large");
111
+ return JSON.parse(text, (key, item) => (key === "__proto__" || key === "constructor" || key === "prototype" ? undefined : item));
112
+ };
113
+ const isPlainObject = value => value !== null && typeof value === "object" && !Array.isArray(value);
114
+ const SAFE_ID = /^[\w.:-]{1,100}$/;
115
+ const LAYOUT_VERSION = 1;
116
+
117
+ /* ------------------THE GRID------------------- */
118
+
119
+ /**
120
+ * A grid of widgets.
121
+ *
122
+ * @param {object} options
123
+ * @param {string|HTMLElement} options.element the container
124
+ * @param {number} [options.columns=12] columns when there are no breakpoints
125
+ * @param {number} [options.rowHeight=80] height of a row in px
126
+ * @param {number} [options.gap=12] gap between widgets in px
127
+ * @param {Record<string, {minWidth?: number, columns: number}>} [options.breakpoints] layouts by the width of the container, for example
128
+ * `{ large: { minWidth: 900, columns: 12 }, small: { minWidth: 0, columns: 4 } }`. A breakpoint without a layout of its own is derived from the widest one.
129
+ * @param {object[]} [options.widgets] first widgets: `{ type, title?, config?, x?, y?, w?, h?, locked?, id? }`
130
+ * @param {object} [options.layout] a saved layout (getLayout()), used instead of `widgets`
131
+ * @param {boolean} [options.editable=false] edit mode: move, resize, settings, duplicate, remove
132
+ * @param {boolean} [options.compact=true] widgets fall upwards when there is room (false: they stay where they are put)
133
+ * @param {boolean} [options.animate=true] widgets slide to their new places (never under reduced motion)
134
+ * @param {string} [options.label] accessible name of the dashboard
135
+ * @param {number} [options.maxWidgets=200]
136
+ * @param {number} [options.changeDelay=0] ms to wait after a change before onChange is called (a drag is many steps: one call after the last); 0 calls it at once. `flush()` calls it now
137
+ * @param {(layout: object, reason: string) => void} [options.onChange] called after a change made by the person or by add/remove/...: "move", "resize", "add", "remove", "duplicate", "settings", "lock", "undo", "redo"
138
+ * @returns the handle: { element, addWidget, addWidgetWithSettings, flush, removeWidget, duplicateWidget, configureWidget, updateWidget, getWidget, getWidgets, lockWidget, setEditable, isEditable,
139
+ * getLayout, setLayout, undo, redo, canUndo, canRedo, getBreakpoint, destroy }
140
+ */
141
+ export function createWidgetGrid(options = {}) {
142
+ const element = resolveElement(options.element);
143
+ if (!element) throw new TypeError("Athena UI: createWidgetGrid needs an element");
144
+ const root = element.getRootNode?.() ?? document;
145
+ const rowHeight = wholeNumber(options.rowHeight, 20, 1000, 80);
146
+ const gap = wholeNumber(options.gap, 0, 100, 12);
147
+ const compactItems = options.compact !== false;
148
+ const animateMoves = options.animate !== false;
149
+ const maxWidgets = wholeNumber(options.maxWidgets, 1, 2000, 200);
150
+ const breakpoints = Object.entries(options.breakpoints ?? { default: { minWidth: 0, columns: options.columns ?? 12 } })
151
+ .map(([name, value]) => ({ name, minWidth: wholeNumber(value.minWidth, 0, 100000, 0), columns: wholeNumber(value.columns, 1, 48, 12) }))
152
+ .sort((a, b) => b.minWidth - a.minWidth);
153
+ if (!breakpoints.length) throw new TypeError("Athena UI: createWidgetGrid needs at least one breakpoint");
154
+
155
+ /** @type {Map<string, any>} */
156
+ const widgets = new Map();
157
+ let breakpoint = breakpoints[0];
158
+ let editable = false;
159
+ let gesture = null;
160
+ let destroyed = false;
161
+ let starting = true; // the first widgets are not a change
162
+ const timers = new Set();
163
+
164
+ const live = el("div", { class: "athena-visually-hidden", attrs: { role: "status", "aria-live": "polite" } });
165
+ element.after(live);
166
+ element.classList.add("athena-widget-grid");
167
+ if (options.label) element.setAttribute("aria-label", options.label);
168
+ element.setAttribute("role", "group");
169
+ const announce = text => {
170
+ live.textContent = "";
171
+ live.textContent = text;
172
+ };
173
+
174
+ const intersection = typeof IntersectionObserver === "function" ? new IntersectionObserver(entries => {
175
+ for (const entry of entries) {
176
+ const widget = widgets.get(entry.target.dataset.widgetId);
177
+ if (!widget) continue;
178
+ widget.visible = entry.isIntersecting;
179
+ if (widget.visible) showWidget(widget);
180
+ }
181
+ }) : null;
182
+ const resizing = typeof ResizeObserver === "function" ? new ResizeObserver(entries => {
183
+ for (const entry of entries) {
184
+ const node = entry.target;
185
+ if (node === element) {
186
+ const next = pickBreakpoint();
187
+ if (next !== breakpoint) switchBreakpoint(next);
188
+ continue;
189
+ }
190
+ const widget = widgets.get(node.closest(".widget")?.dataset.widgetId);
191
+ if (widget) later(widget, "resizeTimer", () => {
192
+ if (!widget.rendered) return;
193
+ measure(widget); // the size the widget is asked about is the one it has now
194
+ widget.def?.resize?.(widget.context, widget.context.size);
195
+ }, 100);
196
+ }
197
+ }) : null;
198
+
199
+ function later(owner, key, fn, ms) {
200
+ clearTimeout(owner[key]);
201
+ owner[key] = setTimeout(() => {
202
+ timers.delete(owner[key]);
203
+ if (!destroyed) fn();
204
+ }, ms);
205
+ timers.add(owner[key]);
206
+ }
207
+
208
+ /* ---- breakpoints and layouts ---- */
209
+
210
+ function pickBreakpoint() {
211
+ const width = element.clientWidth;
212
+ if (!width) return breakpoint;
213
+ return breakpoints.find(entry => width >= entry.minWidth) ?? breakpoints.at(-1);
214
+ }
215
+
216
+ const limitsOf = widget => ({ min: widget.def?.minSize, max: widget.def?.maxSize });
217
+
218
+ /** The items of one breakpoint, in the form of gridLayout.js. */
219
+ function itemsOf(bp) {
220
+ return [...widgets.values()].filter(widget => widget.places[bp.name]).map(widget => ({ id: widget.id, locked: widget.locked, ...widget.places[bp.name] }));
221
+ }
222
+
223
+ function store(bp, items) {
224
+ for (const item of items) {
225
+ const widget = widgets.get(item.id);
226
+ if (widget) widget.places[bp.name] = { x: item.x, y: item.y, w: item.w, h: item.h };
227
+ }
228
+ }
229
+
230
+ /** Widgets without a place at this breakpoint get one, derived from the widest breakpoint that has them. */
231
+ function ensurePlaces(bp) {
232
+ const missing = [...widgets.values()].filter(widget => !widget.places[bp.name]);
233
+ if (!missing.length) return;
234
+ const source = breakpoints.find(entry => entry !== bp && missing.every(widget => widget.places[entry.name])) ?? breakpoints.find(entry => entry !== bp && missing.some(widget => widget.places[entry.name]));
235
+ const items = itemsOf(bp);
236
+ const reading = missing.map(widget => ({ id: widget.id, ...(widget.places[source?.name] ?? { x: 0, y: 1e6, w: 3, h: 2 }) })).sort((a, b) => a.y - b.y || a.x - b.x);
237
+ for (const item of reading) {
238
+ const widget = widgets.get(item.id);
239
+ const size = clampItem(item, bp.columns, limitsOf(widget));
240
+ const spot = findFreeSpot(items, size.w, size.h, bp.columns);
241
+ const placed = { id: item.id, locked: widget.locked, ...spot, w: size.w, h: size.h };
242
+ items.push(placed);
243
+ widget.places[bp.name] = { x: placed.x, y: placed.y, w: placed.w, h: placed.h };
244
+ }
245
+ }
246
+
247
+ function applyContainerClasses() {
248
+ for (const old of [...element.classList].filter(name => /^wg-(cols|rh|gap)-/.test(name))) element.classList.remove(old);
249
+ const names = [
250
+ useClass(root, `wg-cols-${breakpoint.columns}`, `grid-template-columns: repeat(${breakpoint.columns}, minmax(0, 1fr))`),
251
+ useClass(root, `wg-rh-${rowHeight}`, `grid-auto-rows: ${rowHeight}px`),
252
+ useClass(root, `wg-gap-${gap}`, `gap: ${gap}px`)
253
+ ].filter(Boolean);
254
+ if (names.length) element.classList.add(...names);
255
+ else {
256
+ element.style.gridTemplateColumns = `repeat(${breakpoint.columns}, minmax(0, 1fr))`;
257
+ element.style.gridAutoRows = `${rowHeight}px`;
258
+ element.style.gap = `${gap}px`;
259
+ }
260
+ }
261
+
262
+ /** Puts every node on its place; the nodes that moved slide there (FLIP). */
263
+ function applyPlaces({ slide = animateMoves, except } = {}) {
264
+ const nodes = [...widgets.values()].map(widget => widget.node);
265
+ const sliding = slide && !prefersReducedMotion() && nodes.length <= 60;
266
+ const before = sliding ? new Map(nodes.map(node => [node, node.getBoundingClientRect()])) : null;
267
+ for (const widget of widgets.values()) if (widget.places[breakpoint.name]) setPlace(root, widget.node, widget.places[breakpoint.name]);
268
+ if (!before) return;
269
+ for (const node of nodes) {
270
+ if (node === except) continue;
271
+ const was = before.get(node);
272
+ const now = node.getBoundingClientRect();
273
+ const dx = was.left - now.left;
274
+ const dy = was.top - now.top;
275
+ if (Math.abs(dx) > 1 || Math.abs(dy) > 1) animate(node, [{ translate: `${dx}px ${dy}px` }, { translate: "0 0" }], { duration: 160 });
276
+ }
277
+ }
278
+
279
+ function switchBreakpoint(next) {
280
+ cancelGesture();
281
+ breakpoint = next;
282
+ ensurePlaces(next);
283
+ applyContainerClasses();
284
+ applyPlaces({ slide: false });
285
+ }
286
+
287
+ /** Keeps the DOM order equal to the order of reading, so Tab goes through the widgets as the eye does. */
288
+ function orderDom() {
289
+ const order = [...widgets.values()].filter(widget => widget.places[breakpoint.name]).sort((a, b) => a.places[breakpoint.name].y - b.places[breakpoint.name].y || a.places[breakpoint.name].x - b.places[breakpoint.name].x);
290
+ const current = [...element.children].filter(node => node.classList.contains("widget"));
291
+ if (order.every((widget, index) => current[index] === widget.node)) return;
292
+ const focused = element.contains(document.activeElement) ? document.activeElement : null;
293
+ for (const widget of order) element.append(widget.node);
294
+ focused?.focus?.({ preventScroll: true });
295
+ }
296
+
297
+ /* ---- the widget ---- */
298
+
299
+ function buildNode(widget) {
300
+ const titleId = uid("widget-title");
301
+ const handle = el("button", { class: "widget-handle", attrs: { type: "button", "aria-describedby": titleId } }, "⠿");
302
+ const title = el("h3", { class: "widget-title", attrs: { id: titleId } });
303
+ const settings = el("button", { class: "widget-action", attrs: { type: "button", "data-action": "settings" } }, "⚙");
304
+ const copy = el("button", { class: "widget-action", attrs: { type: "button", "data-action": "duplicate" } }, "⧉");
305
+ const remove = el("button", { class: "widget-action", attrs: { type: "button", "data-action": "remove" } }, "✕");
306
+ const body = el("div", { class: "widget-body" });
307
+ const node = el("section", { class: "widget", attrs: { "data-widget-id": widget.id, "data-widget-type": widget.type, "aria-labelledby": titleId } },
308
+ el("header", { class: "widget-header" }, handle, title, el("div", { class: "widget-actions" }, settings, copy, remove)), body);
309
+ for (const dir of ["n", "s", "e", "w", "ne", "nw", "se", "sw"]) node.append(el("span", { class: `widget-resize widget-resize-${dir}`, attrs: { "data-dir": dir } }));
310
+ widget.node = node;
311
+ widget.parts = { handle, title, settings, copy, remove, body };
312
+ widget.context = {
313
+ id: widget.id,
314
+ type: widget.type,
315
+ element: body,
316
+ get config() { return widget.config; },
317
+ get title() { return widget.title; },
318
+ size: { width: 0, height: 0 },
319
+ contentSize: { width: 0, height: 0 },
320
+ setTitle: text => setTitle(widget, text)
321
+ };
322
+ labelNode(widget);
323
+ node.classList.toggle("is-locked", widget.locked);
324
+ resizing?.observe(body);
325
+ if (intersection) intersection.observe(node);
326
+ else {
327
+ widget.visible = true;
328
+ queueMicrotask(() => !destroyed && showWidget(widget));
329
+ }
330
+ }
331
+
332
+ function labelNode(widget) {
333
+ const { handle, title, settings, copy, remove } = widget.parts;
334
+ title.textContent = widget.title;
335
+ const params = { title: widget.title };
336
+ handle.setAttribute("aria-label", translate("widget.move", params));
337
+ settings.setAttribute("aria-label", translate("widget.settings", params));
338
+ copy.setAttribute("aria-label", translate("widget.duplicate", params));
339
+ remove.setAttribute("aria-label", translate("widget.remove", params));
340
+ for (const part of [settings, copy, remove, handle]) part.title = part.getAttribute("aria-label");
341
+ widget.node.querySelectorAll(".widget-resize").forEach(handleNode => handleNode.setAttribute("aria-hidden", "true"));
342
+ }
343
+
344
+ function setTitle(widget, text) {
345
+ widget.title = String(text ?? "").slice(0, 200);
346
+ labelNode(widget);
347
+ }
348
+
349
+ /** Renders the widget when it is visible for the first time, or brings it up to date when it changed while it was not. */
350
+ function showWidget(widget) {
351
+ if (destroyed || !widget.visible) return;
352
+ if (!widget.rendered) renderWidget(widget);
353
+ else if (widget.dirty) updateNow(widget);
354
+ }
355
+
356
+ /** Sets context.size (the box of the body) and context.contentSize (inside its padding). */
357
+ function measure(widget) {
358
+ const body = widget.parts.body;
359
+ const rect = body.getBoundingClientRect();
360
+ widget.context.size = { width: Math.round(rect.width), height: Math.round(rect.height) };
361
+ const style = body.ownerDocument.defaultView?.getComputedStyle?.(body);
362
+ const pad = name => Number.parseFloat(style?.[name]) || 0;
363
+ widget.context.contentSize = {
364
+ width: Math.max(0, widget.context.size.width - pad("paddingLeft") - pad("paddingRight")),
365
+ height: Math.max(0, widget.context.size.height - pad("paddingTop") - pad("paddingBottom"))
366
+ };
367
+ }
368
+
369
+ function renderWidget(widget) {
370
+ widget.rendered = true;
371
+ widget.dirty = false;
372
+ widget.def = registry.get(widget.type);
373
+ widget.parts.body.replaceChildren();
374
+ widget.node.classList.remove("is-unknown", "is-failed");
375
+ measure(widget);
376
+ if (!widget.def) {
377
+ widget.node.classList.add("is-unknown");
378
+ widget.parts.body.append(el("p", { class: "widget-note", text: translate("widget.unknown", { type: widget.type }) }));
379
+ return;
380
+ }
381
+ try {
382
+ const result = widget.def.render(widget.context);
383
+ widget.instance = typeof result === "function" ? { destroy: result } : (result ?? {});
384
+ } catch (error) {
385
+ console.error(`Athena UI: the widget "${widget.type}" failed to render`, error);
386
+ widget.node.classList.add("is-failed");
387
+ widget.parts.body.replaceChildren(el("p", { class: "widget-note", text: translate("widget.failed") }));
388
+ }
389
+ }
390
+
391
+ function disposeWidget(widget) {
392
+ try {
393
+ widget.instance?.destroy?.(widget.context);
394
+ if (widget.rendered && widget.def?.destroy && !widget.instance?.destroy) widget.def.destroy(widget.context);
395
+ } catch (error) {
396
+ console.error(`Athena UI: the widget "${widget.type}" failed to clean up`, error);
397
+ }
398
+ widget.instance = null;
399
+ widget.rendered = false;
400
+ }
401
+
402
+ function updateNow(widget) {
403
+ widget.dirty = false;
404
+ measure(widget);
405
+ const update = widget.instance?.update ?? widget.def?.update;
406
+ if (!update) {
407
+ disposeWidget(widget);
408
+ renderWidget(widget);
409
+ return;
410
+ }
411
+ try {
412
+ update.call(widget.instance, widget.context);
413
+ } catch (error) {
414
+ console.error(`Athena UI: the widget "${widget.type}" failed to update`, error);
415
+ }
416
+ }
417
+
418
+ function createWidget(data) {
419
+ const widget = {
420
+ id: data.id, type: data.type, title: data.title, config: data.config, locked: Boolean(data.locked), places: data.places ?? {},
421
+ node: null, parts: null, context: null, def: registry.get(data.type), instance: null, rendered: false, visible: false, dirty: false
422
+ };
423
+ widgets.set(widget.id, widget);
424
+ buildNode(widget);
425
+ element.append(widget.node);
426
+ return widget;
427
+ }
428
+
429
+ function removeNode(widget) {
430
+ clearTimeout(widget.updateTimer);
431
+ clearTimeout(widget.resizeTimer);
432
+ disposeWidget(widget);
433
+ intersection?.unobserve(widget.node);
434
+ resizing?.unobserve(widget.parts.body);
435
+ widget.node.remove();
436
+ widgets.delete(widget.id);
437
+ }
438
+
439
+ /* ---- layout JSON ---- */
440
+
441
+ /** The layout as plain, versioned JSON: where it is stored is up to the application. */
442
+ function getLayout({ breakpoint: only } = {}) {
443
+ const items = itemsOf(breakpoint);
444
+ const order = new Map(items.sort((a, b) => a.y - b.y || a.x - b.x).map((item, index) => [item.id, index]));
445
+ return {
446
+ version: LAYOUT_VERSION,
447
+ widgets: [...widgets.values()].sort((a, b) => (order.get(a.id) ?? 1e9) - (order.get(b.id) ?? 1e9)).map(widget => ({
448
+ id: widget.id, type: widget.type, title: widget.title, config: plain(widget.config), locked: widget.locked,
449
+ layouts: Object.fromEntries(Object.entries(widget.places).map(([name, place]) => [name, { ...place }])),
450
+ // for an application that keeps ONE layout: the place of the widget in that breakpoint, flat (x, y, w, h)
451
+ ...(only && widget.places[only] ? { x: widget.places[only].x, y: widget.places[only].y, w: widget.places[only].w, h: widget.places[only].h } : {})
452
+ }))
453
+ };
454
+ }
455
+
456
+ /** Checks one entry of a layout; returns the clean widget or a string with the reason. */
457
+ function checkEntry(entry, seen) {
458
+ if (!isPlainObject(entry)) return "not an object";
459
+ if (typeof entry.type !== "string" || !SAFE_ID.test(entry.type)) return "bad type";
460
+ let config;
461
+ try {
462
+ config = isPlainObject(entry.config) ? plain(entry.config) : {};
463
+ } catch {
464
+ return "bad config";
465
+ }
466
+ const places = {};
467
+ for (const bp of breakpoints) {
468
+ const place = entry.layouts?.[bp.name] ?? (breakpoints.length === 1 ? entry : null);
469
+ if (!isPlainObject(place) || ![place.x, place.y, place.w, place.h].every(Number.isFinite)) continue;
470
+ places[bp.name] = { x: wholeNumber(place.x, 0, 10000, 0), y: wholeNumber(place.y, 0, 100000, 0), w: wholeNumber(place.w, 1, 48, 1), h: wholeNumber(place.h, 1, 1000, 1) };
471
+ }
472
+ let id = typeof entry.id === "string" && SAFE_ID.test(entry.id) && !seen.has(entry.id) ? entry.id : null;
473
+ while (!id || seen.has(id)) id = uid("widget");
474
+ seen.add(id);
475
+ const def = registry.get(entry.type);
476
+ return { id, type: entry.type, title: typeof entry.title === "string" ? entry.title.slice(0, 200) : (def?.title ?? entry.type), config, locked: entry.locked === true, places };
477
+ }
478
+
479
+ /**
480
+ * Replaces everything by a saved layout. An entry that is not valid is skipped; a type that is not registered is shown as a placeholder (its data is kept).
481
+ * @returns {{loaded: number, skipped: {index: number, reason: string}[]}}
482
+ */
483
+ function setLayout(layout, { reset = true } = {}) {
484
+ if (!isPlainObject(layout) || layout.version !== LAYOUT_VERSION || !Array.isArray(layout.widgets)) throw new TypeError(`Athena UI: a layout is { version: ${LAYOUT_VERSION}, widgets: [...] }`);
485
+ cancelGesture();
486
+ const seen = new Set();
487
+ const skipped = [];
488
+ const clean = [];
489
+ layout.widgets.forEach((entry, index) => {
490
+ if (clean.length >= maxWidgets) return skipped.push({ index, reason: "too many widgets" });
491
+ const result = checkEntry(entry, seen);
492
+ if (typeof result === "string") skipped.push({ index, reason: result });
493
+ else clean.push(result);
494
+ });
495
+ const keep = new Map(clean.map(item => [item.id, item]));
496
+ for (const widget of [...widgets.values()]) if (!keep.has(widget.id) || widget.type !== keep.get(widget.id).type) removeNode(widget);
497
+ for (const item of clean) {
498
+ const widget = widgets.get(item.id);
499
+ if (!widget) {
500
+ createWidget(item);
501
+ continue;
502
+ }
503
+ const changed = JSON.stringify(widget.config) !== JSON.stringify(item.config) || widget.title !== item.title;
504
+ Object.assign(widget, { config: item.config, locked: item.locked, places: item.places });
505
+ widget.node.classList.toggle("is-locked", item.locked);
506
+ if (widget.title !== item.title) setTitle(widget, item.title);
507
+ if (changed) markChanged(widget);
508
+ }
509
+ // validate the places of every breakpoint: inside the columns, no overlaps
510
+ for (const bp of breakpoints) {
511
+ const items = itemsOf(bp);
512
+ if (items.length) store(bp, normalizeKeeping(items, bp));
513
+ }
514
+ ensurePlaces(breakpoint);
515
+ applyContainerClasses();
516
+ applyPlaces({ slide: false });
517
+ orderDom();
518
+ if (reset) {
519
+ snapshots.length = 0;
520
+ snapshots.push(JSON.stringify(getLayout()));
521
+ position = 0;
522
+ }
523
+ for (const skip of skipped) console.warn(`Athena UI: widget ${skip.index} of the layout was skipped (${skip.reason})`);
524
+ return { loaded: clean.length, skipped };
525
+ }
526
+
527
+ function normalizeKeeping(items, bp) {
528
+ return normalize(items, bp.columns, item => limitsOf(widgets.get(item.id)));
529
+ }
530
+
531
+ function markChanged(widget) {
532
+ widget.dirty = true;
533
+ if (widget.visible && widget.rendered) later(widget, "updateTimer", () => updateNow(widget), 100);
534
+ }
535
+
536
+ /* ---- snapshots ---- */
537
+
538
+ const snapshots = [];
539
+ let position = -1;
540
+
541
+ function commit(reason) {
542
+ const snapshot = JSON.stringify(getLayout());
543
+ if (snapshot === snapshots[position]) return;
544
+ snapshots.length = position + 1;
545
+ snapshots.push(snapshot);
546
+ if (snapshots.length > 100) snapshots.shift();
547
+ position = snapshots.length - 1;
548
+ if (!starting) notify(reason);
549
+ }
550
+
551
+ // onChange is called at once, or, with the option `changeDelay`, a moment after the last change (a drag is many steps): then it is told the reason of the last one.
552
+ let changeTimer = 0;
553
+ let pendingReason = null;
554
+ function notify(reason) {
555
+ if (!(options.changeDelay > 0)) {
556
+ options.onChange?.(getLayout(), reason);
557
+ return;
558
+ }
559
+ pendingReason = reason;
560
+ clearTimeout(changeTimer);
561
+ changeTimer = setTimeout(flush, options.changeDelay);
562
+ }
563
+ /** Calls onChange now when a change is waiting for its delay (leaving the page, a button "save"). */
564
+ function flush() {
565
+ clearTimeout(changeTimer);
566
+ if (pendingReason === null) return;
567
+ const reason = pendingReason;
568
+ pendingReason = null;
569
+ if (!destroyed) options.onChange?.(getLayout(), reason);
570
+ }
571
+
572
+ function travel(step, reason) {
573
+ const next = position + step;
574
+ if (next < 0 || next >= snapshots.length) return false;
575
+ position = next;
576
+ setLayout(JSON.parse(snapshots[position]), { reset: false });
577
+ options.onChange?.(getLayout(), reason);
578
+ return true;
579
+ }
580
+
581
+ /* ---- add, remove, change ---- */
582
+
583
+ // Puts a new widget in the grid without telling anybody (no undo step, no onChange): addWidget and addWidgetWithSettings are the two ways to finish it.
584
+ function place(type, { id, title, config, x, y, w, h, locked } = {}) {
585
+ const def = registry.get(type);
586
+ if (!def) throw new TypeError(`Athena UI: the widget type "${type}" is not registered`);
587
+ if (widgets.size >= maxWidgets) throw new RangeError(`Athena UI: a grid holds at most ${maxWidgets} widgets`);
588
+ const widgetId = typeof id === "string" && SAFE_ID.test(id) && !widgets.has(id) ? id : uid("widget");
589
+ const size = clampItem({ x: 0, y: 0, w: w ?? def.defaultSize?.w ?? 3, h: h ?? def.defaultSize?.h ?? 2 }, breakpoint.columns, { min: def.minSize, max: def.maxSize });
590
+ const items = itemsOf(breakpoint);
591
+ const spot = Number.isFinite(x) && Number.isFinite(y) ? { x, y } : findFreeSpot(items, size.w, size.h, breakpoint.columns);
592
+ const widget = createWidget({ id: widgetId, type, title: String(title ?? def.title ?? type).slice(0, 200), config: plain({ ...def.defaultConfig, ...config }), locked, places: {} });
593
+ widget.places[breakpoint.name] = { ...clampItem({ ...size, ...spot }, breakpoint.columns, { min: def.minSize, max: def.maxSize }) };
594
+ const placed = placeItem([...items, { id: widgetId, ...widget.places[breakpoint.name] }], widgetId, {}, breakpoint.columns, { limits: limitsOf(widget), compactItems });
595
+ if (placed) store(breakpoint, placed);
596
+ for (const bp of breakpoints) if (bp !== breakpoint) delete widget.places[bp.name];
597
+ for (const bp of breakpoints) if (bp !== breakpoint && itemsOf(bp).length) ensurePlaces(bp);
598
+ applyPlaces();
599
+ orderDom();
600
+ return widgetId;
601
+ }
602
+
603
+ function addWidget(type, options = {}) {
604
+ const widgetId = place(type, options);
605
+ commit("add");
606
+ announce(translate("widget.added", { title: widgets.get(widgetId).title }));
607
+ return widgetId;
608
+ }
609
+
610
+ /**
611
+ * Adds a widget and opens its settings at once. A person who gives up leaves the grid as it was: nothing is added, there is no undo step and onChange is not called. A person who saves
612
+ * has added a widget: one undo step ("add") and one call of onChange.
613
+ * @returns {Promise<string|null>} the id of the widget, or null when the settings were dismissed
614
+ */
615
+ async function addWidgetWithSettings(type, options = {}) {
616
+ const widgetId = place(type, options);
617
+ const saved = await configureWidget(widgetId, { reason: "add" });
618
+ if (destroyed) return null;
619
+ if (saved) {
620
+ announce(translate("widget.added", { title: widgets.get(widgetId)?.title ?? "" }));
621
+ return widgetId;
622
+ }
623
+ const widget = widgets.get(widgetId);
624
+ if (widget) {
625
+ removeNode(widget);
626
+ for (const bp of breakpoints) {
627
+ const items = itemsOf(bp);
628
+ if (items.length && compactItems) store(bp, compact(items));
629
+ }
630
+ applyPlaces();
631
+ }
632
+ return null;
633
+ }
634
+
635
+ function removeWidget(id) {
636
+ const widget = widgets.get(id);
637
+ if (!widget) return false;
638
+ const title = widget.title;
639
+ removeNode(widget);
640
+ for (const bp of breakpoints) {
641
+ const items = itemsOf(bp);
642
+ if (items.length && compactItems) store(bp, compact(items));
643
+ }
644
+ applyPlaces();
645
+ commit("remove");
646
+ announce(translate("widget.removed", { title }));
647
+ return true;
648
+ }
649
+
650
+ function duplicateWidget(id) {
651
+ const widget = widgets.get(id);
652
+ if (!widget) return null;
653
+ const place = widget.places[breakpoint.name];
654
+ return addWidget(widget.type, { title: translate("widget.copy", { title: widget.title }), config: plain(widget.config), w: place.w, h: place.h });
655
+ }
656
+
657
+ function lockWidget(id, locked = true) {
658
+ const widget = widgets.get(id);
659
+ if (!widget) return false;
660
+ widget.locked = Boolean(locked);
661
+ widget.node.classList.toggle("is-locked", widget.locked);
662
+ commit("lock");
663
+ return true;
664
+ }
665
+
666
+ /** Changes the title and / or the config (merged) from code, for example with new data. It is not an undo step. */
667
+ function updateWidget(id, { title, config } = {}) {
668
+ const widget = widgets.get(id);
669
+ if (!widget) return false;
670
+ if (title !== undefined) setTitle(widget, title);
671
+ if (config !== undefined) widget.config = plain({ ...widget.config, ...config });
672
+ markChanged(widget);
673
+ return true;
674
+ }
675
+
676
+ function configureWidget(id, { reason = "settings" } = {}) {
677
+ const widget = widgets.get(id);
678
+ if (!widget) return null;
679
+ const form = typeof widget.def?.configForm === "function" ? widget.def.configForm(widget) : (widget.def?.configForm ?? []);
680
+ const fields = [
681
+ { name: "widgetTitle", label: translate("widget.titleLabel"), type: "text", value: widget.title, required: true },
682
+ ...form.map(field => ({ ...field, value: widget.config[field.name] ?? field.value }))
683
+ ];
684
+ return showFormDialog({
685
+ title: translate("widget.settingsTitle"), fields, size: "small",
686
+ onSubmit(values) {
687
+ const { widgetTitle, ...config } = values;
688
+ setTitle(widget, widgetTitle || widget.title);
689
+ widget.config = plain({ ...widget.config, ...config });
690
+ markChanged(widget);
691
+ commit(reason);
692
+ }
693
+ });
694
+ }
695
+
696
+ /* ---- moving and resizing: pointer ---- */
697
+
698
+ function metrics() {
699
+ const rect = element.getBoundingClientRect();
700
+ const cell = (rect.width - gap * (breakpoint.columns - 1)) / breakpoint.columns;
701
+ return { strideX: cell + gap, strideY: rowHeight + gap };
702
+ }
703
+
704
+ function cancelGesture() {
705
+ if (!gesture) return;
706
+ const current = gesture;
707
+ gesture = null;
708
+ current.stop?.();
709
+ store(breakpoint, current.base);
710
+ current.widget.node.classList.remove("is-dragging");
711
+ applyPlaces({ slide: false });
712
+ }
713
+
714
+ /** One try of a gesture: the base layout with the item in the new place; shows it when it is possible. */
715
+ function tryPlace(current, place) {
716
+ const widget = current.widget;
717
+ const next = placeItem(current.base, widget.id, place, breakpoint.columns, { limits: limitsOf(widget), compactItems });
718
+ if (!next) return false;
719
+ const changed = JSON.stringify(next) !== JSON.stringify(current.shown);
720
+ current.shown = next;
721
+ if (changed) {
722
+ store(breakpoint, next);
723
+ applyPlaces({ except: current.pointer ? widget.node : undefined });
724
+ }
725
+ return changed;
726
+ }
727
+
728
+ function finishGesture(current, reason) {
729
+ gesture = null;
730
+ current.widget.node.classList.remove("is-dragging");
731
+ orderDom();
732
+ if (JSON.stringify(current.shown ?? current.base) !== JSON.stringify(current.base)) commit(reason);
733
+ }
734
+
735
+ function startPointer(event) {
736
+ if (!editable || gesture || event.button !== 0) return;
737
+ const resize = event.target.closest(".widget-resize");
738
+ const grab = event.target.closest(".widget-handle");
739
+ if (!resize && !grab) return;
740
+ const node = event.target.closest(".widget");
741
+ const widget = node && widgets.get(node.dataset.widgetId);
742
+ if (!widget || widget.locked) return;
743
+ event.preventDefault();
744
+ const base = itemsOf(breakpoint);
745
+ const start = widget.places[breakpoint.name];
746
+ const { strideX, strideY } = metrics();
747
+ const dir = resize?.dataset.dir ?? "";
748
+ const target = resize ?? grab;
749
+ const limits = limitsOf(widget);
750
+ const current = { widget, base, shown: base, pointer: true, reason: dir ? "resize" : "move" };
751
+ gesture = current;
752
+ node.classList.add("is-dragging");
753
+ try {
754
+ target.setPointerCapture(event.pointerId);
755
+ } catch {
756
+ // no active pointer (a synthetic event): the handle still gets the events that are sent to it
757
+ }
758
+ const move = moveEvent => {
759
+ const dx = Math.round((moveEvent.clientX - event.clientX) / strideX);
760
+ const dy = Math.round((moveEvent.clientY - event.clientY) / strideY);
761
+ if (!dir) return tryPlace(current, { x: start.x + dx, y: start.y + dy });
762
+ const place = {};
763
+ const minW = Math.max(1, limits.min?.w ?? 1);
764
+ const minH = Math.max(1, limits.min?.h ?? 1);
765
+ const maxW = Math.min(limits.max?.w ?? breakpoint.columns, breakpoint.columns);
766
+ const maxH = limits.max?.h ?? Infinity;
767
+ if (dir.includes("e")) place.w = Math.min(Math.max(start.w + dx, minW), maxW);
768
+ if (dir.includes("w")) {
769
+ place.w = Math.min(Math.max(start.w - dx, minW), maxW);
770
+ place.x = start.x + start.w - place.w;
771
+ }
772
+ if (dir.includes("s")) place.h = Math.min(Math.max(start.h + dy, minH), maxH);
773
+ if (dir.includes("n")) {
774
+ place.h = Math.min(Math.max(start.h - dy, minH), maxH);
775
+ place.y = Math.max(start.y + start.h - place.h, 0);
776
+ place.h = start.y + start.h - place.y;
777
+ }
778
+ return tryPlace(current, place);
779
+ };
780
+ const end = () => {
781
+ target.removeEventListener("pointermove", move);
782
+ target.removeEventListener("pointerup", up);
783
+ target.removeEventListener("pointercancel", cancel);
784
+ target.removeEventListener("lostpointercapture", up);
785
+ };
786
+ const up = () => {
787
+ end();
788
+ if (gesture === current) finishGesture(current, current.reason);
789
+ };
790
+ const cancel = () => {
791
+ end();
792
+ if (gesture === current) cancelGesture();
793
+ };
794
+ current.stop = end;
795
+ target.addEventListener("pointermove", move);
796
+ target.addEventListener("pointerup", up);
797
+ target.addEventListener("pointercancel", cancel);
798
+ target.addEventListener("lostpointercapture", up);
799
+ }
800
+
801
+ /* ---- moving and resizing: keyboard ---- */
802
+
803
+ const describe = widget => {
804
+ const place = widget.places[breakpoint.name];
805
+ return translate("widget.position", { x: place.x + 1, y: place.y + 1, w: place.w, h: place.h });
806
+ };
807
+
808
+ function dropKeyboard(current, keep) {
809
+ if (gesture !== current) return;
810
+ if (!keep) {
811
+ cancelGesture();
812
+ announce(translate("widget.cancelled"));
813
+ } else {
814
+ finishGesture(current, current.reason);
815
+ announce(translate("widget.dropped", { title: current.widget.title }) + " " + describe(current.widget));
816
+ }
817
+ current.widget.parts.handle.removeAttribute("aria-pressed");
818
+ }
819
+
820
+ function keyHandle(event) {
821
+ const handle = event.target.closest(".widget-handle");
822
+ if (!handle || !editable) return;
823
+ const node = handle.closest(".widget");
824
+ const widget = widgets.get(node.dataset.widgetId);
825
+ if (!widget || widget.locked) return;
826
+ const picked = gesture?.widget === widget && gesture.keyboard;
827
+ const pick = event.key === " " || event.key === "Enter";
828
+ if (event.type === "keyup") {
829
+ if (event.key === " ") event.preventDefault(); // Space must not click the button
830
+ return;
831
+ }
832
+ if (!picked) {
833
+ if (!pick || gesture) return;
834
+ event.preventDefault();
835
+ gesture = { widget, base: itemsOf(breakpoint), shown: itemsOf(breakpoint), keyboard: true, reason: "move" };
836
+ node.classList.add("is-dragging");
837
+ handle.setAttribute("aria-pressed", "true");
838
+ announce(translate("widget.pickedUp", { title: widget.title }) + " " + describe(widget));
839
+ return;
840
+ }
841
+ const arrows = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
842
+ if (arrows) {
843
+ event.preventDefault();
844
+ const place = widget.places[breakpoint.name];
845
+ const next = event.shiftKey ? { w: place.w + arrows[0], h: place.h + arrows[1] } : { x: place.x + arrows[0], y: place.y + arrows[1] };
846
+ gesture.reason = event.shiftKey ? "resize" : gesture.reason;
847
+ if (event.shiftKey && (arrows[0] < 0 || arrows[1] < 0) && (place.w + arrows[0] < 1 || place.h + arrows[1] < 1)) return announce(translate("widget.blocked"));
848
+ const before = JSON.stringify(widget.places[breakpoint.name]);
849
+ const placed = placeItem(itemsOf(breakpoint), widget.id, next, breakpoint.columns, { limits: limitsOf(widget), compactItems });
850
+ if (placed) {
851
+ store(breakpoint, placed);
852
+ gesture.shown = placed;
853
+ applyPlaces();
854
+ }
855
+ announce(placed && JSON.stringify(widget.places[breakpoint.name]) !== before ? describe(widget) : translate("widget.blocked"));
856
+ } else if (pick) {
857
+ event.preventDefault();
858
+ dropKeyboard(gesture, true);
859
+ } else if (event.key === "Escape") {
860
+ event.preventDefault();
861
+ event.stopPropagation();
862
+ dropKeyboard(gesture, false);
863
+ }
864
+ }
865
+
866
+ function blurHandle(event) {
867
+ if (gesture?.keyboard && event.target.closest?.(".widget-handle")) dropKeyboard(gesture, true);
868
+ }
869
+
870
+ function clickAction(event) {
871
+ const button = event.target.closest(".widget-action");
872
+ if (!button || !editable) return;
873
+ const id = button.closest(".widget")?.dataset.widgetId;
874
+ const action = button.dataset.action;
875
+ if (action === "settings") configureWidget(id);
876
+ else if (action === "duplicate") duplicateWidget(id);
877
+ else if (action === "remove") removeWidget(id);
878
+ }
879
+
880
+ element.addEventListener("pointerdown", startPointer);
881
+ element.addEventListener("keydown", keyHandle);
882
+ element.addEventListener("keyup", keyHandle);
883
+ element.addEventListener("focusout", blurHandle);
884
+ element.addEventListener("click", clickAction);
885
+
886
+ /* ---- start ---- */
887
+
888
+ function setEditable(flag = true) {
889
+ editable = Boolean(flag);
890
+ if (!editable) cancelGesture();
891
+ element.classList.toggle("is-editable", editable);
892
+ }
893
+
894
+ breakpoint = pickBreakpoint();
895
+ applyContainerClasses();
896
+ if (options.layout) setLayout(options.layout);
897
+ else {
898
+ for (const entry of options.widgets ?? []) {
899
+ const def = registry.get(entry.type);
900
+ if (!def) {
901
+ console.warn(`Athena UI: the widget type "${entry.type}" is not registered`);
902
+ continue;
903
+ }
904
+ addWidget(entry.type, entry);
905
+ }
906
+ snapshots.length = 0;
907
+ snapshots.push(JSON.stringify(getLayout()));
908
+ position = 0;
909
+ }
910
+ setEditable(options.editable);
911
+ resizing?.observe(element);
912
+ starting = false;
913
+
914
+ return asHandle({
915
+ element,
916
+ addWidget, addWidgetWithSettings, removeWidget, duplicateWidget, configureWidget, updateWidget, lockWidget, flush,
917
+ getWidget: id => (widgets.has(id) ? { id, type: widgets.get(id).type, title: widgets.get(id).title, config: plain(widgets.get(id).config), locked: widgets.get(id).locked, element: widgets.get(id).node } : null),
918
+ getWidgets: () => [...widgets.keys()],
919
+ setEditable, isEditable: () => editable,
920
+ getLayout, setLayout,
921
+ undo: () => travel(-1, "undo"), redo: () => travel(1, "redo"),
922
+ canUndo: () => position > 0, canRedo: () => position < snapshots.length - 1,
923
+ getBreakpoint: () => breakpoint.name,
924
+ destroy() {
925
+ if (destroyed) return;
926
+ flush(); // a change that waits for its delay is delivered, not lost
927
+ destroyed = true;
928
+ cancelGesture();
929
+ for (const timer of timers) clearTimeout(timer);
930
+ for (const widget of [...widgets.values()]) removeNode(widget);
931
+ intersection?.disconnect();
932
+ resizing?.disconnect();
933
+ element.removeEventListener("pointerdown", startPointer);
934
+ element.removeEventListener("keydown", keyHandle);
935
+ element.removeEventListener("keyup", keyHandle);
936
+ element.removeEventListener("focusout", blurHandle);
937
+ element.removeEventListener("click", clickAction);
938
+ element.classList.remove("athena-widget-grid", "is-editable");
939
+ for (const name of [...element.classList].filter(name => /^wg-/.test(name))) element.classList.remove(name);
940
+ live.remove();
941
+ }
942
+ });
943
+ }