@helsenorge/designsystem-react 12.9.0 → 12.11.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/Drawer.js +4 -204
  3. package/Drawer.js.map +1 -1
  4. package/RadioButton.js +1 -0
  5. package/RadioButton.js.map +1 -1
  6. package/SVGVisualElement.js +3759 -0
  7. package/SVGVisualElement.js.map +1 -0
  8. package/Toast.js +43 -0
  9. package/Toast.js.map +1 -0
  10. package/components/Button/styles.module.scss +59 -24
  11. package/components/Checkbox/styles.module.scss +11 -0
  12. package/components/Drawer/styles.module.scss +19 -18
  13. package/components/Dropdown/index.js +13 -6
  14. package/components/Dropdown/index.js.map +1 -1
  15. package/components/Dropdown/styles.module.scss +2 -0
  16. package/components/RadioButton/styles.module.scss +4 -0
  17. package/components/RadioButton/styles.module.scss.d.ts +1 -0
  18. package/components/Toast/Toast.d.ts +13 -0
  19. package/components/Toast/Toast.test.d.ts +1 -0
  20. package/components/Toast/index.d.ts +3 -0
  21. package/components/Toast/index.js +5 -0
  22. package/components/Toast/index.js.map +1 -0
  23. package/components/Toast/styles.module.scss +70 -0
  24. package/components/ToastList/ToastList.d.ts +14 -0
  25. package/components/ToastList/ToastList.test.d.ts +1 -0
  26. package/components/ToastList/index.d.ts +3 -0
  27. package/components/ToastList/index.js +3531 -0
  28. package/components/ToastList/index.js.map +1 -0
  29. package/components/ToastList/styles.module.scss +12 -0
  30. package/components/ToastList/styles.module.scss.d.ts +9 -0
  31. package/components/Toggle/styles.module.scss +9 -0
  32. package/docs/Tokens/TokensExample.d.ts +7 -0
  33. package/index2.js +213 -0
  34. package/index2.js.map +1 -0
  35. package/package.json +1 -1
  36. package/use-animate.js +50 -3614
  37. package/use-animate.js.map +1 -1
