@mun-ui/web 0.0.0-stage → 0.2.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.
Files changed (107) hide show
  1. package/LICENSE +21 -0
  2. package/dist/accessibility.d.ts +3 -0
  3. package/dist/accessibility.d.ts.map +1 -0
  4. package/dist/accessibility.js +195 -0
  5. package/dist/accessibility.js.map +1 -0
  6. package/dist/content-transition.d.ts +23 -0
  7. package/dist/content-transition.d.ts.map +1 -0
  8. package/dist/content-transition.js +780 -0
  9. package/dist/content-transition.js.map +1 -0
  10. package/dist/continuous-corners.d.ts +3 -0
  11. package/dist/continuous-corners.d.ts.map +1 -0
  12. package/dist/continuous-corners.js +71 -0
  13. package/dist/continuous-corners.js.map +1 -0
  14. package/dist/control-styles.d.ts +7 -0
  15. package/dist/control-styles.d.ts.map +1 -0
  16. package/dist/control-styles.js +141 -0
  17. package/dist/control-styles.js.map +1 -0
  18. package/dist/controls.d.ts +4 -0
  19. package/dist/controls.d.ts.map +1 -0
  20. package/dist/controls.js +249 -0
  21. package/dist/controls.js.map +1 -0
  22. package/dist/devtools.d.ts +50 -0
  23. package/dist/devtools.d.ts.map +1 -0
  24. package/dist/devtools.js +118 -0
  25. package/dist/devtools.js.map +1 -0
  26. package/dist/dom.d.ts +12 -0
  27. package/dist/dom.d.ts.map +1 -0
  28. package/dist/dom.js +5427 -0
  29. package/dist/dom.js.map +1 -0
  30. package/dist/element-motion.d.ts +29 -0
  31. package/dist/element-motion.d.ts.map +1 -0
  32. package/dist/element-motion.js +463 -0
  33. package/dist/element-motion.js.map +1 -0
  34. package/dist/focus.d.ts +3 -0
  35. package/dist/focus.d.ts.map +1 -0
  36. package/dist/focus.js +70 -0
  37. package/dist/focus.js.map +1 -0
  38. package/dist/gpu-island.d.ts +123 -0
  39. package/dist/gpu-island.d.ts.map +1 -0
  40. package/dist/gpu-island.js +1093 -0
  41. package/dist/gpu-island.js.map +1 -0
  42. package/dist/hydration.d.ts +18 -0
  43. package/dist/hydration.d.ts.map +1 -0
  44. package/dist/hydration.js +228 -0
  45. package/dist/hydration.js.map +1 -0
  46. package/dist/index.d.ts +9 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +7 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/lazy-index.d.ts +42 -0
  51. package/dist/lazy-index.d.ts.map +1 -0
  52. package/dist/lazy-index.js +136 -0
  53. package/dist/lazy-index.js.map +1 -0
  54. package/dist/motion.d.ts +49 -0
  55. package/dist/motion.d.ts.map +1 -0
  56. package/dist/motion.js +793 -0
  57. package/dist/motion.js.map +1 -0
  58. package/dist/patch-ir.d.ts +44 -0
  59. package/dist/patch-ir.d.ts.map +1 -0
  60. package/dist/patch-ir.js +221 -0
  61. package/dist/patch-ir.js.map +1 -0
  62. package/dist/path-interpolation.d.ts +29 -0
  63. package/dist/path-interpolation.d.ts.map +1 -0
  64. package/dist/path-interpolation.js +318 -0
  65. package/dist/path-interpolation.js.map +1 -0
  66. package/dist/presentation.d.ts +4 -0
  67. package/dist/presentation.d.ts.map +1 -0
  68. package/dist/presentation.js +207 -0
  69. package/dist/presentation.js.map +1 -0
  70. package/dist/props.d.ts +24 -0
  71. package/dist/props.d.ts.map +1 -0
  72. package/dist/props.js +719 -0
  73. package/dist/props.js.map +1 -0
  74. package/dist/shared.d.ts +79 -0
  75. package/dist/shared.d.ts.map +1 -0
  76. package/dist/shared.js +806 -0
  77. package/dist/shared.js.map +1 -0
  78. package/dist/ssr.d.ts +3 -0
  79. package/dist/ssr.d.ts.map +1 -0
  80. package/dist/ssr.js +280 -0
  81. package/dist/ssr.js.map +1 -0
  82. package/dist/symbols.d.ts +5 -0
  83. package/dist/symbols.d.ts.map +1 -0
  84. package/dist/symbols.js +37 -0
  85. package/dist/symbols.js.map +1 -0
  86. package/dist/text-layout.d.ts +10 -0
  87. package/dist/text-layout.d.ts.map +1 -0
  88. package/dist/text-layout.js +280 -0
  89. package/dist/text-layout.js.map +1 -0
  90. package/dist/transition.d.ts +12 -0
  91. package/dist/transition.d.ts.map +1 -0
  92. package/dist/transition.js +172 -0
  93. package/dist/transition.js.map +1 -0
  94. package/dist/ui-ir.d.ts +12 -0
  95. package/dist/ui-ir.d.ts.map +1 -0
  96. package/dist/ui-ir.js +324 -0
  97. package/dist/ui-ir.js.map +1 -0
  98. package/dist/url-policy.d.ts +2 -0
  99. package/dist/url-policy.d.ts.map +1 -0
  100. package/dist/url-policy.js +27 -0
  101. package/dist/url-policy.js.map +1 -0
  102. package/dist/visual-effects.d.ts +5 -0
  103. package/dist/visual-effects.d.ts.map +1 -0
  104. package/dist/visual-effects.js +166 -0
  105. package/dist/visual-effects.js.map +1 -0
  106. package/package.json +47 -3
  107. package/README.md +0 -3
