athena-ui-js 2.3.0 → 2.4.1
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 +62 -3
- package/docs/styling.md +123 -103
- package/package.json +8 -1
- package/src/athena-ui.js +5 -1
- package/src/code.js +9 -0
- package/src/libs/config/config.js +1 -1
- package/src/libs/core/codeDiff.js +119 -0
- package/src/libs/core/codeLanguages.js +277 -0
- package/src/libs/core/i18n.js +56 -0
- package/src/libs/hephaestus/codeGenerator/codeEditor.js +1037 -0
- package/src/libs/hephaestus/codeGenerator/codeGenerator.js +286 -0
- package/src/libs/hephaestus/widgetGrid/widgetGrid.js +870 -0
- package/src/res/themes/default/style.css +471 -0
- package/src/res/themes/tokens.css +52 -0
- package/types/athena-ui.d.ts +103 -99
- package/types/code.d.ts +4 -0
- package/types/libs/config/config.d.ts +3 -3
- package/types/libs/core/codeDiff.d.ts +32 -0
- package/types/libs/core/codeLanguages.d.ts +58 -0
- package/types/libs/core/gridLayout.d.ts +45 -45
- package/types/libs/hephaestus/codeGenerator/codeEditor.d.ts +60 -0
- package/types/libs/hephaestus/codeGenerator/codeGenerator.d.ts +99 -0
- package/types/libs/hephaestus/widgetGrid/widgetGrid.d.ts +117 -117
- package/types/widgets.d.ts +2 -2
|
@@ -0,0 +1,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
|
|
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
|
+
}
|