package/use-animate.js CHANGED
@@ -1,3579 +1,17 @@
1
- import { useRef, useEffect } from "react";
2
- import { c as clamp } from "./clamp.js";
3
- function useConstant(init) {
4
- const ref = useRef(null);
5
- if (ref.current === null) {
6
- ref.current = init();
7
- }
8
- return ref.current;
9
- }
10
- const isBrowser = typeof window !== "undefined";
11
- const noop = /* @__NO_SIDE_EFFECTS__ */ (any) => any;
12
- let warning = noop;
13
- let invariant = noop;
14
- if (process.env.NODE_ENV !== "production") {
15
- warning = (check, message) => {
16
- if (!check && typeof console !== "undefined") {
17
- console.warn(message);
18
- }
19
- };
20
- invariant = (check, message) => {
21
- if (!check) {
22
- throw new Error(message);
23
- }
24
- };
25
- }
26
- const MotionGlobalConfig = {
27
- useManualTiming: false
28
- };
29
- function createRenderStep(runNextFrame) {
30
- let thisFrame = /* @__PURE__ */ new Set();
31
- let nextFrame = /* @__PURE__ */ new Set();
32
- let isProcessing = false;
33
- let flushNextFrame = false;
34
- const toKeepAlive = /* @__PURE__ */ new WeakSet();
35
- let latestFrameData = {
36
- delta: 0,
37
- timestamp: 0,
38
- isProcessing: false
39
- };
40
- function triggerCallback(callback) {
41
- if (toKeepAlive.has(callback)) {
42
- step.schedule(callback);
43
- runNextFrame();
44
- }
45
- callback(latestFrameData);
46
- }
47
- const step = {
48
- /**
49
- * Schedule a process to run on the next frame.
50
- */
51
- schedule: (callback, keepAlive = false, immediate = false) => {
52
- const addToCurrentFrame = immediate && isProcessing;
53
- const queue = addToCurrentFrame ? thisFrame : nextFrame;
54
- if (keepAlive)
55
- toKeepAlive.add(callback);
56
- if (!queue.has(callback))
57
- queue.add(callback);
58
- return callback;
59
- },
60
- /**
61
- * Cancel the provided callback from running on the next frame.
62
- */
63
- cancel: (callback) => {
64
- nextFrame.delete(callback);
65
- toKeepAlive.delete(callback);
66
- },
67
- /**
68
- * Execute all schedule callbacks.
69
- */
70
- process: (frameData2) => {
71
- latestFrameData = frameData2;
72
- if (isProcessing) {
73
- flushNextFrame = true;
74
- return;
75
- }
76
- isProcessing = true;
77
- [thisFrame, nextFrame] = [nextFrame, thisFrame];
78
- thisFrame.forEach(triggerCallback);
79
- thisFrame.clear();
80
- isProcessing = false;
81
- if (flushNextFrame) {
82
- flushNextFrame = false;
83
- step.process(frameData2);
84
- }
85
- }
86
- };
87
- return step;
88
- }
89
- const stepsOrder = [
90
- "read",
91
- // Read
92
- "resolveKeyframes",
93
- // Write/Read/Write/Read
94
- "update",
95
- // Compute
96
- "preRender",
97
- // Compute
98
- "render",
99
- // Write
100
- "postRender"
101
- // Compute
102
- ];
103
- const maxElapsed = 40;
104
- function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
105
- let runNextFrame = false;
106
- let useDefaultElapsed = true;
107
- const state = {
108
- delta: 0,
109
- timestamp: 0,
110
- isProcessing: false
111
- };
112
- const flagRunNextFrame = () => runNextFrame = true;
113
- const steps = stepsOrder.reduce((acc, key) => {
114
- acc[key] = createRenderStep(flagRunNextFrame);
115
- return acc;
116
- }, {});
117
- const { read, resolveKeyframes, update, preRender, render, postRender } = steps;
118
- const processBatch = () => {
119
- const timestamp = performance.now();
120
- runNextFrame = false;
121
- state.delta = useDefaultElapsed ? 1e3 / 60 : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);
122
- state.timestamp = timestamp;
123
- state.isProcessing = true;
124
- read.process(state);
125
- resolveKeyframes.process(state);
126
- update.process(state);
127
- preRender.process(state);
128
- render.process(state);
129
- postRender.process(state);
130
- state.isProcessing = false;
131
- if (runNextFrame && allowKeepAlive) {
132
- useDefaultElapsed = false;
133
- scheduleNextBatch(processBatch);
134
- }
135
- };
136
- const wake = () => {
137
- runNextFrame = true;
138
- useDefaultElapsed = true;
139
- if (!state.isProcessing) {
140
- scheduleNextBatch(processBatch);
141
- }
142
- };
143
- const schedule = stepsOrder.reduce((acc, key) => {
144
- const step = steps[key];
145
- acc[key] = (process2, keepAlive = false, immediate = false) => {
146
- if (!runNextFrame)
147
- wake();
148
- return step.schedule(process2, keepAlive, immediate);
149
- };
150
- return acc;
151
- }, {});
152
- const cancel = (process2) => {
153
- for (let i = 0; i < stepsOrder.length; i++) {
154
- steps[stepsOrder[i]].cancel(process2);
155
- }
156
- };
157
- return { schedule, cancel, state, steps };
158
- }
159
- const { schedule: frame, cancel: cancelFrame, state: frameData } = createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : noop, true);
160
- const featureProps = {
161
- animation: [
162
- "animate",
163
- "variants",
164
- "whileHover",
165
- "whileTap",
166
- "exit",
167
- "whileInView",
168
- "whileFocus",
169
- "whileDrag"
170
- ],
171
- exit: ["exit"],
172
- drag: ["drag", "dragControls"],
173
- focus: ["whileFocus"],
174
- hover: ["whileHover", "onHoverStart", "onHoverEnd"],
175
- tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"],
176
- pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"],
177
- inView: ["whileInView", "onViewportEnter", "onViewportLeave"],
178
- layout: ["layout", "layoutId"]
179
- };
180
- const featureDefinitions = {};
181
- for (const key in featureProps) {
182
- featureDefinitions[key] = {
183
- isEnabled: (props) => featureProps[key].some((name) => !!props[name])
184
- };
185
- }
186
- const warned = /* @__PURE__ */ new Set();
187
- function warnOnce(condition, message, element) {
188
- if (condition || warned.has(message))
189
- return;
190
- console.warn(message);
191
- warned.add(message);
192
- }
193
- function isVariantLabel(v) {
194
- return typeof v === "string" || Array.isArray(v);
195
- }
196
- function isAnimationControls(v) {
197
- return v !== null && typeof v === "object" && typeof v.start === "function";
198
- }
199
- const variantPriorityOrder = [
200
- "animate",
201
- "whileInView",
202
- "whileFocus",
203
- "whileHover",
204
- "whileTap",
205
- "whileDrag",
206
- "exit"
207
- ];
208
- const variantProps = ["initial", ...variantPriorityOrder];
209
- function isControllingVariants(props) {
210
- return isAnimationControls(props.animate) || variantProps.some((name) => isVariantLabel(props[name]));
211
- }
212
- function isVariantNode(props) {
213
- return Boolean(isControllingVariants(props) || props.variants);
214
- }
215
- const camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, "$1-$2").toLowerCase();
216
- const optimizedAppearDataId = "framerAppearId";
217
- const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId);
218
- function getValueState(visualElement) {
219
- const state = [{}, {}];
220
- visualElement === null || visualElement === void 0 ? void 0 : visualElement.values.forEach((value, key) => {
221
- state[0][key] = value.get();
222
- state[1][key] = value.getVelocity();
223
- });
224
- return state;
225
- }
226
- function resolveVariantFromProps(props, definition, custom, visualElement) {
227
- if (typeof definition === "function") {
228
- const [current, velocity] = getValueState(visualElement);
229
- definition = definition(custom !== void 0 ? custom : props.custom, current, velocity);
230
- }
231
- if (typeof definition === "string") {
232
- definition = props.variants && props.variants[definition];
233
- }
234
- if (typeof definition === "function") {
235
- const [current, velocity] = getValueState(visualElement);
236
- definition = definition(custom !== void 0 ? custom : props.custom, current, velocity);
237
- }
238
- return definition;
239
- }
240
- const isKeyframesTarget = (v) => {
241
- return Array.isArray(v);
242
- };
243
- const resolveFinalValueInKeyframes = (v) => {
244
- return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v;
245
- };
246
- const isMotionValue = (value) => Boolean(value && value.getVelocity);
247
- const transformPropOrder = [
248
- "transformPerspective",
249
- "x",
250
- "y",
251
- "z",
252
- "translateX",
253
- "translateY",
254
- "translateZ",
255
- "scale",
256
- "scaleX",
257
- "scaleY",
258
- "rotate",
259
- "rotateX",
260
- "rotateY",
261
- "rotateZ",
262
- "skew",
263
- "skewX",
264
- "skewY"
265
- ];
266
- const transformProps = new Set(transformPropOrder);
267
- const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token);
268
- const isCSSVariableName = /* @__PURE__ */ checkStringStartsWith("--");
269
- const startsAsVariableToken = /* @__PURE__ */ checkStringStartsWith("var(--");
270
- const isCSSVariableToken = (value) => {
271
- const startsWithToken = startsAsVariableToken(value);
272
- if (!startsWithToken)
273
- return false;
274
- return singleCssVariableRegex.test(value.split("/*")[0].trim());
275
- };
276
- const singleCssVariableRegex = /var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;
277
- const getValueAsType = (value, type) => {
278
- return type && typeof value === "number" ? type.transform(value) : value;
279
- };
280
- const number = {
281
- test: (v) => typeof v === "number",
282
- parse: parseFloat,
283
- transform: (v) => v
284
- };
285
- const alpha = {
286
- ...number,
287
- transform: (v) => clamp(0, 1, v)
288
- };
289
- const scale = {
290
- ...number,
291
- default: 1
292
- };
293
- const createUnitType = (unit) => ({
294
- test: (v) => typeof v === "string" && v.endsWith(unit) && v.split(" ").length === 1,
295
- parse: parseFloat,
296
- transform: (v) => `${v}${unit}`
297
- });
298
- const degrees = /* @__PURE__ */ createUnitType("deg");
299
- const percent = /* @__PURE__ */ createUnitType("%");
300
- const px = /* @__PURE__ */ createUnitType("px");
301
- const vh = /* @__PURE__ */ createUnitType("vh");
302
- const vw = /* @__PURE__ */ createUnitType("vw");
303
- const progressPercentage = {
304
- ...percent,
305
- parse: (v) => percent.parse(v) / 100,
306
- transform: (v) => percent.transform(v * 100)
307
- };
308
- const browserNumberValueTypes = {
309
- // Border props
310
- borderWidth: px,
311
- borderTopWidth: px,
312
- borderRightWidth: px,
313
- borderBottomWidth: px,
314
- borderLeftWidth: px,
315
- borderRadius: px,
316
- radius: px,
317
- borderTopLeftRadius: px,
318
- borderTopRightRadius: px,
319
- borderBottomRightRadius: px,
320
- borderBottomLeftRadius: px,
321
- // Positioning props
322
- width: px,
323
- maxWidth: px,
324
- height: px,
325
- maxHeight: px,
326
- top: px,
327
- right: px,
328
- bottom: px,
329
- left: px,
330
- // Spacing props
331
- padding: px,
332
- paddingTop: px,
333
- paddingRight: px,
334
- paddingBottom: px,
335
- paddingLeft: px,
336
- margin: px,
337
- marginTop: px,
338
- marginRight: px,
339
- marginBottom: px,
340
- marginLeft: px,
341
- // Misc
342
- backgroundPositionX: px,
343
- backgroundPositionY: px
344
- };
345
- const transformValueTypes = {
346
- rotate: degrees,
347
- rotateX: degrees,
348
- rotateY: degrees,
349
- rotateZ: degrees,
350
- scale,
351
- scaleX: scale,
352
- scaleY: scale,
353
- scaleZ: scale,
354
- skew: degrees,
355
- skewX: degrees,
356
- skewY: degrees,
357
- distance: px,
358
- translateX: px,
359
- translateY: px,
360
- translateZ: px,
361
- x: px,
362
- y: px,
363
- z: px,
364
- perspective: px,
365
- transformPerspective: px,
366
- opacity: alpha,
367
- originX: progressPercentage,
368
- originY: progressPercentage,
369
- originZ: px
370
- };
371
- const int = {
372
- ...number,
373
- transform: Math.round
374
- };
375
- const numberValueTypes = {
376
- ...browserNumberValueTypes,
377
- ...transformValueTypes,
378
- zIndex: int,
379
- size: px,
380
- // SVG
381
- fillOpacity: alpha,
382
- strokeOpacity: alpha,
383
- numOctaves: int
384
- };
385
- const translateAlias = {
386
- x: "translateX",
387
- y: "translateY",
388
- z: "translateZ",
389
- transformPerspective: "perspective"
390
- };
391
- const numTransforms = transformPropOrder.length;
392
- function buildTransform(latestValues, transform, transformTemplate) {
393
- let transformString = "";
394
- let transformIsDefault = true;
395
- for (let i = 0; i < numTransforms; i++) {
396
- const key = transformPropOrder[i];
397
- const value = latestValues[key];
398
- if (value === void 0)
399
- continue;
400
- let valueIsDefault = true;
401
- if (typeof value === "number") {
402
- valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
403
- } else {
404
- valueIsDefault = parseFloat(value) === 0;
405
- }
406
- if (!valueIsDefault || transformTemplate) {
407
- const valueAsType = getValueAsType(value, numberValueTypes[key]);
408
- if (!valueIsDefault) {
409
- transformIsDefault = false;
410
- const transformName = translateAlias[key] || key;
411
- transformString += `${transformName}(${valueAsType}) `;
412
- }
413
- if (transformTemplate) {
414
- transform[key] = valueAsType;
415
- }
416
- }
417
- }
418
- transformString = transformString.trim();
419
- if (transformTemplate) {
420
- transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
421
- } else if (transformIsDefault) {
422
- transformString = "none";
423
- }
424
- return transformString;
425
- }
426
- function buildHTMLStyles(state, latestValues, transformTemplate) {
427
- const { style, vars, transformOrigin } = state;
428
- let hasTransform = false;
429
- let hasTransformOrigin = false;
430
- for (const key in latestValues) {
431
- const value = latestValues[key];
432
- if (transformProps.has(key)) {
433
- hasTransform = true;
434
- continue;
435
- } else if (isCSSVariableName(key)) {
436
- vars[key] = value;
437
- continue;
438
- } else {
439
- const valueAsType = getValueAsType(value, numberValueTypes[key]);
440
- if (key.startsWith("origin")) {
441
- hasTransformOrigin = true;
442
- transformOrigin[key] = valueAsType;
443
- } else {
444
- style[key] = valueAsType;
445
- }
446
- }
447
- }
448
- if (!latestValues.transform) {
449
- if (hasTransform || transformTemplate) {
450
- style.transform = buildTransform(latestValues, state.transform, transformTemplate);
451
- } else if (style.transform) {
452
- style.transform = "none";
453
- }
454
- }
455
- if (hasTransformOrigin) {
456
- const { originX = "50%", originY = "50%", originZ = 0 } = transformOrigin;
457
- style.transformOrigin = `${originX} ${originY} ${originZ}`;
458
- }
459
- }
460
- const dashKeys = {
461
- offset: "stroke-dashoffset",
462
- array: "stroke-dasharray"
463
- };
464
- const camelKeys = {
465
- offset: "strokeDashoffset",
466
- array: "strokeDasharray"
467
- };
468
- function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) {
469
- attrs.pathLength = 1;
470
- const keys = useDashCase ? dashKeys : camelKeys;
471
- attrs[keys.offset] = px.transform(-offset);
472
- const pathLength = px.transform(length);
473
- const pathSpacing = px.transform(spacing);
474
- attrs[keys.array] = `${pathLength} ${pathSpacing}`;
475
- }
476
- function calcOrigin(origin, offset, size) {
477
- return typeof origin === "string" ? origin : px.transform(offset + size * origin);
478
- }
479
- function calcSVGTransformOrigin(dimensions, originX, originY) {
480
- const pxOriginX = calcOrigin(originX, dimensions.x, dimensions.width);
481
- const pxOriginY = calcOrigin(originY, dimensions.y, dimensions.height);
482
- return `${pxOriginX} ${pxOriginY}`;
483
- }
484
- function buildSVGAttrs(state, {
485
- attrX,
486
- attrY,
487
- attrScale,
488
- originX,
489
- originY,
490
- pathLength,
491
- pathSpacing = 1,
492
- pathOffset = 0,
493
- // This is object creation, which we try to avoid per-frame.
494
- ...latest
495
- }, isSVGTag2, transformTemplate) {
496
- buildHTMLStyles(state, latest, transformTemplate);
497
- if (isSVGTag2) {
498
- if (state.style.viewBox) {
499
- state.attrs.viewBox = state.style.viewBox;
500
- }
501
- return;
502
- }
503
- state.attrs = state.style;
504
- state.style = {};
505
- const { attrs, style, dimensions } = state;
506
- if (attrs.transform) {
507
- if (dimensions)
508
- style.transform = attrs.transform;
509
- delete attrs.transform;
510
- }
511
- if (dimensions && (originX !== void 0 || originY !== void 0 || style.transform)) {
512
- style.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== void 0 ? originX : 0.5, originY !== void 0 ? originY : 0.5);
513
- }
514
- if (attrX !== void 0)
515
- attrs.x = attrX;
516
- if (attrY !== void 0)
517
- attrs.y = attrY;
518
- if (attrScale !== void 0)
519
- attrs.scale = attrScale;
520
- if (pathLength !== void 0) {
521
- buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false);
522
- }
523
- }
524
- const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg";
525
- function renderHTML(element, { style, vars }, styleProp, projection) {
526
- Object.assign(element.style, style, projection && projection.getProjectionStyles(styleProp));
527
- for (const key in vars) {
528
- element.style.setProperty(key, vars[key]);
529
- }
530
- }
531
- const camelCaseAttributes = /* @__PURE__ */ new Set([
532
- "baseFrequency",
533
- "diffuseConstant",
534
- "kernelMatrix",
535
- "kernelUnitLength",
536
- "keySplines",
537
- "keyTimes",
538
- "limitingConeAngle",
539
- "markerHeight",
540
- "markerWidth",
541
- "numOctaves",
542
- "targetX",
543
- "targetY",
544
- "surfaceScale",
545
- "specularConstant",
546
- "specularExponent",
547
- "stdDeviation",
548
- "tableValues",
549
- "viewBox",
550
- "gradientTransform",
551
- "pathLength",
552
- "startOffset",
553
- "textLength",
554
- "lengthAdjust"
555
- ]);
556
- function renderSVG(element, renderState, _styleProp, projection) {
557
- renderHTML(element, renderState, void 0, projection);
558
- for (const key in renderState.attrs) {
559
- element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]);
560
- }
561
- }
562
- const scaleCorrectors = {};
563
- function isForcedMotionValue(key, { layout, layoutId }) {
564
- return transformProps.has(key) || key.startsWith("origin") || (layout || layoutId !== void 0) && (!!scaleCorrectors[key] || key === "opacity");
565
- }
566
- function scrapeMotionValuesFromProps$1(props, prevProps, visualElement) {
567
- var _a;
568
- const { style } = props;
569
- const newValues = {};
570
- for (const key in style) {
571
- if (isMotionValue(style[key]) || prevProps.style && isMotionValue(prevProps.style[key]) || isForcedMotionValue(key, props) || ((_a = visualElement === null || visualElement === void 0 ? void 0 : visualElement.getValue(key)) === null || _a === void 0 ? void 0 : _a.liveStyle) !== void 0) {
572
- newValues[key] = style[key];
573
- }
574
- }
575
- return newValues;
576
- }
577
- function scrapeMotionValuesFromProps(props, prevProps, visualElement) {
578
- const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement);
579
- for (const key in props) {
580
- if (isMotionValue(props[key]) || isMotionValue(prevProps[key])) {
581
- const targetKey = transformPropOrder.indexOf(key) !== -1 ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) : key;
582
- newValues[targetKey] = props[key];
583
- }
584
- }
585
- return newValues;
586
- }
587
- function resolveVariant(visualElement, definition, custom) {
588
- const props = visualElement.getProps();
589
- return resolveVariantFromProps(props, definition, props.custom, visualElement);
590
- }
591
- function getValueTransition$1(transition, key) {
592
- return transition ? transition[key] || transition["default"] || transition : void 0;
593
- }
594
- const positionalKeys = /* @__PURE__ */ new Set([
595
- "width",
596
- "height",
597
- "top",
598
- "left",
599
- "right",
600
- "bottom",
601
- ...transformPropOrder
602
- ]);
603
- let now;
604
- function clearTime() {
605
- now = void 0;
606
- }
607
- const time = {
608
- now: () => {
609
- if (now === void 0) {
610
- time.set(frameData.isProcessing || MotionGlobalConfig.useManualTiming ? frameData.timestamp : performance.now());
611
- }
612
- return now;
613
- },
614
- set: (newTime) => {
615
- now = newTime;
616
- queueMicrotask(clearTime);
617
- }
618
- };
619
- function addUniqueItem(arr, item) {
620
- if (arr.indexOf(item) === -1)
621
- arr.push(item);
622
- }
623
- function removeItem(arr, item) {
624
- const index = arr.indexOf(item);
625
- if (index > -1)
626
- arr.splice(index, 1);
627
- }
628
- class SubscriptionManager {
629
- constructor() {
630
- this.subscriptions = [];
631
- }
632
- add(handler) {
633
- addUniqueItem(this.subscriptions, handler);
634
- return () => removeItem(this.subscriptions, handler);
635
- }
636
- notify(a, b, c) {
637
- const numSubscriptions = this.subscriptions.length;
638
- if (!numSubscriptions)
639
- return;
640
- if (numSubscriptions === 1) {
641
- this.subscriptions[0](a, b, c);
642
- } else {
643
- for (let i = 0; i < numSubscriptions; i++) {
644
- const handler = this.subscriptions[i];
645
- handler && handler(a, b, c);
646
- }
647
- }
648
- }
649
- getSize() {
650
- return this.subscriptions.length;
651
- }
652
- clear() {
653
- this.subscriptions.length = 0;
654
- }
655
- }
656
- function velocityPerSecond(velocity, frameDuration) {
657
- return frameDuration ? velocity * (1e3 / frameDuration) : 0;
658
- }
659
- const MAX_VELOCITY_DELTA = 30;
660
- const isFloat = (value) => {
661
- return !isNaN(parseFloat(value));
662
- };
663
- class MotionValue {
664
- /**
665
- * @param init - The initiating value
666
- * @param config - Optional configuration options
667
- *
668
- * - `transformer`: A function to transform incoming values with.
669
- *
670
- * @internal
671
- */
672
- constructor(init, options = {}) {
673
- this.version = "11.18.2";
674
- this.canTrackVelocity = null;
675
- this.events = {};
676
- this.updateAndNotify = (v, render = true) => {
677
- const currentTime = time.now();
678
- if (this.updatedAt !== currentTime) {
679
- this.setPrevFrameValue();
680
- }
681
- this.prev = this.current;
682
- this.setCurrent(v);
683
- if (this.current !== this.prev && this.events.change) {
684
- this.events.change.notify(this.current);
685
- }
686
- if (render && this.events.renderRequest) {
687
- this.events.renderRequest.notify(this.current);
688
- }
689
- };
690
- this.hasAnimated = false;
691
- this.setCurrent(init);
692
- this.owner = options.owner;
693
- }
694
- setCurrent(current) {
695
- this.current = current;
696
- this.updatedAt = time.now();
697
- if (this.canTrackVelocity === null && current !== void 0) {
698
- this.canTrackVelocity = isFloat(this.current);
699
- }
700
- }
701
- setPrevFrameValue(prevFrameValue = this.current) {
702
- this.prevFrameValue = prevFrameValue;
703
- this.prevUpdatedAt = this.updatedAt;
704
- }
705
- /**
706
- * Adds a function that will be notified when the `MotionValue` is updated.
707
- *
708
- * It returns a function that, when called, will cancel the subscription.
709
- *
710
- * When calling `onChange` inside a React component, it should be wrapped with the
711
- * `useEffect` hook. As it returns an unsubscribe function, this should be returned
712
- * from the `useEffect` function to ensure you don't add duplicate subscribers..
713
- *
714
- * ```jsx
715
- * export const MyComponent = () => {
716
- * const x = useMotionValue(0)
717
- * const y = useMotionValue(0)
718
- * const opacity = useMotionValue(1)
719
- *
720
- * useEffect(() => {
721
- * function updateOpacity() {
722
- * const maxXY = Math.max(x.get(), y.get())
723
- * const newOpacity = transform(maxXY, [0, 100], [1, 0])
724
- * opacity.set(newOpacity)
725
- * }
726
- *
727
- * const unsubscribeX = x.on("change", updateOpacity)
728
- * const unsubscribeY = y.on("change", updateOpacity)
729
- *
730
- * return () => {
731
- * unsubscribeX()
732
- * unsubscribeY()
733
- * }
734
- * }, [])
735
- *
736
- * return <motion.div style={{ x }} />
737
- * }
738
- * ```
739
- *
740
- * @param subscriber - A function that receives the latest value.
741
- * @returns A function that, when called, will cancel this subscription.
742
- *
743
- * @deprecated
744
- */
745
- onChange(subscription) {
746
- if (process.env.NODE_ENV !== "production") {
747
- warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`);
748
- }
749
- return this.on("change", subscription);
750
- }
751
- on(eventName, callback) {
752
- if (!this.events[eventName]) {
753
- this.events[eventName] = new SubscriptionManager();
754
- }
755
- const unsubscribe = this.events[eventName].add(callback);
756
- if (eventName === "change") {
757
- return () => {
758
- unsubscribe();
759
- frame.read(() => {
760
- if (!this.events.change.getSize()) {
761
- this.stop();
762
- }
763
- });
764
- };
765
- }
766
- return unsubscribe;
767
- }
768
- clearListeners() {
769
- for (const eventManagers in this.events) {
770
- this.events[eventManagers].clear();
771
- }
772
- }
773
- /**
774
- * Attaches a passive effect to the `MotionValue`.
775
- *
776
- * @internal
777
- */
778
- attach(passiveEffect, stopPassiveEffect) {
779
- this.passiveEffect = passiveEffect;
780
- this.stopPassiveEffect = stopPassiveEffect;
781
- }
782
- /**
783
- * Sets the state of the `MotionValue`.
784
- *
785
- * @remarks
786
- *
787
- * ```jsx
788
- * const x = useMotionValue(0)
789
- * x.set(10)
790
- * ```
791
- *
792
- * @param latest - Latest value to set.
793
- * @param render - Whether to notify render subscribers. Defaults to `true`
794
- *
795
- * @public
796
- */
797
- set(v, render = true) {
798
- if (!render || !this.passiveEffect) {
799
- this.updateAndNotify(v, render);
800
- } else {
801
- this.passiveEffect(v, this.updateAndNotify);
802
- }
803
- }
804
- setWithVelocity(prev, current, delta) {
805
- this.set(current);
806
- this.prev = void 0;
807
- this.prevFrameValue = prev;
808
- this.prevUpdatedAt = this.updatedAt - delta;
809
- }
810
- /**
811
- * Set the state of the `MotionValue`, stopping any active animations,
812
- * effects, and resets velocity to `0`.
813
- */
814
- jump(v, endAnimation = true) {
815
- this.updateAndNotify(v);
816
- this.prev = v;
817
- this.prevUpdatedAt = this.prevFrameValue = void 0;
818
- endAnimation && this.stop();
819
- if (this.stopPassiveEffect)
820
- this.stopPassiveEffect();
821
- }
822
- /**
823
- * Returns the latest state of `MotionValue`
824
- *
825
- * @returns - The latest state of `MotionValue`
826
- *
827
- * @public
828
- */
829
- get() {
830
- return this.current;
831
- }
832
- /**
833
- * @public
834
- */
835
- getPrevious() {
836
- return this.prev;
837
- }
838
- /**
839
- * Returns the latest velocity of `MotionValue`
840
- *
841
- * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
842
- *
843
- * @public
844
- */
845
- getVelocity() {
846
- const currentTime = time.now();
847
- if (!this.canTrackVelocity || this.prevFrameValue === void 0 || currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {
848
- return 0;
849
- }
850
- const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);
851
- return velocityPerSecond(parseFloat(this.current) - parseFloat(this.prevFrameValue), delta);
852
- }
853
- /**
854
- * Registers a new animation to control this `MotionValue`. Only one
855
- * animation can drive a `MotionValue` at one time.
856
- *
857
- * ```jsx
858
- * value.start()
859
- * ```
860
- *
861
- * @param animation - A function that starts the provided animation
862
- *
863
- * @internal
864
- */
865
- start(startAnimation) {
866
- this.stop();
867
- return new Promise((resolve) => {
868
- this.hasAnimated = true;
869
- this.animation = startAnimation(resolve);
870
- if (this.events.animationStart) {
871
- this.events.animationStart.notify();
872
- }
873
- }).then(() => {
874
- if (this.events.animationComplete) {
875
- this.events.animationComplete.notify();
876
- }
877
- this.clearAnimation();
878
- });
879
- }
880
- /**
881
- * Stop the currently active animation.
882
- *
883
- * @public
884
- */
885
- stop() {
886
- if (this.animation) {
887
- this.animation.stop();
888
- if (this.events.animationCancel) {
889
- this.events.animationCancel.notify();
890
- }
891
- }
892
- this.clearAnimation();
893
- }
894
- /**
895
- * Returns `true` if this value is currently animating.
896
- *
897
- * @public
898
- */
899
- isAnimating() {
900
- return !!this.animation;
901
- }
902
- clearAnimation() {
903
- delete this.animation;
904
- }
905
- /**
906
- * Destroy and clean up subscribers to this `MotionValue`.
907
- *
908
- * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
909
- * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
910
- * created a `MotionValue` via the `motionValue` function.
911
- *
912
- * @public
913
- */
914
- destroy() {
915
- this.clearListeners();
916
- this.stop();
917
- if (this.stopPassiveEffect) {
918
- this.stopPassiveEffect();
919
- }
920
- }
921
- }
922
- function motionValue(init, options) {
923
- return new MotionValue(init, options);
924
- }
925
- function setMotionValue(visualElement, key, value) {
926
- if (visualElement.hasValue(key)) {
927
- visualElement.getValue(key).set(value);
928
- } else {
929
- visualElement.addValue(key, motionValue(value));
930
- }
931
- }
932
- function setTarget(visualElement, definition) {
933
- const resolved = resolveVariant(visualElement, definition);
934
- let { transitionEnd = {}, transition = {}, ...target } = resolved || {};
935
- target = { ...target, ...transitionEnd };
936
- for (const key in target) {
937
- const value = resolveFinalValueInKeyframes(target[key]);
938
- setMotionValue(visualElement, key, value);
939
- }
940
- }
941
- function isWillChangeMotionValue(value) {
942
- return Boolean(isMotionValue(value) && value.add);
943
- }
944
- function addValueToWillChange(visualElement, key) {
945
- const willChange = visualElement.getValue("willChange");
946
- if (isWillChangeMotionValue(willChange)) {
947
- return willChange.add(key);
948
- }
949
- }
950
- function getOptimisedAppearId(visualElement) {
951
- return visualElement.props[optimizedAppearDataAttribute];
952
- }
953
- // @__NO_SIDE_EFFECTS__
954
- function memo(callback) {
955
- let result;
956
- return () => {
957
- if (result === void 0)
958
- result = callback();
959
- return result;
960
- };
961
- }
962
- const supportsScrollTimeline = /* @__PURE__ */ memo(() => window.ScrollTimeline !== void 0);
963
- class BaseGroupPlaybackControls {
964
- constructor(animations) {
965
- this.stop = () => this.runAll("stop");
966
- this.animations = animations.filter(Boolean);
967
- }
968
- get finished() {
969
- return Promise.all(this.animations.map((animation) => "finished" in animation ? animation.finished : animation));
970
- }
971
- /**
972
- * TODO: Filter out cancelled or stopped animations before returning
973
- */
974
- getAll(propName) {
975
- return this.animations[0][propName];
976
- }
977
- setAll(propName, newValue) {
978
- for (let i = 0; i < this.animations.length; i++) {
979
- this.animations[i][propName] = newValue;
980
- }
981
- }
982
- attachTimeline(timeline, fallback) {
983
- const subscriptions = this.animations.map((animation) => {
984
- if (supportsScrollTimeline() && animation.attachTimeline) {
985
- return animation.attachTimeline(timeline);
986
- } else if (typeof fallback === "function") {
987
- return fallback(animation);
988
- }
989
- });
990
- return () => {
991
- subscriptions.forEach((cancel, i) => {
992
- cancel && cancel();
993
- this.animations[i].stop();
994
- });
995
- };
996
- }
997
- get time() {
998
- return this.getAll("time");
999
- }
1000
- set time(time2) {
1001
- this.setAll("time", time2);
1002
- }
1003
- get speed() {
1004
- return this.getAll("speed");
1005
- }
1006
- set speed(speed) {
1007
- this.setAll("speed", speed);
1008
- }
1009
- get startTime() {
1010
- return this.getAll("startTime");
1011
- }
1012
- get duration() {
1013
- let max = 0;
1014
- for (let i = 0; i < this.animations.length; i++) {
1015
- max = Math.max(max, this.animations[i].duration);
1016
- }
1017
- return max;
1018
- }
1019
- runAll(methodName) {
1020
- this.animations.forEach((controls) => controls[methodName]());
1021
- }
1022
- flatten() {
1023
- this.runAll("flatten");
1024
- }
1025
- play() {
1026
- this.runAll("play");
1027
- }
1028
- pause() {
1029
- this.runAll("pause");
1030
- }
1031
- cancel() {
1032
- this.runAll("cancel");
1033
- }
1034
- complete() {
1035
- this.runAll("complete");
1036
- }
1037
- }
1038
- class GroupPlaybackControls extends BaseGroupPlaybackControls {
1039
- then(onResolve, onReject) {
1040
- return Promise.all(this.animations).then(onResolve).catch(onReject);
1041
- }
1042
- }
1043
- const secondsToMilliseconds = /* @__NO_SIDE_EFFECTS__ */ (seconds) => seconds * 1e3;
1044
- const millisecondsToSeconds = /* @__NO_SIDE_EFFECTS__ */ (milliseconds) => milliseconds / 1e3;
1045
- function isGenerator(type) {
1046
- return typeof type === "function";
1047
- }
1048
- function attachTimeline(animation, timeline) {
1049
- animation.timeline = timeline;
1050
- animation.onfinish = null;
1051
- }
1052
- const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === "number";
1053
- const supportsFlags = {
1054
- linearEasing: void 0
1055
- };
1056
- function memoSupports(callback, supportsFlag) {
1057
- const memoized = /* @__PURE__ */ memo(callback);
1058
- return () => {
1059
- var _a;
1060
- return (_a = supportsFlags[supportsFlag]) !== null && _a !== void 0 ? _a : memoized();
1061
- };
1062
- }
1063
- const supportsLinearEasing = /* @__PURE__ */ memoSupports(() => {
1064
- try {
1065
- document.createElement("div").animate({ opacity: 0 }, { easing: "linear(0, 1)" });
1066
- } catch (e) {
1067
- return false;
1068
- }
1069
- return true;
1070
- }, "linearEasing");
1071
- const progress = /* @__NO_SIDE_EFFECTS__ */ (from, to, value) => {
1072
- const toFromDifference = to - from;
1073
- return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;
1074
- };
1075
- const generateLinearEasing = (easing, duration, resolution = 10) => {
1076
- let points = "";
1077
- const numPoints = Math.max(Math.round(duration / resolution), 2);
1078
- for (let i = 0; i < numPoints; i++) {
1079
- points += easing(/* @__PURE__ */ progress(0, numPoints - 1, i)) + ", ";
1080
- }
1081
- return `linear(${points.substring(0, points.length - 2)})`;
1082
- };
1083
- function isWaapiSupportedEasing(easing) {
1084
- return Boolean(typeof easing === "function" && supportsLinearEasing() || !easing || typeof easing === "string" && (easing in supportedWaapiEasing || supportsLinearEasing()) || isBezierDefinition(easing) || Array.isArray(easing) && easing.every(isWaapiSupportedEasing));
1085
- }
1086
- const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;
1087
- const supportedWaapiEasing = {
1088
- linear: "linear",
1089
- ease: "ease",
1090
- easeIn: "ease-in",
1091
- easeOut: "ease-out",
1092
- easeInOut: "ease-in-out",
1093
- circIn: /* @__PURE__ */ cubicBezierAsString([0, 0.65, 0.55, 1]),
1094
- circOut: /* @__PURE__ */ cubicBezierAsString([0.55, 0, 1, 0.45]),
1095
- backIn: /* @__PURE__ */ cubicBezierAsString([0.31, 0.01, 0.66, -0.59]),
1096
- backOut: /* @__PURE__ */ cubicBezierAsString([0.33, 1.53, 0.69, 0.99])
1097
- };
1098
- function mapEasingToNativeEasing(easing, duration) {
1099
- if (!easing) {
1100
- return void 0;
1101
- } else if (typeof easing === "function" && supportsLinearEasing()) {
1102
- return generateLinearEasing(easing, duration);
1103
- } else if (isBezierDefinition(easing)) {
1104
- return cubicBezierAsString(easing);
1105
- } else if (Array.isArray(easing)) {
1106
- return easing.map((segmentEasing) => mapEasingToNativeEasing(segmentEasing, duration) || supportedWaapiEasing.easeOut);
1107
- } else {
1108
- return supportedWaapiEasing[easing];
1109
- }
1110
- }
1111
- const calcBezier = (t, a1, a2) => (((1 - 3 * a2 + 3 * a1) * t + (3 * a2 - 6 * a1)) * t + 3 * a1) * t;
1112
- const subdivisionPrecision = 1e-7;
1113
- const subdivisionMaxIterations = 12;
1114
- function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {
1115
- let currentX;
1116
- let currentT;
1117
- let i = 0;
1118
- do {
1119
- currentT = lowerBound + (upperBound - lowerBound) / 2;
1120
- currentX = calcBezier(currentT, mX1, mX2) - x;
1121
- if (currentX > 0) {
1122
- upperBound = currentT;
1123
- } else {
1124
- lowerBound = currentT;
1125
- }
1126
- } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations);
1127
- return currentT;
1128
- }
1129
- function cubicBezier(mX1, mY1, mX2, mY2) {
1130
- if (mX1 === mY1 && mX2 === mY2)
1131
- return noop;
1132
- const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);
1133
- return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);
1134
- }
1135
- const mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2;
1136
- const reverseEasing = (easing) => (p) => 1 - easing(1 - p);
1137
- const backOut = /* @__PURE__ */ cubicBezier(0.33, 1.53, 0.69, 0.99);
1138
- const backIn = /* @__PURE__ */ reverseEasing(backOut);
1139
- const backInOut = /* @__PURE__ */ mirrorEasing(backIn);
1140
- const anticipate = (p) => (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
1141
- const circIn = (p) => 1 - Math.sin(Math.acos(p));
1142
- const circOut = reverseEasing(circIn);
1143
- const circInOut = mirrorEasing(circIn);
1144
- const isZeroValueString = (v) => /^0[^.\s]+$/u.test(v);
1145
- function isNone(value) {
1146
- if (typeof value === "number") {
1147
- return value === 0;
1148
- } else if (value !== null) {
1149
- return value === "none" || value === "0" || isZeroValueString(value);
1150
- } else {
1151
- return true;
1152
- }
1153
- }
1154
- const sanitize = (v) => Math.round(v * 1e5) / 1e5;
1155
- const floatRegex = /-?(?:\d+(?:\.\d+)?|\.\d+)/gu;
1156
- function isNullish(v) {
1157
- return v == null;
1158
- }
1159
- const singleColorRegex = /^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu;
1160
- const isColorString = (type, testProp) => (v) => {
1161
- return Boolean(typeof v === "string" && singleColorRegex.test(v) && v.startsWith(type) || testProp && !isNullish(v) && Object.prototype.hasOwnProperty.call(v, testProp));
1162
- };
1163
- const splitColor = (aName, bName, cName) => (v) => {
1164
- if (typeof v !== "string")
1165
- return v;
1166
- const [a, b, c, alpha2] = v.match(floatRegex);
1167
- return {
1168
- [aName]: parseFloat(a),
1169
- [bName]: parseFloat(b),
1170
- [cName]: parseFloat(c),
1171
- alpha: alpha2 !== void 0 ? parseFloat(alpha2) : 1
1172
- };
1173
- };
1174
- const clampRgbUnit = (v) => clamp(0, 255, v);
1175
- const rgbUnit = {
1176
- ...number,
1177
- transform: (v) => Math.round(clampRgbUnit(v))
1178
- };
1179
- const rgba = {
1180
- test: /* @__PURE__ */ isColorString("rgb", "red"),
1181
- parse: /* @__PURE__ */ splitColor("red", "green", "blue"),
1182
- transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" + rgbUnit.transform(red) + ", " + rgbUnit.transform(green) + ", " + rgbUnit.transform(blue) + ", " + sanitize(alpha.transform(alpha$1)) + ")"
1183
- };
1184
- function parseHex(v) {
1185
- let r = "";
1186
- let g = "";
1187
- let b = "";
1188
- let a = "";
1189
- if (v.length > 5) {
1190
- r = v.substring(1, 3);
1191
- g = v.substring(3, 5);
1192
- b = v.substring(5, 7);
1193
- a = v.substring(7, 9);
1194
- } else {
1195
- r = v.substring(1, 2);
1196
- g = v.substring(2, 3);
1197
- b = v.substring(3, 4);
1198
- a = v.substring(4, 5);
1199
- r += r;
1200
- g += g;
1201
- b += b;
1202
- a += a;
1203
- }
1204
- return {
1205
- red: parseInt(r, 16),
1206
- green: parseInt(g, 16),
1207
- blue: parseInt(b, 16),
1208
- alpha: a ? parseInt(a, 16) / 255 : 1
1209
- };
1210
- }
1211
- const hex = {
1212
- test: /* @__PURE__ */ isColorString("#"),
1213
- parse: parseHex,
1214
- transform: rgba.transform
1215
- };
1216
- const hsla = {
1217
- test: /* @__PURE__ */ isColorString("hsl", "hue"),
1218
- parse: /* @__PURE__ */ splitColor("hue", "saturation", "lightness"),
1219
- transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {
1220
- return "hsla(" + Math.round(hue) + ", " + percent.transform(sanitize(saturation)) + ", " + percent.transform(sanitize(lightness)) + ", " + sanitize(alpha.transform(alpha$1)) + ")";
1221
- }
1222
- };
1223
- const color = {
1224
- test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),
1225
- parse: (v) => {
1226
- if (rgba.test(v)) {
1227
- return rgba.parse(v);
1228
- } else if (hsla.test(v)) {
1229
- return hsla.parse(v);
1230
- } else {
1231
- return hex.parse(v);
1232
- }
1233
- },
1234
- transform: (v) => {
1235
- return typeof v === "string" ? v : v.hasOwnProperty("red") ? rgba.transform(v) : hsla.transform(v);
1236
- }
1237
- };
1238
- const colorRegex = /(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;
1239
- function test(v) {
1240
- var _a, _b;
1241
- return isNaN(v) && typeof v === "string" && (((_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) || 0) + (((_b = v.match(colorRegex)) === null || _b === void 0 ? void 0 : _b.length) || 0) > 0;
1242
- }
1243
- const NUMBER_TOKEN = "number";
1244
- const COLOR_TOKEN = "color";
1245
- const VAR_TOKEN = "var";
1246
- const VAR_FUNCTION_TOKEN = "var(";
1247
- const SPLIT_TOKEN = "${}";
1248
- const complexRegex = /var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;
1249
- function analyseComplexValue(value) {
1250
- const originalValue = value.toString();
1251
- const values = [];
1252
- const indexes = {
1253
- color: [],
1254
- number: [],
1255
- var: []
1256
- };
1257
- const types = [];
1258
- let i = 0;
1259
- const tokenised = originalValue.replace(complexRegex, (parsedValue) => {
1260
- if (color.test(parsedValue)) {
1261
- indexes.color.push(i);
1262
- types.push(COLOR_TOKEN);
1263
- values.push(color.parse(parsedValue));
1264
- } else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) {
1265
- indexes.var.push(i);
1266
- types.push(VAR_TOKEN);
1267
- values.push(parsedValue);
1268
- } else {
1269
- indexes.number.push(i);
1270
- types.push(NUMBER_TOKEN);
1271
- values.push(parseFloat(parsedValue));
1272
- }
1273
- ++i;
1274
- return SPLIT_TOKEN;
1275
- });
1276
- const split = tokenised.split(SPLIT_TOKEN);
1277
- return { values, split, indexes, types };
1278
- }
1279
- function parseComplexValue(v) {
1280
- return analyseComplexValue(v).values;
1281
- }
1282
- function createTransformer(source) {
1283
- const { split, types } = analyseComplexValue(source);
1284
- const numSections = split.length;
1285
- return (v) => {
1286
- let output = "";
1287
- for (let i = 0; i < numSections; i++) {
1288
- output += split[i];
1289
- if (v[i] !== void 0) {
1290
- const type = types[i];
1291
- if (type === NUMBER_TOKEN) {
1292
- output += sanitize(v[i]);
1293
- } else if (type === COLOR_TOKEN) {
1294
- output += color.transform(v[i]);
1295
- } else {
1296
- output += v[i];
1297
- }
1298
- }
1299
- }
1300
- return output;
1301
- };
1302
- }
1303
- const convertNumbersToZero = (v) => typeof v === "number" ? 0 : v;
1304
- function getAnimatableNone$1(v) {
1305
- const parsed = parseComplexValue(v);
1306
- const transformer = createTransformer(v);
1307
- return transformer(parsed.map(convertNumbersToZero));
1308
- }
1309
- const complex = {
1310
- test,
1311
- parse: parseComplexValue,
1312
- createTransformer,
1313
- getAnimatableNone: getAnimatableNone$1
1314
- };
1315
- const maxDefaults = /* @__PURE__ */ new Set(["brightness", "contrast", "saturate", "opacity"]);
1316
- function applyDefaultFilter(v) {
1317
- const [name, value] = v.slice(0, -1).split("(");
1318
- if (name === "drop-shadow")
1319
- return v;
1320
- const [number2] = value.match(floatRegex) || [];
1321
- if (!number2)
1322
- return v;
1323
- const unit = value.replace(number2, "");
1324
- let defaultValue = maxDefaults.has(name) ? 1 : 0;
1325
- if (number2 !== value)
1326
- defaultValue *= 100;
1327
- return name + "(" + defaultValue + unit + ")";
1328
- }
1329
- const functionRegex = /\b([a-z-]*)\(.*?\)/gu;
1330
- const filter = {
1331
- ...complex,
1332
- getAnimatableNone: (v) => {
1333
- const functions = v.match(functionRegex);
1334
- return functions ? functions.map(applyDefaultFilter).join(" ") : v;
1335
- }
1336
- };
1337
- const defaultValueTypes = {
1338
- ...numberValueTypes,
1339
- // Color props
1340
- color,
1341
- backgroundColor: color,
1342
- outlineColor: color,
1343
- fill: color,
1344
- stroke: color,
1345
- // Border props
1346
- borderColor: color,
1347
- borderTopColor: color,
1348
- borderRightColor: color,
1349
- borderBottomColor: color,
1350
- borderLeftColor: color,
1351
- filter,
1352
- WebkitFilter: filter
1353
- };
1354
- const getDefaultValueType = (key) => defaultValueTypes[key];
1355
- function getAnimatableNone(key, value) {
1356
- let defaultValueType = getDefaultValueType(key);
1357
- if (defaultValueType !== filter)
1358
- defaultValueType = complex;
1359
- return defaultValueType.getAnimatableNone ? defaultValueType.getAnimatableNone(value) : void 0;
1360
- }
1361
- const invalidTemplates = /* @__PURE__ */ new Set(["auto", "none", "0"]);
1362
- function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name) {
1363
- let i = 0;
1364
- let animatableTemplate = void 0;
1365
- while (i < unresolvedKeyframes.length && !animatableTemplate) {
1366
- const keyframe = unresolvedKeyframes[i];
1367
- if (typeof keyframe === "string" && !invalidTemplates.has(keyframe) && analyseComplexValue(keyframe).values.length) {
1368
- animatableTemplate = unresolvedKeyframes[i];
1369
- }
1370
- i++;
1371
- }
1372
- if (animatableTemplate && name) {
1373
- for (const noneIndex of noneKeyframeIndexes) {
1374
- unresolvedKeyframes[noneIndex] = getAnimatableNone(name, animatableTemplate);
1375
- }
1376
- }
1377
- }
1378
- const isNumOrPxType = (v) => v === number || v === px;
1379
- const getPosFromMatrix = (matrix, pos) => parseFloat(matrix.split(", ")[pos]);
1380
- const getTranslateFromMatrix = (pos2, pos3) => (_bbox, { transform }) => {
1381
- if (transform === "none" || !transform)
1382
- return 0;
1383
- const matrix3d = transform.match(/^matrix3d\((.+)\)$/u);
1384
- if (matrix3d) {
1385
- return getPosFromMatrix(matrix3d[1], pos3);
1386
- } else {
1387
- const matrix = transform.match(/^matrix\((.+)\)$/u);
1388
- if (matrix) {
1389
- return getPosFromMatrix(matrix[1], pos2);
1390
- } else {
1391
- return 0;
1392
- }
1393
- }
1394
- };
1395
- const transformKeys = /* @__PURE__ */ new Set(["x", "y", "z"]);
1396
- const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key));
1397
- function removeNonTranslationalTransform(visualElement) {
1398
- const removedTransforms = [];
1399
- nonTranslationalTransformKeys.forEach((key) => {
1400
- const value = visualElement.getValue(key);
1401
- if (value !== void 0) {
1402
- removedTransforms.push([key, value.get()]);
1403
- value.set(key.startsWith("scale") ? 1 : 0);
1404
- }
1405
- });
1406
- return removedTransforms;
1407
- }
1408
- const positionalValues = {
1409
- // Dimensions
1410
- width: ({ x }, { paddingLeft = "0", paddingRight = "0" }) => x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight),
1411
- height: ({ y }, { paddingTop = "0", paddingBottom = "0" }) => y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom),
1412
- top: (_bbox, { top }) => parseFloat(top),
1413
- left: (_bbox, { left }) => parseFloat(left),
1414
- bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min),
1415
- right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min),
1416
- // Transform
1417
- x: getTranslateFromMatrix(4, 13),
1418
- y: getTranslateFromMatrix(5, 14)
1419
- };
1420
- positionalValues.translateX = positionalValues.x;
1421
- positionalValues.translateY = positionalValues.y;
1422
- const toResolve = /* @__PURE__ */ new Set();
1423
- let isScheduled = false;
1424
- let anyNeedsMeasurement = false;
1425
- function measureAllKeyframes() {
1426
- if (anyNeedsMeasurement) {
1427
- const resolversToMeasure = Array.from(toResolve).filter((resolver) => resolver.needsMeasurement);
1428
- const elementsToMeasure = new Set(resolversToMeasure.map((resolver) => resolver.element));
1429
- const transformsToRestore = /* @__PURE__ */ new Map();
1430
- elementsToMeasure.forEach((element) => {
1431
- const removedTransforms = removeNonTranslationalTransform(element);
1432
- if (!removedTransforms.length)
1433
- return;
1434
- transformsToRestore.set(element, removedTransforms);
1435
- element.render();
1436
- });
1437
- resolversToMeasure.forEach((resolver) => resolver.measureInitialState());
1438
- elementsToMeasure.forEach((element) => {
1439
- element.render();
1440
- const restore = transformsToRestore.get(element);
1441
- if (restore) {
1442
- restore.forEach(([key, value]) => {
1443
- var _a;
1444
- (_a = element.getValue(key)) === null || _a === void 0 ? void 0 : _a.set(value);
1445
- });
1446
- }
1447
- });
1448
- resolversToMeasure.forEach((resolver) => resolver.measureEndState());
1449
- resolversToMeasure.forEach((resolver) => {
1450
- if (resolver.suspendedScrollY !== void 0) {
1451
- window.scrollTo(0, resolver.suspendedScrollY);
1452
- }
1453
- });
1454
- }
1455
- anyNeedsMeasurement = false;
1456
- isScheduled = false;
1457
- toResolve.forEach((resolver) => resolver.complete());
1458
- toResolve.clear();
1459
- }
1460
- function readAllKeyframes() {
1461
- toResolve.forEach((resolver) => {
1462
- resolver.readKeyframes();
1463
- if (resolver.needsMeasurement) {
1464
- anyNeedsMeasurement = true;
1465
- }
1466
- });
1467
- }
1468
- function flushKeyframeResolvers() {
1469
- readAllKeyframes();
1470
- measureAllKeyframes();
1471
- }
1472
- class KeyframeResolver {
1473
- constructor(unresolvedKeyframes, onComplete, name, motionValue2, element, isAsync = false) {
1474
- this.isComplete = false;
1475
- this.isAsync = false;
1476
- this.needsMeasurement = false;
1477
- this.isScheduled = false;
1478
- this.unresolvedKeyframes = [...unresolvedKeyframes];
1479
- this.onComplete = onComplete;
1480
- this.name = name;
1481
- this.motionValue = motionValue2;
1482
- this.element = element;
1483
- this.isAsync = isAsync;
1484
- }
1485
- scheduleResolve() {
1486
- this.isScheduled = true;
1487
- if (this.isAsync) {
1488
- toResolve.add(this);
1489
- if (!isScheduled) {
1490
- isScheduled = true;
1491
- frame.read(readAllKeyframes);
1492
- frame.resolveKeyframes(measureAllKeyframes);
1493
- }
1494
- } else {
1495
- this.readKeyframes();
1496
- this.complete();
1497
- }
1498
- }
1499
- readKeyframes() {
1500
- const { unresolvedKeyframes, name, element, motionValue: motionValue2 } = this;
1501
- for (let i = 0; i < unresolvedKeyframes.length; i++) {
1502
- if (unresolvedKeyframes[i] === null) {
1503
- if (i === 0) {
1504
- const currentValue = motionValue2 === null || motionValue2 === void 0 ? void 0 : motionValue2.get();
1505
- const finalKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];
1506
- if (currentValue !== void 0) {
1507
- unresolvedKeyframes[0] = currentValue;
1508
- } else if (element && name) {
1509
- const valueAsRead = element.readValue(name, finalKeyframe);
1510
- if (valueAsRead !== void 0 && valueAsRead !== null) {
1511
- unresolvedKeyframes[0] = valueAsRead;
1512
- }
1513
- }
1514
- if (unresolvedKeyframes[0] === void 0) {
1515
- unresolvedKeyframes[0] = finalKeyframe;
1516
- }
1517
- if (motionValue2 && currentValue === void 0) {
1518
- motionValue2.set(unresolvedKeyframes[0]);
1519
- }
1520
- } else {
1521
- unresolvedKeyframes[i] = unresolvedKeyframes[i - 1];
1522
- }
1523
- }
1524
- }
1525
- }
1526
- setFinalKeyframe() {
1527
- }
1528
- measureInitialState() {
1529
- }
1530
- renderEndStyles() {
1531
- }
1532
- measureEndState() {
1533
- }
1534
- complete() {
1535
- this.isComplete = true;
1536
- this.onComplete(this.unresolvedKeyframes, this.finalKeyframe);
1537
- toResolve.delete(this);
1538
- }
1539
- cancel() {
1540
- if (!this.isComplete) {
1541
- this.isScheduled = false;
1542
- toResolve.delete(this);
1543
- }
1544
- }
1545
- resume() {
1546
- if (!this.isComplete)
1547
- this.scheduleResolve();
1548
- }
1549
- }
1550
- const isNumericalString = (v) => /^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(v);
1551
- const splitCSSVariableRegex = (
1552
- // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words
1553
- /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u
1554
- );
1555
- function parseCSSVariable(current) {
1556
- const match = splitCSSVariableRegex.exec(current);
1557
- if (!match)
1558
- return [,];
1559
- const [, token1, token2, fallback] = match;
1560
- return [`--${token1 !== null && token1 !== void 0 ? token1 : token2}`, fallback];
1561
- }
1562
- const maxDepth = 4;
1563
- function getVariableValue(current, element, depth = 1) {
1564
- invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`);
1565
- const [token, fallback] = parseCSSVariable(current);
1566
- if (!token)
1567
- return;
1568
- const resolved = window.getComputedStyle(element).getPropertyValue(token);
1569
- if (resolved) {
1570
- const trimmed = resolved.trim();
1571
- return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;
1572
- }
1573
- return isCSSVariableToken(fallback) ? getVariableValue(fallback, element, depth + 1) : fallback;
1574
- }
1575
- const testValueType = (v) => (type) => type.test(v);
1576
- const auto = {
1577
- test: (v) => v === "auto",
1578
- parse: (v) => v
1579
- };
1580
- const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto];
1581
- const findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v));
1582
- class DOMKeyframesResolver extends KeyframeResolver {
1583
- constructor(unresolvedKeyframes, onComplete, name, motionValue2, element) {
1584
- super(unresolvedKeyframes, onComplete, name, motionValue2, element, true);
1585
- }
1586
- readKeyframes() {
1587
- const { unresolvedKeyframes, element, name } = this;
1588
- if (!element || !element.current)
1589
- return;
1590
- super.readKeyframes();
1591
- for (let i = 0; i < unresolvedKeyframes.length; i++) {
1592
- let keyframe = unresolvedKeyframes[i];
1593
- if (typeof keyframe === "string") {
1594
- keyframe = keyframe.trim();
1595
- if (isCSSVariableToken(keyframe)) {
1596
- const resolved = getVariableValue(keyframe, element.current);
1597
- if (resolved !== void 0) {
1598
- unresolvedKeyframes[i] = resolved;
1599
- }
1600
- if (i === unresolvedKeyframes.length - 1) {
1601
- this.finalKeyframe = keyframe;
1602
- }
1603
- }
1604
- }
1605
- }
1606
- this.resolveNoneKeyframes();
1607
- if (!positionalKeys.has(name) || unresolvedKeyframes.length !== 2) {
1608
- return;
1609
- }
1610
- const [origin, target] = unresolvedKeyframes;
1611
- const originType = findDimensionValueType(origin);
1612
- const targetType = findDimensionValueType(target);
1613
- if (originType === targetType)
1614
- return;
1615
- if (isNumOrPxType(originType) && isNumOrPxType(targetType)) {
1616
- for (let i = 0; i < unresolvedKeyframes.length; i++) {
1617
- const value = unresolvedKeyframes[i];
1618
- if (typeof value === "string") {
1619
- unresolvedKeyframes[i] = parseFloat(value);
1620
- }
1621
- }
1622
- } else {
1623
- this.needsMeasurement = true;
1624
- }
1625
- }
1626
- resolveNoneKeyframes() {
1627
- const { unresolvedKeyframes, name } = this;
1628
- const noneKeyframeIndexes = [];
1629
- for (let i = 0; i < unresolvedKeyframes.length; i++) {
1630
- if (isNone(unresolvedKeyframes[i])) {
1631
- noneKeyframeIndexes.push(i);
1632
- }
1633
- }
1634
- if (noneKeyframeIndexes.length) {
1635
- makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name);
1636
- }
1637
- }
1638
- measureInitialState() {
1639
- const { element, unresolvedKeyframes, name } = this;
1640
- if (!element || !element.current)
1641
- return;
1642
- if (name === "height") {
1643
- this.suspendedScrollY = window.pageYOffset;
1644
- }
1645
- this.measuredOrigin = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current));
1646
- unresolvedKeyframes[0] = this.measuredOrigin;
1647
- const measureKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];
1648
- if (measureKeyframe !== void 0) {
1649
- element.getValue(name, measureKeyframe).jump(measureKeyframe, false);
1650
- }
1651
- }
1652
- measureEndState() {
1653
- var _a;
1654
- const { element, name, unresolvedKeyframes } = this;
1655
- if (!element || !element.current)
1656
- return;
1657
- const value = element.getValue(name);
1658
- value && value.jump(this.measuredOrigin, false);
1659
- const finalKeyframeIndex = unresolvedKeyframes.length - 1;
1660
- const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex];
1661
- unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current));
1662
- if (finalKeyframe !== null && this.finalKeyframe === void 0) {
1663
- this.finalKeyframe = finalKeyframe;
1664
- }
1665
- if ((_a = this.removedTransforms) === null || _a === void 0 ? void 0 : _a.length) {
1666
- this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => {
1667
- element.getValue(unsetTransformName).set(unsetTransformValue);
1668
- });
1669
- }
1670
- this.resolveNoneKeyframes();
1671
- }
1672
- }
1673
- const isAnimatable = (value, name) => {
1674
- if (name === "zIndex")
1675
- return false;
1676
- if (typeof value === "number" || Array.isArray(value))
1677
- return true;
1678
- if (typeof value === "string" && // It's animatable if we have a string
1679
- (complex.test(value) || value === "0") && // And it contains numbers and/or colors
1680
- !value.startsWith("url(")) {
1681
- return true;
1682
- }
1683
- return false;
1684
- };
1685
- function hasKeyframesChanged(keyframes2) {
1686
- const current = keyframes2[0];
1687
- if (keyframes2.length === 1)
1688
- return true;
1689
- for (let i = 0; i < keyframes2.length; i++) {
1690
- if (keyframes2[i] !== current)
1691
- return true;
1692
- }
1693
- }
1694
- function canAnimate(keyframes2, name, type, velocity) {
1695
- const originKeyframe = keyframes2[0];
1696
- if (originKeyframe === null)
1697
- return false;
1698
- if (name === "display" || name === "visibility")
1699
- return true;
1700
- const targetKeyframe = keyframes2[keyframes2.length - 1];
1701
- const isOriginAnimatable = isAnimatable(originKeyframe, name);
1702
- const isTargetAnimatable = isAnimatable(targetKeyframe, name);
1703
- warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". ${originKeyframe} is not an animatable value - to enable this animation set ${originKeyframe} to a value animatable to ${targetKeyframe} via the \`style\` property.`);
1704
- if (!isOriginAnimatable || !isTargetAnimatable) {
1705
- return false;
1706
- }
1707
- return hasKeyframesChanged(keyframes2) || (type === "spring" || isGenerator(type)) && velocity;
1708
- }
1709
- const isNotNull = (value) => value !== null;
1710
- function getFinalKeyframe(keyframes2, { repeat, repeatType = "loop" }, finalKeyframe) {
1711
- const resolvedKeyframes = keyframes2.filter(isNotNull);
1712
- const index = repeat && repeatType !== "loop" && repeat % 2 === 1 ? 0 : resolvedKeyframes.length - 1;
1713
- return !index || finalKeyframe === void 0 ? resolvedKeyframes[index] : finalKeyframe;
1714
- }
1715
- const MAX_RESOLVE_DELAY = 40;
1716
- class BaseAnimation {
1717
- constructor({ autoplay = true, delay = 0, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", ...options }) {
1718
- this.isStopped = false;
1719
- this.hasAttemptedResolve = false;
1720
- this.createdAt = time.now();
1721
- this.options = {
1722
- autoplay,
1723
- delay,
1724
- type,
1725
- repeat,
1726
- repeatDelay,
1727
- repeatType,
1728
- ...options
1729
- };
1730
- this.updateFinishedPromise();
1731
- }
1732
- /**
1733
- * This method uses the createdAt and resolvedAt to calculate the
1734
- * animation startTime. *Ideally*, we would use the createdAt time as t=0
1735
- * as the following frame would then be the first frame of the animation in
1736
- * progress, which would feel snappier.
1737
- *
1738
- * However, if there's a delay (main thread work) between the creation of
1739
- * the animation and the first commited frame, we prefer to use resolvedAt
1740
- * to avoid a sudden jump into the animation.
1741
- */
1742
- calcStartTime() {
1743
- if (!this.resolvedAt)
1744
- return this.createdAt;
1745
- return this.resolvedAt - this.createdAt > MAX_RESOLVE_DELAY ? this.resolvedAt : this.createdAt;
1746
- }
1747
- /**
1748
- * A getter for resolved data. If keyframes are not yet resolved, accessing
1749
- * this.resolved will synchronously flush all pending keyframe resolvers.
1750
- * This is a deoptimisation, but at its worst still batches read/writes.
1751
- */
1752
- get resolved() {
1753
- if (!this._resolved && !this.hasAttemptedResolve) {
1754
- flushKeyframeResolvers();
1755
- }
1756
- return this._resolved;
1757
- }
1758
- /**
1759
- * A method to be called when the keyframes resolver completes. This method
1760
- * will check if its possible to run the animation and, if not, skip it.
1761
- * Otherwise, it will call initPlayback on the implementing class.
1762
- */
1763
- onKeyframesResolved(keyframes2, finalKeyframe) {
1764
- this.resolvedAt = time.now();
1765
- this.hasAttemptedResolve = true;
1766
- const { name, type, velocity, delay, onComplete, onUpdate, isGenerator: isGenerator2 } = this.options;
1767
- if (!isGenerator2 && !canAnimate(keyframes2, name, type, velocity)) {
1768
- if (!delay) {
1769
- onUpdate && onUpdate(getFinalKeyframe(keyframes2, this.options, finalKeyframe));
1770
- onComplete && onComplete();
1771
- this.resolveFinishedPromise();
1772
- return;
1773
- } else {
1774
- this.options.duration = 0;
1775
- }
1776
- }
1777
- const resolvedAnimation = this.initPlayback(keyframes2, finalKeyframe);
1778
- if (resolvedAnimation === false)
1779
- return;
1780
- this._resolved = {
1781
- keyframes: keyframes2,
1782
- finalKeyframe,
1783
- ...resolvedAnimation
1784
- };
1785
- this.onPostResolved();
1786
- }
1787
- onPostResolved() {
1788
- }
1789
- /**
1790
- * Allows the returned animation to be awaited or promise-chained. Currently
1791
- * resolves when the animation finishes at all but in a future update could/should
1792
- * reject if its cancels.
1793
- */
1794
- then(resolve, reject) {
1795
- return this.currentFinishedPromise.then(resolve, reject);
1796
- }
1797
- flatten() {
1798
- this.options.type = "keyframes";
1799
- this.options.ease = "linear";
1800
- }
1801
- updateFinishedPromise() {
1802
- this.currentFinishedPromise = new Promise((resolve) => {
1803
- this.resolveFinishedPromise = resolve;
1804
- });
1805
- }
1806
- }
1807
- const maxGeneratorDuration = 2e4;
1808
- function calcGeneratorDuration(generator) {
1809
- let duration = 0;
1810
- const timeStep = 50;
1811
- let state = generator.next(duration);
1812
- while (!state.done && duration < maxGeneratorDuration) {
1813
- duration += timeStep;
1814
- state = generator.next(duration);
1815
- }
1816
- return duration >= maxGeneratorDuration ? Infinity : duration;
1817
- }
1818
- const mixNumber$1 = (from, to, progress2) => {
1819
- return from + (to - from) * progress2;
1820
- };
1821
- function hueToRgb(p, q, t) {
1822
- if (t < 0)
1823
- t += 1;
1824
- if (t > 1)
1825
- t -= 1;
1826
- if (t < 1 / 6)
1827
- return p + (q - p) * 6 * t;
1828
- if (t < 1 / 2)
1829
- return q;
1830
- if (t < 2 / 3)
1831
- return p + (q - p) * (2 / 3 - t) * 6;
1832
- return p;
1833
- }
1834
- function hslaToRgba({ hue, saturation, lightness, alpha: alpha2 }) {
1835
- hue /= 360;
1836
- saturation /= 100;
1837
- lightness /= 100;
1838
- let red = 0;
1839
- let green = 0;
1840
- let blue = 0;
1841
- if (!saturation) {
1842
- red = green = blue = lightness;
1843
- } else {
1844
- const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
1845
- const p = 2 * lightness - q;
1846
- red = hueToRgb(p, q, hue + 1 / 3);
1847
- green = hueToRgb(p, q, hue);
1848
- blue = hueToRgb(p, q, hue - 1 / 3);
1849
- }
1850
- return {
1851
- red: Math.round(red * 255),
1852
- green: Math.round(green * 255),
1853
- blue: Math.round(blue * 255),
1854
- alpha: alpha2
1855
- };
1856
- }
1857
- function mixImmediate(a, b) {
1858
- return (p) => p > 0 ? b : a;
1859
- }
1860
- const mixLinearColor = (from, to, v) => {
1861
- const fromExpo = from * from;
1862
- const expo = v * (to * to - fromExpo) + fromExpo;
1863
- return expo < 0 ? 0 : Math.sqrt(expo);
1864
- };
1865
- const colorTypes = [hex, rgba, hsla];
1866
- const getColorType = (v) => colorTypes.find((type) => type.test(v));
1867
- function asRGBA(color2) {
1868
- const type = getColorType(color2);
1869
- warning(Boolean(type), `'${color2}' is not an animatable color. Use the equivalent color code instead.`);
1870
- if (!Boolean(type))
1871
- return false;
1872
- let model = type.parse(color2);
1873
- if (type === hsla) {
1874
- model = hslaToRgba(model);
1875
- }
1876
- return model;
1877
- }
1878
- const mixColor = (from, to) => {
1879
- const fromRGBA = asRGBA(from);
1880
- const toRGBA = asRGBA(to);
1881
- if (!fromRGBA || !toRGBA) {
1882
- return mixImmediate(from, to);
1883
- }
1884
- const blended = { ...fromRGBA };
1885
- return (v) => {
1886
- blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v);
1887
- blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v);
1888
- blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v);
1889
- blended.alpha = mixNumber$1(fromRGBA.alpha, toRGBA.alpha, v);
1890
- return rgba.transform(blended);
1891
- };
1892
- };
1893
- const combineFunctions = (a, b) => (v) => b(a(v));
1894
- const pipe = (...transformers) => transformers.reduce(combineFunctions);
1895
- const invisibleValues = /* @__PURE__ */ new Set(["none", "hidden"]);
1896
- function mixVisibility(origin, target) {
1897
- if (invisibleValues.has(origin)) {
1898
- return (p) => p <= 0 ? origin : target;
1899
- } else {
1900
- return (p) => p >= 1 ? target : origin;
1901
- }
1902
- }
1903
- function mixNumber(a, b) {
1904
- return (p) => mixNumber$1(a, b, p);
1905
- }
1906
- function getMixer(a) {
1907
- if (typeof a === "number") {
1908
- return mixNumber;
1909
- } else if (typeof a === "string") {
1910
- return isCSSVariableToken(a) ? mixImmediate : color.test(a) ? mixColor : mixComplex;
1911
- } else if (Array.isArray(a)) {
1912
- return mixArray;
1913
- } else if (typeof a === "object") {
1914
- return color.test(a) ? mixColor : mixObject;
1915
- }
1916
- return mixImmediate;
1917
- }
1918
- function mixArray(a, b) {
1919
- const output = [...a];
1920
- const numValues = output.length;
1921
- const blendValue = a.map((v, i) => getMixer(v)(v, b[i]));
1922
- return (p) => {
1923
- for (let i = 0; i < numValues; i++) {
1924
- output[i] = blendValue[i](p);
1925
- }
1926
- return output;
1927
- };
1928
- }
1929
- function mixObject(a, b) {
1930
- const output = { ...a, ...b };
1931
- const blendValue = {};
1932
- for (const key in output) {
1933
- if (a[key] !== void 0 && b[key] !== void 0) {
1934
- blendValue[key] = getMixer(a[key])(a[key], b[key]);
1935
- }
1936
- }
1937
- return (v) => {
1938
- for (const key in blendValue) {
1939
- output[key] = blendValue[key](v);
1940
- }
1941
- return output;
1942
- };
1943
- }
1944
- function matchOrder(origin, target) {
1945
- var _a;
1946
- const orderedOrigin = [];
1947
- const pointers = { color: 0, var: 0, number: 0 };
1948
- for (let i = 0; i < target.values.length; i++) {
1949
- const type = target.types[i];
1950
- const originIndex = origin.indexes[type][pointers[type]];
1951
- const originValue = (_a = origin.values[originIndex]) !== null && _a !== void 0 ? _a : 0;
1952
- orderedOrigin[i] = originValue;
1953
- pointers[type]++;
1954
- }
1955
- return orderedOrigin;
1956
- }
1957
- const mixComplex = (origin, target) => {
1958
- const template = complex.createTransformer(target);
1959
- const originStats = analyseComplexValue(origin);
1960
- const targetStats = analyseComplexValue(target);
1961
- const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length && originStats.indexes.color.length === targetStats.indexes.color.length && originStats.indexes.number.length >= targetStats.indexes.number.length;
1962
- if (canInterpolate) {
1963
- if (invisibleValues.has(origin) && !targetStats.values.length || invisibleValues.has(target) && !originStats.values.length) {
1964
- return mixVisibility(origin, target);
1965
- }
1966
- return pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template);
1967
- } else {
1968
- warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`);
1969
- return mixImmediate(origin, target);
1970
- }
1971
- };
1972
- function mix(from, to, p) {
1973
- if (typeof from === "number" && typeof to === "number" && typeof p === "number") {
1974
- return mixNumber$1(from, to, p);
1975
- }
1976
- const mixer = getMixer(from);
1977
- return mixer(from, to);
1978
- }
1979
- const velocitySampleDuration = 5;
1980
- function calcGeneratorVelocity(resolveValue, t, current) {
1981
- const prevT = Math.max(t - velocitySampleDuration, 0);
1982
- return velocityPerSecond(current - resolveValue(prevT), t - prevT);
1983
- }
1984
- const springDefaults = {
1985
- // Default spring physics
1986
- stiffness: 100,
1987
- damping: 10,
1988
- mass: 1,
1989
- velocity: 0,
1990
- // Default duration/bounce-based options
1991
- duration: 800,
1992
- // in ms
1993
- bounce: 0.3,
1994
- visualDuration: 0.3,
1995
- // in seconds
1996
- // Rest thresholds
1997
- restSpeed: {
1998
- granular: 0.01,
1999
- default: 2
2000
- },
2001
- restDelta: {
2002
- granular: 5e-3,
2003
- default: 0.5
2004
- },
2005
- // Limits
2006
- minDuration: 0.01,
2007
- // in seconds
2008
- maxDuration: 10,
2009
- // in seconds
2010
- minDamping: 0.05,
2011
- maxDamping: 1
2012
- };
2013
- const safeMin = 1e-3;
2014
- function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass }) {
2015
- let envelope;
2016
- let derivative;
2017
- warning(duration <= /* @__PURE__ */ secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less");
2018
- let dampingRatio = 1 - bounce;
2019
- dampingRatio = clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio);
2020
- duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, /* @__PURE__ */ millisecondsToSeconds(duration));
2021
- if (dampingRatio < 1) {
2022
- envelope = (undampedFreq2) => {
2023
- const exponentialDecay = undampedFreq2 * dampingRatio;
2024
- const delta = exponentialDecay * duration;
2025
- const a = exponentialDecay - velocity;
2026
- const b = calcAngularFreq(undampedFreq2, dampingRatio);
2027
- const c = Math.exp(-delta);
2028
- return safeMin - a / b * c;
2029
- };
2030
- derivative = (undampedFreq2) => {
2031
- const exponentialDecay = undampedFreq2 * dampingRatio;
2032
- const delta = exponentialDecay * duration;
2033
- const d = delta * velocity + velocity;
2034
- const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq2, 2) * duration;
2035
- const f = Math.exp(-delta);
2036
- const g = calcAngularFreq(Math.pow(undampedFreq2, 2), dampingRatio);
2037
- const factor = -envelope(undampedFreq2) + safeMin > 0 ? -1 : 1;
2038
- return factor * ((d - e) * f) / g;
2039
- };
2040
- } else {
2041
- envelope = (undampedFreq2) => {
2042
- const a = Math.exp(-undampedFreq2 * duration);
2043
- const b = (undampedFreq2 - velocity) * duration + 1;
2044
- return -safeMin + a * b;
2045
- };
2046
- derivative = (undampedFreq2) => {
2047
- const a = Math.exp(-undampedFreq2 * duration);
2048
- const b = (velocity - undampedFreq2) * (duration * duration);
2049
- return a * b;
2050
- };
2051
- }
2052
- const initialGuess = 5 / duration;
2053
- const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
2054
- duration = /* @__PURE__ */ secondsToMilliseconds(duration);
2055
- if (isNaN(undampedFreq)) {
2056
- return {
2057
- stiffness: springDefaults.stiffness,
2058
- damping: springDefaults.damping,
2059
- duration
2060
- };
2061
- } else {
2062
- const stiffness = Math.pow(undampedFreq, 2) * mass;
2063
- return {
2064
- stiffness,
2065
- damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
2066
- duration
2067
- };
2068
- }
2069
- }
2070
- const rootIterations = 12;
2071
- function approximateRoot(envelope, derivative, initialGuess) {
2072
- let result = initialGuess;
2073
- for (let i = 1; i < rootIterations; i++) {
2074
- result = result - envelope(result) / derivative(result);
2075
- }
2076
- return result;
2077
- }
2078
- function calcAngularFreq(undampedFreq, dampingRatio) {
2079
- return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
2080
- }
2081
- const durationKeys = ["duration", "bounce"];
2082
- const physicsKeys = ["stiffness", "damping", "mass"];
2083
- function isSpringType(options, keys) {
2084
- return keys.some((key) => options[key] !== void 0);
2085
- }
2086
- function getSpringOptions(options) {
2087
- let springOptions = {
2088
- velocity: springDefaults.velocity,
2089
- stiffness: springDefaults.stiffness,
2090
- damping: springDefaults.damping,
2091
- mass: springDefaults.mass,
2092
- isResolvedFromDuration: false,
2093
- ...options
2094
- };
2095
- if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) {
2096
- if (options.visualDuration) {
2097
- const visualDuration = options.visualDuration;
2098
- const root = 2 * Math.PI / (visualDuration * 1.2);
2099
- const stiffness = root * root;
2100
- const damping = 2 * clamp(0.05, 1, 1 - (options.bounce || 0)) * Math.sqrt(stiffness);
2101
- springOptions = {
2102
- ...springOptions,
2103
- mass: springDefaults.mass,
2104
- stiffness,
2105
- damping
2106
- };
2107
- } else {
2108
- const derived = findSpring(options);
2109
- springOptions = {
2110
- ...springOptions,
2111
- ...derived,
2112
- mass: springDefaults.mass
2113
- };
2114
- springOptions.isResolvedFromDuration = true;
2115
- }
2116
- }
2117
- return springOptions;
2118
- }
2119
- function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) {
2120
- const options = typeof optionsOrVisualDuration !== "object" ? {
2121
- visualDuration: optionsOrVisualDuration,
2122
- keyframes: [0, 1],
2123
- bounce
2124
- } : optionsOrVisualDuration;
2125
- let { restSpeed, restDelta } = options;
2126
- const origin = options.keyframes[0];
2127
- const target = options.keyframes[options.keyframes.length - 1];
2128
- const state = { done: false, value: origin };
2129
- const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration } = getSpringOptions({
2130
- ...options,
2131
- velocity: -/* @__PURE__ */ millisecondsToSeconds(options.velocity || 0)
2132
- });
2133
- const initialVelocity = velocity || 0;
2134
- const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
2135
- const initialDelta = target - origin;
2136
- const undampedAngularFreq = /* @__PURE__ */ millisecondsToSeconds(Math.sqrt(stiffness / mass));
2137
- const isGranularScale = Math.abs(initialDelta) < 5;
2138
- restSpeed || (restSpeed = isGranularScale ? springDefaults.restSpeed.granular : springDefaults.restSpeed.default);
2139
- restDelta || (restDelta = isGranularScale ? springDefaults.restDelta.granular : springDefaults.restDelta.default);
2140
- let resolveSpring;
2141
- if (dampingRatio < 1) {
2142
- const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
2143
- resolveSpring = (t) => {
2144
- const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
2145
- return target - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t));
2146
- };
2147
- } else if (dampingRatio === 1) {
2148
- resolveSpring = (t) => target - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t);
2149
- } else {
2150
- const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
2151
- resolveSpring = (t) => {
2152
- const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
2153
- const freqForT = Math.min(dampedAngularFreq * t, 300);
2154
- return target - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq;
2155
- };
2156
- }
2157
- const generator = {
2158
- calculatedDuration: isResolvedFromDuration ? duration || null : null,
2159
- next: (t) => {
2160
- const current = resolveSpring(t);
2161
- if (!isResolvedFromDuration) {
2162
- let currentVelocity = 0;
2163
- if (dampingRatio < 1) {
2164
- currentVelocity = t === 0 ? /* @__PURE__ */ secondsToMilliseconds(initialVelocity) : calcGeneratorVelocity(resolveSpring, t, current);
2165
- }
2166
- const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed;
2167
- const isBelowDisplacementThreshold = Math.abs(target - current) <= restDelta;
2168
- state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold;
2169
- } else {
2170
- state.done = t >= duration;
2171
- }
2172
- state.value = state.done ? target : current;
2173
- return state;
2174
- },
2175
- toString: () => {
2176
- const calculatedDuration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
2177
- const easing = generateLinearEasing((progress2) => generator.next(calculatedDuration * progress2).value, calculatedDuration, 30);
2178
- return calculatedDuration + "ms " + easing;
2179
- }
2180
- };
2181
- return generator;
2182
- }
2183
- function inertia({ keyframes: keyframes2, velocity = 0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed }) {
2184
- const origin = keyframes2[0];
2185
- const state = {
2186
- done: false,
2187
- value: origin
2188
- };
2189
- const isOutOfBounds = (v) => min !== void 0 && v < min || max !== void 0 && v > max;
2190
- const nearestBoundary = (v) => {
2191
- if (min === void 0)
2192
- return max;
2193
- if (max === void 0)
2194
- return min;
2195
- return Math.abs(min - v) < Math.abs(max - v) ? min : max;
2196
- };
2197
- let amplitude = power * velocity;
2198
- const ideal = origin + amplitude;
2199
- const target = modifyTarget === void 0 ? ideal : modifyTarget(ideal);
2200
- if (target !== ideal)
2201
- amplitude = target - origin;
2202
- const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant);
2203
- const calcLatest = (t) => target + calcDelta(t);
2204
- const applyFriction = (t) => {
2205
- const delta = calcDelta(t);
2206
- const latest = calcLatest(t);
2207
- state.done = Math.abs(delta) <= restDelta;
2208
- state.value = state.done ? target : latest;
2209
- };
2210
- let timeReachedBoundary;
2211
- let spring$1;
2212
- const checkCatchBoundary = (t) => {
2213
- if (!isOutOfBounds(state.value))
2214
- return;
2215
- timeReachedBoundary = t;
2216
- spring$1 = spring({
2217
- keyframes: [state.value, nearestBoundary(state.value)],
2218
- velocity: calcGeneratorVelocity(calcLatest, t, state.value),
2219
- // TODO: This should be passing * 1000
2220
- damping: bounceDamping,
2221
- stiffness: bounceStiffness,
2222
- restDelta,
2223
- restSpeed
2224
- });
2225
- };
2226
- checkCatchBoundary(0);
2227
- return {
2228
- calculatedDuration: null,
2229
- next: (t) => {
2230
- let hasUpdatedFrame = false;
2231
- if (!spring$1 && timeReachedBoundary === void 0) {
2232
- hasUpdatedFrame = true;
2233
- applyFriction(t);
2234
- checkCatchBoundary(t);
2235
- }
2236
- if (timeReachedBoundary !== void 0 && t >= timeReachedBoundary) {
2237
- return spring$1.next(t - timeReachedBoundary);
2238
- } else {
2239
- !hasUpdatedFrame && applyFriction(t);
2240
- return state;
2241
- }
2242
- }
2243
- };
2244
- }
2245
- const easeIn = /* @__PURE__ */ cubicBezier(0.42, 0, 1, 1);
2246
- const easeOut = /* @__PURE__ */ cubicBezier(0, 0, 0.58, 1);
2247
- const easeInOut = /* @__PURE__ */ cubicBezier(0.42, 0, 0.58, 1);
2248
- const isEasingArray = (ease2) => {
2249
- return Array.isArray(ease2) && typeof ease2[0] !== "number";
2250
- };
2251
- const easingLookup = {
2252
- linear: noop,
2253
- easeIn,
2254
- easeInOut,
2255
- easeOut,
2256
- circIn,
2257
- circInOut,
2258
- circOut,
2259
- backIn,
2260
- backInOut,
2261
- backOut,
2262
- anticipate
2263
- };
2264
- const easingDefinitionToFunction = (definition) => {
2265
- if (isBezierDefinition(definition)) {
2266
- invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`);
2267
- const [x1, y1, x2, y2] = definition;
2268
- return cubicBezier(x1, y1, x2, y2);
2269
- } else if (typeof definition === "string") {
2270
- invariant(easingLookup[definition] !== void 0, `Invalid easing type '${definition}'`);
2271
- return easingLookup[definition];
2272
- }
2273
- return definition;
2274
- };
2275
- function createMixers(output, ease2, customMixer) {
2276
- const mixers = [];
2277
- const mixerFactory = customMixer || mix;
2278
- const numMixers = output.length - 1;
2279
- for (let i = 0; i < numMixers; i++) {
2280
- let mixer = mixerFactory(output[i], output[i + 1]);
2281
- if (ease2) {
2282
- const easingFunction = Array.isArray(ease2) ? ease2[i] || noop : ease2;
2283
- mixer = pipe(easingFunction, mixer);
2284
- }
2285
- mixers.push(mixer);
2286
- }
2287
- return mixers;
2288
- }
2289
- function interpolate(input, output, { clamp: isClamp = true, ease: ease2, mixer } = {}) {
2290
- const inputLength = input.length;
2291
- invariant(inputLength === output.length, "Both input and output ranges must be the same length");
2292
- if (inputLength === 1)
2293
- return () => output[0];
2294
- if (inputLength === 2 && output[0] === output[1])
2295
- return () => output[1];
2296
- const isZeroDeltaRange = input[0] === input[1];
2297
- if (input[0] > input[inputLength - 1]) {
2298
- input = [...input].reverse();
2299
- output = [...output].reverse();
2300
- }
2301
- const mixers = createMixers(output, ease2, mixer);
2302
- const numMixers = mixers.length;
2303
- const interpolator = (v) => {
2304
- if (isZeroDeltaRange && v < input[0])
2305
- return output[0];
2306
- let i = 0;
2307
- if (numMixers > 1) {
2308
- for (; i < input.length - 2; i++) {
2309
- if (v < input[i + 1])
2310
- break;
2311
- }
2312
- }
2313
- const progressInRange = /* @__PURE__ */ progress(input[i], input[i + 1], v);
2314
- return mixers[i](progressInRange);
2315
- };
2316
- return isClamp ? (v) => interpolator(clamp(input[0], input[inputLength - 1], v)) : interpolator;
2317
- }
2318
- function fillOffset(offset, remaining) {
2319
- const min = offset[offset.length - 1];
2320
- for (let i = 1; i <= remaining; i++) {
2321
- const offsetProgress = /* @__PURE__ */ progress(0, remaining, i);
2322
- offset.push(mixNumber$1(min, 1, offsetProgress));
2323
- }
2324
- }
2325
- function defaultOffset(arr) {
2326
- const offset = [0];
2327
- fillOffset(offset, arr.length - 1);
2328
- return offset;
2329
- }
2330
- function convertOffsetToTimes(offset, duration) {
2331
- return offset.map((o) => o * duration);
2332
- }
2333
- function defaultEasing(values, easing) {
2334
- return values.map(() => easing || easeInOut).splice(0, values.length - 1);
2335
- }
2336
- function keyframes({ duration = 300, keyframes: keyframeValues, times, ease: ease2 = "easeInOut" }) {
2337
- const easingFunctions = isEasingArray(ease2) ? ease2.map(easingDefinitionToFunction) : easingDefinitionToFunction(ease2);
2338
- const state = {
2339
- done: false,
2340
- value: keyframeValues[0]
2341
- };
2342
- const absoluteTimes = convertOffsetToTimes(
2343
- // Only use the provided offsets if they're the correct length
2344
- // TODO Maybe we should warn here if there's a length mismatch
2345
- times && times.length === keyframeValues.length ? times : defaultOffset(keyframeValues),
2346
- duration
2347
- );
2348
- const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, {
2349
- ease: Array.isArray(easingFunctions) ? easingFunctions : defaultEasing(keyframeValues, easingFunctions)
2350
- });
2351
- return {
2352
- calculatedDuration: duration,
2353
- next: (t) => {
2354
- state.value = mapTimeToKeyframe(t);
2355
- state.done = t >= duration;
2356
- return state;
2357
- }
2358
- };
2359
- }
2360
- const frameloopDriver = (update) => {
2361
- const passTimestamp = ({ timestamp }) => update(timestamp);
2362
- return {
2363
- start: () => frame.update(passTimestamp, true),
2364
- stop: () => cancelFrame(passTimestamp),
2365
- /**
2366
- * If we're processing this frame we can use the
2367
- * framelocked timestamp to keep things in sync.
2368
- */
2369
- now: () => frameData.isProcessing ? frameData.timestamp : time.now()
2370
- };
2371
- };
2372
- const generators = {
2373
- decay: inertia,
2374
- inertia,
2375
- tween: keyframes,
2376
- keyframes,
2377
- spring
2378
- };
2379
- const percentToProgress = (percent2) => percent2 / 100;
2380
- class MainThreadAnimation extends BaseAnimation {
2381
- constructor(options) {
2382
- super(options);
2383
- this.holdTime = null;
2384
- this.cancelTime = null;
2385
- this.currentTime = 0;
2386
- this.playbackSpeed = 1;
2387
- this.pendingPlayState = "running";
2388
- this.startTime = null;
2389
- this.state = "idle";
2390
- this.stop = () => {
2391
- this.resolver.cancel();
2392
- this.isStopped = true;
2393
- if (this.state === "idle")
2394
- return;
2395
- this.teardown();
2396
- const { onStop } = this.options;
2397
- onStop && onStop();
2398
- };
2399
- const { name, motionValue: motionValue2, element, keyframes: keyframes2 } = this.options;
2400
- const KeyframeResolver$1 = (element === null || element === void 0 ? void 0 : element.KeyframeResolver) || KeyframeResolver;
2401
- const onResolved = (resolvedKeyframes, finalKeyframe) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe);
2402
- this.resolver = new KeyframeResolver$1(keyframes2, onResolved, name, motionValue2, element);
2403
- this.resolver.scheduleResolve();
2404
- }
2405
- flatten() {
2406
- super.flatten();
2407
- if (this._resolved) {
2408
- Object.assign(this._resolved, this.initPlayback(this._resolved.keyframes));
2409
- }
2410
- }
2411
- initPlayback(keyframes$1) {
2412
- const { type = "keyframes", repeat = 0, repeatDelay = 0, repeatType, velocity = 0 } = this.options;
2413
- const generatorFactory = isGenerator(type) ? type : generators[type] || keyframes;
2414
- let mapPercentToKeyframes;
2415
- let mirroredGenerator;
2416
- if (generatorFactory !== keyframes && typeof keyframes$1[0] !== "number") {
2417
- if (process.env.NODE_ENV !== "production") {
2418
- invariant(keyframes$1.length === 2, `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes$1}`);
2419
- }
2420
- mapPercentToKeyframes = pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1]));
2421
- keyframes$1 = [0, 100];
2422
- }
2423
- const generator = generatorFactory({ ...this.options, keyframes: keyframes$1 });
2424
- if (repeatType === "mirror") {
2425
- mirroredGenerator = generatorFactory({
2426
- ...this.options,
2427
- keyframes: [...keyframes$1].reverse(),
2428
- velocity: -velocity
2429
- });
2430
- }
2431
- if (generator.calculatedDuration === null) {
2432
- generator.calculatedDuration = calcGeneratorDuration(generator);
2433
- }
2434
- const { calculatedDuration } = generator;
2435
- const resolvedDuration = calculatedDuration + repeatDelay;
2436
- const totalDuration = resolvedDuration * (repeat + 1) - repeatDelay;
2437
- return {
2438
- generator,
2439
- mirroredGenerator,
2440
- mapPercentToKeyframes,
2441
- calculatedDuration,
2442
- resolvedDuration,
2443
- totalDuration
2444
- };
2445
- }
2446
- onPostResolved() {
2447
- const { autoplay = true } = this.options;
2448
- this.play();
2449
- if (this.pendingPlayState === "paused" || !autoplay) {
2450
- this.pause();
2451
- } else {
2452
- this.state = this.pendingPlayState;
2453
- }
2454
- }
2455
- tick(timestamp, sample = false) {
2456
- const { resolved } = this;
2457
- if (!resolved) {
2458
- const { keyframes: keyframes3 } = this.options;
2459
- return { done: true, value: keyframes3[keyframes3.length - 1] };
2460
- }
2461
- const { finalKeyframe, generator, mirroredGenerator, mapPercentToKeyframes, keyframes: keyframes2, calculatedDuration, totalDuration, resolvedDuration } = resolved;
2462
- if (this.startTime === null)
2463
- return generator.next(0);
2464
- const { delay, repeat, repeatType, repeatDelay, onUpdate } = this.options;
2465
- if (this.speed > 0) {
2466
- this.startTime = Math.min(this.startTime, timestamp);
2467
- } else if (this.speed < 0) {
2468
- this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime);
2469
- }
2470
- if (sample) {
2471
- this.currentTime = timestamp;
2472
- } else if (this.holdTime !== null) {
2473
- this.currentTime = this.holdTime;
2474
- } else {
2475
- this.currentTime = Math.round(timestamp - this.startTime) * this.speed;
2476
- }
2477
- const timeWithoutDelay = this.currentTime - delay * (this.speed >= 0 ? 1 : -1);
2478
- const isInDelayPhase = this.speed >= 0 ? timeWithoutDelay < 0 : timeWithoutDelay > totalDuration;
2479
- this.currentTime = Math.max(timeWithoutDelay, 0);
2480
- if (this.state === "finished" && this.holdTime === null) {
2481
- this.currentTime = totalDuration;
2482
- }
2483
- let elapsed = this.currentTime;
2484
- let frameGenerator = generator;
2485
- if (repeat) {
2486
- const progress2 = Math.min(this.currentTime, totalDuration) / resolvedDuration;
2487
- let currentIteration = Math.floor(progress2);
2488
- let iterationProgress = progress2 % 1;
2489
- if (!iterationProgress && progress2 >= 1) {
2490
- iterationProgress = 1;
2491
- }
2492
- iterationProgress === 1 && currentIteration--;
2493
- currentIteration = Math.min(currentIteration, repeat + 1);
2494
- const isOddIteration = Boolean(currentIteration % 2);
2495
- if (isOddIteration) {
2496
- if (repeatType === "reverse") {
2497
- iterationProgress = 1 - iterationProgress;
2498
- if (repeatDelay) {
2499
- iterationProgress -= repeatDelay / resolvedDuration;
2500
- }
2501
- } else if (repeatType === "mirror") {
2502
- frameGenerator = mirroredGenerator;
2503
- }
2504
- }
2505
- elapsed = clamp(0, 1, iterationProgress) * resolvedDuration;
2506
- }
2507
- const state = isInDelayPhase ? { done: false, value: keyframes2[0] } : frameGenerator.next(elapsed);
2508
- if (mapPercentToKeyframes) {
2509
- state.value = mapPercentToKeyframes(state.value);
2510
- }
2511
- let { done } = state;
2512
- if (!isInDelayPhase && calculatedDuration !== null) {
2513
- done = this.speed >= 0 ? this.currentTime >= totalDuration : this.currentTime <= 0;
2514
- }
2515
- const isAnimationFinished = this.holdTime === null && (this.state === "finished" || this.state === "running" && done);
2516
- if (isAnimationFinished && finalKeyframe !== void 0) {
2517
- state.value = getFinalKeyframe(keyframes2, this.options, finalKeyframe);
2518
- }
2519
- if (onUpdate) {
2520
- onUpdate(state.value);
2521
- }
2522
- if (isAnimationFinished) {
2523
- this.finish();
2524
- }
2525
- return state;
2526
- }
2527
- get duration() {
2528
- const { resolved } = this;
2529
- return resolved ? /* @__PURE__ */ millisecondsToSeconds(resolved.calculatedDuration) : 0;
2530
- }
2531
- get time() {
2532
- return /* @__PURE__ */ millisecondsToSeconds(this.currentTime);
2533
- }
2534
- set time(newTime) {
2535
- newTime = /* @__PURE__ */ secondsToMilliseconds(newTime);
2536
- this.currentTime = newTime;
2537
- if (this.holdTime !== null || this.speed === 0) {
2538
- this.holdTime = newTime;
2539
- } else if (this.driver) {
2540
- this.startTime = this.driver.now() - newTime / this.speed;
2541
- }
2542
- }
2543
- get speed() {
2544
- return this.playbackSpeed;
2545
- }
2546
- set speed(newSpeed) {
2547
- const hasChanged = this.playbackSpeed !== newSpeed;
2548
- this.playbackSpeed = newSpeed;
2549
- if (hasChanged) {
2550
- this.time = /* @__PURE__ */ millisecondsToSeconds(this.currentTime);
2551
- }
2552
- }
2553
- play() {
2554
- if (!this.resolver.isScheduled) {
2555
- this.resolver.resume();
2556
- }
2557
- if (!this._resolved) {
2558
- this.pendingPlayState = "running";
2559
- return;
2560
- }
2561
- if (this.isStopped)
2562
- return;
2563
- const { driver = frameloopDriver, onPlay, startTime } = this.options;
2564
- if (!this.driver) {
2565
- this.driver = driver((timestamp) => this.tick(timestamp));
2566
- }
2567
- onPlay && onPlay();
2568
- const now2 = this.driver.now();
2569
- if (this.holdTime !== null) {
2570
- this.startTime = now2 - this.holdTime;
2571
- } else if (!this.startTime) {
2572
- this.startTime = startTime !== null && startTime !== void 0 ? startTime : this.calcStartTime();
2573
- } else if (this.state === "finished") {
2574
- this.startTime = now2;
2575
- }
2576
- if (this.state === "finished") {
2577
- this.updateFinishedPromise();
2578
- }
2579
- this.cancelTime = this.startTime;
2580
- this.holdTime = null;
2581
- this.state = "running";
2582
- this.driver.start();
2583
- }
2584
- pause() {
2585
- var _a;
2586
- if (!this._resolved) {
2587
- this.pendingPlayState = "paused";
2588
- return;
2589
- }
2590
- this.state = "paused";
2591
- this.holdTime = (_a = this.currentTime) !== null && _a !== void 0 ? _a : 0;
2592
- }
2593
- complete() {
2594
- if (this.state !== "running") {
2595
- this.play();
2596
- }
2597
- this.pendingPlayState = this.state = "finished";
2598
- this.holdTime = null;
2599
- }
2600
- finish() {
2601
- this.teardown();
2602
- this.state = "finished";
2603
- const { onComplete } = this.options;
2604
- onComplete && onComplete();
2605
- }
2606
- cancel() {
2607
- if (this.cancelTime !== null) {
2608
- this.tick(this.cancelTime);
2609
- }
2610
- this.teardown();
2611
- this.updateFinishedPromise();
2612
- }
2613
- teardown() {
2614
- this.state = "idle";
2615
- this.stopDriver();
2616
- this.resolveFinishedPromise();
2617
- this.updateFinishedPromise();
2618
- this.startTime = this.cancelTime = null;
2619
- this.resolver.cancel();
2620
- }
2621
- stopDriver() {
2622
- if (!this.driver)
2623
- return;
2624
- this.driver.stop();
2625
- this.driver = void 0;
2626
- }
2627
- sample(time2) {
2628
- this.startTime = 0;
2629
- return this.tick(time2, true);
2630
- }
2631
- }
2632
- const acceleratedValues = /* @__PURE__ */ new Set([
2633
- "opacity",
2634
- "clipPath",
2635
- "filter",
2636
- "transform"
2637
- // TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved
2638
- // or until we implement support for linear() easing.
2639
- // "background-color"
2640
- ]);
2641
- function startWaapiAnimation(element, valueName, keyframes2, { delay = 0, duration = 300, repeat = 0, repeatType = "loop", ease: ease2 = "easeInOut", times } = {}) {
2642
- const keyframeOptions = { [valueName]: keyframes2 };
2643
- if (times)
2644
- keyframeOptions.offset = times;
2645
- const easing = mapEasingToNativeEasing(ease2, duration);
2646
- if (Array.isArray(easing))
2647
- keyframeOptions.easing = easing;
2648
- return element.animate(keyframeOptions, {
2649
- delay,
2650
- duration,
2651
- easing: !Array.isArray(easing) ? easing : "linear",
2652
- fill: "both",
2653
- iterations: repeat + 1,
2654
- direction: repeatType === "reverse" ? "alternate" : "normal"
2655
- });
2656
- }
2657
- const supportsWaapi = /* @__PURE__ */ memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
2658
- const sampleDelta = 10;
2659
- const maxDuration = 2e4;
2660
- function requiresPregeneratedKeyframes(options) {
2661
- return isGenerator(options.type) || options.type === "spring" || !isWaapiSupportedEasing(options.ease);
2662
- }
2663
- function pregenerateKeyframes(keyframes2, options) {
2664
- const sampleAnimation = new MainThreadAnimation({
2665
- ...options,
2666
- keyframes: keyframes2,
2667
- repeat: 0,
2668
- delay: 0,
2669
- isGenerator: true
2670
- });
2671
- let state = { done: false, value: keyframes2[0] };
2672
- const pregeneratedKeyframes = [];
2673
- let t = 0;
2674
- while (!state.done && t < maxDuration) {
2675
- state = sampleAnimation.sample(t);
2676
- pregeneratedKeyframes.push(state.value);
2677
- t += sampleDelta;
2678
- }
2679
- return {
2680
- times: void 0,
2681
- keyframes: pregeneratedKeyframes,
2682
- duration: t - sampleDelta,
2683
- ease: "linear"
2684
- };
2685
- }
2686
- const unsupportedEasingFunctions = {
2687
- anticipate,
2688
- backInOut,
2689
- circInOut
2690
- };
2691
- function isUnsupportedEase(key) {
2692
- return key in unsupportedEasingFunctions;
2693
- }
2694
- class AcceleratedAnimation extends BaseAnimation {
2695
- constructor(options) {
2696
- super(options);
2697
- const { name, motionValue: motionValue2, element, keyframes: keyframes2 } = this.options;
2698
- this.resolver = new DOMKeyframesResolver(keyframes2, (resolvedKeyframes, finalKeyframe) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe), name, motionValue2, element);
2699
- this.resolver.scheduleResolve();
2700
- }
2701
- initPlayback(keyframes2, finalKeyframe) {
2702
- let { duration = 300, times, ease: ease2, type, motionValue: motionValue2, name, startTime } = this.options;
2703
- if (!motionValue2.owner || !motionValue2.owner.current) {
2704
- return false;
2705
- }
2706
- if (typeof ease2 === "string" && supportsLinearEasing() && isUnsupportedEase(ease2)) {
2707
- ease2 = unsupportedEasingFunctions[ease2];
2708
- }
2709
- if (requiresPregeneratedKeyframes(this.options)) {
2710
- const { onComplete, onUpdate, motionValue: motionValue3, element, ...options } = this.options;
2711
- const pregeneratedAnimation = pregenerateKeyframes(keyframes2, options);
2712
- keyframes2 = pregeneratedAnimation.keyframes;
2713
- if (keyframes2.length === 1) {
2714
- keyframes2[1] = keyframes2[0];
2715
- }
2716
- duration = pregeneratedAnimation.duration;
2717
- times = pregeneratedAnimation.times;
2718
- ease2 = pregeneratedAnimation.ease;
2719
- type = "keyframes";
2720
- }
2721
- const animation = startWaapiAnimation(motionValue2.owner.current, name, keyframes2, { ...this.options, duration, times, ease: ease2 });
2722
- animation.startTime = startTime !== null && startTime !== void 0 ? startTime : this.calcStartTime();
2723
- if (this.pendingTimeline) {
2724
- attachTimeline(animation, this.pendingTimeline);
2725
- this.pendingTimeline = void 0;
2726
- } else {
2727
- animation.onfinish = () => {
2728
- const { onComplete } = this.options;
2729
- motionValue2.set(getFinalKeyframe(keyframes2, this.options, finalKeyframe));
2730
- onComplete && onComplete();
2731
- this.cancel();
2732
- this.resolveFinishedPromise();
2733
- };
2734
- }
2735
- return {
2736
- animation,
2737
- duration,
2738
- times,
2739
- type,
2740
- ease: ease2,
2741
- keyframes: keyframes2
2742
- };
2743
- }
2744
- get duration() {
2745
- const { resolved } = this;
2746
- if (!resolved)
2747
- return 0;
2748
- const { duration } = resolved;
2749
- return /* @__PURE__ */ millisecondsToSeconds(duration);
2750
- }
2751
- get time() {
2752
- const { resolved } = this;
2753
- if (!resolved)
2754
- return 0;
2755
- const { animation } = resolved;
2756
- return /* @__PURE__ */ millisecondsToSeconds(animation.currentTime || 0);
2757
- }
2758
- set time(newTime) {
2759
- const { resolved } = this;
2760
- if (!resolved)
2761
- return;
2762
- const { animation } = resolved;
2763
- animation.currentTime = /* @__PURE__ */ secondsToMilliseconds(newTime);
2764
- }
2765
- get speed() {
2766
- const { resolved } = this;
2767
- if (!resolved)
2768
- return 1;
2769
- const { animation } = resolved;
2770
- return animation.playbackRate;
2771
- }
2772
- set speed(newSpeed) {
2773
- const { resolved } = this;
2774
- if (!resolved)
2775
- return;
2776
- const { animation } = resolved;
2777
- animation.playbackRate = newSpeed;
2778
- }
2779
- get state() {
2780
- const { resolved } = this;
2781
- if (!resolved)
2782
- return "idle";
2783
- const { animation } = resolved;
2784
- return animation.playState;
2785
- }
2786
- get startTime() {
2787
- const { resolved } = this;
2788
- if (!resolved)
2789
- return null;
2790
- const { animation } = resolved;
2791
- return animation.startTime;
2792
- }
2793
- /**
2794
- * Replace the default DocumentTimeline with another AnimationTimeline.
2795
- * Currently used for scroll animations.
2796
- */
2797
- attachTimeline(timeline) {
2798
- if (!this._resolved) {
2799
- this.pendingTimeline = timeline;
2800
- } else {
2801
- const { resolved } = this;
2802
- if (!resolved)
2803
- return noop;
2804
- const { animation } = resolved;
2805
- attachTimeline(animation, timeline);
2806
- }
2807
- return noop;
2808
- }
2809
- play() {
2810
- if (this.isStopped)
2811
- return;
2812
- const { resolved } = this;
2813
- if (!resolved)
2814
- return;
2815
- const { animation } = resolved;
2816
- if (animation.playState === "finished") {
2817
- this.updateFinishedPromise();
2818
- }
2819
- animation.play();
2820
- }
2821
- pause() {
2822
- const { resolved } = this;
2823
- if (!resolved)
2824
- return;
2825
- const { animation } = resolved;
2826
- animation.pause();
2827
- }
2828
- stop() {
2829
- this.resolver.cancel();
2830
- this.isStopped = true;
2831
- if (this.state === "idle")
2832
- return;
2833
- this.resolveFinishedPromise();
2834
- this.updateFinishedPromise();
2835
- const { resolved } = this;
2836
- if (!resolved)
2837
- return;
2838
- const { animation, keyframes: keyframes2, duration, type, ease: ease2, times } = resolved;
2839
- if (animation.playState === "idle" || animation.playState === "finished") {
2840
- return;
2841
- }
2842
- if (this.time) {
2843
- const { motionValue: motionValue2, onUpdate, onComplete, element, ...options } = this.options;
2844
- const sampleAnimation = new MainThreadAnimation({
2845
- ...options,
2846
- keyframes: keyframes2,
2847
- duration,
2848
- type,
2849
- ease: ease2,
2850
- times,
2851
- isGenerator: true
2852
- });
2853
- const sampleTime = /* @__PURE__ */ secondsToMilliseconds(this.time);
2854
- motionValue2.setWithVelocity(sampleAnimation.sample(sampleTime - sampleDelta).value, sampleAnimation.sample(sampleTime).value, sampleDelta);
2855
- }
2856
- const { onStop } = this.options;
2857
- onStop && onStop();
2858
- this.cancel();
2859
- }
2860
- complete() {
2861
- const { resolved } = this;
2862
- if (!resolved)
2863
- return;
2864
- resolved.animation.finish();
2865
- }
2866
- cancel() {
2867
- const { resolved } = this;
2868
- if (!resolved)
2869
- return;
2870
- resolved.animation.cancel();
2871
- }
2872
- static supports(options) {
2873
- const { motionValue: motionValue2, name, repeatDelay, repeatType, damping, type } = options;
2874
- if (!motionValue2 || !motionValue2.owner || !(motionValue2.owner.current instanceof HTMLElement)) {
2875
- return false;
2876
- }
2877
- const { onUpdate, transformTemplate } = motionValue2.owner.getProps();
2878
- return supportsWaapi() && name && acceleratedValues.has(name) && /**
2879
- * If we're outputting values to onUpdate then we can't use WAAPI as there's
2880
- * no way to read the value from WAAPI every frame.
2881
- */
2882
- !onUpdate && !transformTemplate && !repeatDelay && repeatType !== "mirror" && damping !== 0 && type !== "inertia";
2883
- }
2884
- }
2885
- const underDampedSpring = {
2886
- type: "spring",
2887
- stiffness: 500,
2888
- damping: 25,
2889
- restSpeed: 10
2890
- };
2891
- const criticallyDampedSpring = (target) => ({
2892
- type: "spring",
2893
- stiffness: 550,
2894
- damping: target === 0 ? 2 * Math.sqrt(550) : 30,
2895
- restSpeed: 10
2896
- });
2897
- const keyframesTransition = {
2898
- type: "keyframes",
2899
- duration: 0.8
2900
- };
2901
- const ease = {
2902
- type: "keyframes",
2903
- ease: [0.25, 0.1, 0.35, 1],
2904
- duration: 0.3
2905
- };
2906
- const getDefaultTransition = (valueKey, { keyframes: keyframes2 }) => {
2907
- if (keyframes2.length > 2) {
2908
- return keyframesTransition;
2909
- } else if (transformProps.has(valueKey)) {
2910
- return valueKey.startsWith("scale") ? criticallyDampedSpring(keyframes2[1]) : underDampedSpring;
2911
- }
2912
- return ease;
2913
- };
2914
- function isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) {
2915
- return !!Object.keys(transition).length;
2916
- }
2917
- const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => {
2918
- const valueTransition = getValueTransition$1(transition, name) || {};
2919
- const delay = valueTransition.delay || transition.delay || 0;
2920
- let { elapsed = 0 } = transition;
2921
- elapsed = elapsed - /* @__PURE__ */ secondsToMilliseconds(delay);
2922
- let options = {
2923
- keyframes: Array.isArray(target) ? target : [null, target],
2924
- ease: "easeOut",
2925
- velocity: value.getVelocity(),
2926
- ...valueTransition,
2927
- delay: -elapsed,
2928
- onUpdate: (v) => {
2929
- value.set(v);
2930
- valueTransition.onUpdate && valueTransition.onUpdate(v);
2931
- },
2932
- onComplete: () => {
2933
- onComplete();
2934
- valueTransition.onComplete && valueTransition.onComplete();
2935
- },
2936
- name,
2937
- motionValue: value,
2938
- element: isHandoff ? void 0 : element
2939
- };
2940
- if (!isTransitionDefined(valueTransition)) {
2941
- options = {
2942
- ...options,
2943
- ...getDefaultTransition(name, options)
2944
- };
2945
- }
2946
- if (options.duration) {
2947
- options.duration = /* @__PURE__ */ secondsToMilliseconds(options.duration);
2948
- }
2949
- if (options.repeatDelay) {
2950
- options.repeatDelay = /* @__PURE__ */ secondsToMilliseconds(options.repeatDelay);
2951
- }
2952
- if (options.from !== void 0) {
2953
- options.keyframes[0] = options.from;
2954
- }
2955
- let shouldSkip = false;
2956
- if (options.type === false || options.duration === 0 && !options.repeatDelay) {
2957
- options.duration = 0;
2958
- if (options.delay === 0) {
2959
- shouldSkip = true;
2960
- }
2961
- }
2962
- if (shouldSkip && !isHandoff && value.get() !== void 0) {
2963
- const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition);
2964
- if (finalKeyframe !== void 0) {
2965
- frame.update(() => {
2966
- options.onUpdate(finalKeyframe);
2967
- options.onComplete();
2968
- });
2969
- return new GroupPlaybackControls([]);
2970
- }
2971
- }
2972
- if (!isHandoff && AcceleratedAnimation.supports(options)) {
2973
- return new AcceleratedAnimation(options);
2974
- } else {
2975
- return new MainThreadAnimation(options);
2976
- }
2977
- };
2978
- function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) {
2979
- const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;
2980
- needsAnimating[key] = false;
2981
- return shouldBlock;
2982
- }
2983
- function animateTarget(visualElement, targetAndTransition, { delay = 0, transitionOverride, type } = {}) {
2984
- var _a;
2985
- let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = targetAndTransition;
2986
- if (transitionOverride)
2987
- transition = transitionOverride;
2988
- const animations = [];
2989
- const animationTypeState = type && visualElement.animationState && visualElement.animationState.getState()[type];
2990
- for (const key in target) {
2991
- const value = visualElement.getValue(key, (_a = visualElement.latestValues[key]) !== null && _a !== void 0 ? _a : null);
2992
- const valueTarget = target[key];
2993
- if (valueTarget === void 0 || animationTypeState && shouldBlockAnimation(animationTypeState, key)) {
2994
- continue;
2995
- }
2996
- const valueTransition = {
2997
- delay,
2998
- ...getValueTransition$1(transition || {}, key)
2999
- };
3000
- let isHandoff = false;
3001
- if (window.MotionHandoffAnimation) {
3002
- const appearId = getOptimisedAppearId(visualElement);
3003
- if (appearId) {
3004
- const startTime = window.MotionHandoffAnimation(appearId, key, frame);
3005
- if (startTime !== null) {
3006
- valueTransition.startTime = startTime;
3007
- isHandoff = true;
3008
- }
3009
- }
3010
- }
3011
- addValueToWillChange(visualElement, key);
3012
- value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && positionalKeys.has(key) ? { type: false } : valueTransition, visualElement, isHandoff));
3013
- const animation = value.animation;
3014
- if (animation) {
3015
- animations.push(animation);
3016
- }
3017
- }
3018
- if (transitionEnd) {
3019
- Promise.all(animations).then(() => {
3020
- frame.update(() => {
3021
- transitionEnd && setTarget(visualElement, transitionEnd);
3022
- });
3023
- });
3024
- }
3025
- return animations;
3026
- }
3027
- const createAxis = () => ({ min: 0, max: 0 });
3028
- const createBox = () => ({
3029
- x: createAxis(),
3030
- y: createAxis()
3031
- });
3032
- function convertBoundingBoxToBox({ top, left, right, bottom }) {
3033
- return {
3034
- x: { min: left, max: right },
3035
- y: { min: top, max: bottom }
3036
- };
3037
- }
3038
- function transformBoxPoints(point, transformPoint) {
3039
- if (!transformPoint)
3040
- return point;
3041
- const topLeft = transformPoint({ x: point.left, y: point.top });
3042
- const bottomRight = transformPoint({ x: point.right, y: point.bottom });
3043
- return {
3044
- top: topLeft.y,
3045
- left: topLeft.x,
3046
- bottom: bottomRight.y,
3047
- right: bottomRight.x
3048
- };
3049
- }
3050
- function measureViewportBox(instance, transformPoint) {
3051
- return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint));
3052
- }
3053
- function animateSingleValue(value, keyframes2, options) {
3054
- const motionValue$1 = isMotionValue(value) ? value : motionValue(value);
3055
- motionValue$1.start(animateMotionValue("", motionValue$1, keyframes2, options));
3056
- return motionValue$1.animation;
3057
- }
3058
- function isSVGElement(element) {
3059
- return element instanceof SVGElement && element.tagName !== "svg";
3060
- }
3061
- function resolveElements(elementOrSelector, scope, selectorCache) {
3062
- var _a;
3063
- if (elementOrSelector instanceof Element) {
3064
- return [elementOrSelector];
3065
- } else if (typeof elementOrSelector === "string") {
3066
- let root = document;
3067
- if (scope) {
3068
- root = scope.current;
3069
- }
3070
- const elements = (_a = selectorCache === null || selectorCache === void 0 ? void 0 : selectorCache[elementOrSelector]) !== null && _a !== void 0 ? _a : root.querySelectorAll(elementOrSelector);
3071
- return elements ? Array.from(elements) : [];
3072
- }
3073
- return Array.from(elementOrSelector);
3074
- }
3075
- const prefersReducedMotion = { current: null };
3076
- const hasReducedMotionListener = { current: false };
3077
- function initPrefersReducedMotion() {
3078
- hasReducedMotionListener.current = true;
3079
- if (!isBrowser)
3080
- return;
3081
- if (window.matchMedia) {
3082
- const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)");
3083
- const setReducedMotionPreferences = () => prefersReducedMotion.current = motionMediaQuery.matches;
3084
- motionMediaQuery.addListener(setReducedMotionPreferences);
3085
- setReducedMotionPreferences();
3086
- } else {
3087
- prefersReducedMotion.current = false;
3088
- }
3089
- }
3090
- const valueTypes = [...dimensionValueTypes, color, complex];
3091
- const findValueType = (v) => valueTypes.find(testValueType(v));
3092
- const visualElementStore = /* @__PURE__ */ new WeakMap();
3093
- function updateMotionValuesFromProps(element, next, prev) {
3094
- for (const key in next) {
3095
- const nextValue = next[key];
3096
- const prevValue = prev[key];
3097
- if (isMotionValue(nextValue)) {
3098
- element.addValue(key, nextValue);
3099
- if (process.env.NODE_ENV === "development") {
3100
- warnOnce(nextValue.version === "11.18.2", `Attempting to mix Motion versions ${nextValue.version} with 11.18.2 may not work as expected.`);
3101
- }
3102
- } else if (isMotionValue(prevValue)) {
3103
- element.addValue(key, motionValue(nextValue, { owner: element }));
3104
- } else if (prevValue !== nextValue) {
3105
- if (element.hasValue(key)) {
3106
- const existingValue = element.getValue(key);
3107
- if (existingValue.liveStyle === true) {
3108
- existingValue.jump(nextValue);
3109
- } else if (!existingValue.hasAnimated) {
3110
- existingValue.set(nextValue);
3111
- }
3112
- } else {
3113
- const latestValue = element.getStaticValue(key);
3114
- element.addValue(key, motionValue(latestValue !== void 0 ? latestValue : nextValue, { owner: element }));
3115
- }
3116
- }
3117
- }
3118
- for (const key in prev) {
3119
- if (next[key] === void 0)
3120
- element.removeValue(key);
3121
- }
3122
- return next;
3123
- }
3124
- const propEventHandlers = [
3125
- "AnimationStart",
3126
- "AnimationComplete",
3127
- "Update",
3128
- "BeforeLayoutMeasure",
3129
- "LayoutMeasure",
3130
- "LayoutAnimationStart",
3131
- "LayoutAnimationComplete"
3132
- ];
3133
- class VisualElement {
3134
- /**
3135
- * This method takes React props and returns found MotionValues. For example, HTML
3136
- * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays.
3137
- *
3138
- * This isn't an abstract method as it needs calling in the constructor, but it is
3139
- * intended to be one.
3140
- */
3141
- scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) {
3142
- return {};
3143
- }
3144
- constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState }, options = {}) {
3145
- this.current = null;
3146
- this.children = /* @__PURE__ */ new Set();
3147
- this.isVariantNode = false;
3148
- this.isControllingVariants = false;
3149
- this.shouldReduceMotion = null;
3150
- this.values = /* @__PURE__ */ new Map();
3151
- this.KeyframeResolver = KeyframeResolver;
3152
- this.features = {};
3153
- this.valueSubscriptions = /* @__PURE__ */ new Map();
3154
- this.prevMotionValues = {};
3155
- this.events = {};
3156
- this.propEventSubscriptions = {};
3157
- this.notifyUpdate = () => this.notify("Update", this.latestValues);
3158
- this.render = () => {
3159
- if (!this.current)
3160
- return;
3161
- this.triggerBuild();
3162
- this.renderInstance(this.current, this.renderState, this.props.style, this.projection);
3163
- };
3164
- this.renderScheduledAt = 0;
3165
- this.scheduleRender = () => {
3166
- const now2 = time.now();
3167
- if (this.renderScheduledAt < now2) {
3168
- this.renderScheduledAt = now2;
3169
- frame.render(this.render, false, true);
3170
- }
3171
- };
3172
- const { latestValues, renderState, onUpdate } = visualState;
3173
- this.onUpdate = onUpdate;
3174
- this.latestValues = latestValues;
3175
- this.baseTarget = { ...latestValues };
3176
- this.initialValues = props.initial ? { ...latestValues } : {};
3177
- this.renderState = renderState;
3178
- this.parent = parent;
3179
- this.props = props;
3180
- this.presenceContext = presenceContext;
3181
- this.depth = parent ? parent.depth + 1 : 0;
3182
- this.reducedMotionConfig = reducedMotionConfig;
3183
- this.options = options;
3184
- this.blockInitialAnimation = Boolean(blockInitialAnimation);
3185
- this.isControllingVariants = isControllingVariants(props);
3186
- this.isVariantNode = isVariantNode(props);
3187
- if (this.isVariantNode) {
3188
- this.variantChildren = /* @__PURE__ */ new Set();
3189
- }
3190
- this.manuallyAnimateOnMount = Boolean(parent && parent.current);
3191
- const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {}, this);
3192
- for (const key in initialMotionValues) {
3193
- const value = initialMotionValues[key];
3194
- if (latestValues[key] !== void 0 && isMotionValue(value)) {
3195
- value.set(latestValues[key], false);
3196
- }
3197
- }
3198
- }
3199
- mount(instance) {
3200
- this.current = instance;
3201
- visualElementStore.set(instance, this);
3202
- if (this.projection && !this.projection.instance) {
3203
- this.projection.mount(instance);
3204
- }
3205
- if (this.parent && this.isVariantNode && !this.isControllingVariants) {
3206
- this.removeFromVariantTree = this.parent.addVariantChild(this);
3207
- }
3208
- this.values.forEach((value, key) => this.bindToMotionValue(key, value));
3209
- if (!hasReducedMotionListener.current) {
3210
- initPrefersReducedMotion();
3211
- }
3212
- this.shouldReduceMotion = this.reducedMotionConfig === "never" ? false : this.reducedMotionConfig === "always" ? true : prefersReducedMotion.current;
3213
- if (process.env.NODE_ENV !== "production") {
3214
- warnOnce(this.shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.");
3215
- }
3216
- if (this.parent)
3217
- this.parent.children.add(this);
3218
- this.update(this.props, this.presenceContext);
3219
- }
3220
- unmount() {
3221
- visualElementStore.delete(this.current);
3222
- this.projection && this.projection.unmount();
3223
- cancelFrame(this.notifyUpdate);
3224
- cancelFrame(this.render);
3225
- this.valueSubscriptions.forEach((remove) => remove());
3226
- this.valueSubscriptions.clear();
3227
- this.removeFromVariantTree && this.removeFromVariantTree();
3228
- this.parent && this.parent.children.delete(this);
3229
- for (const key in this.events) {
3230
- this.events[key].clear();
3231
- }
3232
- for (const key in this.features) {
3233
- const feature = this.features[key];
3234
- if (feature) {
3235
- feature.unmount();
3236
- feature.isMounted = false;
3237
- }
3238
- }
3239
- this.current = null;
3240
- }
3241
- bindToMotionValue(key, value) {
3242
- if (this.valueSubscriptions.has(key)) {
3243
- this.valueSubscriptions.get(key)();
3244
- }
3245
- const valueIsTransform = transformProps.has(key);
3246
- const removeOnChange = value.on("change", (latestValue) => {
3247
- this.latestValues[key] = latestValue;
3248
- this.props.onUpdate && frame.preRender(this.notifyUpdate);
3249
- if (valueIsTransform && this.projection) {
3250
- this.projection.isTransformDirty = true;
3251
- }
3252
- });
3253
- const removeOnRenderRequest = value.on("renderRequest", this.scheduleRender);
3254
- let removeSyncCheck;
3255
- if (window.MotionCheckAppearSync) {
3256
- removeSyncCheck = window.MotionCheckAppearSync(this, key, value);
3257
- }
3258
- this.valueSubscriptions.set(key, () => {
3259
- removeOnChange();
3260
- removeOnRenderRequest();
3261
- if (removeSyncCheck)
3262
- removeSyncCheck();
3263
- if (value.owner)
3264
- value.stop();
3265
- });
3266
- }
3267
- sortNodePosition(other) {
3268
- if (!this.current || !this.sortInstanceNodePosition || this.type !== other.type) {
3269
- return 0;
3270
- }
3271
- return this.sortInstanceNodePosition(this.current, other.current);
3272
- }
3273
- updateFeatures() {
3274
- let key = "animation";
3275
- for (key in featureDefinitions) {
3276
- const featureDefinition = featureDefinitions[key];
3277
- if (!featureDefinition)
3278
- continue;
3279
- const { isEnabled, Feature: FeatureConstructor } = featureDefinition;
3280
- if (!this.features[key] && FeatureConstructor && isEnabled(this.props)) {
3281
- this.features[key] = new FeatureConstructor(this);
3282
- }
3283
- if (this.features[key]) {
3284
- const feature = this.features[key];
3285
- if (feature.isMounted) {
3286
- feature.update();
3287
- } else {
3288
- feature.mount();
3289
- feature.isMounted = true;
3290
- }
3291
- }
3292
- }
3293
- }
3294
- triggerBuild() {
3295
- this.build(this.renderState, this.latestValues, this.props);
3296
- }
3297
- /**
3298
- * Measure the current viewport box with or without transforms.
3299
- * Only measures axis-aligned boxes, rotate and skew must be manually
3300
- * removed with a re-render to work.
3301
- */
3302
- measureViewportBox() {
3303
- return this.current ? this.measureInstanceViewportBox(this.current, this.props) : createBox();
3304
- }
3305
- getStaticValue(key) {
3306
- return this.latestValues[key];
3307
- }
3308
- setStaticValue(key, value) {
3309
- this.latestValues[key] = value;
3310
- }
3311
- /**
3312
- * Update the provided props. Ensure any newly-added motion values are
3313
- * added to our map, old ones removed, and listeners updated.
3314
- */
3315
- update(props, presenceContext) {
3316
- if (props.transformTemplate || this.props.transformTemplate) {
3317
- this.scheduleRender();
3318
- }
3319
- this.prevProps = this.props;
3320
- this.props = props;
3321
- this.prevPresenceContext = this.presenceContext;
3322
- this.presenceContext = presenceContext;
3323
- for (let i = 0; i < propEventHandlers.length; i++) {
3324
- const key = propEventHandlers[i];
3325
- if (this.propEventSubscriptions[key]) {
3326
- this.propEventSubscriptions[key]();
3327
- delete this.propEventSubscriptions[key];
3328
- }
3329
- const listenerName = "on" + key;
3330
- const listener = props[listenerName];
3331
- if (listener) {
3332
- this.propEventSubscriptions[key] = this.on(key, listener);
3333
- }
3334
- }
3335
- this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps, this), this.prevMotionValues);
3336
- if (this.handleChildMotionValue) {
3337
- this.handleChildMotionValue();
3338
- }
3339
- this.onUpdate && this.onUpdate(this);
3340
- }
3341
- getProps() {
3342
- return this.props;
3343
- }
3344
- /**
3345
- * Returns the variant definition with a given name.
3346
- */
3347
- getVariant(name) {
3348
- return this.props.variants ? this.props.variants[name] : void 0;
3349
- }
3350
- /**
3351
- * Returns the defined default transition on this component.
3352
- */
3353
- getDefaultTransition() {
3354
- return this.props.transition;
3355
- }
3356
- getTransformPagePoint() {
3357
- return this.props.transformPagePoint;
3358
- }
3359
- getClosestVariantNode() {
3360
- return this.isVariantNode ? this : this.parent ? this.parent.getClosestVariantNode() : void 0;
3361
- }
3362
- /**
3363
- * Add a child visual element to our set of children.
3364
- */
3365
- addVariantChild(child) {
3366
- const closestVariantNode = this.getClosestVariantNode();
3367
- if (closestVariantNode) {
3368
- closestVariantNode.variantChildren && closestVariantNode.variantChildren.add(child);
3369
- return () => closestVariantNode.variantChildren.delete(child);
3370
- }
3371
- }
3372
- /**
3373
- * Add a motion value and bind it to this visual element.
3374
- */
3375
- addValue(key, value) {
3376
- const existingValue = this.values.get(key);
3377
- if (value !== existingValue) {
3378
- if (existingValue)
3379
- this.removeValue(key);
3380
- this.bindToMotionValue(key, value);
3381
- this.values.set(key, value);
3382
- this.latestValues[key] = value.get();
3383
- }
3384
- }
3385
- /**
3386
- * Remove a motion value and unbind any active subscriptions.
3387
- */
3388
- removeValue(key) {
3389
- this.values.delete(key);
3390
- const unsubscribe = this.valueSubscriptions.get(key);
3391
- if (unsubscribe) {
3392
- unsubscribe();
3393
- this.valueSubscriptions.delete(key);
3394
- }
3395
- delete this.latestValues[key];
3396
- this.removeValueFromRenderState(key, this.renderState);
3397
- }
3398
- /**
3399
- * Check whether we have a motion value for this key
3400
- */
3401
- hasValue(key) {
3402
- return this.values.has(key);
3403
- }
3404
- getValue(key, defaultValue) {
3405
- if (this.props.values && this.props.values[key]) {
3406
- return this.props.values[key];
3407
- }
3408
- let value = this.values.get(key);
3409
- if (value === void 0 && defaultValue !== void 0) {
3410
- value = motionValue(defaultValue === null ? void 0 : defaultValue, { owner: this });
3411
- this.addValue(key, value);
3412
- }
3413
- return value;
3414
- }
3415
- /**
3416
- * If we're trying to animate to a previously unencountered value,
3417
- * we need to check for it in our state and as a last resort read it
3418
- * directly from the instance (which might have performance implications).
3419
- */
3420
- readValue(key, target) {
3421
- var _a;
3422
- let value = this.latestValues[key] !== void 0 || !this.current ? this.latestValues[key] : (_a = this.getBaseTargetFromProps(this.props, key)) !== null && _a !== void 0 ? _a : this.readValueFromInstance(this.current, key, this.options);
3423
- if (value !== void 0 && value !== null) {
3424
- if (typeof value === "string" && (isNumericalString(value) || isZeroValueString(value))) {
3425
- value = parseFloat(value);
3426
- } else if (!findValueType(value) && complex.test(target)) {
3427
- value = getAnimatableNone(key, target);
3428
- }
3429
- this.setBaseTarget(key, isMotionValue(value) ? value.get() : value);
3430
- }
3431
- return isMotionValue(value) ? value.get() : value;
3432
- }
3433
- /**
3434
- * Set the base target to later animate back to. This is currently
3435
- * only hydrated on creation and when we first read a value.
3436
- */
3437
- setBaseTarget(key, value) {
3438
- this.baseTarget[key] = value;
3439
- }
3440
- /**
3441
- * Find the base target for a value thats been removed from all animation
3442
- * props.
3443
- */
3444
- getBaseTarget(key) {
3445
- var _a;
3446
- const { initial } = this.props;
3447
- let valueFromInitial;
3448
- if (typeof initial === "string" || typeof initial === "object") {
3449
- const variant = resolveVariantFromProps(this.props, initial, (_a = this.presenceContext) === null || _a === void 0 ? void 0 : _a.custom);
3450
- if (variant) {
3451
- valueFromInitial = variant[key];
3452
- }
3453
- }
3454
- if (initial && valueFromInitial !== void 0) {
3455
- return valueFromInitial;
3456
- }
3457
- const target = this.getBaseTargetFromProps(this.props, key);
3458
- if (target !== void 0 && !isMotionValue(target))
3459
- return target;
3460
- return this.initialValues[key] !== void 0 && valueFromInitial === void 0 ? void 0 : this.baseTarget[key];
3461
- }
3462
- on(eventName, callback) {
3463
- if (!this.events[eventName]) {
3464
- this.events[eventName] = new SubscriptionManager();
3465
- }
3466
- return this.events[eventName].add(callback);
3467
- }
3468
- notify(eventName, ...args) {
3469
- if (this.events[eventName]) {
3470
- this.events[eventName].notify(...args);
3471
- }
3472
- }
3473
- }
3474
- class DOMVisualElement extends VisualElement {
3475
- constructor() {
3476
- super(...arguments);
3477
- this.KeyframeResolver = DOMKeyframesResolver;
3478
- }
3479
- sortInstanceNodePosition(a, b) {
3480
- return a.compareDocumentPosition(b) & 2 ? 1 : -1;
3481
- }
3482
- getBaseTargetFromProps(props, key) {
3483
- return props.style ? props.style[key] : void 0;
3484
- }
3485
- removeValueFromRenderState(key, { vars, style }) {
3486
- delete vars[key];
3487
- delete style[key];
3488
- }
3489
- handleChildMotionValue() {
3490
- if (this.childSubscription) {
3491
- this.childSubscription();
3492
- delete this.childSubscription;
3493
- }
3494
- const { children } = this.props;
3495
- if (isMotionValue(children)) {
3496
- this.childSubscription = children.on("change", (latest) => {
3497
- if (this.current) {
3498
- this.current.textContent = `${latest}`;
3499
- }
3500
- });
3501
- }
3502
- }
3503
- }
3504
- function getComputedStyle(element) {
3505
- return window.getComputedStyle(element);
3506
- }
3507
- class HTMLVisualElement extends DOMVisualElement {
3508
- constructor() {
3509
- super(...arguments);
3510
- this.type = "html";
3511
- this.renderInstance = renderHTML;
3512
- }
3513
- readValueFromInstance(instance, key) {
3514
- if (transformProps.has(key)) {
3515
- const defaultType = getDefaultValueType(key);
3516
- return defaultType ? defaultType.default || 0 : 0;
3517
- } else {
3518
- const computedStyle = getComputedStyle(instance);
3519
- const value = (isCSSVariableName(key) ? computedStyle.getPropertyValue(key) : computedStyle[key]) || 0;
3520
- return typeof value === "string" ? value.trim() : value;
3521
- }
3522
- }
3523
- measureInstanceViewportBox(instance, { transformPagePoint }) {
3524
- return measureViewportBox(instance, transformPagePoint);
3525
- }
3526
- build(renderState, latestValues, props) {
3527
- buildHTMLStyles(renderState, latestValues, props.transformTemplate);
3528
- }
3529
- scrapeMotionValuesFromProps(props, prevProps, visualElement) {
3530
- return scrapeMotionValuesFromProps$1(props, prevProps, visualElement);
3531
- }
3532
- }
3533
- class SVGVisualElement extends DOMVisualElement {
3534
- constructor() {
3535
- super(...arguments);
3536
- this.type = "svg";
3537
- this.isSVGTag = false;
3538
- this.measureInstanceViewportBox = createBox;
3539
- }
3540
- getBaseTargetFromProps(props, key) {
3541
- return props[key];
3542
- }
3543
- readValueFromInstance(instance, key) {
3544
- if (transformProps.has(key)) {
3545
- const defaultType = getDefaultValueType(key);
3546
- return defaultType ? defaultType.default || 0 : 0;
3547
- }
3548
- key = !camelCaseAttributes.has(key) ? camelToDash(key) : key;
3549
- return instance.getAttribute(key);
3550
- }
3551
- scrapeMotionValuesFromProps(props, prevProps, visualElement) {
3552
- return scrapeMotionValuesFromProps(props, prevProps, visualElement);
3553
- }
3554
- build(renderState, latestValues, props) {
3555
- buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate);
3556
- }
3557
- renderInstance(instance, renderState, styleProp, projection) {
3558
- renderSVG(instance, renderState, styleProp, projection);
3559
- }
3560
- mount(instance) {
3561
- this.isSVGTag = isSVGTag(instance.tagName);
3562
- super.mount(instance);
3563
- }
3564
- }
1
+ import { c as calcGeneratorDuration, m as maxGeneratorDuration, a as millisecondsToSeconds, b as isEasingArray, r as resolveElements, d as mixNumber, e as removeItem, f as isMotionValue, g as defaultOffset, h as fillOffset, j as isGenerator, s as secondsToMilliseconds, k as invariant, p as progress, V as VisualElement, l as createBox, n as isSVGElement, S as SVGVisualElement, H as HTMLVisualElement, v as visualElementStore, o as animateSingleValue, q as animateTarget, t as spring, G as GroupPlaybackControls, u as useConstant } from "./SVGVisualElement.js";
2
+ import { useEffect } from "react";
3565
3
  function useUnmountEffect(callback) {
3566
4
  return useEffect(() => () => callback(), []);
3567
5
  }