package/dist/motion.js ADDED
@@ -0,0 +1,793 @@
1
+ import { animate, curves, createInterpolator, motionValue, smooth, spring, timing, } from "@mun-ui/animation";
2
+ import { compositorMotionPropertyMask, layoutMotionPropertyMask, motionPropertyBit, paintMotionPropertyMask } from "@mun-ui/core/internal/motion-abi";
3
+ import { svgPathInterpolatorOptions } from "./path-interpolation.js";
4
+ const paintMotionPropertyFallback = new Set(["filter", "box-shadow", "text-shadow"]);
5
+ const layoutMotionPropertyFallback = new Set([
6
+ "word-spacing", "border-width", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
7
+ "flex-basis", "grid-template-columns", "grid-template-rows",
8
+ ]);
9
+ /** Stable launch lane used by automatic motion batches: compositor -> paint -> layout -> other. */
10
+ function motionPropertyPriority(property) {
11
+ const bit = motionPropertyBit(property);
12
+ if (bit !== 0 && (bit & compositorMotionPropertyMask) !== 0)
13
+ return 0;
14
+ if ((bit !== 0 && (bit & paintMotionPropertyMask) !== 0) || paintMotionPropertyFallback.has(property) || property.endsWith("-color"))
15
+ return 1;
16
+ if ((bit !== 0 && (bit & layoutMotionPropertyMask) !== 0) || layoutMotionPropertyFallback.has(property))
17
+ return 2;
18
+ return 3;
19
+ }
20
+ const compiledMotionPlans = new WeakMap();
21
+ const compiledDescriptorPlans = new Map();
22
+ const maximumCompiledDescriptorPlans = 128;
23
+ const activeChannels = new WeakMap();
24
+ const activeAttributeChannels = new WeakMap();
25
+ const pendingStyleWrites = new Map();
26
+ const pendingAttributeWrites = new Map();
27
+ let styleWriteScheduled = false;
28
+ let attributeWriteScheduled = false;
29
+ function queueStyleWrite(element, property, value) {
30
+ let writes = pendingStyleWrites.get(element);
31
+ if (!writes) {
32
+ writes = new Map();
33
+ pendingStyleWrites.set(element, writes);
34
+ }
35
+ writes.set(property, value);
36
+ if (styleWriteScheduled)
37
+ return;
38
+ styleWriteScheduled = true;
39
+ queueMicrotask(() => {
40
+ styleWriteScheduled = false;
41
+ const batch = [...pendingStyleWrites];
42
+ pendingStyleWrites.clear();
43
+ for (const [target, properties] of batch) {
44
+ const style = target.style;
45
+ if (!style)
46
+ continue;
47
+ for (const [name, next] of properties)
48
+ style.setProperty(name, next);
49
+ }
50
+ });
51
+ }
52
+ function removePendingStyleWrite(element, property) {
53
+ const writes = pendingStyleWrites.get(element);
54
+ if (!writes)
55
+ return;
56
+ if (property === undefined) {
57
+ pendingStyleWrites.delete(element);
58
+ return;
59
+ }
60
+ writes.delete(property);
61
+ if (writes.size === 0)
62
+ pendingStyleWrites.delete(element);
63
+ }
64
+ function queueAttributeWrite(element, name, value) {
65
+ let writes = pendingAttributeWrites.get(element);
66
+ if (!writes) {
67
+ writes = new Map();
68
+ pendingAttributeWrites.set(element, writes);
69
+ }
70
+ writes.set(name, value);
71
+ if (attributeWriteScheduled)
72
+ return;
73
+ attributeWriteScheduled = true;
74
+ queueMicrotask(() => {
75
+ attributeWriteScheduled = false;
76
+ const batch = [...pendingAttributeWrites];
77
+ pendingAttributeWrites.clear();
78
+ for (const [target, attributes] of batch) {
79
+ for (const [name, next] of attributes)
80
+ target.setAttribute(name, next);
81
+ }
82
+ });
83
+ }
84
+ function removePendingAttributeWrite(element, name) {
85
+ const writes = pendingAttributeWrites.get(element);
86
+ if (!writes)
87
+ return;
88
+ if (name === undefined) {
89
+ pendingAttributeWrites.delete(element);
90
+ return;
91
+ }
92
+ writes.delete(name);
93
+ if (writes.size === 0)
94
+ pendingAttributeWrites.delete(element);
95
+ }
96
+ /**
97
+ * Every channel advances on the animation engine's frame clock, and a document
98
+ * that is not being rendered (background tab, occluded or minimized webview)
99
+ * receives no requestAnimationFrame callbacks. An animated commit started there
100
+ * would leave the DOM at the previous value for as long as the page stays
101
+ * hidden, although the same change without an animation applies at once. With
102
+ * nothing to present, such a change is committed directly instead.
103
+ */
104
+ function framesSuspended(element) {
105
+ return element.ownerDocument?.visibilityState === "hidden" && typeof globalThis.requestAnimationFrame === "function";
106
+ }
107
+ function channelsFor(element) {
108
+ let channels = activeChannels.get(element);
109
+ if (!channels) {
110
+ channels = new Map();
111
+ activeChannels.set(element, channels);
112
+ }
113
+ return channels;
114
+ }
115
+ function curveFor(kind) {
116
+ switch (kind) {
117
+ case "linear": return timing({ duration: 0.35, curve: curves.linear });
118
+ case "easeIn": return timing({ duration: 0.35, curve: curves.easeIn });
119
+ case "easeOut": return timing({ duration: 0.35, curve: curves.easeOut });
120
+ case "easeInOut": return timing({ duration: 0.35, curve: curves.easeInOut });
121
+ default: return smooth();
122
+ }
123
+ }
124
+ function compileMotionPlan(animation) {
125
+ const cached = compiledMotionPlans.get(animation);
126
+ if (cached)
127
+ return cached;
128
+ const descriptor = animation.descriptor;
129
+ const speed = Number.isFinite(descriptor.speed) && descriptor.speed > 0 ? descriptor.speed : 1;
130
+ const duration = Number.isFinite(descriptor.duration) ? Math.max(0, descriptor.duration) / speed : 0.35;
131
+ const response = Math.max(0.001, (descriptor.response ?? descriptor.duration) / speed);
132
+ const dampingRatio = descriptor.dampingFraction ?? 0.825;
133
+ const blendDuration = Math.max(0, Number.isFinite(descriptor.blendDuration) ? descriptor.blendDuration ?? 0 : 0) / speed;
134
+ const delayMs = Math.max(0, Number.isFinite(descriptor.delay) ? descriptor.delay : 0) * 1000 / speed;
135
+ const repeatCount = descriptor.repeatCount === Number.POSITIVE_INFINITY
136
+ ? Number.POSITIVE_INFINITY
137
+ : Math.max(1, Math.floor(Number.isFinite(descriptor.repeatCount) ? descriptor.repeatCount : 1));
138
+ const autoreverses = descriptor.autoreverses ?? true;
139
+ // Compiler-hoisted Animation values hit the WeakMap above. This bounded
140
+ // structural cache covers dynamic code that recreates an equivalent immutable
141
+ // descriptor, so easing LUT/spring coefficient compilation is still paid once.
142
+ const descriptorKey = [
143
+ descriptor.kind, duration, response, dampingRatio, blendDuration, delayMs,
144
+ repeatCount, autoreverses ? 1 : 0,
145
+ ].join("|");
146
+ const shared = compiledDescriptorPlans.get(descriptorKey);
147
+ if (shared) {
148
+ compiledDescriptorPlans.delete(descriptorKey);
149
+ compiledDescriptorPlans.set(descriptorKey, shared);
150
+ compiledMotionPlans.set(animation, shared);
151
+ return shared;
152
+ }
153
+ const spec = descriptor.kind === "spring"
154
+ ? Object.freeze({ ...spring({ response, dampingRatio }), blendDuration })
155
+ : (() => {
156
+ const base = curveFor(descriptor.kind);
157
+ return base.kind === "timing" ? timing({ duration, curve: base.curve }) : base;
158
+ })();
159
+ const plan = Object.freeze({
160
+ spec,
161
+ delayMs,
162
+ repeatCount,
163
+ autoreverses,
164
+ });
165
+ compiledMotionPlans.set(animation, plan);
166
+ compiledDescriptorPlans.set(descriptorKey, plan);
167
+ while (compiledDescriptorPlans.size > maximumCompiledDescriptorPlans) {
168
+ const oldest = compiledDescriptorPlans.keys().next().value;
169
+ if (oldest === undefined)
170
+ break;
171
+ compiledDescriptorPlans.delete(oldest);
172
+ }
173
+ return plan;
174
+ }
175
+ /** Convert and memoize Mun's SwiftUI-shaped value into a public @mun-ui/animation spec. */
176
+ export function motionSpecForAnimation(animation) {
177
+ return compileMotionPlan(animation).spec;
178
+ }
179
+ function isColorProperty(property) {
180
+ return property === "color" || property === "background" || property === "background-color" || property === "border-color" || property.endsWith("-color");
181
+ }
182
+ function parseScalar(value) {
183
+ if (typeof value === "number")
184
+ return Number.isFinite(value) ? { value, unit: "" } : undefined;
185
+ if (typeof value !== "string")
186
+ return undefined;
187
+ // A scalar CSS value is one number plus one simple unit. Do not classify
188
+ // compound values such as `17.6px 0px` as a scalar whose unit happens to be
189
+ // `px 0px`: that route carries spring velocity through the first numeric token
190
+ // and can make a rapidly reversed switch thumb keep travelling the old way.
191
+ // Compound numeric CSS belongs to the template interpolator below instead.
192
+ const match = value.trim().match(/^(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)([A-Za-z%]*)$/i);
193
+ if (!match)
194
+ return undefined;
195
+ const scalar = Number(match[1]);
196
+ return Number.isFinite(scalar) ? { value: scalar, unit: match[2] } : undefined;
197
+ }
198
+ function numericCssTemplate(value) {
199
+ const pattern = /-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi;
200
+ const parts = [];
201
+ const values = [];
202
+ let cursor = 0;
203
+ let match;
204
+ while ((match = pattern.exec(value))) {
205
+ parts.push(value.slice(cursor, match.index));
206
+ const number = Number(match[0]);
207
+ if (!Number.isFinite(number))
208
+ return undefined;
209
+ values.push(number);
210
+ cursor = match.index + match[0].length;
211
+ }
212
+ if (values.length === 0)
213
+ return undefined;
214
+ parts.push(value.slice(cursor));
215
+ return { parts, values };
216
+ }
217
+ function numericCssInterpolatorOptions(from, to) {
218
+ const left = numericCssTemplate(from);
219
+ const right = numericCssTemplate(to);
220
+ if (!left || !right || left.values.length !== right.values.length || left.parts.length !== right.parts.length)
221
+ return undefined;
222
+ for (let index = 0; index < left.parts.length; index += 1) {
223
+ if (left.parts[index] !== right.parts[index])
224
+ return undefined;
225
+ }
226
+ return {
227
+ interpolate(_from, _to, progress) {
228
+ let output = left.parts[0];
229
+ for (let index = 0; index < left.values.length; index += 1) {
230
+ const value = left.values[index] + (right.values[index] - left.values[index]) * progress;
231
+ const normalized = Math.abs(value) < 1e-10 ? 0 : Math.round(value * 100000) / 100000;
232
+ output += `${normalized}${left.parts[index + 1]}`;
233
+ }
234
+ return output;
235
+ },
236
+ };
237
+ }
238
+ function interpolatorOptions(property, from, to) {
239
+ if (property === "transform" && typeof from === "string" && typeof to === "string")
240
+ return { type: "transform" };
241
+ if (isColorProperty(property) && typeof from === "string" && typeof to === "string")
242
+ return { type: "color", color: { space: "oklab" } };
243
+ // CSS has many numerically-interpolable compound values (translate/scale,
244
+ // border radii, filters, shadows without color changes, background position,
245
+ // etc.). If the token skeleton is stable, interpolate every numeric token in
246
+ // one channel rather than falling back to a discrete jump.
247
+ if (typeof from === "string" && typeof to === "string")
248
+ return numericCssInterpolatorOptions(from, to);
249
+ return undefined;
250
+ }
251
+ function routeFor(property, from, to) {
252
+ const left = parseScalar(from);
253
+ const right = parseScalar(to);
254
+ if (left && right && left.unit === right.unit)
255
+ return { kind: "scalar", value: right.value, unit: right.unit };
256
+ const options = interpolatorOptions(property, from, to);
257
+ return options ? { kind: "interpolated", options } : undefined;
258
+ }
259
+ /**
260
+ * `translate` and `scale` take one to three components, and the browser
261
+ * serializes an inline value in its shortest form (`0px 0px` reads back as
262
+ * `0px`, `2 2` as `2`). The value read from the element and the authored target
263
+ * can therefore differ in component count although both are interpolable.
264
+ * Expand both to the same count so they share one numeric template.
265
+ */
266
+ function alignTransformComponents(property, from, to) {
267
+ if ((property !== "translate" && property !== "scale") || typeof from !== "string" || typeof to !== "string")
268
+ return [from, to];
269
+ const left = from.trim().split(/\s+/);
270
+ const right = to.trim().split(/\s+/);
271
+ const count = Math.max(left.length, right.length);
272
+ if (left.length === right.length || count > 3 || left[0] === "none" || right[0] === "none")
273
+ return [from, to];
274
+ const expand = (parts) => {
275
+ const expanded = [...parts];
276
+ // A single scale factor applies to both axes; every other omitted component is the identity.
277
+ if (property === "scale" && expanded.length === 1 && count > 1)
278
+ expanded.push(expanded[0]);
279
+ while (expanded.length < count)
280
+ expanded.push(property === "scale" ? "1" : "0px");
281
+ return expanded.join(" ");
282
+ };
283
+ return [expand(left), expand(right)];
284
+ }
285
+ function startAfterDelay(delayMs, start) {
286
+ if (!(delayMs > 0)) {
287
+ start();
288
+ return undefined;
289
+ }
290
+ return setTimeout(start, delayMs);
291
+ }
292
+ class ScalarMotionChannel {
293
+ element;
294
+ property;
295
+ route = "scalar";
296
+ #value;
297
+ #unsubscribe;
298
+ #control;
299
+ #timer;
300
+ #generation = 0;
301
+ #active = false;
302
+ #unit;
303
+ #currentStyle;
304
+ constructor(element, property, start, unit) {
305
+ this.element = element;
306
+ this.property = property;
307
+ this.#unit = unit;
308
+ this.#currentStyle = `${start}${unit}`;
309
+ this.#value = motionValue(start);
310
+ this.#unsubscribe = this.#value.subscribeValue(value => {
311
+ this.#currentStyle = `${value}${this.#unit}`;
312
+ queueStyleWrite(this.element, this.property, this.#currentStyle);
313
+ }, { emitCurrent: false });
314
+ }
315
+ currentStyleValue() { return this.#currentStyle; }
316
+ isActive() { return this.#active; }
317
+ retarget(to, plan) {
318
+ const target = parseScalar(to);
319
+ if (!target || target.unit !== this.#unit)
320
+ return false;
321
+ const generation = ++this.#generation;
322
+ this.#active = true;
323
+ if (this.#timer !== undefined)
324
+ clearTimeout(this.#timer);
325
+ this.#timer = undefined;
326
+ const run = async () => {
327
+ if (generation !== this.#generation)
328
+ return;
329
+ const origin = this.#value.get();
330
+ let cycle = 0;
331
+ try {
332
+ while (generation === this.#generation && (plan.repeatCount === Number.POSITIVE_INFINITY || cycle < plan.repeatCount)) {
333
+ const reverse = plan.autoreverses && cycle % 2 === 1;
334
+ // Calling animate() on the same MotionValue deliberately avoids a
335
+ // pre-cancel here: @mun-ui/animation retargets a live spring in-place and carries
336
+ // its velocity into the new target.
337
+ this.#control = animate(this.#value, reverse ? origin : target.value, plan.spec);
338
+ const result = await this.#control.finished;
339
+ if (generation !== this.#generation || result.status !== "finished")
340
+ return;
341
+ cycle += 1;
342
+ if (!plan.autoreverses
343
+ && (plan.repeatCount === Number.POSITIVE_INFINITY || cycle < plan.repeatCount)) {
344
+ this.#value.set(origin, 0);
345
+ }
346
+ }
347
+ }
348
+ finally {
349
+ if (generation === this.#generation && plan.repeatCount !== Number.POSITIVE_INFINITY)
350
+ this.#active = false;
351
+ }
352
+ };
353
+ // A delayed retarget intentionally leaves the current engine animation
354
+ // running. When the timer fires animate() retargets the same MotionValue
355
+ // from its then-current presentation value/velocity instead of freezing it
356
+ // at request time and later reviving stale velocity.
357
+ this.#timer = startAfterDelay(plan.delayMs, () => {
358
+ this.#timer = undefined;
359
+ void run();
360
+ });
361
+ return true;
362
+ }
363
+ dispose() {
364
+ this.#generation += 1;
365
+ this.#active = false;
366
+ if (this.#timer !== undefined)
367
+ clearTimeout(this.#timer);
368
+ this.#timer = undefined;
369
+ this.#control?.cancel();
370
+ this.#control = undefined;
371
+ this.#unsubscribe();
372
+ removePendingStyleWrite(this.element, this.property);
373
+ }
374
+ }
375
+ class InterpolatedMotionChannel {
376
+ element;
377
+ property;
378
+ route = "interpolated";
379
+ #progress = motionValue(0);
380
+ #unsubscribe;
381
+ #control;
382
+ #timer;
383
+ #generation = 0;
384
+ #active = false;
385
+ #interpolate;
386
+ #currentStyle;
387
+ #origin;
388
+ #target;
389
+ #options;
390
+ constructor(element, property, from, to, options) {
391
+ this.element = element;
392
+ this.property = property;
393
+ this.#origin = from;
394
+ this.#target = to;
395
+ this.#options = options;
396
+ this.#interpolate = createInterpolator(from, to, options);
397
+ this.#currentStyle = String(from);
398
+ this.#unsubscribe = this.#progress.subscribeValue(progress => {
399
+ const value = this.#interpolate(progress);
400
+ this.#currentStyle = String(value);
401
+ queueStyleWrite(this.element, this.property, this.#currentStyle);
402
+ }, { emitCurrent: false });
403
+ }
404
+ currentStyleValue() { return this.#currentStyle; }
405
+ isActive() { return this.#active; }
406
+ retarget(to, plan) {
407
+ const options = interpolatorOptions(this.property, this.#currentStyle, to);
408
+ if (!options)
409
+ return false;
410
+ const generation = ++this.#generation;
411
+ this.#active = true;
412
+ if (this.#timer !== undefined)
413
+ clearTimeout(this.#timer);
414
+ this.#timer = undefined;
415
+ const run = async () => {
416
+ if (generation !== this.#generation)
417
+ return;
418
+ this.#control?.cancel();
419
+ this.#origin = this.#currentStyle;
420
+ this.#target = to;
421
+ this.#options = options;
422
+ try {
423
+ this.#interpolate = createInterpolator(this.#origin, this.#target, this.#options);
424
+ }
425
+ catch {
426
+ if (generation === this.#generation)
427
+ this.#active = false;
428
+ return;
429
+ }
430
+ this.#progress.set(0, 0);
431
+ let cycle = 0;
432
+ try {
433
+ while (generation === this.#generation && (plan.repeatCount === Number.POSITIVE_INFINITY || cycle < plan.repeatCount)) {
434
+ const reverse = plan.autoreverses && cycle % 2 === 1;
435
+ this.#progress.set(reverse ? 1 : 0, 0);
436
+ this.#control = animate(this.#progress, reverse ? 0 : 1, plan.spec);
437
+ const result = await this.#control.finished;
438
+ if (generation !== this.#generation || result.status !== "finished")
439
+ return;
440
+ cycle += 1;
441
+ }
442
+ }
443
+ finally {
444
+ if (generation === this.#generation && plan.repeatCount !== Number.POSITIVE_INFINITY)
445
+ this.#active = false;
446
+ }
447
+ };
448
+ this.#timer = startAfterDelay(plan.delayMs, () => {
449
+ this.#timer = undefined;
450
+ void run();
451
+ });
452
+ return true;
453
+ }
454
+ dispose() {
455
+ this.#generation += 1;
456
+ this.#active = false;
457
+ if (this.#timer !== undefined)
458
+ clearTimeout(this.#timer);
459
+ this.#timer = undefined;
460
+ this.#control?.cancel();
461
+ this.#control = undefined;
462
+ this.#unsubscribe();
463
+ removePendingStyleWrite(this.element, this.property);
464
+ }
465
+ }
466
+ class InterpolatedAttributeMotionChannel {
467
+ element;
468
+ name;
469
+ #progress = motionValue(0);
470
+ #unsubscribe;
471
+ #control;
472
+ #timer;
473
+ #generation = 0;
474
+ #active = false;
475
+ #interpolate;
476
+ #current;
477
+ constructor(element, name, from, to, options) {
478
+ this.element = element;
479
+ this.name = name;
480
+ this.#interpolate = createInterpolator(from, to, options);
481
+ this.#current = String(from);
482
+ this.#unsubscribe = this.#progress.subscribeValue(progress => {
483
+ this.#current = String(this.#interpolate(progress));
484
+ queueAttributeWrite(this.element, this.name, this.#current);
485
+ }, { emitCurrent: false });
486
+ }
487
+ currentValue() { return this.#current; }
488
+ isActive() { return this.#active; }
489
+ retarget(to, plan, options) {
490
+ const generation = ++this.#generation;
491
+ this.#active = true;
492
+ if (this.#timer !== undefined)
493
+ clearTimeout(this.#timer);
494
+ this.#timer = undefined;
495
+ const origin = this.#current;
496
+ const target = String(to);
497
+ let interpolate;
498
+ try {
499
+ interpolate = createInterpolator(this.#current, to, options);
500
+ }
501
+ catch {
502
+ this.#active = false;
503
+ return false;
504
+ }
505
+ const run = async () => {
506
+ if (generation !== this.#generation)
507
+ return;
508
+ this.#control?.cancel();
509
+ this.#interpolate = interpolate;
510
+ this.#progress.set(0, 0);
511
+ let cycle = 0;
512
+ try {
513
+ while (generation === this.#generation && (plan.repeatCount === Number.POSITIVE_INFINITY || cycle < plan.repeatCount)) {
514
+ const reverse = plan.autoreverses && cycle % 2 === 1;
515
+ this.#progress.set(reverse ? 1 : 0, 0);
516
+ this.#control = animate(this.#progress, reverse ? 0 : 1, plan.spec);
517
+ const result = await this.#control.finished;
518
+ if (generation !== this.#generation || result.status !== "finished")
519
+ return;
520
+ cycle += 1;
521
+ }
522
+ }
523
+ finally {
524
+ if (generation === this.#generation && plan.repeatCount !== Number.POSITIVE_INFINITY) {
525
+ this.#active = false;
526
+ const finishesAtOrigin = plan.autoreverses && plan.repeatCount > 1 && plan.repeatCount % 2 === 0;
527
+ this.#current = finishesAtOrigin ? origin : target;
528
+ queueAttributeWrite(this.element, this.name, this.#current);
529
+ }
530
+ }
531
+ };
532
+ this.#timer = startAfterDelay(plan.delayMs, () => {
533
+ this.#timer = undefined;
534
+ void run();
535
+ });
536
+ return true;
537
+ }
538
+ dispose() {
539
+ this.#generation += 1;
540
+ this.#active = false;
541
+ if (this.#timer !== undefined)
542
+ clearTimeout(this.#timer);
543
+ this.#timer = undefined;
544
+ this.#control?.cancel();
545
+ this.#control = undefined;
546
+ this.#unsubscribe();
547
+ removePendingAttributeWrite(this.element, this.name);
548
+ }
549
+ }
550
+ function attributeInterpolatorOptions(name, from, to) {
551
+ if (name === "d" && typeof from === "string" && typeof to === "string") {
552
+ try {
553
+ return svgPathInterpolatorOptions(from, to);
554
+ }
555
+ catch {
556
+ return undefined;
557
+ }
558
+ }
559
+ if ((name === "fill" || name === "stroke" || name.endsWith("color")) && typeof from === "string" && typeof to === "string") {
560
+ return { type: "color", color: { space: "oklab" } };
561
+ }
562
+ if (typeof from === "string" || typeof from === "number") {
563
+ if (typeof to === "string" || typeof to === "number")
564
+ return numericCssInterpolatorOptions(String(from), String(to));
565
+ }
566
+ return undefined;
567
+ }
568
+ function dropAttributeChannel(element, name) {
569
+ const channels = activeAttributeChannels.get(element);
570
+ const channel = channels?.get(name);
571
+ channel?.dispose();
572
+ channels?.delete(name);
573
+ if (channels?.size === 0)
574
+ activeAttributeChannels.delete(element);
575
+ }
576
+ /** Stop one animated DOM attribute before a direct patch. */
577
+ export function cancelDomAttributeAnimation(element, name) {
578
+ dropAttributeChannel(element, name);
579
+ }
580
+ /**
581
+ * Animate a DOM attribute through the same Mun animation clock as style motion.
582
+ * SVG path data uses @mun-ui/animation's cubic-normalizing path interpolator and keeps its
583
+ * current presentation value when interrupted and retargeted.
584
+ */
585
+ export function animateDomAttribute(element, name, from, to, animation) {
586
+ const running = activeAttributeChannels.get(element)?.get(name);
587
+ const options = attributeInterpolatorOptions(name, running?.isActive() ? running.currentValue() : from, to);
588
+ const plan = compileMotionPlan(animation);
589
+ if (!options || (plan.repeatCount !== Number.POSITIVE_INFINITY && framesSuspended(element))) {
590
+ dropAttributeChannel(element, name);
591
+ return false;
592
+ }
593
+ let channels = activeAttributeChannels.get(element);
594
+ if (!channels) {
595
+ channels = new Map();
596
+ activeAttributeChannels.set(element, channels);
597
+ }
598
+ let existing = channels.get(name);
599
+ if (existing && !existing.isActive() && String(from) !== existing.currentValue()) {
600
+ existing.dispose();
601
+ channels.delete(name);
602
+ existing = undefined;
603
+ }
604
+ if (existing?.retarget(to, plan, options))
605
+ return true;
606
+ existing?.dispose();
607
+ try {
608
+ const channel = new InterpolatedAttributeMotionChannel(element, name, existing?.currentValue() ?? from, to, options);
609
+ channels.set(name, channel);
610
+ return channel.retarget(to, plan, options);
611
+ }
612
+ catch {
613
+ channels.delete(name);
614
+ return false;
615
+ }
616
+ }
617
+ function dropChannel(element, property) {
618
+ const channels = activeChannels.get(element);
619
+ const channel = channels?.get(property);
620
+ channel?.dispose();
621
+ channels?.delete(property);
622
+ if (channels?.size === 0)
623
+ activeChannels.delete(element);
624
+ }
625
+ /** Stop one property channel before a direct/remove style patch. */
626
+ export function cancelDomStyleAnimation(element, property) {
627
+ dropChannel(element, property);
628
+ }
629
+ /**
630
+ * Animate one DOM style value with a precompiled motion plan and a persistent
631
+ * per-property channel. Returns false when the value cannot be interpolated
632
+ * safely, allowing the normal DOM patcher to apply it directly.
633
+ */
634
+ function animateDomStyleWithPlan(element, property, from, to, plan) {
635
+ // A repeat-forever animation has no final value to commit; it keeps its
636
+ // channel and starts with the first frame once the document is shown.
637
+ if (plan.repeatCount !== Number.POSITIVE_INFINITY && framesSuspended(element)) {
638
+ dropChannel(element, property);
639
+ return false;
640
+ }
641
+ const channels = channelsFor(element);
642
+ let existing = channels.get(property);
643
+ // While a channel is running, its presentation value is the authoritative
644
+ // starting point for retargeting. Once it settles, the renderer-provided
645
+ // `from` value wins again so external/direct style patches can resynchronize
646
+ // the persistent channel without an artificial jump.
647
+ if (existing && !existing.isActive() && String(from) !== existing.currentStyleValue()) {
648
+ existing.dispose();
649
+ channels.delete(property);
650
+ existing = undefined;
651
+ }
652
+ const [effectiveFrom, target] = alignTransformComponents(property, existing?.isActive() ? existing.currentStyleValue() : from, to);
653
+ const route = routeFor(property, effectiveFrom, target);
654
+ if (!route) {
655
+ dropChannel(element, property);
656
+ return false;
657
+ }
658
+ if (route.kind === "scalar") {
659
+ if (existing?.route === "scalar" && existing.retarget(target, plan))
660
+ return true;
661
+ existing?.dispose();
662
+ const start = parseScalar(effectiveFrom);
663
+ if (!start || start.unit !== route.unit) {
664
+ channels.delete(property);
665
+ return false;
666
+ }
667
+ const channel = new ScalarMotionChannel(element, property, start.value, start.unit);
668
+ channels.set(property, channel);
669
+ return channel.retarget(target, plan);
670
+ }
671
+ if (existing?.route === "interpolated" && existing.retarget(target, plan))
672
+ return true;
673
+ existing?.dispose();
674
+ try {
675
+ const channel = new InterpolatedMotionChannel(element, property, effectiveFrom, target, route.options);
676
+ channels.set(property, channel);
677
+ return channel.retarget(target, plan);
678
+ }
679
+ catch {
680
+ channels.delete(property);
681
+ return false;
682
+ }
683
+ }
684
+ /** Animate one style property. Kept as the small compatibility surface. */
685
+ export function animateDomStyle(element, property, from, to, animation) {
686
+ return animateDomStyleWithPlan(element, property, from, to, compileMotionPlan(animation));
687
+ }
688
+ /**
689
+ * Launch a whole style diff as one motion batch. Every property keeps its own
690
+ * persistent channel and execution plan, while @mun-ui/animation shares the frame loop and
691
+ * Mun coalesces the resulting DOM writes into one commit batch.
692
+ */
693
+ export function animateDomStyles(element, changes) {
694
+ const animated = new Set();
695
+ if (changes.length === 0)
696
+ return animated;
697
+ const plans = new Map();
698
+ const ordered = changes.length < 2
699
+ ? changes
700
+ : changes.map((change, index) => ({ change, index }))
701
+ .sort((left, right) => motionPropertyPriority(left.change.property) - motionPropertyPriority(right.change.property) || left.index - right.index)
702
+ .map(item => item.change);
703
+ for (const change of ordered) {
704
+ let plan = plans.get(change.animation);
705
+ if (!plan) {
706
+ plan = compileMotionPlan(change.animation);
707
+ plans.set(change.animation, plan);
708
+ }
709
+ if (animateDomStyleWithPlan(element, change.property, change.from, change.to, plan))
710
+ animated.add(change.property);
711
+ }
712
+ return animated;
713
+ }
714
+ /**
715
+ * FLIP-style geometry animation for intrinsic layout changes. Built-in offset,
716
+ * rotation and scale use the independent CSS translate/rotate/scale channels,
717
+ * leaving `transform` available as an internal layout channel. If user code is
718
+ * already occupying transform, the conservative choice is to skip FLIP rather
719
+ * than interfere with it.
720
+ */
721
+ export function animateDomLayout(element, before, after, animation) {
722
+ if (![before.left, before.top, before.width, before.height, after.left, after.top, after.width, after.height].every(Number.isFinite))
723
+ return false;
724
+ if (!(after.width > 0) || !(after.height > 0) || !(before.width > 0) || !(before.height > 0))
725
+ return false;
726
+ const dx = before.left + before.width / 2 - (after.left + after.width / 2);
727
+ const dy = before.top + before.height / 2 - (after.top + after.height / 2);
728
+ const sx = before.width / after.width;
729
+ const sy = before.height / after.height;
730
+ const moved = Math.abs(dx) >= 0.01 || Math.abs(dy) >= 0.01;
731
+ const resized = Math.abs(sx - 1) >= 0.0001 || Math.abs(sy - 1) >= 0.0001;
732
+ if (!moved && !resized)
733
+ return false;
734
+ // FLIP writes an inverse offset first; without frames it would never converge.
735
+ if (framesSuspended(element))
736
+ return false;
737
+ const style = element.style;
738
+ if (!style)
739
+ return false;
740
+ const channels = activeChannels.get(element);
741
+ const changes = [];
742
+ // Use the independent CSS translate/scale channels for FLIP. This keeps the
743
+ // user's transform property entirely free and lets an opacity/rotation/scale
744
+ // animation continue with its own curve while layout converges in parallel.
745
+ if (moved) {
746
+ const currentTranslate = style.getPropertyValue("translate").trim();
747
+ if (!channels?.get("translate")?.isActive() && (!currentTranslate || currentTranslate === "none" || currentTranslate === "0px" || currentTranslate === "0px 0px")) {
748
+ const inverse = `${dx}px ${dy}px`;
749
+ dropChannel(element, "translate");
750
+ style.setProperty("translate", inverse);
751
+ changes.push({ property: "translate", from: inverse, to: "0px 0px", animation });
752
+ }
753
+ }
754
+ if (resized) {
755
+ const currentScale = style.getPropertyValue("scale").trim();
756
+ if (!channels?.get("scale")?.isActive() && (!currentScale || currentScale === "none" || currentScale === "1" || currentScale === "1 1")) {
757
+ const inverse = `${sx} ${sy}`;
758
+ dropChannel(element, "scale");
759
+ style.setProperty("scale", inverse);
760
+ changes.push({ property: "scale", from: inverse, to: "1 1", animation });
761
+ }
762
+ }
763
+ if (changes.length === 0) {
764
+ // Older browsers or applications already owning both independent channels
765
+ // still receive the conservative transform fallback when it is unused.
766
+ const transformChannel = channels?.get("transform");
767
+ const current = style.getPropertyValue("transform").trim();
768
+ if (current && current !== "none" && !transformChannel)
769
+ return false;
770
+ const inverse = `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})`;
771
+ dropChannel(element, "transform");
772
+ style.setProperty("transform", inverse);
773
+ return animateDomStyleWithPlan(element, "transform", inverse, "none", compileMotionPlan(animation));
774
+ }
775
+ return animateDomStyles(element, changes).size > 0;
776
+ }
777
+ export function cancelDomAnimations(element) {
778
+ const channels = activeChannels.get(element);
779
+ if (channels) {
780
+ channels.forEach(channel => channel.dispose());
781
+ channels.clear();
782
+ activeChannels.delete(element);
783
+ }
784
+ removePendingStyleWrite(element);
785
+ const attributeChannels = activeAttributeChannels.get(element);
786
+ if (attributeChannels) {
787
+ attributeChannels.forEach(channel => channel.dispose());
788
+ attributeChannels.clear();
789
+ activeAttributeChannels.delete(element);
790
+ }
791
+ removePendingAttributeWrite(element);
792
+ }
793
+ //# sourceMappingURL=motion.js.map