@mun-ui/animation 0.2.0 → 0.2.2

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,3 +1,4 @@
1
+ import { AnimationControls } from '../core/controls.js';
1
2
  import { defaultEngine } from '../core/default-engine.js';
2
3
  import { motionValue } from '../core/motion-value.js';
3
4
  import { smooth } from '../core/specs.js';
@@ -12,6 +13,18 @@ import {
12
13
 
13
14
  const activeTransitions = new WeakMap();
14
15
  const EPSILON = 1e-6;
16
+ // Layout frames to keep re-measuring while a target is still resizing.
17
+ const SETTLE_FRAME_LIMIT = 10;
18
+
19
+ /** Same rule as web motion: a hidden document receives no animation frames. */
20
+ function framesSuspendedFor(elements) {
21
+ const doc = elements[0]?.ownerDocument;
22
+ return doc?.visibilityState === 'hidden' && typeof globalThis.requestAnimationFrame === 'function';
23
+ }
24
+
25
+ function completedControls() {
26
+ return new AnimationControls(() => {}, () => {}, Promise.resolve());
27
+ }
15
28
 
16
29
  function asElements(elements) {
17
30
  if (!elements) return [];
@@ -119,6 +132,46 @@ function setStyleValue(element, property, value) {
119
132
  element.style[property] = value;
120
133
  }
121
134
 
135
+ /**
136
+ * Layout can still change after play() (late fonts, content measured later, a
137
+ * lazy window moving). While a target is resizing, call onChange on the next
138
+ * frame so the projection can be re-measured. Stops after SETTLE_FRAME_LIMIT
139
+ * frames or once sizes stop changing. Returns a stop function, or null when the
140
+ * environment has no ResizeObserver or animation frames.
141
+ */
142
+ function watchSettle(elements, onChange) {
143
+ const view = elements[0]?.ownerDocument?.defaultView;
144
+ const ResizeObserverCtor = view?.ResizeObserver ?? globalThis.ResizeObserver;
145
+ const raf = view?.requestAnimationFrame ?? globalThis.requestAnimationFrame;
146
+ const cancelRaf = view?.cancelAnimationFrame ?? globalThis.cancelAnimationFrame;
147
+ if (typeof ResizeObserverCtor !== 'function' || typeof raf !== 'function') return null;
148
+
149
+ let changed = false;
150
+ let frames = 0;
151
+ let frame = 0;
152
+ const observer = new ResizeObserverCtor(() => { changed = true; });
153
+ for (const element of elements) observer.observe(element);
154
+ let stopped = false;
155
+ const stop = () => {
156
+ if (stopped) return;
157
+ stopped = true;
158
+ observer.disconnect();
159
+ if (frame) cancelRaf?.(frame);
160
+ frame = 0;
161
+ };
162
+ const tick = () => {
163
+ frame = 0;
164
+ frames += 1;
165
+ const moved = changed;
166
+ changed = false;
167
+ if (moved) onChange();
168
+ if (!moved || frames >= SETTLE_FRAME_LIMIT) return stop();
169
+ frame = raf(tick);
170
+ };
171
+ frame = raf(tick);
172
+ return stop;
173
+ }
174
+
122
175
  export class LayoutTransition {
123
176
  constructor(elements, {
124
177
  engine = defaultEngine,
@@ -137,6 +190,9 @@ export class LayoutTransition {
137
190
  this.firstByElement = new Map(this.first.map((entry) => [entry.element, entry]));
138
191
  this.items = [];
139
192
  this.controls = null;
193
+ this.progress = null;
194
+ this.unsubscribe = null;
195
+ this.stopSettle = null;
140
196
  this.cancelled = false;
141
197
 
142
198
  // Capture the currently rendered geometry before cancelling an older projection.
@@ -148,44 +204,20 @@ export class LayoutTransition {
148
204
 
149
205
  play() {
150
206
  if (this.cancelled) return null;
151
- const currentScroll = this.measureScroll();
152
- const last = captureLayout(this.elements, { measureScroll: () => currentScroll });
153
- const lastByElement = new Map(last.map((entry) => [entry.element, entry]));
154
- const selected = new Set(this.elements);
155
- const desiredWorld = new Map();
156
- const localProjection = new Map();
157
-
158
- // READ phase is complete before any style writes happen.
159
- for (const element of this.elements) {
160
- const first = this.firstByElement.get(element);
161
- const lastEntry = lastByElement.get(element);
162
- if (!first || !lastEntry) continue;
163
- const adjustedFirst = adjustForScroll(first, currentScroll);
164
- desiredWorld.set(element, projectionMatrixForRects(adjustedFirst, lastEntry.rect, { includeSize: this.includeSize }));
165
- }
166
-
167
- for (const element of this.elements) {
168
- const world = desiredWorld.get(element) ?? [...identityMatrix2D];
169
- const parent = nearestSelectedAncestor(element, selected);
170
- const parentWorld = parent ? desiredWorld.get(parent) ?? identityMatrix2D : identityMatrix2D;
171
- const relativeWorld = multiplyMatrix2D(invertMatrix2D(parentWorld), world);
172
- const lastRect = lastByElement.get(element)?.rect;
173
- if (!lastRect) continue;
174
- localProjection.set(element, matrixInElementSpace(relativeWorld, lastRect));
175
- }
207
+ // A hidden document gets no animation frames, so a projection would stay
208
+ // displaced until it is shown. The final layout is already in place: skip.
209
+ if (framesSuspendedFor(this.elements)) return completedControls();
176
210
 
177
- this.items = this.elements.map((element) => {
178
- const matrix = localProjection.get(element) ?? [...identityMatrix2D];
179
- return {
180
- element,
181
- projection: decomposeMatrix2D(matrix),
182
- originalTransform: getStyleValue(element, 'transform', ''),
183
- originalTransformOrigin: getStyleValue(element, 'transformOrigin', ''),
184
- originalWillChange: getStyleValue(element, 'willChange', ''),
185
- matrixBuffer: new Float64Array(6),
186
- baseTransformSuffix: '',
187
- };
188
- });
211
+ this.items = this.elements.map((element) => ({
212
+ element,
213
+ projection: null,
214
+ originalTransform: getStyleValue(element, 'transform', ''),
215
+ originalTransformOrigin: getStyleValue(element, 'transformOrigin', ''),
216
+ originalWillChange: getStyleValue(element, 'willChange', ''),
217
+ matrixBuffer: new Float64Array(6),
218
+ baseTransformSuffix: '',
219
+ }));
220
+ this.#applyProjections();
189
221
 
190
222
  for (const item of this.items) {
191
223
  item.baseTransformSuffix = this.preserveTransform && item.originalTransform && item.originalTransform !== 'none'
@@ -203,9 +235,44 @@ export class LayoutTransition {
203
235
  for (const item of this.items) activeTransitions.set(item.element, this);
204
236
  this.controls = this.engine.animate(progress, 1, this.spec);
205
237
  this.controls.finished.then(() => this.#cleanup()).catch(() => this.#cleanup());
238
+ this.stopSettle = watchSettle(this.elements, () => this.#retarget());
206
239
  return this.controls;
207
240
  }
208
241
 
242
+ /** READ every rect first, then compute each element's projection in its parent's space. */
243
+ #applyProjections() {
244
+ const currentScroll = this.measureScroll();
245
+ const lastByElement = new Map(
246
+ captureLayout(this.elements, { measureScroll: () => currentScroll }).map((entry) => [entry.element, entry]),
247
+ );
248
+ const selected = new Set(this.elements);
249
+ const desiredWorld = new Map();
250
+ for (const element of this.elements) {
251
+ const first = this.firstByElement.get(element);
252
+ const lastEntry = lastByElement.get(element);
253
+ if (!first || !lastEntry) continue;
254
+ const adjustedFirst = adjustForScroll(first, currentScroll);
255
+ desiredWorld.set(element, projectionMatrixForRects(adjustedFirst, lastEntry.rect, { includeSize: this.includeSize }));
256
+ }
257
+
258
+ for (const item of this.items) {
259
+ const element = item.element;
260
+ const world = desiredWorld.get(element) ?? [...identityMatrix2D];
261
+ const parent = nearestSelectedAncestor(element, selected);
262
+ const parentWorld = parent ? desiredWorld.get(parent) ?? identityMatrix2D : identityMatrix2D;
263
+ const relativeWorld = multiplyMatrix2D(invertMatrix2D(parentWorld), world);
264
+ const lastRect = lastByElement.get(element)?.rect;
265
+ const matrix = lastRect ? matrixInElementSpace(relativeWorld, lastRect) : [...identityMatrix2D];
266
+ item.projection = decomposeMatrix2D(matrix);
267
+ }
268
+ }
269
+
270
+ #retarget() {
271
+ if (this.cancelled || !this.progress) return;
272
+ this.#applyProjections();
273
+ this.#commit(this.progress.get());
274
+ }
275
+
209
276
  #commit(progress) {
210
277
  // WRITE phase: every measurement has already happened in play().
211
278
  for (const item of this.items) {
@@ -215,6 +282,7 @@ export class LayoutTransition {
215
282
  }
216
283
 
217
284
  #cleanup() {
285
+ this.stopSettle?.();
218
286
  if (this.unsubscribe) this.unsubscribe();
219
287
  this.unsubscribe = null;
220
288
  for (const item of this.items) {
@@ -233,6 +301,7 @@ export class LayoutTransition {
233
301
  }
234
302
  }
235
303
 
304
+
236
305
  export function createLayoutTransition(elements, options) {
237
306
  return new LayoutTransition(elements, options);
238
307
  }
@@ -349,38 +418,9 @@ export class SharedLayoutTransition {
349
418
 
350
419
  play() {
351
420
  if (this.cancelled) return null;
352
- const currentScroll = this.measureScroll();
353
- const selected = new Set();
354
- const desiredWorld = new Map();
355
- const lastByElement = new Map();
356
- const sourceByElement = new Map();
357
-
358
- // READ phase: collect every target rect and desired viewport projection.
359
- const seenTargetKeys = new Set();
360
- for (const element of this.elements) {
361
- const identity = this.getKey(element);
362
- if (identity != null && identity !== '') {
363
- if (seenTargetKeys.has(identity)) throw new Error(`Duplicate shared-layout target key: ${String(identity)}`);
364
- seenTargetKeys.add(identity);
365
- }
366
- const source = identity == null ? null : (this.interruptedVisual.get(identity) ?? this.snapshot.get(identity));
367
- if (!source) continue;
368
- const lastRect = copyRect(element.getBoundingClientRect());
369
- const adjustedFirst = adjustForScroll(source, currentScroll);
370
- selected.add(element);
371
- sourceByElement.set(element, source);
372
- lastByElement.set(element, lastRect);
373
- desiredWorld.set(element, projectionMatrixForRects(adjustedFirst, lastRect, { includeSize: this.includeSize }));
374
- }
375
-
376
- // Remove projection already supplied by a matched target ancestor.
377
- const localProjection = new Map();
378
- for (const element of selected) {
379
- const parent = nearestSelectedAncestor(element, selected);
380
- const parentWorld = parent ? desiredWorld.get(parent) ?? identityMatrix2D : identityMatrix2D;
381
- const relativeWorld = multiplyMatrix2D(invertMatrix2D(parentWorld), desiredWorld.get(element) ?? identityMatrix2D);
382
- localProjection.set(element, matrixInElementSpace(relativeWorld, lastByElement.get(element)));
383
- }
421
+ // Same rule as LayoutTransition: no frames in a hidden document, so the final layout stays.
422
+ if (framesSuspendedFor(this.elements)) return completedControls();
423
+ const { selected, sourceByElement, projections } = this.#measure();
384
424
 
385
425
  this.items = [];
386
426
  for (const element of selected) {
@@ -389,7 +429,8 @@ export class SharedLayoutTransition {
389
429
  this.items.push({
390
430
  element,
391
431
  sourceElement: sourceByElement.get(element)?.element ?? null,
392
- projection: decomposeMatrix2D(localProjection.get(element) ?? identityMatrix2D),
432
+ projection: projections.get(element),
433
+ detached: false,
393
434
  originalTransform: getStyleValue(element, 'transform', ''),
394
435
  originalTransformOrigin: getStyleValue(element, 'transformOrigin', ''),
395
436
  originalWillChange: getStyleValue(element, 'willChange', ''),
@@ -414,11 +455,66 @@ export class SharedLayoutTransition {
414
455
  for (const item of this.items) activeTransitions.set(item.element, this);
415
456
  this.controls = this.engine.animate(progress, 1, this.spec);
416
457
  this.controls.finished.then(() => this.#cleanup()).catch(() => this.#cleanup());
458
+ this.stopSettle = watchSettle(this.elements, () => this.#retarget());
417
459
  return this.controls;
418
460
  }
419
461
 
462
+ /**
463
+ * READ phase: every target rect and its projection in the nearest selected
464
+ * ancestor's space. Targets without a source, or detached from the document,
465
+ * are not projected.
466
+ */
467
+ #measure() {
468
+ const currentScroll = this.measureScroll();
469
+ const selected = new Set();
470
+ const desiredWorld = new Map();
471
+ const lastByElement = new Map();
472
+ const sourceByElement = new Map();
473
+
474
+ const seenTargetKeys = new Set();
475
+ for (const element of this.elements) {
476
+ const identity = this.getKey(element);
477
+ if (identity != null && identity !== '') {
478
+ if (seenTargetKeys.has(identity)) throw new Error(`Duplicate shared-layout target key: ${String(identity)}`);
479
+ seenTargetKeys.add(identity);
480
+ }
481
+ if (element.isConnected === false) continue;
482
+ const source = identity == null ? null : (this.interruptedVisual.get(identity) ?? this.snapshot.get(identity));
483
+ if (!source) continue;
484
+ const lastRect = copyRect(element.getBoundingClientRect());
485
+ const adjustedFirst = adjustForScroll(source, currentScroll);
486
+ selected.add(element);
487
+ sourceByElement.set(element, source);
488
+ lastByElement.set(element, lastRect);
489
+ desiredWorld.set(element, projectionMatrixForRects(adjustedFirst, lastRect, { includeSize: this.includeSize }));
490
+ }
491
+
492
+ // Remove projection already supplied by a matched target ancestor.
493
+ const projections = new Map();
494
+ for (const element of selected) {
495
+ const parent = nearestSelectedAncestor(element, selected);
496
+ const parentWorld = parent ? desiredWorld.get(parent) ?? identityMatrix2D : identityMatrix2D;
497
+ const relativeWorld = multiplyMatrix2D(invertMatrix2D(parentWorld), desiredWorld.get(element) ?? identityMatrix2D);
498
+ projections.set(element, decomposeMatrix2D(matrixInElementSpace(relativeWorld, lastByElement.get(element))));
499
+ }
500
+ return { selected, sourceByElement, projections };
501
+ }
502
+
503
+ #retarget() {
504
+ if (this.cancelled || !this.progress) return;
505
+ const { projections } = this.#measure();
506
+ // Targets that left the document (for example, rows scrolled out of a lazy window) stop moving.
507
+ for (const item of this.items) {
508
+ const projection = projections.get(item.element);
509
+ item.detached = !projection;
510
+ if (projection) item.projection = projection;
511
+ }
512
+ this.#commit(this.progress.get());
513
+ }
514
+
420
515
  #commit(progress) {
421
516
  for (const item of this.items) {
517
+ if (item.detached) continue;
422
518
  const matrix = matrixAtProgress(item.projection, progress, item.matrixBuffer);
423
519
  setStyleValue(item.element, 'transform', `${formatMatrix(matrix)}${item.baseTransformSuffix}`);
424
520
  if (this.fadeTarget && item.sourceElement !== item.element) {
@@ -428,6 +524,7 @@ export class SharedLayoutTransition {
428
524
  }
429
525
 
430
526
  #cleanup() {
527
+ this.stopSettle?.();
431
528
  this.unsubscribe?.();
432
529
  this.unsubscribe = null;
433
530
  for (const item of this.items) {
@@ -5,7 +5,28 @@ export const inputEvents = ['pointerdown', 'pointermove', 'keydown', 'wheel', 't
5
5
  const cachePrefix = 'mun:backdrop-quality:v1:';
6
6
  export const screenKey = owner => JSON.stringify([owner.navigator.userAgent, owner.screen.width, owner.screen.height, owner.screen.colorDepth, owner.devicePixelRatio]);
7
7
  const isQuality = value => value === 'full' || value === 'reduced' || value === 'none';
8
- const requiredAPIs = ['requestIdleCallback', 'cancelIdleCallback', 'requestAnimationFrame', 'cancelAnimationFrame'];
8
+ const requiredAPIs = ['requestAnimationFrame', 'cancelAnimationFrame'];
9
+
10
+ /**
11
+ * Idle callbacks, or a timer stand-in where the platform has none (WebKit, so every
12
+ * iPhone browser). Without it the probe never ran there and blur stayed at full quality
13
+ * however slow the device was. The stand-in cannot see idle time, so it reports a fixed
14
+ * budget; the probe's own guards still hold: it waits for a quiet second after load,
15
+ * cancels on any input, and rejects unstable frame samples.
16
+ */
17
+ const fallbackBudgetMs = 50;
18
+ export function idleScheduler(owner) {
19
+ if (typeof owner.requestIdleCallback === 'function' && typeof owner.cancelIdleCallback === 'function') {
20
+ return { request: callback => owner.requestIdleCallback(callback), cancel: id => owner.cancelIdleCallback(id) };
21
+ }
22
+ return {
23
+ request: callback => owner.setTimeout(() => {
24
+ const start = owner.performance.now();
25
+ callback({ didTimeout: false, timeRemaining: () => Math.max(0, fallbackBudgetMs - (owner.performance.now() - start)) });
26
+ }, 16),
27
+ cancel: id => owner.clearTimeout(id),
28
+ };
29
+ }
9
30
 
10
31
  function classifyFrames(baseline, filtered) {
11
32
  if (baseline.length !== 2 || filtered.length !== 2) return undefined;
@@ -32,13 +53,14 @@ export function probeRenderingQuality(owner, { cached = false, signal } = {}) {
32
53
  const missing = requiredAPIs.filter(name => typeof owner[name] !== 'function');
33
54
  if (missing.length) return resolve({ source: 'unavailable', reason: 'unsupported-api', missing });
34
55
  const key = screenKey(owner);
56
+ const idleCallbacks = idleScheduler(owner);
35
57
  let done = false, frame = 0, idle = 0, quiet = 0, watchdog = 0;
36
58
  let sample;
37
59
  const finish = (result = { source: 'unavailable' }) => {
38
60
  if (done) return;
39
61
  done = true;
40
62
  owner.cancelAnimationFrame(frame);
41
- owner.cancelIdleCallback(idle);
63
+ idleCallbacks.cancel(idle);
42
64
  owner.clearTimeout(quiet);
43
65
  owner.clearTimeout(watchdog);
44
66
  owner.removeEventListener('load', loaded);
@@ -54,7 +76,7 @@ export function probeRenderingQuality(owner, { cached = false, signal } = {}) {
54
76
  const safe = work => { try { work(); } catch { finish({ source: 'unavailable', reason: 'exception' }); } };
55
77
  const available = () => !done && document.visibilityState === 'visible' && screenKey(owner) === key;
56
78
  const whenIdle = work => {
57
- idle = owner.requestIdleCallback(deadline => safe(() => {
79
+ idle = idleCallbacks.request(deadline => safe(() => {
58
80
  if (!available()) return finish({ source: 'unavailable', reason: 'not-visible-or-screen-changed' });
59
81
  if (deadline.didTimeout || deadline.timeRemaining() < 8) return finish({ source: 'unavailable', reason: 'insufficient-idle-budget' });
60
82
  work();
@@ -124,8 +146,7 @@ export function probeRenderingQuality(owner, { cached = false, signal } = {}) {
124
146
 
125
147
  /** Persist the selected policy, rather than a noisy raw sample, outside input work. */
126
148
  export function cacheRenderingQuality(owner, key, quality) {
127
- if (typeof owner.requestIdleCallback !== 'function') return;
128
- owner.requestIdleCallback(deadline => {
149
+ idleScheduler(owner).request(deadline => {
129
150
  if (deadline.timeRemaining() < 2) return;
130
151
  try { owner.localStorage.setItem(cachePrefix + key, quality); } catch { /* blocked or full storage */ }
131
152
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mun-ui/animation",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "description": "Renderer-agnostic Mün animation runtime with JS/WASM/Worker execution, gestures, timelines, transitions, scroll linking, constraints, and GPU/canvas adapters.",
6
6
  "sideEffects": false,
@@ -85,7 +85,7 @@
85
85
  }
86
86
  },
87
87
  "dependencies": {
88
- "@mun-ui/execution": "0.2.0"
88
+ "@mun-ui/execution": "0.2.2"
89
89
  },
90
90
  "engines": {
91
91
  "node": ">=20.19.0"