athena-ui-js 2.1.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -3
- package/docs/styling.md +21 -6
- package/package.json +9 -1
- package/src/athena-ui.js +4 -1
- package/src/libs/config/config.js +1 -1
- package/src/libs/core/gridLayout.js +102 -0
- package/src/libs/core/i18n.js +32 -0
- package/src/libs/core/motion.js +358 -0
- package/src/libs/core/theme.js +12 -0
- package/src/libs/hephaestus/chartGenerator/chartGenerator.js +9 -5
- package/src/libs/hephaestus/componentGenerator/componentGenerator.js +17 -0
- package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +2 -1
- package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +3 -1
- package/src/libs/hephaestus/router/router.js +18 -9
- package/src/libs/hephaestus/tableGenerator/tableGenerator.js +25 -0
- package/src/motion.js +6 -0
- package/src/res/themes/default/style.css +413 -10
- package/src/res/themes/tokens.css +25 -0
- package/src/widgets.js +7 -0
- package/types/athena-ui.d.ts +99 -96
- package/types/libs/config/config.d.ts +3 -3
- package/types/libs/core/gridLayout.d.ts +45 -0
- package/types/libs/core/motion.d.ts +123 -0
- package/types/libs/core/popover.d.ts +36 -36
- package/types/libs/core/theme.d.ts +2 -0
- package/types/libs/hephaestus/chartGenerator/chartGenerator.d.ts +2 -0
- package/types/libs/hephaestus/componentGenerator/componentGenerator.d.ts +238 -224
- package/types/libs/hephaestus/navigationGenerator/navigationGenerator.d.ts +153 -153
- package/types/libs/hephaestus/router/router.d.ts +4 -0
- package/types/libs/hephaestus/tableGenerator/tableGenerator.d.ts +3 -0
- package/types/libs/hephaestus/widgetGrid/widgetGrid.d.ts +117 -0
- package/types/motion.d.ts +1 -0
- package/types/widgets.d.ts +2 -0
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
//motion for Athena UI
|
|
2
|
+
//Author: Csaba Tóth https://github.com/csabatibortoth/
|
|
3
|
+
//LICENCE: MIT
|
|
4
|
+
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
|
+
|
|
6
|
+
// Animations and transitions. The rule for everything here: motion is an enhancement. It is off when the person prefers reduced motion (the system setting,
|
|
7
|
+
// or setMotion("reduce")), nothing waits for an animation before it works (every function resolves at once under reduced motion), and nothing needs an inline
|
|
8
|
+
// style: CSS classes, custom properties, and the Web Animations API, which a strict Content-Security-Policy allows.
|
|
9
|
+
|
|
10
|
+
/* ------------------THE PREFERENCE------------------- */
|
|
11
|
+
|
|
12
|
+
const listeners = new Set();
|
|
13
|
+
|
|
14
|
+
// The choice lives on <html> as data-motion ("reduce" or "full"), where the CSS tokens read it too. No attribute: follow the system.
|
|
15
|
+
const chosen = () => {
|
|
16
|
+
const value = globalThis.document?.documentElement.dataset.motion;
|
|
17
|
+
return value === "reduce" || value === "full" ? value : "system";
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Does the person want less motion? The choice made with setMotion wins over the setting of the system. */
|
|
21
|
+
export function prefersReducedMotion() {
|
|
22
|
+
const preference = chosen();
|
|
23
|
+
if (preference === "reduce") return true;
|
|
24
|
+
if (preference === "full") return false;
|
|
25
|
+
return Boolean(globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** "system" (follow the setting of the system), "reduce" or "full". */
|
|
29
|
+
export const getMotion = chosen;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Chooses how much motion there is: "system", "reduce" (none) or "full". It is put on <html> as data-motion, which the CSS tokens read (the durations
|
|
33
|
+
* become 0), and the functions of this module read it too.
|
|
34
|
+
*/
|
|
35
|
+
export function setMotion(value) {
|
|
36
|
+
if (!["system", "reduce", "full"].includes(value)) return false;
|
|
37
|
+
const root = globalThis.document?.documentElement;
|
|
38
|
+
if (root) {
|
|
39
|
+
if (value === "system") delete root.dataset.motion;
|
|
40
|
+
else root.dataset.motion = value;
|
|
41
|
+
}
|
|
42
|
+
listeners.forEach(listener => listener({ preference: value, reduced: prefersReducedMotion() }));
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Called with { preference, reduced } when setMotion changes it, and when the system setting changes. Returns a function that stops it. */
|
|
47
|
+
export function onMotionChange(listener) {
|
|
48
|
+
listeners.add(listener);
|
|
49
|
+
return () => listeners.delete(listener);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").addEventListener?.("change", () => {
|
|
53
|
+
if (chosen() === "system") listeners.forEach(listener => listener({ preference: "system", reduced: prefersReducedMotion() }));
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/* ------------------TOKENS------------------- */
|
|
57
|
+
|
|
58
|
+
/** A duration token as milliseconds: readDuration("--athena-duration-base") -> 200. 0 under reduced motion. */
|
|
59
|
+
export function readDuration(token = "--athena-duration-base", element = globalThis.document?.documentElement) {
|
|
60
|
+
if (!element) return 0;
|
|
61
|
+
const value = getComputedStyle(element).getPropertyValue(token).trim();
|
|
62
|
+
return toMs(value);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const toMs = text => {
|
|
66
|
+
const match = /^(-?[\d.]+)(ms|s)$/.exec(String(text).trim());
|
|
67
|
+
return match ? Number(match[1]) * (match[2] === "s" ? 1000 : 1) : 0;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** How long an element takes to finish its CSS transitions, delays included, in ms (0 when it has none, or under reduced motion). */
|
|
71
|
+
export function transitionTime(element) {
|
|
72
|
+
const style = getComputedStyle(element);
|
|
73
|
+
const durations = style.transitionDuration.split(",").map(toMs);
|
|
74
|
+
const delays = style.transitionDelay.split(",").map(toMs);
|
|
75
|
+
return Math.max(0, ...durations.map((duration, index) => duration + (delays[index % delays.length] ?? 0)));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Removes an element when its exit transition is over (at once when it has none, which is also what reduced motion gives). */
|
|
79
|
+
export function removeAfterTransition(element) {
|
|
80
|
+
const time = element.isConnected ? transitionTime(element) : 0;
|
|
81
|
+
if (time <= 0) element.remove();
|
|
82
|
+
else setTimeout(() => element.remove(), time + 30);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/* ------------------EASINGS------------------- */
|
|
86
|
+
|
|
87
|
+
/** Easing functions for numbers: f(t) with t from 0 to 1, for tweens. (CSS has its own, see the --athena-ease-* tokens.) */
|
|
88
|
+
export const easings = {
|
|
89
|
+
linear: t => t,
|
|
90
|
+
easeInQuad: t => t * t,
|
|
91
|
+
easeOutQuad: t => 1 - (1 - t) * (1 - t),
|
|
92
|
+
easeInOutQuad: t => (t < 0.5 ? 2 * t * t : 1 - ((-2 * t + 2) ** 2) / 2),
|
|
93
|
+
easeInCubic: t => t ** 3,
|
|
94
|
+
easeOutCubic: t => 1 - (1 - t) ** 3,
|
|
95
|
+
easeInOutCubic: t => (t < 0.5 ? 4 * t ** 3 : 1 - ((-2 * t + 2) ** 3) / 2),
|
|
96
|
+
easeOutBack: t => 1 + 2.70158 * (t - 1) ** 3 + 1.70158 * (t - 1) ** 2,
|
|
97
|
+
easeOutElastic: t => (t === 0 || t === 1 ? t : 2 ** (-10 * t) * Math.sin((t * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1)
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* A spring as a CSS easing: simulates a damped spring and returns the points as a `linear()` easing (which can overshoot) and how long it takes.
|
|
102
|
+
* `element.animate(keyframes, { duration, easing })` then moves like a spring. Settles when it stays within `precision` of 1.
|
|
103
|
+
*
|
|
104
|
+
* @param {{stiffness?: number, damping?: number, mass?: number, precision?: number}} [options]
|
|
105
|
+
* @returns {{easing: string, duration: number}} duration in ms
|
|
106
|
+
*/
|
|
107
|
+
export function spring({ stiffness = 170, damping = 15, mass = 1, precision = 0.002 } = {}) {
|
|
108
|
+
const step = 1 / 120;
|
|
109
|
+
let position = 0;
|
|
110
|
+
let velocity = 0;
|
|
111
|
+
const points = [0];
|
|
112
|
+
let settled = 0;
|
|
113
|
+
let time = 0;
|
|
114
|
+
while (time < 10 && settled < 12) {
|
|
115
|
+
const force = -stiffness * (position - 1) - damping * velocity;
|
|
116
|
+
velocity += (force / mass) * step;
|
|
117
|
+
position += velocity * step;
|
|
118
|
+
time += step;
|
|
119
|
+
points.push(position);
|
|
120
|
+
settled = Math.abs(position - 1) < precision && Math.abs(velocity) < precision * 10 ? settled + 1 : 0;
|
|
121
|
+
}
|
|
122
|
+
points[points.length - 1] = 1;
|
|
123
|
+
// About 40 points are enough for the eye
|
|
124
|
+
const every = Math.max(1, Math.floor(points.length / 40));
|
|
125
|
+
const sampled = points.filter((_, index) => index % every === 0 || index === points.length - 1).map(value => +value.toFixed(4));
|
|
126
|
+
return { easing: `linear(${sampled.join(", ")})`, duration: Math.round(time * 1000) };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/* ------------------ANIMATE------------------- */
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Animates an element with the Web Animations API and resolves when it is over. Under reduced motion it does nothing and resolves at once.
|
|
133
|
+
* It resolves (never rejects) when the animation is cancelled, and `null` when there was none.
|
|
134
|
+
*
|
|
135
|
+
* @param {Element} element
|
|
136
|
+
* @param {Keyframe[]|PropertyIndexedKeyframes} keyframes e.g. [{ opacity: 0 }, { opacity: 1 }]
|
|
137
|
+
* @param {object} [options] the options of element.animate (duration, easing, delay, fill, ...), and
|
|
138
|
+
* @param {boolean} [options.commit=false] write the end state to the element's style when it is over (CSSOM: allowed by a strict policy)
|
|
139
|
+
* @param {AbortSignal} [options.signal] cancels the animation when aborted
|
|
140
|
+
* @returns {Promise<Animation|null>}
|
|
141
|
+
*/
|
|
142
|
+
export async function animate(element, keyframes, options = {}) {
|
|
143
|
+
if (prefersReducedMotion() || typeof element?.animate !== "function") return null;
|
|
144
|
+
const { commit = false, signal, ...timing } = options;
|
|
145
|
+
const animation = element.animate(keyframes, {
|
|
146
|
+
duration: readDuration("--athena-duration-base"),
|
|
147
|
+
easing: getComputedStyle(globalThis.document.documentElement).getPropertyValue("--athena-ease-standard").trim() || "ease",
|
|
148
|
+
fill: "backwards",
|
|
149
|
+
...timing
|
|
150
|
+
});
|
|
151
|
+
signal?.addEventListener("abort", () => animation.cancel(), { once: true });
|
|
152
|
+
// A page that is not drawn (a hidden tab) gets no frames, so its animations would never finish: a timer finishes it, a moment after it should be over
|
|
153
|
+
const length = (typeof timing.duration === "number" ? timing.duration : readDuration("--athena-duration-base")) * (timing.iterations ?? 1) + (timing.delay ?? 0) + (timing.endDelay ?? 0);
|
|
154
|
+
const timer = Number.isFinite(length) ? setTimeout(() => { if (animation.playState === "running") animation.finish(); }, length + 100) : 0;
|
|
155
|
+
try {
|
|
156
|
+
await animation.finished;
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
if (commit) {
|
|
159
|
+
animation.commitStyles();
|
|
160
|
+
animation.cancel();
|
|
161
|
+
}
|
|
162
|
+
} catch {
|
|
163
|
+
return animation; // cancelled: not an error
|
|
164
|
+
}
|
|
165
|
+
return animation;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Fades an element in. */
|
|
169
|
+
export const fadeIn = (element, options) => animate(element, [{ opacity: 0 }, { opacity: 1 }], options);
|
|
170
|
+
|
|
171
|
+
/** Fades an element out and removes it. Under reduced motion it is removed at once. */
|
|
172
|
+
export async function fadeOut(element, options) {
|
|
173
|
+
await animate(element, [{ opacity: 1 }, { opacity: 0 }], { fill: "forwards", ...options });
|
|
174
|
+
element.remove();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* A change that is done with CSS (a class, an attribute) and has a CSS transition: runs `change()` and resolves when the element's transition is over.
|
|
179
|
+
* It waits at most the length of the transition (plus a little), so a transition that never ends does not hang anything.
|
|
180
|
+
*/
|
|
181
|
+
export function transition(element, change) {
|
|
182
|
+
return new Promise(resolve => {
|
|
183
|
+
change();
|
|
184
|
+
// The styles of the change are computed in the next frame
|
|
185
|
+
requestAnimationFrame(() => {
|
|
186
|
+
const time = transitionTime(element);
|
|
187
|
+
if (time <= 0) return resolve();
|
|
188
|
+
let done = false;
|
|
189
|
+
const finish = () => {
|
|
190
|
+
if (done) return;
|
|
191
|
+
done = true;
|
|
192
|
+
element.removeEventListener("transitionend", onEnd);
|
|
193
|
+
resolve();
|
|
194
|
+
};
|
|
195
|
+
const onEnd = event => { if (event.target === element) finish(); };
|
|
196
|
+
element.addEventListener("transitionend", onEnd);
|
|
197
|
+
setTimeout(finish, time + 50);
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/* ------------------SEVERAL AT ONCE OR ONE AFTER THE OTHER------------------- */
|
|
203
|
+
|
|
204
|
+
/** Runs the functions one after the other, each when the one before is over. Resolves with their results. */
|
|
205
|
+
export async function sequence(steps) {
|
|
206
|
+
const results = [];
|
|
207
|
+
for (const step of steps) results.push(await (typeof step === "function" ? step() : step));
|
|
208
|
+
return results;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Runs the functions (or promises) together. Resolves with their results. */
|
|
212
|
+
export const parallel = steps => Promise.all(steps.map(step => (typeof step === "function" ? step() : step)));
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The delays of a staggered animation: `count` items, `step` ms apart, starting from "start", "end" or "center".
|
|
216
|
+
* @returns {number[]}
|
|
217
|
+
*/
|
|
218
|
+
export function staggerDelays(count, step = 40, from = "start") {
|
|
219
|
+
return Array.from({ length: count }, (_, index) => {
|
|
220
|
+
const distance = from === "end" ? count - 1 - index : from === "center" ? Math.abs(index - (count - 1) / 2) : index;
|
|
221
|
+
return Math.round(distance * step);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Calls `run(item, index, delay)` for every item with its delay, and resolves when all are over: `stagger(rows, (row, i, delay) => fadeIn(row, { delay }))`.
|
|
227
|
+
* No more than `limit` items are staggered (the rest run with the last delay), so a long list does not take long.
|
|
228
|
+
*/
|
|
229
|
+
export function stagger(items, run, { step = 40, from = "start", limit = 30 } = {}) {
|
|
230
|
+
const list = [...items];
|
|
231
|
+
const delays = staggerDelays(Math.min(list.length, limit), step, from);
|
|
232
|
+
return Promise.all(list.map((item, index) => run(item, index, delays[Math.min(index, delays.length - 1)] ?? 0)));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/* ------------------LISTS: FLIP------------------- */
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Lets the children of a container move smoothly when `change()` rearranges them (sorting, filtering, inserting, removing): First (measure), Last (do the change,
|
|
239
|
+
* measure), Invert and Play (each child that moved starts at its old place and slides to the new one). New children fade in. Under reduced motion `change()` is
|
|
240
|
+
* just done.
|
|
241
|
+
*
|
|
242
|
+
* @param {Element} container its children are what moves
|
|
243
|
+
* @param {() => void} change rearranges the children (synchronously)
|
|
244
|
+
* @param {object} [options]
|
|
245
|
+
* @param {(element: Element) => *} [options.key] what makes a child "the same" before and after, default: the element itself
|
|
246
|
+
* @param {number} [options.limit=60] at most this many children are animated (a long list does not need it, and costs time)
|
|
247
|
+
* @param {number} [options.duration] ms, default the token --athena-duration-base
|
|
248
|
+
* @returns {Promise<void>} resolves when the animations are over
|
|
249
|
+
*/
|
|
250
|
+
export async function flip(container, change, { key = element => element, limit = 60, duration } = {}) {
|
|
251
|
+
if (prefersReducedMotion()) {
|
|
252
|
+
change();
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const first = new Map();
|
|
256
|
+
for (const child of [...container.children].slice(0, limit)) first.set(key(child), child.getBoundingClientRect());
|
|
257
|
+
change();
|
|
258
|
+
const animations = [];
|
|
259
|
+
for (const child of [...container.children].slice(0, limit)) {
|
|
260
|
+
const before = first.get(key(child));
|
|
261
|
+
const after = child.getBoundingClientRect();
|
|
262
|
+
if (!before) {
|
|
263
|
+
animations.push(animate(child, [{ opacity: 0 }, { opacity: 1 }], { duration }));
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
const dx = before.left - after.left;
|
|
267
|
+
const dy = before.top - after.top;
|
|
268
|
+
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
|
|
269
|
+
animations.push(animate(child, [{ translate: `${dx}px ${dy}px` }, { translate: "0 0" }], { duration, easing: "cubic-bezier(0.2, 0, 0, 1)" }));
|
|
270
|
+
}
|
|
271
|
+
await Promise.all(animations);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/* ------------------TWEENS (for games and anything that is not CSS)------------------- */
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Changes numbers over time with requestAnimationFrame: tween({ from: 0, to: 100, duration: 500, easing: easings.easeOutCubic, onUpdate: v => ... }).
|
|
278
|
+
* `from` and `to` can be numbers, or objects with the same keys ({ x: 0, y: 0 } to { x: 10, y: 5 }); onUpdate then gets an object.
|
|
279
|
+
* Under reduced motion it jumps to the end (one onUpdate call). It runs on animation frames; in a page that is not drawn a timer keeps it going slowly, so it still ends.
|
|
280
|
+
*
|
|
281
|
+
* @returns {Promise<void> & {cancel: () => void}} resolves when it is over (also when cancelled)
|
|
282
|
+
*/
|
|
283
|
+
export function tween({ from = 0, to = 1, duration = 300, easing = easings.easeOutCubic, onUpdate, delay = 0 } = {}) {
|
|
284
|
+
let cancelled = false;
|
|
285
|
+
let frame = 0;
|
|
286
|
+
const value = progress => (typeof from === "number"
|
|
287
|
+
? from + (to - from) * progress
|
|
288
|
+
: Object.fromEntries(Object.keys(from).map(name => [name, from[name] + (to[name] - from[name]) * progress])));
|
|
289
|
+
const promise = new Promise(resolve => {
|
|
290
|
+
if (prefersReducedMotion() || duration <= 0) {
|
|
291
|
+
onUpdate?.(value(1));
|
|
292
|
+
resolve();
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
let start = null;
|
|
296
|
+
let timer = 0;
|
|
297
|
+
// The frame clock is the clock; the timer next to it keeps a tween going (more slowly) in a page that is not drawn, so it still ends
|
|
298
|
+
const schedule = () => {
|
|
299
|
+
frame = requestAnimationFrame(tick);
|
|
300
|
+
timer = setTimeout(tick, 100);
|
|
301
|
+
};
|
|
302
|
+
const tick = () => {
|
|
303
|
+
cancelAnimationFrame(frame);
|
|
304
|
+
clearTimeout(timer);
|
|
305
|
+
if (cancelled) return resolve();
|
|
306
|
+
const now = performance.now();
|
|
307
|
+
start ??= now + delay;
|
|
308
|
+
const t = Math.min(Math.max((now - start) / duration, 0), 1);
|
|
309
|
+
if (now >= start) onUpdate?.(value(easing(t)));
|
|
310
|
+
if (t >= 1) return resolve();
|
|
311
|
+
schedule();
|
|
312
|
+
};
|
|
313
|
+
schedule();
|
|
314
|
+
});
|
|
315
|
+
return Object.assign(promise, { cancel() { cancelled = true; cancelAnimationFrame(frame); } });
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/* ------------------PAGES------------------- */
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Runs `update()` (which changes the DOM) as a view transition when the browser can and motion is wanted: the old and the new state cross-fade
|
|
322
|
+
* (or whatever the CSS ::view-transition-* rules say). Elements with a `view-transition-name` move from one place to the other. Without the API,
|
|
323
|
+
* or under reduced motion, `update()` is just run. Resolves when it is over.
|
|
324
|
+
*/
|
|
325
|
+
export async function viewTransition(update) {
|
|
326
|
+
if (prefersReducedMotion() || typeof globalThis.document?.startViewTransition !== "function") {
|
|
327
|
+
await update();
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
let failure = null;
|
|
331
|
+
let started = false;
|
|
332
|
+
let done = false;
|
|
333
|
+
const run = async () => {
|
|
334
|
+
if (started) return;
|
|
335
|
+
started = true;
|
|
336
|
+
try {
|
|
337
|
+
await update();
|
|
338
|
+
} catch (error) {
|
|
339
|
+
failure = error;
|
|
340
|
+
}
|
|
341
|
+
done = true;
|
|
342
|
+
};
|
|
343
|
+
const transition = document.startViewTransition(run);
|
|
344
|
+
// A page that is not drawn (a hidden tab) never calls the update of a view transition: after a moment it is run here, so the page does not stay as it was
|
|
345
|
+
const guard = setTimeout(run, 400);
|
|
346
|
+
const later = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
347
|
+
try {
|
|
348
|
+
await Promise.race([transition.updateCallbackDone, later(2000)]);
|
|
349
|
+
// the animation needs frames: do not wait for it longer than it can last
|
|
350
|
+
await Promise.race([transition.finished, later(readDuration("--athena-duration-slow") + 1000)]);
|
|
351
|
+
} catch {
|
|
352
|
+
// skipped (for example the page was hidden): the update was run all the same
|
|
353
|
+
}
|
|
354
|
+
clearTimeout(guard);
|
|
355
|
+
await run();
|
|
356
|
+
while (!done) await later(10);
|
|
357
|
+
if (failure) throw failure;
|
|
358
|
+
}
|
package/src/libs/core/theme.js
CHANGED
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
// Nothing is sent to a server. theme-boot.js (a classic script of its own) sets the two attributes before the page is
|
|
16
16
|
// drawn, so the wrong colours never flash.
|
|
17
17
|
|
|
18
|
+
import { prefersReducedMotion, readDuration } from "./motion.js";
|
|
19
|
+
|
|
18
20
|
export const DEFAULT_MODES = [
|
|
19
21
|
{ id: "system", name: "Like the system" },
|
|
20
22
|
{ id: "light", name: "Light" },
|
|
@@ -29,6 +31,7 @@ export const DEFAULT_MODES = [
|
|
|
29
31
|
* @param {string} [options.themeColorVariable] CSS variable whose value becomes <meta name="theme-color"> (the bar of a phone browser)
|
|
30
32
|
* @param {HTMLElement} [options.root] element that gets the attributes (default: <html>)
|
|
31
33
|
* @param {Storage} [options.storage] default: localStorage
|
|
34
|
+
* @param {boolean} [options.transition=true] colours cross-fade when the theme or the mode changes (not under reduced motion)
|
|
32
35
|
* @returns {{themes, modes, appearance: () => object, setTheme: (id) => boolean, setMode: (id) => boolean,
|
|
33
36
|
* onChange: (listener) => Function, refresh: Function, destroy: Function}}
|
|
34
37
|
*/
|
|
@@ -58,7 +61,16 @@ export function createThemeManager(options = {}) {
|
|
|
58
61
|
let current = read();
|
|
59
62
|
const appearance = () => ({ ...current, dark: root.dataset.mode === "dark" });
|
|
60
63
|
|
|
64
|
+
let fade = 0;
|
|
65
|
+
let started = false;
|
|
61
66
|
function apply() {
|
|
67
|
+
// A change after the first one cross-fades: the class makes every colour transition for a moment
|
|
68
|
+
if (started && options.transition !== false && !prefersReducedMotion()) {
|
|
69
|
+
root.classList.add("athena-switching");
|
|
70
|
+
clearTimeout(fade);
|
|
71
|
+
fade = setTimeout(() => root.classList.remove("athena-switching"), readDuration("--athena-duration-slow", root) + 60);
|
|
72
|
+
}
|
|
73
|
+
started = true;
|
|
62
74
|
const dark = current.mode === "dark" || (current.mode === "system" && Boolean(systemDark()?.matches));
|
|
63
75
|
root.dataset.theme = current.theme;
|
|
64
76
|
root.dataset.mode = dark ? "dark" : "light";
|
|
@@ -274,7 +274,7 @@ function drawLine(svg, ctx) {
|
|
|
274
274
|
const outline = [`M${points[0][0]},${baseline}`, ...points.map(p => `L${p.join(",")}`), `L${points.at(-1)[0]},${baseline}`, "Z"];
|
|
275
275
|
clipped.append(svgEl("path", { d: outline.join(" "), class: "chart-area" }));
|
|
276
276
|
}
|
|
277
|
-
clipped.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none" }));
|
|
277
|
+
clipped.append(svgEl("polyline", { points: points.map(p => p.join(",")).join(" "), class: "chart-line", fill: "none", pathLength: 1 }));
|
|
278
278
|
group.append(clipped);
|
|
279
279
|
if (dotted) {
|
|
280
280
|
for (const i of inside) {
|
|
@@ -524,6 +524,7 @@ function buildDataTable({ labels, series, times, title, type }) {
|
|
|
524
524
|
* @param {(range: ({from: number, to: number}|null)) => void} [options.onZoom] called when a person zooms or resets
|
|
525
525
|
* @param {number} [options.maxPoints] `push` keeps at most this many points per series (the oldest are dropped)
|
|
526
526
|
* @param {number[]} [options.hiddenSeries] the series (or slices) that are hidden at the start; a person hides and shows them with the legend, and a redraw keeps that
|
|
527
|
+
* @param {boolean} [options.animate=true] the first drawing animates: bars grow, a line is drawn, slices pop in (not when it is redrawn, and not under reduced motion)
|
|
527
528
|
* @param {boolean} [options.interactive=true] line and area charts: false leaves out the pointer layer (tooltip that follows the pointer, zoom)
|
|
528
529
|
* @returns {(SVGElement & {element: SVGElement, update: (options?: object) => SVGElement, destroy: () => void,
|
|
529
530
|
* zoom: (from: number, to: number) => void, resetZoom: () => void, getZoom: () => ({from: number, to: number}|null),
|
|
@@ -539,6 +540,8 @@ export function generateChart(options = {}) {
|
|
|
539
540
|
if (options.labels) state.used.labels = [...options.labels];
|
|
540
541
|
if (options.times) state.used.times = [...options.times];
|
|
541
542
|
const hidden = new Set(options.hiddenSeries ?? []);
|
|
543
|
+
// Only the first drawing animates (bars grow, the line is drawn, slices pop in): a redraw while streaming or zooming must not start it again
|
|
544
|
+
let firstDrawing = options.animate !== false;
|
|
542
545
|
const hooks = {
|
|
543
546
|
legend: (series, off) => {
|
|
544
547
|
if (off) hidden.add(series);
|
|
@@ -554,7 +557,7 @@ export function generateChart(options = {}) {
|
|
|
554
557
|
const handle = {
|
|
555
558
|
element: () => state.current.svg,
|
|
556
559
|
redraw() {
|
|
557
|
-
const next = buildChart(state.used, hooks);
|
|
560
|
+
const next = buildChart(state.used, hooks, { animate: false });
|
|
558
561
|
if (!next) return state.current?.svg;
|
|
559
562
|
// A redraw replaces the whole SVG (every second while streaming, and when someone zooms). The keyboard focus would be lost
|
|
560
563
|
// with it, so it goes to the same place in the new one: the same legend entry, the same point, or the plot.
|
|
@@ -623,7 +626,8 @@ export function generateChart(options = {}) {
|
|
|
623
626
|
dataTable: { get: () => state.current.table ?? null, configurable: true }
|
|
624
627
|
});
|
|
625
628
|
|
|
626
|
-
const built = buildChart(state.used, hooks);
|
|
629
|
+
const built = buildChart(state.used, hooks, { animate: firstDrawing });
|
|
630
|
+
firstDrawing = false;
|
|
627
631
|
if (!built) return null;
|
|
628
632
|
state.current = built;
|
|
629
633
|
const host = resolveElement(options.parent ?? "wrapper") ?? document.body;
|
|
@@ -632,7 +636,7 @@ export function generateChart(options = {}) {
|
|
|
632
636
|
return attach(built.svg);
|
|
633
637
|
}
|
|
634
638
|
|
|
635
|
-
function buildChart(options = {}, hooks) {
|
|
639
|
+
function buildChart(options = {}, hooks, { animate = false } = {}) {
|
|
636
640
|
const { type = "bar", id, title } = options;
|
|
637
641
|
const sparkline = type === "sparkline";
|
|
638
642
|
const width = options.width ?? (sparkline ? 120 : 600);
|
|
@@ -652,7 +656,7 @@ function buildChart(options = {}, hooks) {
|
|
|
652
656
|
return null;
|
|
653
657
|
}
|
|
654
658
|
|
|
655
|
-
const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class: `athena-chart athena-chart-${type}`, role: "img" });
|
|
659
|
+
const svg = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, width, height, class: `athena-chart athena-chart-${type}${animate && type !== "sparkline" ? " athena-chart-animated" : ""}`, role: "img" });
|
|
656
660
|
if (id) svg.id = id;
|
|
657
661
|
const summary = `${title ?? translate(`chart.${type}`)}: ${series.map(s => s.name ?? "").filter(Boolean).join(", ")}`.replace(/: $/, "");
|
|
658
662
|
svg.setAttribute("aria-label", options.ariaLabel ?? summary);
|
|
@@ -326,6 +326,23 @@ export function generateEmptyState(options = {}) {
|
|
|
326
326
|
return asHandle({ element });
|
|
327
327
|
}
|
|
328
328
|
|
|
329
|
+
/**
|
|
330
|
+
* A skeleton: grey lines with a shimmer where text or a card will be, so the page does not jump when it arrives. It is a live region that says
|
|
331
|
+
* "Loading..." to a screen reader; the shimmer stops under reduced motion.
|
|
332
|
+
*
|
|
333
|
+
* @param {object} [options]
|
|
334
|
+
* @param {string|Element} [options.parent]
|
|
335
|
+
* @param {number} [options.lines=3] the last of several lines is shorter
|
|
336
|
+
* @param {string} [options.class] e.g. "skeleton-card" in your own CSS gives the box a height
|
|
337
|
+
*/
|
|
338
|
+
export function generateSkeleton(options = {}) {
|
|
339
|
+
const lines = Array.from({ length: Math.max(1, options.lines ?? 3) }, () => el("span", { class: "athena-skeleton athena-skeleton-line", attrs: { "aria-hidden": "true" } }));
|
|
340
|
+
const element = el("div", { id: options.id, class: cx("athena-skeleton-box", options.class), attrs: { role: "status", "aria-live": "polite" } },
|
|
341
|
+
...lines, el("span", { class: "athena-visually-hidden", text: translate("loading") }));
|
|
342
|
+
mount(options.parent, element);
|
|
343
|
+
return asHandle({ element });
|
|
344
|
+
}
|
|
345
|
+
|
|
329
346
|
/**
|
|
330
347
|
* A placeholder while something loads: a spinner and a text (a live region, so a screen reader says it).
|
|
331
348
|
*
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
5
|
|
|
6
6
|
import { cx, el, setContent, uid } from "../../core/dom.js";
|
|
7
|
+
import { removeAfterTransition } from "../../core/motion.js";
|
|
7
8
|
import { translate } from "../../core/i18n.js";
|
|
8
9
|
import { generateButton, generateForm } from "../formGenerator/formBuilder.js";
|
|
9
10
|
|
|
@@ -48,8 +49,8 @@ export function showDialog(options = {}) {
|
|
|
48
49
|
return;
|
|
49
50
|
}
|
|
50
51
|
if (dialog.open) dialog.close();
|
|
51
|
-
dialog.remove();
|
|
52
52
|
resolve(value);
|
|
53
|
+
removeAfterTransition(dialog); // it fades out first (at once under reduced motion)
|
|
53
54
|
};
|
|
54
55
|
|
|
55
56
|
// Esc: the browser asks (cancel); a dialog that cannot be dismissed stays, and beforeClose can still say no
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
5
|
|
|
6
6
|
import { asHandle, cx, el, mount, setContent } from "../../core/dom.js";
|
|
7
|
+
import { removeAfterTransition } from "../../core/motion.js";
|
|
7
8
|
import { translate } from "../../core/i18n.js";
|
|
8
9
|
|
|
9
10
|
const TOAST_CONTAINER_ID = "athena-toasts";
|
|
@@ -38,7 +39,8 @@ export function showToast(options) {
|
|
|
38
39
|
let timer;
|
|
39
40
|
const close = () => {
|
|
40
41
|
clearTimeout(timer);
|
|
41
|
-
toast.
|
|
42
|
+
toast.classList.add("is-leaving");
|
|
43
|
+
removeAfterTransition(toast);
|
|
42
44
|
};
|
|
43
45
|
const toast = el("div", {
|
|
44
46
|
class: cx("toast", `alert-${type}`),
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
5
|
|
|
6
6
|
import { resolveElement } from "../../core/dom.js";
|
|
7
|
+
import { viewTransition } from "../../core/motion.js";
|
|
7
8
|
import { matchRoute, normalizePath, parseQuery } from "./matchRoute.js";
|
|
8
9
|
|
|
9
10
|
/**
|
|
@@ -25,6 +26,9 @@ import { matchRoute, normalizePath, parseQuery } from "./matchRoute.js";
|
|
|
25
26
|
* @param {boolean} [options.focusContent=false] after a page is shown the outlet gets the focus (it is made focusable for that), so a
|
|
26
27
|
* screen reader starts reading the new page and the keyboard continues there
|
|
27
28
|
* @param {boolean} [options.scrollTop=false] scroll to the top after a page is shown
|
|
29
|
+
* @param {boolean} [options.transition=false] a page change is a view transition (document.startViewTransition): the old page cross-fades into the new one,
|
|
30
|
+
* and elements with a `view-transition-name` move from one page to the next. Without the API, or under reduced motion, nothing changes. The old page
|
|
31
|
+
* stays on the screen until the page function of the new one is done, so pages that need long to build should draw something quickly.
|
|
28
32
|
* @param {object} [options.auth] sign-in rules for routes, see the route options below
|
|
29
33
|
* @param {() => boolean} [options.auth.isSignedIn]
|
|
30
34
|
* @param {(role: string) => boolean} [options.auth.hasRole]
|
|
@@ -91,15 +95,20 @@ export function createRouter(options = {}) {
|
|
|
91
95
|
}
|
|
92
96
|
|
|
93
97
|
const host = resolveElement(outlet);
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
98
|
+
const show = async () => {
|
|
99
|
+
if (token !== renderToken) return; // a newer navigation took over while the transition was starting
|
|
100
|
+
host?.replaceChildren();
|
|
101
|
+
currentContext = context;
|
|
102
|
+
options.onRender?.(context, matched?.route);
|
|
103
|
+
if (!matched) {
|
|
104
|
+
notFound?.(context);
|
|
105
|
+
} else {
|
|
106
|
+
if (matched.route.title) document.title = titlePrefix + matched.route.title;
|
|
107
|
+
await matched.route.handler(context);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
if (options.transition) await viewTransition(show);
|
|
111
|
+
else await show();
|
|
103
112
|
if (token !== renderToken) return;
|
|
104
113
|
if (options.focusContent && host) {
|
|
105
114
|
if (!host.hasAttribute("tabindex")) host.setAttribute("tabindex", "-1");
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { downloadFile, toCsv } from "../../core/csv.js";
|
|
7
7
|
import { asHandle, resolveElement } from "../../core/dom.js";
|
|
8
8
|
import { translate } from "../../core/i18n.js";
|
|
9
|
+
import { animate, fadeIn, prefersReducedMotion } from "../../core/motion.js";
|
|
9
10
|
import { clampWidth, virtualWindow } from "../../core/tableMath.js";
|
|
10
11
|
|
|
11
12
|
const el = (tag, className, text) => {
|
|
@@ -65,6 +66,8 @@ const compare = (a, b) =>
|
|
|
65
66
|
* in chunks of `chunkSize` (`page` is the chunk number), rows that have not arrived yet show a placeholder, and sorting or the filter
|
|
66
67
|
* start again from the top.
|
|
67
68
|
* @param {number} [options.chunkSize=50] rows per request of a data source with `virtual`
|
|
69
|
+
* @param {boolean} [options.animateRows=false] rows slide to their new place when the table is sorted, filtered or changes page, and new rows fade in
|
|
70
|
+
* (at most 60 rows are animated, none under reduced motion, none in a virtual table)
|
|
68
71
|
* @param {number} [options.filterDelay=300] ms to wait after typing before the data source is asked
|
|
69
72
|
* @param {{label: string, onclick: (row: object) => void, danger?: boolean, hidden?: (row: object) => boolean, ariaLabel?: (row: object) => string}[]} [options.rowActions]
|
|
70
73
|
* a column of buttons at the end of every row
|
|
@@ -355,8 +358,12 @@ export function generateTable(options = {}) {
|
|
|
355
358
|
return tr;
|
|
356
359
|
}
|
|
357
360
|
|
|
361
|
+
const rowOf = new WeakMap(); // the element of a row -> its row object, to find the same row again after a redraw (animateRows)
|
|
362
|
+
let rendered = false;
|
|
363
|
+
|
|
358
364
|
function renderRow(row, index) {
|
|
359
365
|
const tr = el("tr");
|
|
366
|
+
if (row !== undefined) rowOf.set(tr, row);
|
|
360
367
|
if (virtual) tr.setAttribute("aria-rowindex", String(index + 2));
|
|
361
368
|
if (row === undefined) {
|
|
362
369
|
// A row of a data source that has not arrived yet
|
|
@@ -558,10 +565,28 @@ export function generateTable(options = {}) {
|
|
|
558
565
|
root.classList.toggle("athena-table-is-loading", remote && server.loading);
|
|
559
566
|
renderPager(current.length);
|
|
560
567
|
if (virtual) table.setAttribute("aria-rowcount", String(current.length + 1));
|
|
568
|
+
// Where the rows were before (FLIP): the same row object is the same row
|
|
569
|
+
const before = options.animateRows && rendered && !virtual && !prefersReducedMotion()
|
|
570
|
+
? new Map([...(table.tBodies[0]?.rows ?? [])].slice(0, 60).map(tr => [rowOf.get(tr), tr.getBoundingClientRect()]).filter(([row]) => row !== undefined))
|
|
571
|
+
: null;
|
|
561
572
|
const parts = [renderHead(current), renderBody()];
|
|
562
573
|
if (resizableColumns || Object.keys(widths).length) parts.unshift(renderColgroup());
|
|
563
574
|
if (options.caption) parts.unshift(el("caption", null, options.caption));
|
|
564
575
|
table.replaceChildren(...parts);
|
|
576
|
+
if (before?.size) {
|
|
577
|
+
for (const tr of [...table.tBodies[0].rows].slice(0, 60)) {
|
|
578
|
+
const row = rowOf.get(tr);
|
|
579
|
+
if (row === undefined) continue;
|
|
580
|
+
const old = before.get(row);
|
|
581
|
+
if (!old) {
|
|
582
|
+
fadeIn(tr);
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
const now = tr.getBoundingClientRect();
|
|
586
|
+
if (Math.abs(old.top - now.top) > 1) animate(tr, [{ translate: `0 ${old.top - now.top}px` }, { translate: "0 0" }], { easing: "cubic-bezier(0.2, 0, 0, 1)" });
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
rendered = true;
|
|
565
590
|
if (Object.keys(widths).length) applyWidths();
|
|
566
591
|
if (scroller) scroller.scrollTop = scrollTop;
|
|
567
592
|
}
|
package/src/motion.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//motion entry of Athena UI: animate, transition, flip, tween, spring, stagger, viewTransition, setMotion
|
|
2
|
+
//Import only what you use: `import { animate } from "athena-ui-js/motion"`.
|
|
3
|
+
//LICENCE: MIT
|
|
4
|
+
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
|
+
|
|
6
|
+
export * from "./libs/core/motion.js";
|