3568
- function createGeneratorEasing(options, scale2 = 100, createGenerator) {
3569
- const generator = createGenerator({ ...options, keyframes: [0, scale2] });
6
+ function createGeneratorEasing(options, scale = 100, createGenerator) {
7
+ const generator = createGenerator({ ...options, keyframes: [0, scale] });
3570
8
  const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
3571
9
  return {
3572
10
  type: "keyframes",
3573
11
  ease: (progress2) => {
3574
- return generator.next(duration * progress2).value / scale2;
12
+ return generator.next(duration * progress2).value / scale;
3575
13
  },
3576
- duration: /* @__PURE__ */ millisecondsToSeconds(duration)
14
+ duration: millisecondsToSeconds(duration)
3577
15
  };
3578
16
  }
3579
17
  const wrap = (min, max, v) => {
@@ -3583,11 +21,11 @@ const wrap = (min, max, v) => {
3583
21
  function getEasingForSegment(easing, i) {
3584
22
  return isEasingArray(easing) ? easing[wrap(0, easing.length, i)] : easing;
3585
23
  }
3586
- function isDOMKeyframes(keyframes2) {
3587
- return typeof keyframes2 === "object" && !Array.isArray(keyframes2);
24
+ function isDOMKeyframes(keyframes) {
25
+ return typeof keyframes === "object" && !Array.isArray(keyframes);
3588
26
  }
3589
- function resolveSubjects(subject, keyframes2, scope, selectorCache) {
3590
- if (typeof subject === "string" && isDOMKeyframes(keyframes2)) {
27
+ function resolveSubjects(subject, keyframes, scope, selectorCache) {
28
+ if (typeof subject === "string" && isDOMKeyframes(keyframes)) {
3591
29
  return resolveElements(subject, scope, selectorCache);
3592
30
  } else if (subject instanceof NodeList) {
3593
31
  return Array.from(subject);
@@ -3621,12 +59,12 @@ function eraseKeyframes(sequence, startTime, endTime) {
3621
59
  }
3622
60
  }
3623
61
  }
3624
- function addKeyframes(sequence, keyframes2, easing, offset, startTime, endTime) {
62
+ function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) {
3625
63
  eraseKeyframes(sequence, startTime, endTime);
3626
- for (let i = 0; i < keyframes2.length; i++) {
64
+ for (let i = 0; i < keyframes.length; i++) {
3627
65
  sequence.push({
3628
- value: keyframes2[i],
3629
- at: mixNumber$1(startTime, endTime, offset[i]),
66
+ value: keyframes[i],
67
+ at: mixNumber(startTime, endTime, offset[i]),
3630
68
  easing: getEasingForSegment(easing, i)
3631
69
  });
3632
70
  }
@@ -3649,7 +87,7 @@ function compareByTime(a, b) {
3649
87
  }
3650
88
  const defaultSegmentEasing = "easeInOut";
3651
89
  const MAX_REPEAT = 20;
3652
- function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators2) {
90
+ function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators) {
3653
91
  const defaultDuration = defaultTransition.duration || 0.3;
3654
92
  const animationDefinitions = /* @__PURE__ */ new Map();
3655
93
  const sequences = /* @__PURE__ */ new Map();
@@ -3667,18 +105,18 @@ function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...seq
3667
105
  timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels));
3668
106
  continue;
3669
107
  }
3670
- let [subject, keyframes2, transition = {}] = segment;
108
+ let [subject, keyframes, transition = {}] = segment;
3671
109
  if (transition.at !== void 0) {
3672
110
  currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels);
3673
111
  }
3674
- let maxDuration2 = 0;
112
+ let maxDuration = 0;
3675
113
  const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numSubjects = 0) => {
3676
114
  const valueKeyframesAsList = keyframesAsList(valueKeyframes);
3677
115
  const { delay = 0, times = defaultOffset(valueKeyframesAsList), type = "keyframes", repeat, repeatType, repeatDelay = 0, ...remainingTransition } = valueTransition;
3678
- let { ease: ease2 = defaultTransition.ease || "easeOut", duration } = valueTransition;
116
+ let { ease = defaultTransition.ease || "easeOut", duration } = valueTransition;
3679
117
  const calculatedDelay = typeof delay === "function" ? delay(elementIndex, numSubjects) : delay;
3680
118
  const numKeyframes = valueKeyframesAsList.length;
3681
- const createGenerator = isGenerator(type) ? type : generators2 === null || generators2 === void 0 ? void 0 : generators2[type];
119
+ const createGenerator = isGenerator(type) ? type : generators === null || generators === void 0 ? void 0 : generators[type];
3682
120
  if (numKeyframes <= 2 && createGenerator) {
3683
121
  let absoluteDelta = 100;
3684
122
  if (numKeyframes === 2 && isNumberKeyframesArray(valueKeyframesAsList)) {
@@ -3687,10 +125,10 @@ function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...seq
3687
125
  }
3688
126
  const springTransition = { ...remainingTransition };
3689
127
  if (duration !== void 0) {
3690
- springTransition.duration = /* @__PURE__ */ secondsToMilliseconds(duration);
128
+ springTransition.duration = secondsToMilliseconds(duration);
3691
129
  }
3692
130
  const springEasing = createGeneratorEasing(springTransition, absoluteDelta, createGenerator);
3693
- ease2 = springEasing.ease;
131
+ ease = springEasing.ease;
3694
132
  duration = springEasing.duration;
3695
133
  }
3696
134
  duration !== null && duration !== void 0 ? duration : duration = defaultDuration;
@@ -3706,62 +144,62 @@ function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...seq
3706
144
  duration = calculateRepeatDuration(duration, repeat);
3707
145
  const originalKeyframes = [...valueKeyframesAsList];
3708
146
  const originalTimes = [...times];
3709
- ease2 = Array.isArray(ease2) ? [...ease2] : [ease2];
3710
- const originalEase = [...ease2];
147
+ ease = Array.isArray(ease) ? [...ease] : [ease];
148
+ const originalEase = [...ease];
3711
149
  for (let repeatIndex = 0; repeatIndex < repeat; repeatIndex++) {
3712
150
  valueKeyframesAsList.push(...originalKeyframes);
3713
151
  for (let keyframeIndex = 0; keyframeIndex < originalKeyframes.length; keyframeIndex++) {
3714
152
  times.push(originalTimes[keyframeIndex] + (repeatIndex + 1));
3715
- ease2.push(keyframeIndex === 0 ? "linear" : getEasingForSegment(originalEase, keyframeIndex - 1));
153
+ ease.push(keyframeIndex === 0 ? "linear" : getEasingForSegment(originalEase, keyframeIndex - 1));
3716
154
  }
3717
155
  }
3718
156
  normalizeTimes(times, repeat);
3719
157
  }
3720
158
  const targetTime = startTime + duration;
3721
- addKeyframes(valueSequence, valueKeyframesAsList, ease2, times, startTime, targetTime);
3722
- maxDuration2 = Math.max(calculatedDelay + duration, maxDuration2);
159
+ addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime);
160
+ maxDuration = Math.max(calculatedDelay + duration, maxDuration);
3723
161
  totalDuration = Math.max(targetTime, totalDuration);
3724
162
  };
3725
163
  if (isMotionValue(subject)) {
3726
164
  const subjectSequence = getSubjectSequence(subject, sequences);
3727
- resolveValueSequence(keyframes2, transition, getValueSequence("default", subjectSequence));
165
+ resolveValueSequence(keyframes, transition, getValueSequence("default", subjectSequence));
3728
166
  } else {
3729
- const subjects = resolveSubjects(subject, keyframes2, scope, elementCache);
167
+ const subjects = resolveSubjects(subject, keyframes, scope, elementCache);
3730
168
  const numSubjects = subjects.length;
3731
169
  for (let subjectIndex = 0; subjectIndex < numSubjects; subjectIndex++) {
3732
- keyframes2 = keyframes2;
170
+ keyframes = keyframes;
3733
171
  transition = transition;
3734
172
  const thisSubject = subjects[subjectIndex];
3735
173
  const subjectSequence = getSubjectSequence(thisSubject, sequences);
3736
- for (const key in keyframes2) {
3737
- resolveValueSequence(keyframes2[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects);
174
+ for (const key in keyframes) {
175
+ resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects);
3738
176
  }
3739
177
  }
3740
178
  }
3741
179
  prevTime = currentTime;
3742
- currentTime += maxDuration2;
180
+ currentTime += maxDuration;
3743
181
  }
3744
182
  sequences.forEach((valueSequences, element) => {
3745
183
  for (const key in valueSequences) {
3746
184
  const valueSequence = valueSequences[key];
3747
185
  valueSequence.sort(compareByTime);
3748
- const keyframes2 = [];
186
+ const keyframes = [];
3749
187
  const valueOffset = [];
3750
188
  const valueEasing = [];
3751
189
  for (let i = 0; i < valueSequence.length; i++) {
3752
190
  const { at, value, easing } = valueSequence[i];
3753
- keyframes2.push(value);
3754
- valueOffset.push(/* @__PURE__ */ progress(0, totalDuration, at));
191
+ keyframes.push(value);
192
+ valueOffset.push(progress(0, totalDuration, at));
3755
193
  valueEasing.push(easing || "easeOut");
3756
194
  }
3757
195
  if (valueOffset[0] !== 0) {
3758
196
  valueOffset.unshift(0);
3759
- keyframes2.unshift(keyframes2[0]);
197
+ keyframes.unshift(keyframes[0]);
3760
198
  valueEasing.unshift(defaultSegmentEasing);
3761
199
  }
3762
200
  if (valueOffset[valueOffset.length - 1] !== 1) {
3763
201
  valueOffset.push(1);
3764
- keyframes2.push(null);
202
+ keyframes.push(null);
3765
203
  }
3766
204
  if (!animationDefinitions.has(element)) {
3767
205
  animationDefinitions.set(element, {
@@ -3770,7 +208,7 @@ function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...seq
3770
208
  });
3771
209
  }
3772
210
  const definition = animationDefinitions.get(element);
3773
- definition.keyframes[key] = keyframes2;
211
+ definition.keyframes[key] = keyframes;
3774
212
  definition.transition[key] = {
3775
213
  ...defaultTransition,
3776
214
  duration: totalDuration,
@@ -3791,8 +229,8 @@ function getValueSequence(name, sequences) {
3791
229
  sequences[name] = [];
3792
230
  return sequences[name];
3793
231
  }
3794
- function keyframesAsList(keyframes2) {
3795
- return Array.isArray(keyframes2) ? keyframes2 : [keyframes2];
232
+ function keyframesAsList(keyframes) {
233
+ return Array.isArray(keyframes) ? keyframes : [keyframes];
3796
234
  }
3797
235
  function getValueTransition(transition, key) {
3798
236
  return transition && transition[key] ? {
@@ -3801,7 +239,7 @@ function getValueTransition(transition, key) {
3801
239
  } : { ...transition };
3802
240
  }
3803
241
  const isNumber = (keyframe) => typeof keyframe === "number";
3804
- const isNumberKeyframesArray = (keyframes2) => keyframes2.every(isNumber);
242
+ const isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber);
3805
243
  function isObjectKey(key, object) {
3806
244
  return key in object;
3807
245
  }
@@ -3872,15 +310,15 @@ function createObjectVisualElement(subject) {
3872
310
  node.mount(subject);
3873
311
  visualElementStore.set(subject, node);
3874
312
  }
3875
- function isSingleValue(subject, keyframes2) {
3876
- return isMotionValue(subject) || typeof subject === "number" || typeof subject === "string" && !isDOMKeyframes(keyframes2);
313
+ function isSingleValue(subject, keyframes) {
314
+ return isMotionValue(subject) || typeof subject === "number" || typeof subject === "string" && !isDOMKeyframes(keyframes);
3877
315
  }
3878
- function animateSubject(subject, keyframes2, options, scope) {
316
+ function animateSubject(subject, keyframes, options, scope) {
3879
317
  const animations = [];
3880
- if (isSingleValue(subject, keyframes2)) {
3881
- animations.push(animateSingleValue(subject, isDOMKeyframes(keyframes2) ? keyframes2.default || keyframes2 : keyframes2, options ? options.default || options : options));
318
+ if (isSingleValue(subject, keyframes)) {
319
+ animations.push(animateSingleValue(subject, isDOMKeyframes(keyframes) ? keyframes.default || keyframes : keyframes, options ? options.default || options : options));
3882
320
  } else {
3883
- const subjects = resolveSubjects(subject, keyframes2, scope);
321
+ const subjects = resolveSubjects(subject, keyframes, scope);
3884
322
  const numSubjects = subjects.length;
3885
323
  invariant(Boolean(numSubjects), "No valid elements provided.");
3886
324
  for (let i = 0; i < numSubjects; i++) {
@@ -3894,7 +332,7 @@ function animateSubject(subject, keyframes2, options, scope) {
3894
332
  if ("delay" in transition && typeof transition.delay === "function") {
3895
333
  transition.delay = transition.delay(i, numSubjects);
3896
334
  }
3897
- animations.push(...animateTarget(visualElement, { ...keyframes2, transition }, {}));
335
+ animations.push(...animateTarget(visualElement, { ...keyframes, transition }, {}));
3898
336
  }
3899
337
  }
3900
338
  return animations;
@@ -3902,8 +340,8 @@ function animateSubject(subject, keyframes2, options, scope) {
3902
340
  function animateSequence(sequence, options, scope) {
3903
341
  const animations = [];
3904
342
  const animationDefinitions = createAnimationsFromSequence(sequence, options, scope, { spring });
3905
- animationDefinitions.forEach(({ keyframes: keyframes2, transition }, subject) => {
3906
- animations.push(...animateSubject(subject, keyframes2, transition));
343
+ animationDefinitions.forEach(({ keyframes, transition }, subject) => {
344
+ animations.push(...animateSubject(subject, keyframes, transition));
3907
345
  });
3908
346
  return animations;
3909
347
  }
@@ -3939,8 +377,6 @@ function useAnimate() {
3939
377
  return [scope, animate];
3940
378
  }
3941
379
  export {
3942
- useConstant as a,
3943
- isBrowser as i,
3944
380
  useAnimate as u
3945
381
  };
3946
382
  //# sourceMappingURL=use-animate.js.map