Skip to content

armgit / anime

Public Imported from GitHub
0

JavaScript animation engine

4.2.0-beta.0

Julian Garnier36c932c01143
diff --git a/README.md b/README.md
index 81073147..527a2622 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,7 @@
</strong>
</p>
+
<p align="center">
<img alt="NPM Downloads" src="https://img.shields.io/npm/dm/animejs?style=flat-square&logo=npm">
<img alt="jsDelivr hits (npm)" src="https://img.shields.io/jsdelivr/npm/hm/animejs?style=flat-square&logo=jsdeliver">
@@ -45,6 +46,7 @@ Help the project become sustainable by sponsoring us on <a target="_blank" href=
<img align="center" src="./assets/sponsors/lambdatest-logomark-dark.png" width="150">
</picture>
</a>
+
<a target="_blank" href="https://inspatialapp.com/?ref=animejs">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./assets/sponsors/inspatial-logomark.png">
@@ -53,10 +55,12 @@ Help the project become sustainable by sponsoring us on <a target="_blank" href=
</a>
</p>
+
## Usage
Anime.js V4 works by importing ES modules like so:
+
<table>
<tr>
<td>
@@ -100,11 +104,11 @@ Then, execute the following scripts with `npm run <script>`.
| script | action |
| ------ | ------ |
-| `dev` | Watch any changes in `src/` and compiles the esm version to `lib/anime.esm.js` |
-| `dev-types` | Same as `dev`, but also run TypeScript and generate the `types/index.d.ts` file |
-| `build` | Generate types definition and compiles ESM / UMD / IIFE versions to `lib/` |
-| `test-browser` | Start a local server and start all browser related tests |
-| `test-node` | Start all Node related tests |
-| `open-examples` | Start a local server to browse the examples locally |
-
-© [Julian Garnier](http://juliangarnier.com) | [MIT License](LICENSE.md)
\ No newline at end of file
+| `dev` | Watches for changes in `src/**/*.js`, bundles the ESM version to `lib/` and creates type declarations in `types/` |
+| `dev:test` | Runs `dev` and `test:browser` concurrently |
+| `build` | Bundles ESM / UMD / CJS / IIFE versions to `lib/` and creates type declarations in `types/` |
+| `test:browser` | Starts a local server and runs all browser-related tests |
+| `test:node` | Starts Node-related tests |
+| `open:examples` | Starts a local server to browse the examples locally |
+
+© [Julian Garnier](http://juliangarnier.com) | [MIT License](LICENSE.md)
diff --git a/lib/anime.esm.js b/dist/bundles/anime.esm.js
similarity index 91%
rename from lib/anime.esm.js
rename to dist/bundles/anime.esm.js
index adfd272e..f713d730 100644
--- a/lib/anime.esm.js
+++ b/dist/bundles/anime.esm.js
@@ -1,13 +1,11 @@
/**
- * anime.js - ESM
- * @version v4.1.3
- * @author Julian Garnier
+ * Anime.js - ESM bundle
+ * @version v4.2.0
* @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
+ * @copyright 2025 - Julian Garnier
*/
-// Global types ////////////////////////////////////////////////////////////////
+// Global types
/**
* @typedef {Object} DefaultsParams
@@ -40,7 +38,7 @@
/** @typedef {Timer&JSAnimation&Timeline} CallbackArgument */
/** @typedef {Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */
-// Stagger types ///////////////////////////////////////////////////////////////
+// Stagger types
/**
* @template T
@@ -65,7 +63,21 @@
* @property {TweenModifier} [modifier]
*/
-// Eases types /////////////////////////////////////////////////////////////////
+// Targets types
+
+/** @typedef {HTMLElement|SVGElement} DOMTarget */
+/** @typedef {Record<String, any>} JSTarget */
+/** @typedef {DOMTarget|JSTarget} Target */
+/** @typedef {Target|NodeList|String} TargetSelector */
+/** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */
+/** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */
+/** @typedef {Array.<DOMTarget>} DOMTargetsArray */
+/** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */
+/** @typedef {Array.<JSTarget>} JSTargetsArray */
+/** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */
+/** @typedef {Array.<Target>} TargetsArray */
+
+// Eases types
/**
* @callback EasingFunction
@@ -77,23 +89,32 @@
* @typedef {('linear'|'linear(x1, x2 25%, x3)'|'in'|'out'|'inOut'|'inQuad'|'outQuad'|'inOutQuad'|'inCubic'|'outCubic'|'inOutCubic'|'inQuart'|'outQuart'|'inOutQuart'|'inQuint'|'outQuint'|'inOutQuint'|'inSine'|'outSine'|'inOutSine'|'inCirc'|'outCirc'|'inOutCirc'|'inExpo'|'outExpo'|'inOutExpo'|'inBounce'|'outBounce'|'inOutBounce'|'inBack'|'outBack'|'inOutBack'|'inElastic'|'outElastic'|'inOutElastic'|'irregular'|'cubicBezier'|'steps'|'in(p = 1.675)'|'out(p = 1.675)'|'inOut(p = 1.675)'|'inBack(overshoot = 1.70158)'|'outBack(overshoot = 1.70158)'|'inOutBack(overshoot = 1.70158)'|'inElastic(amplitude = 1, period = .3)'|'outElastic(amplitude = 1, period = .3)'|'inOutElastic(amplitude = 1, period = .3)'|'irregular(length = 10, randomness = 1)'|'cubicBezier(x1, y1, x2, y2)'|'steps(steps = 10)')} EaseStringParamNames
*/
+/**
+ * @callback PowerEasing
+ * @param {Number|String} [power=1.675]
+ * @return {EasingFunction}
+ */
+
+/**
+ * @callback BackEasing
+ * @param {Number|String} [overshoot=1.70158]
+ * @return {EasingFunction}
+ */
+
+/**
+ * @callback ElasticEasing
+ * @param {Number|String} [amplitude=1]
+ * @param {Number|String} [period=.3]
+ * @return {EasingFunction}
+ */
+
+/** @typedef {PowerEasing|BackEasing|ElasticEasing} EasingFunctionWithParams */
+
// A hack to get both ease names suggestions AND allow any strings
// https://github.com/microsoft/TypeScript/issues/29729#issuecomment-460346421
/** @typedef {(String & {})|EaseStringParamNames|EasingFunction|Spring} EasingParam */
-/** @typedef {HTMLElement|SVGElement} DOMTarget */
-/** @typedef {Record<String, any>} JSTarget */
-/** @typedef {DOMTarget|JSTarget} Target */
-/** @typedef {Target|NodeList|String} TargetSelector */
-/** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */
-/** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */
-/** @typedef {Array.<DOMTarget>} DOMTargetsArray */
-/** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */
-/** @typedef {Array.<JSTarget>} JSTargetsArray */
-/** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */
-/** @typedef {Array.<Target>} TargetsArray */
-
-// Spring types ////////////////////////////////////////////////////////////////
+// Spring types
/**
* @typedef {Object} SpringParams
@@ -103,7 +124,7 @@
* @property {Number} [velocity=0] - Initial velocity, default 0
*/
- // Callback types //////////////////////////////////////////////////////////////
+ // Callback types
/**
* @template T
@@ -130,7 +151,7 @@
* @property {Callback<T>} [onRender]
*/
-// Timer types /////////////////////////////////////////////////////////////////
+// Timer types
/**
* @typedef {Object} TimerOptions
@@ -146,13 +167,11 @@
* @property {Number} [playbackRate]
*/
-/**
-
/**
* @typedef {TimerOptions & TickableCallbacks<Timer>} TimerParams
*/
-// Tween types /////////////////////////////////////////////////////////////////
+// Tween types
/**
* @callback FunctionValue
@@ -223,7 +242,7 @@
/** @typedef {WeakMap.<Target, TweenLookups>} TweenReplaceLookups */
/** @typedef {Map.<Target, TweenLookups>} TweenAdditiveLookups */
-// JSAnimation types ///////////////////////////////////////////////////////////
+// JSAnimation types
/**
* @typedef {Number|String|FunctionValue} TweenParamValue
@@ -297,7 +316,7 @@
* @typedef {Record<String, TweenOptions | Callback<JSAnimation> | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & TickableCallbacks<JSAnimation> & RenderableCallbacks<JSAnimation>} AnimationParams
*/
-// Timeline types //////////////////////////////////////////////////////////////
+// Timeline types
/**
* Accepts:<br>
@@ -338,7 +357,7 @@
* @typedef {TimerOptions & TimelineOptions & TickableCallbacks<Timeline> & RenderableCallbacks<Timeline>} TimelineParams
*/
-// WAAPIAnimation types ////////////////////////////////////////////////////////
+// WAAPIAnimation types
/**
* @typedef {String|Number|Array<String>|Array<Number>} WAAPITweenValue
@@ -388,7 +407,7 @@
* @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | WAAPICallback | EasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams
*/
-// Animatable types ////////////////////////////////////////////////////////////
+// Animatable types
/**
* @callback AnimatablePropertySetter
@@ -424,7 +443,7 @@
* @typedef {Record<String, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions} AnimatableParams
*/
-// Scope types /////////////////////////////////////////////////////////////////
+// Scope types
/**
* @typedef {Object} ReactRef
@@ -467,7 +486,7 @@
* @return {ScopeCleanupCallback|void}
*/
-// Scroll types ////////////////////////////////////////////////////////////////
+// Scroll types
/**
* @typedef {String|Number} ScrollThresholdValue
@@ -512,7 +531,7 @@
* @property {Callback<ScrollObserver>} [onSyncComplete]
*/
-// Draggable types /////////////////////////////////////////////////////////////
+// Draggable types
/**
* @typedef {Object} DraggableAxisParam
@@ -561,10 +580,10 @@
* @property {Callback<Draggable>} [onAfterResize]
*/
-// Text types //////////////////////////////////////////////////////////////////
+// Text types
/**
- * @typedef {Object} splitTemplateParams
+ * @typedef {Object} SplitTemplateParams
* @property {false|String} [class]
* @property {Boolean|'hidden'|'clip'|'visible'|'scroll'|'auto'} [wrap]
* @property {Boolean|'top'|'right'|'bottom'|'left'|'center'} [clone]
@@ -582,15 +601,15 @@
/**
* @typedef {Object} TextSplitterParams
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [lines]
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [words]
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [chars]
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [lines]
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [words]
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [chars]
* @property {Boolean} [accessible]
* @property {Boolean} [includeSpaces]
* @property {Boolean} [debug]
*/
-// SVG types ///////////////////////////////////////////////////////////////////
+// SVG types
/**
* @typedef {SVGGeometryElement & {
@@ -715,7 +734,6 @@ const relativeValuesExecRgx = /(\*=|\+=|-=)/;
-
/** @type {DefaultsParams} */
const defaults = {
id: null,
@@ -760,13 +778,15 @@ const globals = {
tickThreshold: 200,
};
-const globalVersions = { version: '4.1.3', engine: null };
+const globalVersions = { version: '4.2.0', engine: null };
if (isBrowser) {
if (!win.AnimeJS) win.AnimeJS = [];
win.AnimeJS.push(globalVersions);
}
+
+
// Strings
/**
@@ -814,6 +834,30 @@ const isCol = a => isHex(a) || isRgb(a) || isHsl(a);
/**@param {any} a @return {Boolean} */
const isKey = a => !globals.defaults.hasOwnProperty(a);
+// SVG
+
+// Consider the following as CSS animation
+// CSS opacity animation has better default values (opacity: 1 instead of 0))
+// rotate is more commonly intended to be used as a transform
+const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
+
+/**
+ * @param {Target} el
+ * @param {String} propertyName
+ * @return {Boolean}
+ */
+const isValidSVGAttribute = (el, propertyName) => {
+ if (svgCssReservedProperties.includes(propertyName)) return false;
+ if (el.getAttribute(propertyName) || propertyName in el) {
+ if (propertyName === 'scale') { // Scale
+ const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
+ // Only consider scale as a valid SVG attribute on filter element
+ return elParentNode && elParentNode.tagName === 'filter';
+ }
+ return true;
+ }
+};
+
// Number
/**
@@ -841,21 +885,25 @@ const PI = Math.PI;
const _round = Math.round;
/**
- * @param {Number} v
- * @param {Number} min
- * @param {Number} max
+ * Clamps a value between min and max bounds
+ *
+ * @param {Number} v - Value to clamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
* @return {Number}
*/
-const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
+const clamp$1 = (v, min, max) => v < min ? min : v > max ? max : v;
const powCache = {};
/**
- * @param {Number} v
- * @param {Number} decimalLength
+ * Rounds a number to specified decimal places
+ *
+ * @param {Number} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
* @return {Number}
*/
-const round = (v, decimalLength) => {
+const round$1 = (v, decimalLength) => {
if (decimalLength < 0) return v;
if (!decimalLength) return _round(v);
let p = powCache[decimalLength];
@@ -864,57 +912,46 @@ const round = (v, decimalLength) => {
};
/**
- * @param {Number} v
- * @param {Number|Array<Number>} increment
- * @return {Number}
- */
-const snap = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
-
-/**
- * @param {Number} start
- * @param {Number} end
- * @param {Number} progress
- * @return {Number}
- */
-const interpolate = (start, end, progress) => start + (end - start) * progress;
-
-/**
- * @param {Number} min
- * @param {Number} max
- * @param {Number} [decimalLength]
+ * Snaps a value to nearest increment or array value
+ *
+ * @param {Number} v - Value to snap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
* @return {Number}
*/
-const random = (min, max, decimalLength) => { const m = 10 ** (decimalLength || 0); return floor((Math.random() * (max - min + (1 / m)) + min) * m) / m };
+const snap$1 = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
/**
- * Adapted from https://bost.ocks.org/mike/shuffle/
- * @param {Array} items
- * @return {Array}
+ * Linear interpolation between two values
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
*/
-const shuffle = items => {
- let m = items.length, t, i;
- while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; }
- return items;
-};
+const lerp$1 = (start, end, factor) => start + (end - start) * factor;
/**
- * @param {Number} v
+ * Replaces infinity with maximum safe value
+ *
+ * @param {Number} v - Value to check
* @return {Number}
*/
-const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -1e12 : v;
+const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v;
/**
- * @param {Number} v
+ * Normalizes time value with minimum threshold
+ *
+ * @param {Number} v - Time value to normalize
* @return {Number}
*/
-const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round(v, 11));
+const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round$1(v, 11));
// Arrays
/**
* @template T
- * @param {T[]} a
- * @return {T[]}
+ * @param {T[]} a
+ * @return {T[]}
*/
const cloneArray = a => isArr(a) ? [ ...a ] : a;
@@ -923,9 +960,9 @@ const cloneArray = a => isArr(a) ? [ ...a ] : a;
/**
* @template T
* @template U
- * @param {T} o1
- * @param {U} o2
- * @return {T & U}
+ * @param {T} o1
+ * @param {U} o2
+ * @return {T & U}
*/
const mergeObjects = (o1, o2) => {
const merged = /** @type {T & U} */({ ...o1 });
@@ -938,11 +975,11 @@ const mergeObjects = (o1, o2) => {
// Linked lists
/**
- * @param {Object} parent
- * @param {Function} callback
- * @param {Boolean} [reverse]
- * @param {String} [prevProp]
- * @param {String} [nextProp]
+ * @param {Object} parent
+ * @param {Function} callback
+ * @param {Boolean} [reverse]
+ * @param {String} [prevProp]
+ * @param {String} [nextProp]
* @return {void}
*/
const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => {
@@ -993,121 +1030,309 @@ const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_ne
child[nextProp] = next;
};
+
+
/**
- * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor
- * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)}
+ * @param {DOMTarget} target
+ * @param {String} propName
+ * @param {Object} animationInlineStyles
+ * @return {String}
*/
-const createRefreshable = constructor => {
- /** @type {Tickable} */
- let tracked;
- return (...args) => {
- let currentIteration, currentIterationProgress, reversed, alternate;
- if (tracked) {
- currentIteration = tracked.currentIteration;
- currentIterationProgress = tracked.iterationProgress;
- reversed = tracked.reversed;
- alternate = tracked._alternate;
- tracked.revert();
- }
- const cleanup = constructor(...args);
- if (cleanup && !isFnc(cleanup) && cleanup.revert) tracked = cleanup;
- if (!isUnd(currentIterationProgress)) {
- /** @type {Tickable} */(tracked).currentIteration = currentIteration;
- /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress;
+const parseInlineTransforms = (target, propName, animationInlineStyles) => {
+ const inlineTransforms = target.style.transform;
+ let inlinedStylesPropertyValue;
+ if (inlineTransforms) {
+ const cachedTransforms = target[transformsSymbol];
+ let t; while (t = transformsExecRgx.exec(inlineTransforms)) {
+ const inlinePropertyName = t[1];
+ // const inlinePropertyValue = t[2];
+ const inlinePropertyValue = t[2].slice(1, -1);
+ cachedTransforms[inlinePropertyName] = inlinePropertyValue;
+ if (inlinePropertyName === propName) {
+ inlinedStylesPropertyValue = inlinePropertyValue;
+ // Store the new parsed inline styles if animationInlineStyles is provided
+ if (animationInlineStyles) {
+ animationInlineStyles[propName] = inlinePropertyValue;
+ }
+ }
}
- return cleanup || noop;
}
+ return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue :
+ stringStartsWith(propName, 'scale') ? '1' :
+ stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px';
};
-/*
- * Base class to control framerate and playback rate.
- * Inherited by Engine, Timer, Animation and Timeline.
- */
-class Clock {
- /** @param {Number} [initTime] */
- constructor(initTime = 0) {
- /** @type {Number} */
- this.deltaTime = 0;
- /** @type {Number} */
- this._currentTime = initTime;
- /** @type {Number} */
- this._elapsedTime = initTime;
- /** @type {Number} */
- this._startTime = initTime;
- /** @type {Number} */
- this._lastTime = initTime;
- /** @type {Number} */
- this._scheduledTime = 0;
- /** @type {Number} */
- this._frameDuration = round(K / maxFps, 0);
- /** @type {Number} */
- this._fps = maxFps;
- /** @type {Number} */
- this._speed = 1;
- /** @type {Boolean} */
- this._hasChildren = false;
- /** @type {Tickable|Tween} */
- this._head = null;
- /** @type {Tickable|Tween} */
- this._tail = null;
- }
- get fps() {
- return this._fps;
- }
+/**
+ * RGB / RGBA Color value string -> RGBA values array
+ * @param {String} rgbValue
+ * @return {ColorArray}
+ */
+const rgbToRgba = rgbValue => {
+ const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue);
+ const a = !isUnd(rgba[4]) ? +rgba[4] : 1;
+ return [
+ +rgba[1],
+ +rgba[2],
+ +rgba[3],
+ a
+ ]
+};
- set fps(frameRate) {
- const previousFrameDuration = this._frameDuration;
- const fr = +frameRate;
- const fps = fr < minValue ? minValue : fr;
- const frameDuration = round(K / fps, 0);
- this._fps = fps;
- this._frameDuration = frameDuration;
- this._scheduledTime += frameDuration - previousFrameDuration;
- }
+/**
+ * HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array
+ * @param {String} hexValue
+ * @return {ColorArray}
+ */
+const hexToRgba = hexValue => {
+ const hexLength = hexValue.length;
+ const isShort = hexLength === 4 || hexLength === 5;
+ return [
+ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]),
+ +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]),
+ +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]),
+ ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1)
+ ]
+};
- get speed() {
- return this._speed;
- }
+/**
+ * @param {Number} p
+ * @param {Number} q
+ * @param {Number} t
+ * @return {Number}
+ */
+const hue2rgb = (p, q, t) => {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ return t < 1 / 6 ? p + (q - p) * 6 * t :
+ t < 1 / 2 ? q :
+ t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 :
+ p;
+};
- set speed(playbackRate) {
- const pbr = +playbackRate;
- this._speed = pbr < minValue ? minValue : pbr;
+/**
+ * HSL / HSLA Color value string -> RGBA values array
+ * @param {String} hslValue
+ * @return {ColorArray}
+ */
+const hslToRgba = hslValue => {
+ const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue);
+ const h = +hsla[1] / 360;
+ const s = +hsla[2] / 100;
+ const l = +hsla[3] / 100;
+ const a = !isUnd(hsla[4]) ? +hsla[4] : 1;
+ let r, g, b;
+ if (s === 0) {
+ r = g = b = l;
+ } else {
+ const q = l < .5 ? l * (1 + s) : l + s - l * s;
+ const p = 2 * l - q;
+ r = round$1(hue2rgb(p, q, h + 1 / 3) * 255, 0);
+ g = round$1(hue2rgb(p, q, h) * 255, 0);
+ b = round$1(hue2rgb(p, q, h - 1 / 3) * 255, 0);
}
+ return [r, g, b, a];
+};
- /**
- * @param {Number} time
- * @return {tickModes}
- */
- requestTick(time) {
- const scheduledTime = this._scheduledTime;
- const elapsedTime = this._elapsedTime;
- this._elapsedTime += (time - elapsedTime);
- // If the elapsed time is lower than the scheduled time
- // this means not enough time has passed to hit one frameDuration
- // so skip that frame
- if (elapsedTime < scheduledTime) return tickModes.NONE;
- const frameDuration = this._frameDuration;
- const frameDelta = elapsedTime - scheduledTime;
- // Ensures that _scheduledTime progresses in steps of at least 1 frameDuration.
- // Skips ahead if the actual elapsed time is higher.
- this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta;
- return tickModes.AUTO;
+/**
+ * All in one color converter that converts a color string value into an array of RGBA values
+ * @param {String} colorString
+ * @return {ColorArray}
+ */
+const convertColorStringValuesToRgbaArray = colorString => {
+ return isRgb(colorString) ? rgbToRgba(colorString) :
+ isHex(colorString) ? hexToRgba(colorString) :
+ isHsl(colorString) ? hslToRgba(colorString) :
+ [0, 0, 0, 1];
+};
+
+
+
+/**
+ * @template T, D
+ * @param {T|undefined} targetValue
+ * @param {D} defaultValue
+ * @return {T|D}
+ */
+const setValue = (targetValue, defaultValue) => {
+ return isUnd(targetValue) ? defaultValue : targetValue;
+};
+
+/**
+ * @param {TweenPropValue} value
+ * @param {Target} target
+ * @param {Number} index
+ * @param {Number} total
+ * @param {Object} [store]
+ * @return {any}
+ */
+const getFunctionValue = (value, target, index, total, store) => {
+ if (isFnc(value)) {
+ const func = () => {
+ const computed = /** @type {Function} */(value)(target, index, total);
+ // Fallback to 0 if the function returns undefined / NaN / null / false / 0
+ return !isNaN(+computed) ? +computed : computed || 0;
+ };
+ if (store) {
+ store.func = func;
+ }
+ return func();
+ } else {
+ return value;
}
+};
- /**
- * @param {Number} time
- * @return {Number}
- */
- computeDeltaTime(time) {
- const delta = time - this._lastTime;
- this.deltaTime = delta;
- this._lastTime = time;
- return delta;
+/**
+ * @param {Target} target
+ * @param {String} prop
+ * @return {tweenTypes}
+ */
+const getTweenType = (target, prop) => {
+ return !target[isDomSymbol] ? tweenTypes.OBJECT :
+ // Handle SVG attributes
+ target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE :
+ // Handle CSS Transform properties differently than CSS to allow individual animations
+ validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM :
+ // CSS variables
+ stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR :
+ // All other CSS properties
+ prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS :
+ // Handle other DOM Attributes
+ prop in target ? tweenTypes.OBJECT :
+ tweenTypes.ATTRIBUTE;
+};
+
+/**
+ * @param {DOMTarget} target
+ * @param {String} propName
+ * @param {Object} animationInlineStyles
+ * @return {String}
+ */
+const getCSSValue = (target, propName, animationInlineStyles) => {
+ const inlineStyles = target.style[propName];
+ if (inlineStyles && animationInlineStyles) {
+ animationInlineStyles[propName] = inlineStyles;
}
+ const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName);
+ return value === 'auto' ? '0' : value;
+};
+
+/**
+ * @param {Target} target
+ * @param {String} propName
+ * @param {tweenTypes} [tweenType]
+ * @param {Object|void} [animationInlineStyles]
+ * @return {String|Number}
+ */
+const getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => {
+ const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName);
+ return type === tweenTypes.OBJECT ? target[propName] || 0 :
+ type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) :
+ type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) :
+ type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() :
+ getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles);
+};
+
+/**
+ * @param {Number} x
+ * @param {Number} y
+ * @param {String} operator
+ * @return {Number}
+ */
+const getRelativeValue = (x, y, operator) => {
+ return operator === '-' ? x - y :
+ operator === '+' ? x + y :
+ x * y;
+};
+
+/** @return {TweenDecomposedValue} */
+const createDecomposedValueTargetObject = () => {
+ return {
+ /** @type {valueTypes} */
+ t: valueTypes.NUMBER,
+ n: 0,
+ u: null,
+ o: null,
+ d: null,
+ s: null,
+ }
+};
+
+/**
+ * @param {String|Number} rawValue
+ * @param {TweenDecomposedValue} targetObject
+ * @return {TweenDecomposedValue}
+ */
+const decomposeRawValue = (rawValue, targetObject) => {
+ /** @type {valueTypes} */
+ targetObject.t = valueTypes.NUMBER;
+ targetObject.n = 0;
+ targetObject.u = null;
+ targetObject.o = null;
+ targetObject.d = null;
+ targetObject.s = null;
+ if (!rawValue) return targetObject;
+ const num = +rawValue;
+ if (!isNaN(num)) {
+ // It's a number
+ targetObject.n = num;
+ return targetObject;
+ } else {
+ // let str = /** @type {String} */(rawValue).trim();
+ let str = /** @type {String} */(rawValue);
+ // Parsing operators (+=, -=, *=) manually is much faster than using regex here
+ if (str[1] === '=') {
+ targetObject.o = str[0];
+ str = str.slice(2);
+ }
+ // Skip exec regex if the value type is complex or color to avoid long regex backtracking
+ const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str);
+ if (unitMatch) {
+ // Has a number and a unit
+ targetObject.t = valueTypes.UNIT;
+ targetObject.n = +unitMatch[1];
+ targetObject.u = unitMatch[2];
+ return targetObject;
+ } else if (targetObject.o) {
+ // Has an operator (+=, -=, *=)
+ targetObject.n = +str;
+ return targetObject;
+ } else if (isCol(str)) {
+ // Is a color
+ targetObject.t = valueTypes.COLOR;
+ targetObject.d = convertColorStringValuesToRgbaArray(str);
+ return targetObject;
+ } else {
+ // Is a more complex string (generally svg coords, calc() or filters CSS values)
+ const matchedNumbers = str.match(digitWithExponentRgx);
+ targetObject.t = valueTypes.COMPLEX;
+ targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : [];
+ targetObject.s = str.split(digitWithExponentRgx) || [];
+ return targetObject;
+ }
+ }
+};
+
+/**
+ * @param {Tween} tween
+ * @param {TweenDecomposedValue} targetObject
+ * @return {TweenDecomposedValue}
+ */
+const decomposeTweenValue = (tween, targetObject) => {
+ targetObject.t = tween._valueType;
+ targetObject.n = tween._toNumber;
+ targetObject.u = tween._unit;
+ targetObject.o = null;
+ targetObject.d = cloneArray(tween._toNumbers);
+ targetObject.s = cloneArray(tween._strings);
+ return targetObject;
+};
+
+const decomposedOriginalValue = createDecomposedValueTargetObject();
+
+
-}
@@ -1137,8 +1362,8 @@ const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
const tickableEndTime = tickableDelay + iterationDuration;
const tickableAbsoluteTime = time - tickableDelay;
- const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration);
- const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration);
+ const tickablePrevTime = clamp$1(tickablePrevAbsoluteTime, -tickableDelay, duration);
+ const tickableCurrentTime = clamp$1(tickableAbsoluteTime, -tickableDelay, duration);
const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime;
const isCurrentTimeAboveZero = tickableCurrentTime > 0;
const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration;
@@ -1155,7 +1380,7 @@ const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
if (iterationCount > 1) {
// bitwise NOT operator seems to be generally faster than Math.floor() across browsers
const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay)));
- tickable._currentIteration = clamp(currentIteration, 0, iterationCount);
+ tickable._currentIteration = clamp$1(currentIteration, 0, iterationCount);
// Prevent the iteration count to go above the max iterations when reaching the end of the animation
if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--;
isOdd = tickable._currentIteration % 2;
@@ -1243,7 +1468,7 @@ const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
))
) {
- const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration);
+ const tweenNewTime = tween._currentTime = clamp$1(iterationTime - tween._startTime, 0, tweenChangeDuration);
const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration);
const tweenModifier = tween._modifier;
const tweenValueType = tween._valueType;
@@ -1260,18 +1485,18 @@ const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
let number;
if (tweenIsNumber) {
- value = number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
+ value = number = /** @type {Number} */(tweenModifier(round$1(lerp$1(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
} else if (tweenValueType === valueTypes.UNIT) {
// Rounding the values speed up string composition
- number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
+ number = /** @type {Number} */(tweenModifier(round$1(lerp$1(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
value = `${number}${tween._unit}`;
} else if (tweenValueType === valueTypes.COLOR) {
const fn = tween._fromNumbers;
const tn = tween._toNumbers;
- const r = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[0], tn[0], tweenProgress))), 0, 255), 0);
- const g = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[1], tn[1], tweenProgress))), 0, 255), 0);
- const b = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[2], tn[2], tweenProgress))), 0, 255), 0);
- const a = clamp(/** @type {Number} */(tweenModifier(round(interpolate(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
+ const r = round$1(clamp$1(/** @type {Number} */(tweenModifier(lerp$1(fn[0], tn[0], tweenProgress))), 0, 255), 0);
+ const g = round$1(clamp$1(/** @type {Number} */(tweenModifier(lerp$1(fn[1], tn[1], tweenProgress))), 0, 255), 0);
+ const b = round$1(clamp$1(/** @type {Number} */(tweenModifier(lerp$1(fn[2], tn[2], tweenProgress))), 0, 255), 0);
+ const a = clamp$1(/** @type {Number} */(tweenModifier(round$1(lerp$1(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
value = `rgba(${r},${g},${b},${a})`;
if (tweenHasComposition) {
const ns = tween._numbers;
@@ -1283,7 +1508,7 @@ const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
} else if (tweenValueType === valueTypes.COMPLEX) {
value = tween._strings[0];
for (let j = 0, l = tween._toNumbers.length; j < l; j++) {
- const n = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
+ const n = /** @type {Number} */(tweenModifier(round$1(lerp$1(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
const s = tween._strings[j + 1];
value += `${s ? n + s : n}`;
if (tweenHasComposition) {
@@ -1440,7 +1665,7 @@ const tick = (tickable, time, muteCallbacks, internalRender, tickMode) => {
}
forEachChildren(tl, (/** @type {JSAnimation} */child) => {
- const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds
+ const childTime = round$1((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds
const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode;
tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode);
if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false;
@@ -1464,28 +1689,210 @@ const tick = (tickable, time, muteCallbacks, internalRender, tickMode) => {
}
};
+const propertyNamesCache = {};
+
+
-const additive = {
- animation: null,
- update: noop,
-};
/**
- * @typedef AdditiveAnimation
- * @property {Number} duration
- * @property {Number} _offset
- * @property {Number} _delay
- * @property {Tween} _head
- * @property {Tween} _tail
+ * @param {String} propertyName
+ * @param {Target} target
+ * @param {tweenTypes} tweenType
+ * @return {String}
*/
+const sanitizePropertyName = (propertyName, target, tweenType) => {
+ if (tweenType === tweenTypes.TRANSFORM) {
+ const t = shortTransforms.get(propertyName);
+ return t ? t : propertyName;
+ } else if (
+ tweenType === tweenTypes.CSS ||
+ // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
+ // but properties like "baseFrequency" should stay in lowerCamelCase
+ (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
+ ) {
+ const cachedPropertyName = propertyNamesCache[propertyName];
+ if (cachedPropertyName) {
+ return cachedPropertyName;
+ } else {
+ const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
+ propertyNamesCache[propertyName] = lowerCaseName;
+ return lowerCaseName;
+ }
+ } else {
+ return propertyName;
+ }
+};
/**
- * @param {TweenAdditiveLookups} lookups
- * @return {AdditiveAnimation}
- */
-const addAdditiveAnimation = lookups => {
+ * @template {Renderable} T
+ * @param {T} renderable
+ * @return {T}
+ */
+const cleanInlineStyles = renderable => {
+ // Allow cleanInlineStyles() to be called on timelines
+ if (renderable._hasChildren) {
+ forEachChildren(renderable, cleanInlineStyles, true);
+ } else {
+ const animation = /** @type {JSAnimation} */(renderable);
+ animation.pause();
+ forEachChildren(animation, (/** @type {Tween} */tween) => {
+ const tweenProperty = tween.property;
+ const tweenTarget = tween.target;
+ if (tweenTarget[isDomSymbol]) {
+ const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
+ const originalInlinedValue = animation._inlineStyles[tweenProperty];
+ if (tween._tweenType === tweenTypes.TRANSFORM) {
+ const cachedTransforms = tweenTarget[transformsSymbol];
+ if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
+ delete cachedTransforms[tweenProperty];
+ } else {
+ cachedTransforms[tweenProperty] = originalInlinedValue;
+ }
+ if (tween._renderTransforms) {
+ if (!Object.keys(cachedTransforms).length) {
+ targetStyle.removeProperty('transform');
+ } else {
+ let str = emptyString;
+ for (let key in cachedTransforms) {
+ str += transformsFragmentStrings[key] + cachedTransforms[key] + ') ';
+ }
+ targetStyle.transform = str;
+ }
+ }
+ } else {
+ if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
+ targetStyle.removeProperty(tweenProperty);
+ } else {
+ targetStyle[tweenProperty] = originalInlinedValue;
+ }
+ }
+ if (animation._tail === tween) {
+ animation.targets.forEach(t => {
+ if (t.getAttribute && t.getAttribute('style') === emptyString) {
+ t.removeAttribute('style');
+ } });
+ }
+ }
+ });
+ }
+ return renderable;
+};
+
+
+
+/*
+ * Base class to control framerate and playback rate.
+ * Inherited by Engine, Timer, Animation and Timeline.
+ */
+class Clock {
+
+ /** @param {Number} [initTime] */
+ constructor(initTime = 0) {
+ /** @type {Number} */
+ this.deltaTime = 0;
+ /** @type {Number} */
+ this._currentTime = initTime;
+ /** @type {Number} */
+ this._elapsedTime = initTime;
+ /** @type {Number} */
+ this._startTime = initTime;
+ /** @type {Number} */
+ this._lastTime = initTime;
+ /** @type {Number} */
+ this._scheduledTime = 0;
+ /** @type {Number} */
+ this._frameDuration = round$1(K / maxFps, 0);
+ /** @type {Number} */
+ this._fps = maxFps;
+ /** @type {Number} */
+ this._speed = 1;
+ /** @type {Boolean} */
+ this._hasChildren = false;
+ /** @type {Tickable|Tween} */
+ this._head = null;
+ /** @type {Tickable|Tween} */
+ this._tail = null;
+ }
+
+ get fps() {
+ return this._fps;
+ }
+
+ set fps(frameRate) {
+ const previousFrameDuration = this._frameDuration;
+ const fr = +frameRate;
+ const fps = fr < minValue ? minValue : fr;
+ const frameDuration = round$1(K / fps, 0);
+ this._fps = fps;
+ this._frameDuration = frameDuration;
+ this._scheduledTime += frameDuration - previousFrameDuration;
+ }
+
+ get speed() {
+ return this._speed;
+ }
+
+ set speed(playbackRate) {
+ const pbr = +playbackRate;
+ this._speed = pbr < minValue ? minValue : pbr;
+ }
+
+ /**
+ * @param {Number} time
+ * @return {tickModes}
+ */
+ requestTick(time) {
+ const scheduledTime = this._scheduledTime;
+ const elapsedTime = this._elapsedTime;
+ this._elapsedTime += (time - elapsedTime);
+ // If the elapsed time is lower than the scheduled time
+ // this means not enough time has passed to hit one frameDuration
+ // so skip that frame
+ if (elapsedTime < scheduledTime) return tickModes.NONE;
+ const frameDuration = this._frameDuration;
+ const frameDelta = elapsedTime - scheduledTime;
+ // Ensures that _scheduledTime progresses in steps of at least 1 frameDuration.
+ // Skips ahead if the actual elapsed time is higher.
+ this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta;
+ return tickModes.AUTO;
+ }
+
+ /**
+ * @param {Number} time
+ * @return {Number}
+ */
+ computeDeltaTime(time) {
+ const delta = time - this._lastTime;
+ this.deltaTime = delta;
+ this._lastTime = time;
+ return delta;
+ }
+
+}
+
+const additive = {
+ animation: null,
+ update: noop,
+};
+
+
+
+/**
+ * @typedef AdditiveAnimation
+ * @property {Number} duration
+ * @property {Number} _offset
+ * @property {Number} _delay
+ * @property {Tween} _head
+ * @property {Tween} _tail
+ */
+
+/**
+ * @param {TweenAdditiveLookups} lookups
+ * @return {AdditiveAnimation}
+ */
+const addAdditiveAnimation = lookups => {
let animation = additive.animation;
if (!animation) {
animation = {
@@ -1527,6 +1934,10 @@ const addAdditiveAnimation = lookups => {
return animation;
};
+
+
+
+
const engineTickMethod = /*#__PURE__*/ (() => isBrowser ? requestAnimationFrame : setImmediate)();
const engineCancelMethod = /*#__PURE__*/ (() => isBrowser ? cancelAnimationFrame : clearImmediate)();
@@ -1611,7 +2022,7 @@ class Engine extends Clock {
// Getter and setter for timeUnit
get timeUnit() {
return globals.timeScale === 1 ? 'ms' : 's';
- };
+ }
set timeUnit(unit) {
const secondsScale = 0.001;
@@ -1637,6 +2048,7 @@ class Engine extends Clock {
}
}
+
const engine = /*#__PURE__*/(() => {
const engine = new Engine(now());
if (isBrowser) {
@@ -1667,927 +2079,368 @@ const killEngine = () => {
+const lookups = {
+ /** @type {TweenReplaceLookups} */
+ _rep: new WeakMap(),
+ /** @type {TweenAdditiveLookups} */
+ _add: new Map(),
+};
/**
- * @param {DOMTarget} target
- * @param {String} propName
- * @param {Object} animationInlineStyles
- * @return {String}
+ * @param {Target} target
+ * @param {String} property
+ * @param {String} lookup
+ * @return {TweenPropertySiblings}
*/
-const parseInlineTransforms = (target, propName, animationInlineStyles) => {
- const inlineTransforms = target.style.transform;
- let inlinedStylesPropertyValue;
- if (inlineTransforms) {
- const cachedTransforms = target[transformsSymbol];
- let t; while (t = transformsExecRgx.exec(inlineTransforms)) {
- const inlinePropertyName = t[1];
- // const inlinePropertyValue = t[2];
- const inlinePropertyValue = t[2].slice(1, -1);
- cachedTransforms[inlinePropertyName] = inlinePropertyValue;
- if (inlinePropertyName === propName) {
- inlinedStylesPropertyValue = inlinePropertyValue;
- // Store the new parsed inline styles if animationInlineStyles is provided
- if (animationInlineStyles) {
- animationInlineStyles[propName] = inlinePropertyValue;
- }
- }
- }
+const getTweenSiblings = (target, property, lookup = '_rep') => {
+ const lookupMap = lookups[lookup];
+ let targetLookup = lookupMap.get(target);
+ if (!targetLookup) {
+ targetLookup = {};
+ lookupMap.set(target, targetLookup);
+ }
+ return targetLookup[property] ? targetLookup[property] : targetLookup[property] = {
+ _head: null,
+ _tail: null,
}
- return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue :
- stringStartsWith(propName, 'scale') ? '1' :
- stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px';
};
-
-
+/**
+ * @param {Tween} p
+ * @param {Tween} c
+ * @return {Number|Boolean}
+ */
+const addTweenSortMethod = (p, c) => {
+ return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime;
+};
/**
- * @param {DOMTargetsParam|TargetsParam} v
- * @return {NodeList|HTMLCollection}
+ * @param {Tween} tween
*/
-function getNodeList(v) {
- const n = isStr(v) ? scope.root.querySelectorAll(v) : v;
- if (n instanceof NodeList || n instanceof HTMLCollection) return n;
-}
+const overrideTween = tween => {
+ tween._isOverlapped = 1;
+ tween._isOverridden = 1;
+ tween._changeDuration = minValue;
+ tween._currentTime = minValue;
+};
/**
- * @overload
- * @param {DOMTargetsParam} targets
- * @return {DOMTargetsArray}
- *
- * @overload
- * @param {JSTargetsParam} targets
- * @return {JSTargetsArray}
- *
- * @overload
- * @param {TargetsParam} targets
- * @return {TargetsArray}
- *
- * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ * @param {Tween} tween
+ * @param {TweenPropertySiblings} siblings
+ * @return {Tween}
*/
-function parseTargets(targets) {
- if (isNil(targets)) return /** @type {TargetsArray} */([]);
- if (!isBrowser) return /** @type {JSTargetsArray} */(isArr(targets) && targets.flat(Infinity) || [targets]);
- if (isArr(targets)) {
- const flattened = targets.flat(Infinity);
- /** @type {TargetsArray} */
- const parsed = [];
- for (let i = 0, l = flattened.length; i < l; i++) {
- const item = flattened[i];
- if (!isNil(item)) {
- const nodeList = getNodeList(item);
- if (nodeList) {
- for (let j = 0, jl = nodeList.length; j < jl; j++) {
- const subItem = nodeList[j];
- if (!isNil(subItem)) {
- let isDuplicate = false;
- for (let k = 0, kl = parsed.length; k < kl; k++) {
- if (parsed[k] === subItem) {
- isDuplicate = true;
- break;
- }
- }
- if (!isDuplicate) {
- parsed.push(subItem);
- }
- }
- }
- } else {
- let isDuplicate = false;
- for (let j = 0, jl = parsed.length; j < jl; j++) {
- if (parsed[j] === item) {
- isDuplicate = true;
- break;
- }
- }
- if (!isDuplicate) {
- parsed.push(item);
- }
- }
- }
- }
- return parsed;
- }
- const nodeList = getNodeList(targets);
- if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList));
- return /** @type {TargetsArray} */([targets]);
-}
+const composeTween = (tween, siblings) => {
-/**
- * @overload
- * @param {DOMTargetsParam} targets
- * @return {DOMTargetsArray}
- *
- * @overload
- * @param {JSTargetsParam} targets
- * @return {JSTargetsArray}
- *
- * @overload
- * @param {TargetsParam} targets
- * @return {TargetsArray}
- *
- * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
- */
-function registerTargets(targets) {
- const parsedTargetsArray = parseTargets(targets);
- const parsedTargetsLength = parsedTargetsArray.length;
- if (parsedTargetsLength) {
- for (let i = 0; i < parsedTargetsLength; i++) {
- const target = parsedTargetsArray[i];
- if (!target[isRegisteredTargetSymbol]) {
- target[isRegisteredTargetSymbol] = true;
- const isSvgType = isSvg(target);
- const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType;
- if (isDom) {
- target[isDomSymbol] = true;
- target[isSvgSymbol] = isSvgType;
- target[transformsSymbol] = {};
- }
- }
- }
- }
- return parsedTargetsArray;
-}
+ const tweenCompositionType = tween._composition;
+ // Handle replaced tweens
+ if (tweenCompositionType === compositionTypes.replace) {
+ const tweenAbsStartTime = tween._absoluteStartTime;
-/**
- * @param {TargetsParam} path
- * @return {SVGGeometryElement|undefined}
- */
-const getPath = path => {
- const parsedTargets = parseTargets(path);
- const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
- if (!$parsedSvg || !isSvg($parsedSvg)) return;
- return $parsedSvg;
-};
+ addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep');
-/**
- * @param {TargetsParam} path2
- * @param {Number} [precision]
- * @return {FunctionValue}
- */
-const morphTo = (path2, precision = .33) => ($path1) => {
- const $path2 = /** @type {SVGGeometryElement} */(getPath(path2));
- if (!$path2) return;
- const isPath = $path1.tagName === 'path';
- const separator = isPath ? ' ' : ',';
- const previousPoints = $path1[morphPointsSymbol];
- if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
+ const prevSibling = tween._prevRep;
- let v1 = '', v2 = '';
+ // Update the previous siblings for composition replace tweens
- if (!precision) {
- v1 = $path1.getAttribute(isPath ? 'd' : 'points');
- v2 = $path2.getAttribute(isPath ? 'd' : 'points');
- } else {
- const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
- const length2 = $path2.getTotalLength();
- const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
- for (let i = 0; i < maxPoints; i++) {
- const t = i / (maxPoints - 1);
- const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
- const pointOnPath2 = $path2.getPointAtLength(length2 * t);
- const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
- v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
- v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
- }
- }
+ if (prevSibling) {
- $path1[morphPointsSymbol] = v2;
+ const prevParent = prevSibling.parent;
+ const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration;
- return [v1, v2];
-};
+ // Handle looped animations tween
-/**
- * @param {SVGGeometryElement} [$el]
- * @return {Number}
- */
-const getScaleFactor = $el => {
- let scaleFactor = 1;
- if ($el && $el.getCTM) {
- const ctm = $el.getCTM();
- if (ctm) {
- const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
- const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
- scaleFactor = (scaleX + scaleY) / 2;
- }
- }
- return scaleFactor;
-};
+ if (
+ // Check if the previous tween is from a different animation
+ tween.parent.id !== prevParent.id &&
+ // Check if the animation has loops
+ prevParent.iterationCount> 1 &&
+ // Check if _absoluteChangeEndTime of last loop overlaps the current tween
+ prevAbsEndTime + (prevParent.duration - prevParent.iterationDuration) > tweenAbsStartTime
+ ) {
-/**
- * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
- * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
- * @param {number} start - Starting position (0-1)
- * @param {number} end - Ending position (0-1)
- * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
- */
-const createDrawableProxy = ($el, start, end) => {
- const pathLength = K;
- const computedStyles = getComputedStyle($el);
- const strokeLineCap = computedStyles.strokeLinecap;
- // @ts-ignore
- const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
- let currentCap = strokeLineCap;
+ // TODO: Find a way to only override the iterations overlapping with the tween
+ overrideTween(prevSibling);
- const proxy = new Proxy($el, {
- get(target, property) {
- const value = target[property];
- if (property === proxyTargetSymbol) return target;
- if (property === 'setAttribute') {
- return (...args) => {
- if (args[0] === 'draw') {
- const value = args[1];
- const values = value.split(' ');
- const v1 = +values[0];
- const v2 = +values[1];
- // TOTO: Benchmark if performing two slices is more performant than one split
- // const spaceIndex = value.indexOf(' ');
- // const v1 = round(+value.slice(0, spaceIndex), precision);
- // const v2 = round(+value.slice(spaceIndex + 1), precision);
- const scaleFactor = getScaleFactor($scalled);
- const os = v1 * -1e3 * scaleFactor;
- const d1 = (v2 * pathLength * scaleFactor) + os;
- const d2 = (pathLength * scaleFactor +
- ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
- if (strokeLineCap !== 'butt') {
- const newCap = v1 === v2 ? 'butt' : strokeLineCap;
- if (currentCap !== newCap) {
- target.style.strokeLinecap = `${newCap}`;
- currentCap = newCap;
- }
- }
- target.setAttribute('stroke-dashoffset', `${os}`);
- target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
- }
- return Reflect.apply(value, target, args);
- };
- }
+ let prevPrevSibling = prevSibling._prevRep;
- if (isFnc(value)) {
- return (...args) => Reflect.apply(value, target, args);
- } else {
- return value;
- }
- }
- });
+ // If the tween was part of a set of keyframes, override its siblings
+ while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) {
+ overrideTween(prevPrevSibling);
+ prevPrevSibling = prevPrevSibling._prevRep;
+ }
- if ($el.getAttribute('pathLength') !== `${pathLength}`) {
- $el.setAttribute('pathLength', `${pathLength}`);
- proxy.setAttribute('draw', `${start} ${end}`);
- }
+ }
- return /** @type {DrawableSVGGeometry} */(proxy);
-};
+ const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay;
-/**
- * Creates drawable proxies for multiple SVG elements.
- * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
- * @param {number} [start=0] - Starting position (0-1)
- * @param {number} [end=0] - Ending position (0-1)
- * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
- */
-const createDrawable = (selector, start = 0, end = 0) => {
- const els = parseTargets(selector);
- return els.map($el => createDrawableProxy(
- /** @type {SVGGeometryElement} */($el),
- start,
- end
- ));
-};
+ if (prevAbsEndTime > absoluteUpdateStartTime) {
-// Motion path animation
+ const prevChangeStartTime = prevSibling._startTime;
+ const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration);
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const updatedPrevChangeDuration = round$1(absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime, 12);
-/**
- * @param {SVGGeometryElement} $path
- * @param {Number} progress
- * @param {Number}lookup
- * @return {DOMPoint}
- */
-const getPathPoint = ($path, progress, lookup = 0) => {
- return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0);
-};
+ prevSibling._changeDuration = updatedPrevChangeDuration;
+ prevSibling._currentTime = updatedPrevChangeDuration;
+ prevSibling._isOverlapped = 1;
-/**
- * @param {SVGGeometryElement} $path
- * @param {String} pathProperty
- * @return {FunctionValue}
- */
-const getPathProgess = ($path, pathProperty) => {
- return $el => {
- const totalLength = +($path.getTotalLength());
- const inSvg = $el[isSvgSymbol];
- const ctm = $path.getCTM();
- /** @type {TweenObjectValue} */
- return {
- from: 0,
- to: totalLength,
- /** @type {TweenModifier} */
- modifier: progress => {
- if (pathProperty === 'a') {
- const p0 = getPathPoint($path, progress, -1);
- const p1 = getPathPoint($path, progress, 1);
- return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI;
- } else {
- const p = getPathPoint($path, progress, 0);
- return pathProperty === 'x' ?
- inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
- inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
+ // Override the previous tween if its new _changeDuration is lower than minValue
+ // TODO: See if it's even neceseeary to test against minValue, checking for 0 might be enough
+ if (updatedPrevChangeDuration < minValue) {
+ overrideTween(prevSibling);
}
}
- }
- }
-};
-/**
- * @param {TargetsParam} path
- */
-const createMotionPath = path => {
- const $path = getPath(path);
- if (!$path) return;
- return {
- translateX: getPathProgess($path, 'x'),
- translateY: getPathProgess($path, 'y'),
- rotate: getPathProgess($path, 'a'),
- }
-};
+ // Pause (and cancel) the parent if it only contains overlapped tweens
-// Check for valid SVG attribute
+ let pausePrevParentAnimation = true;
-const cssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
+ forEachChildren(prevParent, (/** @type Tween */t) => {
+ if (!t._isOverlapped) pausePrevParentAnimation = false;
+ });
+
+ if (pausePrevParentAnimation) {
+ const prevParentTL = prevParent.parent;
+ if (prevParentTL) {
+ let pausePrevParentTL = true;
+ forEachChildren(prevParentTL, (/** @type JSAnimation */a) => {
+ if (a !== prevParent) {
+ forEachChildren(a, (/** @type Tween */t) => {
+ if (!t._isOverlapped) pausePrevParentTL = false;
+ });
+ }
+ });
+ if (pausePrevParentTL) {
+ prevParentTL.cancel();
+ }
+ } else {
+ prevParent.cancel();
+ // Previously, calling .cancel() on a timeline child would affect the render order of other children
+ // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop
+ // This is no longer needed since timeline tween composition is now handled separately
+ // Keeping this here for reference
+ // prevParent.completed = true;
+ // prevParent.pause();
+ }
+ }
-/**
- * @param {Target} el
- * @param {String} propertyName
- * @return {Boolean}
- */
-const isValidSVGAttribute = (el, propertyName) => {
- // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform
- if (cssReservedProperties.includes(propertyName)) return false;
- if (el.getAttribute(propertyName) || propertyName in el) {
- if (propertyName === 'scale') { // Scale
- const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
- // Only consider scale as a valid SVG attribute on filter element
- return elParentNode && elParentNode.tagName === 'filter';
}
- return true;
- }
-};
-const svg = {
- morphTo,
- createMotionPath,
- createDrawable,
-};
+ // let nextSibling = tween._nextRep;
+ // // All the next siblings are automatically overridden
+ // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) {
+ // while (nextSibling) {
+ // overrideTween(nextSibling);
+ // nextSibling = nextSibling._nextRep;
+ // }
+ // }
+ // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) {
+ // while (nextSibling) {
+ // overrideTween(nextSibling);
+ // console.log(tween.id, nextSibling.id);
+ // nextSibling = nextSibling._nextRep;
+ // }
+ // }
-/**
- * RGB / RGBA Color value string -> RGBA values array
- * @param {String} rgbValue
- * @return {ColorArray}
- */
-const rgbToRgba = rgbValue => {
- const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue);
- const a = !isUnd(rgba[4]) ? +rgba[4] : 1;
- return [
- +rgba[1],
- +rgba[2],
- +rgba[3],
- a
- ]
-};
+ // Handle additive tweens composition
-/**
- * HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array
- * @param {String} hexValue
- * @return {ColorArray}
- */
-const hexToRgba = hexValue => {
- const hexLength = hexValue.length;
- const isShort = hexLength === 4 || hexLength === 5;
- return [
- +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]),
- +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]),
- +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]),
- ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1)
- ]
-};
+ } else if (tweenCompositionType === compositionTypes.blend) {
-/**
- * @param {Number} p
- * @param {Number} q
- * @param {Number} t
- * @return {Number}
- */
-const hue2rgb = (p, q, t) => {
- if (t < 0) t += 1;
- if (t > 1) t -= 1;
- return t < 1 / 6 ? p + (q - p) * 6 * t :
- t < 1 / 2 ? q :
- t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 :
- p;
-};
+ const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add');
+ const additiveAnimation = addAdditiveAnimation(lookups._add);
-/**
- * HSL / HSLA Color value string -> RGBA values array
- * @param {String} hslValue
- * @return {ColorArray}
- */
-const hslToRgba = hslValue => {
- const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue);
- const h = +hsla[1] / 360;
- const s = +hsla[2] / 100;
- const l = +hsla[3] / 100;
- const a = !isUnd(hsla[4]) ? +hsla[4] : 1;
- let r, g, b;
- if (s === 0) {
- r = g = b = l;
- } else {
- const q = l < .5 ? l * (1 + s) : l + s - l * s;
- const p = 2 * l - q;
- r = round(hue2rgb(p, q, h + 1 / 3) * 255, 0);
- g = round(hue2rgb(p, q, h) * 255, 0);
- b = round(hue2rgb(p, q, h - 1 / 3) * 255, 0);
- }
- return [r, g, b, a];
-};
+ let lookupTween = additiveTweenSiblings._head;
-/**
- * All in one color converter that converts a color string value into an array of RGBA values
- * @param {String} colorString
- * @return {ColorArray}
- */
-const convertColorStringValuesToRgbaArray = colorString => {
- return isRgb(colorString) ? rgbToRgba(colorString) :
- isHex(colorString) ? hexToRgba(colorString) :
- isHsl(colorString) ? hslToRgba(colorString) :
- [0, 0, 0, 1];
-};
+ if (!lookupTween) {
+ lookupTween = { ...tween };
+ lookupTween._composition = compositionTypes.replace;
+ lookupTween._updateDuration = minValue;
+ lookupTween._startTime = 0;
+ lookupTween._numbers = cloneArray(tween._fromNumbers);
+ lookupTween._number = 0;
+ lookupTween._next = null;
+ lookupTween._prev = null;
+ addChild(additiveTweenSiblings, lookupTween);
+ addChild(additiveAnimation, lookupTween);
+ }
+ // Convert the values of TO to FROM and set TO to 0
+ const toNumber = tween._toNumber;
+ tween._fromNumber = lookupTween._fromNumber - toNumber;
+ tween._toNumber = 0;
+ tween._numbers = cloneArray(tween._fromNumbers);
+ tween._number = 0;
+ lookupTween._fromNumber = toNumber;
+ if (tween._toNumbers) {
+ const toNumbers = cloneArray(tween._toNumbers);
+ if (toNumbers) {
+ toNumbers.forEach((value, i) => {
+ tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value;
+ tween._toNumbers[i] = 0;
+ });
+ }
+ lookupTween._fromNumbers = toNumbers;
+ }
-/**
- * @template T, D
- * @param {T|undefined} targetValue
- * @param {D} defaultValue
- * @return {T|D}
- */
-const setValue = (targetValue, defaultValue) => {
- return isUnd(targetValue) ? defaultValue : targetValue;
-};
+ addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd');
-/**
- * @param {TweenPropValue} value
- * @param {Target} target
- * @param {Number} index
- * @param {Number} total
- * @param {Object} [store]
- * @return {any}
- */
-const getFunctionValue = (value, target, index, total, store) => {
- if (isFnc(value)) {
- const func = () => {
- const computed = /** @type {Function} */(value)(target, index, total);
- // Fallback to 0 if the function returns undefined / NaN / null / false / 0
- return !isNaN(+computed) ? +computed : computed || 0;
- };
- if (store) {
- store.func = func;
- }
- return func();
- } else {
- return value;
}
+
+ return tween;
+
};
/**
- * @param {Target} target
- * @param {String} prop
- * @return {tweenTypes}
+ * @param {Tween} tween
+ * @return {Tween}
*/
-const getTweenType = (target, prop) => {
- return !target[isDomSymbol] ? tweenTypes.OBJECT :
- // Handle SVG attributes
- target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE :
- // Handle CSS Transform properties differently than CSS to allow individual animations
- validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM :
- // CSS variables
- stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR :
- // All other CSS properties
- prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS :
- // Handle other DOM Attributes
- prop in target ? tweenTypes.OBJECT :
- tweenTypes.ATTRIBUTE;
-};
-
-/**
- * @param {DOMTarget} target
- * @param {String} propName
- * @param {Object} animationInlineStyles
- * @return {String}
- */
-const getCSSValue = (target, propName, animationInlineStyles) => {
- const inlineStyles = target.style[propName];
- if (inlineStyles && animationInlineStyles) {
- animationInlineStyles[propName] = inlineStyles;
+const removeTweenSliblings = tween => {
+ const tweenComposition = tween._composition;
+ if (tweenComposition !== compositionTypes.none) {
+ const tweenTarget = tween.target;
+ const tweenProperty = tween.property;
+ const replaceTweensLookup = lookups._rep;
+ const replaceTargetProps = replaceTweensLookup.get(tweenTarget);
+ const tweenReplaceSiblings = replaceTargetProps[tweenProperty];
+ removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep');
+ if (tweenComposition === compositionTypes.blend) {
+ const addTweensLookup = lookups._add;
+ const addTargetProps = addTweensLookup.get(tweenTarget);
+ if (!addTargetProps) return;
+ const additiveTweenSiblings = addTargetProps[tweenProperty];
+ const additiveAnimation = additive.animation;
+ removeChild(additiveTweenSiblings, tween, '_prevAdd', '_nextAdd');
+ // If only one tween is left in the additive lookup, it's the tween lookup
+ const lookupTween = additiveTweenSiblings._head;
+ if (lookupTween && lookupTween === additiveTweenSiblings._tail) {
+ removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd');
+ removeChild(additiveAnimation, lookupTween);
+ let shouldClean = true;
+ for (let prop in addTargetProps) {
+ if (addTargetProps[prop]._head) {
+ shouldClean = false;
+ break;
+ }
+ }
+ if (shouldClean) {
+ addTweensLookup.delete(tweenTarget);
+ }
+ }
+ }
}
- const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName);
- return value === 'auto' ? '0' : value;
-};
-
-/**
- * @param {Target} target
- * @param {String} propName
- * @param {tweenTypes} [tweenType]
- * @param {Object|void} [animationInlineStyles]
- * @return {String|Number}
- */
-const getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => {
- const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName);
- return type === tweenTypes.OBJECT ? target[propName] || 0 :
- type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) :
- type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) :
- type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() :
- getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles);
+ return tween;
};
/**
- * @param {Number} x
- * @param {Number} y
- * @param {String} operator
- * @return {Number}
+ * @param {TargetsArray} targetsArray
+ * @param {JSAnimation} animation
+ * @param {String} [propertyName]
+ * @return {Boolean}
*/
-const getRelativeValue = (x, y, operator) => {
- return operator === '-' ? x - y :
- operator === '+' ? x + y :
- x * y;
-};
-
-/** @return {TweenDecomposedValue} */
-const createDecomposedValueTargetObject = () => {
- return {
- /** @type {valueTypes} */
- t: valueTypes.NUMBER,
- n: 0,
- u: null,
- o: null,
- d: null,
- s: null,
- }
+const removeTargetsFromJSAnimation = (targetsArray, animation, propertyName) => {
+ let tweensMatchesTargets = false;
+ forEachChildren(animation, (/**@type {Tween} */tween) => {
+ const tweenTarget = tween.target;
+ if (targetsArray.includes(tweenTarget)) {
+ const tweenName = tween.property;
+ const tweenType = tween._tweenType;
+ const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
+ if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
+ // Make sure to flag the previous CSS transform tween to renderTransform
+ if (tween.parent._tail === tween &&
+ tween._tweenType === tweenTypes.TRANSFORM &&
+ tween._prev &&
+ tween._prev._tweenType === tweenTypes.TRANSFORM
+ ) {
+ tween._prev._renderTransforms = 1;
+ }
+ // Removes the tween from the selected animation
+ removeChild(animation, tween);
+ // Detach the tween from its siblings to make sure blended tweens are correctlly removed
+ removeTweenSliblings(tween);
+ tweensMatchesTargets = true;
+ }
+ }
+ }, true);
+ return tweensMatchesTargets;
};
/**
- * @param {String|Number} rawValue
- * @param {TweenDecomposedValue} targetObject
- * @return {TweenDecomposedValue}
+ * @param {TargetsArray} targetsArray
+ * @param {Renderable} [renderable]
+ * @param {String} [propertyName]
*/
-const decomposeRawValue = (rawValue, targetObject) => {
- /** @type {valueTypes} */
- targetObject.t = valueTypes.NUMBER;
- targetObject.n = 0;
- targetObject.u = null;
- targetObject.o = null;
- targetObject.d = null;
- targetObject.s = null;
- if (!rawValue) return targetObject;
- const num = +rawValue;
- if (!isNaN(num)) {
- // It's a number
- targetObject.n = num;
- return targetObject;
- } else {
- // let str = /** @type {String} */(rawValue).trim();
- let str = /** @type {String} */(rawValue);
- // Parsing operators (+=, -=, *=) manually is much faster than using regex here
- if (str[1] === '=') {
- targetObject.o = str[0];
- str = str.slice(2);
- }
- // Skip exec regex if the value type is complex or color to avoid long regex backtracking
- const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str);
- if (unitMatch) {
- // Has a number and a unit
- targetObject.t = valueTypes.UNIT;
- targetObject.n = +unitMatch[1];
- targetObject.u = unitMatch[2];
- return targetObject;
- } else if (targetObject.o) {
- // Has an operator (+=, -=, *=)
- targetObject.n = +str;
- return targetObject;
- } else if (isCol(str)) {
- // Is a color
- targetObject.t = valueTypes.COLOR;
- targetObject.d = convertColorStringValuesToRgbaArray(str);
- return targetObject;
- } else {
- // Is a more complex string (generally svg coords, calc() or filters CSS values)
- const matchedNumbers = str.match(digitWithExponentRgx);
- targetObject.t = valueTypes.COMPLEX;
- targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : [];
- targetObject.s = str.split(digitWithExponentRgx) || [];
- return targetObject;
+const removeTargetsFromRenderable = (targetsArray, renderable, propertyName) => {
+ const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine);
+ let removeMatches;
+ if (parent._hasChildren) {
+ let iterationDuration = 0;
+ forEachChildren(parent, (/** @type {Renderable} */child) => {
+ if (!child._hasChildren) {
+ removeMatches = removeTargetsFromJSAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName);
+ // Remove the child from its parent if no tweens and no children left after the removal
+ if (removeMatches && !child._head) {
+ child.cancel();
+ removeChild(parent, child);
+ } else {
+ // Calculate the new iterationDuration value to handle onComplete with last child in render()
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > iterationDuration) {
+ iterationDuration = childDur;
+ }
+ }
+ }
+ // Make sure to also remove engine's children targets
+ // NOTE: Avoid recursion?
+ if (child._head) {
+ removeTargetsFromRenderable(targetsArray, child, propertyName);
+ } else {
+ child._hasChildren = false;
+ }
+ }, true);
+ // Update iterationDuration value to handle onComplete with last child in render()
+ if (!isUnd(/** @type {Renderable} */(parent).iterationDuration)) {
+ /** @type {Renderable} */(parent).iterationDuration = iterationDuration;
}
+ } else {
+ removeMatches = removeTargetsFromJSAnimation(
+ targetsArray,
+ /** @type {JSAnimation} */(parent),
+ propertyName
+ );
+ }
+ if (removeMatches && !parent._head) {
+ parent._hasChildren = false;
+ // Cancel the parent if there are no tweens and no children left after the removal
+ // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
+ if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel();
}
};
-/**
- * @param {Tween} tween
- * @param {TweenDecomposedValue} targetObject
- * @return {TweenDecomposedValue}
- */
-const decomposeTweenValue = (tween, targetObject) => {
- targetObject.t = tween._valueType;
- targetObject.n = tween._toNumber;
- targetObject.u = tween._unit;
- targetObject.o = null;
- targetObject.d = cloneArray(tween._toNumbers);
- targetObject.s = cloneArray(tween._strings);
- return targetObject;
-};
-const decomposedOriginalValue = createDecomposedValueTargetObject();
-const lookups = {
- /** @type {TweenReplaceLookups} */
- _rep: new WeakMap(),
- /** @type {TweenAdditiveLookups} */
- _add: new Map(),
-};
/**
- * @param {Target} target
- * @param {String} property
- * @param {String} lookup
- * @return {TweenPropertySiblings}
+ * @param {Timer} timer
+ * @return {Timer}
*/
-const getTweenSiblings = (target, property, lookup = '_rep') => {
- const lookupMap = lookups[lookup];
- let targetLookup = lookupMap.get(target);
- if (!targetLookup) {
- targetLookup = {};
- lookupMap.set(target, targetLookup);
- }
- return targetLookup[property] ? targetLookup[property] : targetLookup[property] = {
- _head: null,
- _tail: null,
- }
-};
-
-/**
- * @param {Tween} p
- * @param {Tween} c
- * @return {Number|Boolean}
- */
-const addTweenSortMethod = (p, c) => {
- return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime;
-};
-
-/**
- * @param {Tween} tween
- */
-const overrideTween = tween => {
- tween._isOverlapped = 1;
- tween._isOverridden = 1;
- tween._changeDuration = minValue;
- tween._currentTime = minValue;
-};
-
-/**
- * @param {Tween} tween
- * @param {TweenPropertySiblings} siblings
- * @return {Tween}
- */
-const composeTween = (tween, siblings) => {
-
- const tweenCompositionType = tween._composition;
-
- // Handle replaced tweens
-
- if (tweenCompositionType === compositionTypes.replace) {
-
- const tweenAbsStartTime = tween._absoluteStartTime;
-
- addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep');
-
- const prevSibling = tween._prevRep;
-
- // Update the previous siblings for composition replace tweens
-
- if (prevSibling) {
-
- const prevParent = prevSibling.parent;
- const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration;
-
- // Handle looped animations tween
-
- if (
- // Check if the previous tween is from a different animation
- tween.parent.id !== prevParent.id &&
- // Check if the animation has loops
- prevParent.iterationCount> 1 &&
- // Check if _absoluteChangeEndTime of last loop overlaps the current tween
- prevAbsEndTime + (prevParent.duration - prevParent.iterationDuration) > tweenAbsStartTime
- ) {
-
- // TODO: Find a way to only override the iterations overlapping with the tween
- overrideTween(prevSibling);
-
- let prevPrevSibling = prevSibling._prevRep;
-
- // If the tween was part of a set of keyframes, override its siblings
- while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) {
- overrideTween(prevPrevSibling);
- prevPrevSibling = prevPrevSibling._prevRep;
- }
-
- }
-
- const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay;
-
- if (prevAbsEndTime > absoluteUpdateStartTime) {
-
- const prevChangeStartTime = prevSibling._startTime;
- const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration);
- // Rounding is necessary here to minimize floating point errors when working in seconds
- const updatedPrevChangeDuration = round(absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime, 12);
-
- prevSibling._changeDuration = updatedPrevChangeDuration;
- prevSibling._currentTime = updatedPrevChangeDuration;
- prevSibling._isOverlapped = 1;
-
- // Override the previous tween if its new _changeDuration is lower than minValue
- // TODO: See if it's even neceseeary to test against minValue, checking for 0 might be enough
- if (updatedPrevChangeDuration < minValue) {
- overrideTween(prevSibling);
- }
- }
-
- // Pause (and cancel) the parent if it only contains overlapped tweens
-
- let pausePrevParentAnimation = true;
-
- forEachChildren(prevParent, (/** @type Tween */t) => {
- if (!t._isOverlapped) pausePrevParentAnimation = false;
- });
-
- if (pausePrevParentAnimation) {
- const prevParentTL = prevParent.parent;
- if (prevParentTL) {
- let pausePrevParentTL = true;
- forEachChildren(prevParentTL, (/** @type JSAnimation */a) => {
- if (a !== prevParent) {
- forEachChildren(a, (/** @type Tween */t) => {
- if (!t._isOverlapped) pausePrevParentTL = false;
- });
- }
- });
- if (pausePrevParentTL) {
- prevParentTL.cancel();
- }
- } else {
- prevParent.cancel();
- // Previously, calling .cancel() on a timeline child would affect the render order of other children
- // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop
- // This is no longer needed since timeline tween composition is now handled separately
- // Keeping this here for reference
- // prevParent.completed = true;
- // prevParent.pause();
- }
- }
-
- }
-
- // let nextSibling = tween._nextRep;
-
- // // All the next siblings are automatically overridden
-
- // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) {
- // while (nextSibling) {
- // overrideTween(nextSibling);
- // nextSibling = nextSibling._nextRep;
- // }
- // }
-
- // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) {
- // while (nextSibling) {
- // overrideTween(nextSibling);
- // console.log(tween.id, nextSibling.id);
- // nextSibling = nextSibling._nextRep;
- // }
- // }
-
- // Handle additive tweens composition
-
- } else if (tweenCompositionType === compositionTypes.blend) {
-
- const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add');
- const additiveAnimation = addAdditiveAnimation(lookups._add);
-
- let lookupTween = additiveTweenSiblings._head;
-
- if (!lookupTween) {
- lookupTween = { ...tween };
- lookupTween._composition = compositionTypes.replace;
- lookupTween._updateDuration = minValue;
- lookupTween._startTime = 0;
- lookupTween._numbers = cloneArray(tween._fromNumbers);
- lookupTween._number = 0;
- lookupTween._next = null;
- lookupTween._prev = null;
- addChild(additiveTweenSiblings, lookupTween);
- addChild(additiveAnimation, lookupTween);
- }
-
- // Convert the values of TO to FROM and set TO to 0
-
- const toNumber = tween._toNumber;
- tween._fromNumber = lookupTween._fromNumber - toNumber;
- tween._toNumber = 0;
- tween._numbers = cloneArray(tween._fromNumbers);
- tween._number = 0;
- lookupTween._fromNumber = toNumber;
-
- if (tween._toNumbers) {
- const toNumbers = cloneArray(tween._toNumbers);
- if (toNumbers) {
- toNumbers.forEach((value, i) => {
- tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value;
- tween._toNumbers[i] = 0;
- });
- }
- lookupTween._fromNumbers = toNumbers;
- }
-
- addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd');
-
- }
-
- return tween;
-
-};
-
-/**
- * @param {Tween} tween
- * @return {Tween}
- */
-const removeTweenSliblings = tween => {
- const tweenComposition = tween._composition;
- if (tweenComposition !== compositionTypes.none) {
- const tweenTarget = tween.target;
- const tweenProperty = tween.property;
- const replaceTweensLookup = lookups._rep;
- const replaceTargetProps = replaceTweensLookup.get(tweenTarget);
- const tweenReplaceSiblings = replaceTargetProps[tweenProperty];
- removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep');
- if (tweenComposition === compositionTypes.blend) {
- const addTweensLookup = lookups._add;
- const addTargetProps = addTweensLookup.get(tweenTarget);
- if (!addTargetProps) return;
- const additiveTweenSiblings = addTargetProps[tweenProperty];
- const additiveAnimation = additive.animation;
- removeChild(additiveTweenSiblings, tween, '_prevAdd', '_nextAdd');
- // If only one tween is left in the additive lookup, it's the tween lookup
- const lookupTween = additiveTweenSiblings._head;
- if (lookupTween && lookupTween === additiveTweenSiblings._tail) {
- removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd');
- removeChild(additiveAnimation, lookupTween);
- let shouldClean = true;
- for (let prop in addTargetProps) {
- if (addTargetProps[prop]._head) {
- shouldClean = false;
- break;
- }
- }
- if (shouldClean) {
- addTweensLookup.delete(tweenTarget);
- }
- }
- }
- }
- return tween;
-};
-
-
-
-
-/**
- * @param {Timer} timer
- * @return {Timer}
- */
-const resetTimerProperties = timer => {
- timer.paused = true;
- timer.began = false;
- timer.completed = false;
- return timer;
+const resetTimerProperties = timer => {
+ timer.paused = true;
+ timer.began = false;
+ timer.completed = false;
+ return timer;
};
/**
@@ -2745,16 +2598,14 @@ class Timer extends Clock {
return !!this._cancelled;
}
- /** @param {Boolean} cancelled */
set cancelled(cancelled) {
cancelled ? this.cancel() : this.reset(1).play();
}
get currentTime() {
- return clamp(round(this._currentTime, globals.precision), -this._delay, this.duration);
+ return clamp$1(round$1(this._currentTime, globals.precision), -this._delay, this.duration);
}
- /** @param {Number} time */
set currentTime(time) {
const paused = this.paused;
// Pausing the timer is necessary to avoid time jumps on a running instance
@@ -2763,28 +2614,25 @@ class Timer extends Clock {
}
get iterationCurrentTime() {
- return round(this._iterationTime, globals.precision);
+ return round$1(this._iterationTime, globals.precision);
}
- /** @param {Number} time */
set iterationCurrentTime(time) {
this.currentTime = (this.iterationDuration * this._currentIteration) + time;
}
get progress() {
- return clamp(round(this._currentTime / this.duration, 10), 0, 1);
+ return clamp$1(round$1(this._currentTime / this.duration, 10), 0, 1);
}
- /** @param {Number} progress */
set progress(progress) {
this.currentTime = this.duration * progress;
}
get iterationProgress() {
- return clamp(round(this._iterationTime / this.iterationDuration, 10), 0, 1);
+ return clamp$1(round$1(this._iterationTime / this.iterationDuration, 10), 0, 1);
}
- /** @param {Number} progress */
set iterationProgress(progress) {
const iterationDuration = this.iterationDuration;
this.currentTime = (iterationDuration * this._currentIteration) + (iterationDuration * progress);
@@ -2794,16 +2642,14 @@ class Timer extends Clock {
return this._currentIteration;
}
- /** @param {Number} iterationCount */
set currentIteration(iterationCount) {
- this.currentTime = (this.iterationDuration * clamp(+iterationCount, 0, this.iterationCount - 1));
+ this.currentTime = (this.iterationDuration * clamp$1(+iterationCount, 0, this.iterationCount - 1));
}
get reversed() {
return !!this._reversed;
}
- /** @param {Boolean} reverse */
set reversed(reverse) {
reverse ? this.reverse() : this.play();
}
@@ -2812,7 +2658,6 @@ class Timer extends Clock {
return super.speed;
}
- /** @param {Number} playbackRate */
set speed(playbackRate) {
super.speed = playbackRate;
this.resetTime();
@@ -3039,17 +2884,218 @@ const createTimer = parameters => new Timer(parameters, null, 0).init();
-
-/** @type {EasingFunction} */
-const none = t => t;
-
-// Cubic Bezier solver adapted from https://github.com/gre/bezier-ease © Gaëtan Renaudeau
-
/**
- * @param {Number} aT
- * @param {Number} aA1
- * @param {Number} aA2
- * @return {Number}
+ * @param {DOMTargetsParam|TargetsParam} v
+ * @return {NodeList|HTMLCollection}
+ */
+function getNodeList(v) {
+ const n = isStr(v) ? scope.root.querySelectorAll(v) : v;
+ if (n instanceof NodeList || n instanceof HTMLCollection) return n;
+}
+
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+function parseTargets(targets) {
+ if (isNil(targets)) return /** @type {TargetsArray} */([]);
+ if (!isBrowser) return /** @type {JSTargetsArray} */(isArr(targets) && targets.flat(Infinity) || [targets]);
+ if (isArr(targets)) {
+ const flattened = targets.flat(Infinity);
+ /** @type {TargetsArray} */
+ const parsed = [];
+ for (let i = 0, l = flattened.length; i < l; i++) {
+ const item = flattened[i];
+ if (!isNil(item)) {
+ const nodeList = getNodeList(item);
+ if (nodeList) {
+ for (let j = 0, jl = nodeList.length; j < jl; j++) {
+ const subItem = nodeList[j];
+ if (!isNil(subItem)) {
+ let isDuplicate = false;
+ for (let k = 0, kl = parsed.length; k < kl; k++) {
+ if (parsed[k] === subItem) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ parsed.push(subItem);
+ }
+ }
+ }
+ } else {
+ let isDuplicate = false;
+ for (let j = 0, jl = parsed.length; j < jl; j++) {
+ if (parsed[j] === item) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ parsed.push(item);
+ }
+ }
+ }
+ }
+ return parsed;
+ }
+ const nodeList = getNodeList(targets);
+ if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList));
+ return /** @type {TargetsArray} */([targets]);
+}
+
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+function registerTargets(targets) {
+ const parsedTargetsArray = parseTargets(targets);
+ const parsedTargetsLength = parsedTargetsArray.length;
+ if (parsedTargetsLength) {
+ for (let i = 0; i < parsedTargetsLength; i++) {
+ const target = parsedTargetsArray[i];
+ if (!target[isRegisteredTargetSymbol]) {
+ target[isRegisteredTargetSymbol] = true;
+ const isSvgType = isSvg(target);
+ const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType;
+ if (isDom) {
+ target[isDomSymbol] = true;
+ target[isSvgSymbol] = isSvgType;
+ target[transformsSymbol] = {};
+ }
+ }
+ }
+ }
+ return parsedTargetsArray;
+}
+
+const angleUnitsMap = { 'deg': 1, 'rad': 180 / PI, 'turn': 360 };
+const convertedValuesCache = {};
+
+
+
+/**
+ * @param {DOMTarget} el
+ * @param {TweenDecomposedValue} decomposedValue
+ * @param {String} unit
+ * @param {Boolean} [force]
+ * @return {TweenDecomposedValue}
+ */
+const convertValueUnit = (el, decomposedValue, unit, force = false) => {
+ const currentUnit = decomposedValue.u;
+ const currentNumber = decomposedValue.n;
+ if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary
+ return decomposedValue;
+ }
+ const cachedKey = currentNumber + currentUnit + unit;
+ const cached = convertedValuesCache[cachedKey];
+ if (!isUnd(cached) && !force) {
+ decomposedValue.n = cached;
+ } else {
+ let convertedValue;
+ if (currentUnit in angleUnitsMap) {
+ convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit];
+ } else {
+ const baseline = 100;
+ const tempEl = /** @type {DOMTarget} */(el.cloneNode());
+ const parentNode = el.parentNode;
+ const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body;
+ parentEl.appendChild(tempEl);
+ const elStyle = tempEl.style;
+ elStyle.width = baseline + currentUnit;
+ const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
+ elStyle.width = baseline + unit;
+ const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
+ const factor = currentUnitWidth / newUnitWidth;
+ parentEl.removeChild(tempEl);
+ convertedValue = factor * currentNumber;
+ }
+ decomposedValue.n = convertedValue;
+ convertedValuesCache[cachedKey] = convertedValue;
+ }
+ decomposedValue.t === valueTypes.UNIT;
+ decomposedValue.u = unit;
+ return decomposedValue;
+};
+
+
+
+/** @type {EasingFunction} */
+const none = t => t;
+
+
+
+/** @type {PowerEasing} */
+const easeInPower = (p = 1.68) => t => pow(t, +p);
+
+/**
+ * @callback EaseType
+ * @param {EasingFunction} Ease
+ * @return {EasingFunction}
+ */
+
+/** @type {Record<String, EaseType>} */
+const easeTypes = {
+ in: easeIn => t => easeIn(t),
+ out: easeIn => t => 1 - easeIn(1 - t),
+ inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2,
+ outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2,
+};
+
+/**
+ * @param {String} string
+ * @param {Record<String, EasingFunctionWithParams|EasingFunction>} easesFunctions
+ * @param {Object} easesLookups
+ * @return {EasingFunction}
+ */
+const parseEaseString = (string, easesFunctions, easesLookups) => {
+ if (easesLookups[string]) return easesLookups[string];
+ if (string.indexOf('(') <= -1) {
+ const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic');
+ const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasingFunctionWithParams} */(easesFunctions[string])() : easesFunctions[string]);
+ return parsedFn ? easesLookups[string] = parsedFn : none;
+ } else {
+ const split = string.slice(0, -1).split('(');
+ const parsedFn = /** @type {EasingFunctionWithParams} */(easesFunctions[split[0]]);
+ return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none;
+ }
+};
+
+
+
+/**
+ * Cubic Bezier solver adapted from https://github.com/gre/bezier-easing
+ * (c) 2014 Gaëtan Renaudeau
+ */
+
+/**
+ * @param {Number} aT
+ * @param {Number} aA1
+ * @param {Number} aA2
+ * @return {Number}
*/
const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT;
@@ -3085,6 +3131,8 @@ const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1
t => t === 0 || t === 1 ? t :
calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
+
+
/**
* Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
* Only covers 'end' and 'start' jumpterms
@@ -3094,12 +3142,15 @@ const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1
*/
const steps = (steps = 10, fromStart) => {
const roundMethod = fromStart ? ceil : floor;
- return t => roundMethod(clamp(t, 0, 1) * steps) * (1 / steps);
+ return t => roundMethod(clamp$1(t, 0, 1) * steps) * (1 / steps);
};
+
+
/**
* Without parameters, the linear function creates a non-eased transition.
* Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points.
+ *
* @param {...(String|Number)} args - Points
* @return {EasingFunction}
*/
@@ -3136,6 +3187,8 @@ const linear = (...args) => {
}
};
+
+
/**
* Generate random steps
* @param {Number} [length] - The number of steps
@@ -3152,48 +3205,23 @@ const irregular = (length = 10, randomness = 1) => {
const randomVariation = spacing + (segmentEnd - spacing) * Math.random();
// Mix the even spacing and random variation based on the randomness parameter
const randomValue = spacing * (1 - randomness) + randomVariation * randomness;
- values.push(clamp(randomValue, previousValue, 1));
+ values.push(clamp$1(randomValue, previousValue, 1));
}
values.push(1);
return linear(...values);
};
-// Easing functions adapted from http://www.robertpenner.com/ease © Robert Penner
-
-/**
- * @callback PowerEasing
- * @param {Number|String} [power=1.675]
- * @return {EasingFunction}
- */
-
-/**
- * @callback BackEasing
- * @param {Number|String} [overshoot=1.70158]
- * @return {EasingFunction}
- */
-/**
- * @callback ElasticEasing
- * @param {Number|String} [amplitude=1]
- * @param {Number|String} [period=.3]
- * @return {EasingFunction}
- */
/**
- * @callback EaseFactory
- * @param {Number|String} [paramA]
- * @param {Number|String} [paramB]
- * @return {EasingFunction|Number}
+ * Easing functions adapted and simplified from https://robertpenner.com/easing/
+ * (c) 2001 Robert Penner
*/
-/** @typedef {PowerEasing|BackEasing|ElasticEasing} EasesFactory */
-
const halfPI = PI / 2;
const doublePI = PI * 2;
-/** @type {PowerEasing} */
-const easeInPower = (p = 1.68) => t => pow(t, +p);
-/** @type {Record<String, EasesFactory|EasingFunction>} */
+/** @type {Record<String, EasingFunctionWithParams|EasingFunction>} */
const easeInFunctions = {
[emptyString]: easeInPower,
Quad: easeInPower(2),
@@ -3216,47 +3244,14 @@ const easeInFunctions = {
Back: (overshoot = 1.70158) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t,
/** @type {ElasticEasing} */
Elastic: (amplitude = 1, period = .3) => {
- const a = clamp(+amplitude, 1, 10);
- const p = clamp(+period, minValue, 2);
+ const a = clamp$1(+amplitude, 1, 10);
+ const p = clamp$1(+period, minValue, 2);
const s = (p / doublePI) * asin(1 / a);
const e = doublePI / p;
return t => t === 0 || t === 1 ? t : -a * pow(2, -10 * (1 - t)) * sin(((1 - t) - s) * e);
}
};
-/**
- * @callback EaseType
- * @param {EasingFunction} Ease
- * @return {EasingFunction}
- */
-
-/** @type {Record<String, EaseType>} */
-const easeTypes = {
- in: easeIn => t => easeIn(t),
- out: easeIn => t => 1 - easeIn(1 - t),
- inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2,
- outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2,
-};
-
-/**
- * @param {String} string
- * @param {Record<String, EasesFactory|EasingFunction>} easesFunctions
- * @param {Object} easesLookups
- * @return {EasingFunction}
- */
-const parseEaseString = (string, easesFunctions, easesLookups) => {
- if (easesLookups[string]) return easesLookups[string];
- if (string.indexOf('(') <= -1) {
- const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic');
- const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasesFactory} */(easesFunctions[string])() : easesFunctions[string]);
- return parsedFn ? easesLookups[string] = parsedFn : none;
- } else {
- const split = string.slice(0, -1).split('(');
- const parsedFn = /** @type {EasesFactory} */(easesFunctions[split[0]]);
- return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none;
- }
-};
-
/**
* @typedef {Object} EasesFunctions
* @property {typeof linear} linear
@@ -3309,15 +3304,15 @@ const parseEaseString = (string, easesFunctions, easesLookups) => {
* @property {ElasticEasing} outInElastic
*/
-const eases = (/*#__PURE__*/ (() => {
+const eases = (/*#__PURE__ */ (() => {
const list = { linear, irregular, steps, cubicBezier };
for (let type in easeTypes) {
for (let name in easeInFunctions) {
const easeIn = easeInFunctions[name];
const easeType = easeTypes[type];
- list[type + name] = /** @type {EasesFactory|EasingFunction} */(
+ list[type + name] = /** @type {EasingFunctionWithParams|EasingFunction} */(
name === emptyString || name === 'Back' || name === 'Elastic' ?
- (a, b) => easeType(/** @type {EasesFactory} */(easeIn)(a, b)) :
+ (a, b) => easeType(/** @type {EasingFunctionWithParams} */(easeIn)(a, b)) :
easeType(/** @type {EasingFunction} */(easeIn))
);
}
@@ -3332,152 +3327,12 @@ const JSEasesLookups = { linear: none };
* @param {EasingParam} ease
* @return {EasingFunction}
*/
-const parseEasings = ease => isFnc(ease) ? ease :
+const parseEase = ease => isFnc(ease) ? ease :
isStr(ease) ? parseEaseString(/** @type {String} */(ease), eases, JSEasesLookups) :
none;
-
-const propertyNamesCache = {};
-
-/**
- * @param {String} propertyName
- * @param {Target} target
- * @param {tweenTypes} tweenType
- * @return {String}
- */
-const sanitizePropertyName = (propertyName, target, tweenType) => {
- if (tweenType === tweenTypes.TRANSFORM) {
- const t = shortTransforms.get(propertyName);
- return t ? t : propertyName;
- } else if (
- tweenType === tweenTypes.CSS ||
- // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
- // but properties like "baseFrequency" should stay in lowerCamelCase
- (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
- ) {
- const cachedPropertyName = propertyNamesCache[propertyName];
- if (cachedPropertyName) {
- return cachedPropertyName;
- } else {
- const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
- propertyNamesCache[propertyName] = lowerCaseName;
- return lowerCaseName;
- }
- } else {
- return propertyName;
- }
-};
-
-
-
-
-const angleUnitsMap = { 'deg': 1, 'rad': 180 / PI, 'turn': 360 };
-const convertedValuesCache = {};
-
-/**
- * @param {DOMTarget} el
- * @param {TweenDecomposedValue} decomposedValue
- * @param {String} unit
- * @param {Boolean} [force]
- * @return {TweenDecomposedValue}
- */
-const convertValueUnit = (el, decomposedValue, unit, force = false) => {
- const currentUnit = decomposedValue.u;
- const currentNumber = decomposedValue.n;
- if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary
- return decomposedValue;
- }
- const cachedKey = currentNumber + currentUnit + unit;
- const cached = convertedValuesCache[cachedKey];
- if (!isUnd(cached) && !force) {
- decomposedValue.n = cached;
- } else {
- let convertedValue;
- if (currentUnit in angleUnitsMap) {
- convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit];
- } else {
- const baseline = 100;
- const tempEl = /** @type {DOMTarget} */(el.cloneNode());
- const parentNode = el.parentNode;
- const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body;
- parentEl.appendChild(tempEl);
- const elStyle = tempEl.style;
- elStyle.width = baseline + currentUnit;
- const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
- elStyle.width = baseline + unit;
- const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
- const factor = currentUnitWidth / newUnitWidth;
- parentEl.removeChild(tempEl);
- convertedValue = factor * currentNumber;
- }
- decomposedValue.n = convertedValue;
- convertedValuesCache[cachedKey] = convertedValue;
- }
- decomposedValue.t === valueTypes.UNIT;
- decomposedValue.u = unit;
- return decomposedValue;
-};
-
-
-
-
-/**
- * @template {Renderable} T
- * @param {T} renderable
- * @return {T}
- */
-const cleanInlineStyles = renderable => {
- // Allow cleanInlineStyles() to be called on timelines
- if (renderable._hasChildren) {
- forEachChildren(renderable, cleanInlineStyles, true);
- } else {
- const animation = /** @type {JSAnimation} */(renderable);
- animation.pause();
- forEachChildren(animation, (/** @type {Tween} */tween) => {
- const tweenProperty = tween.property;
- const tweenTarget = tween.target;
- if (tweenTarget[isDomSymbol]) {
- const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
- const originalInlinedValue = animation._inlineStyles[tweenProperty];
- if (tween._tweenType === tweenTypes.TRANSFORM) {
- const cachedTransforms = tweenTarget[transformsSymbol];
- if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
- delete cachedTransforms[tweenProperty];
- } else {
- cachedTransforms[tweenProperty] = originalInlinedValue;
- }
- if (tween._renderTransforms) {
- if (!Object.keys(cachedTransforms).length) {
- targetStyle.removeProperty('transform');
- } else {
- let str = emptyString;
- for (let key in cachedTransforms) {
- str += transformsFragmentStrings[key] + cachedTransforms[key] + ') ';
- }
- targetStyle.transform = str;
- }
- }
- } else {
- if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
- targetStyle.removeProperty(tweenProperty);
- } else {
- targetStyle[tweenProperty] = originalInlinedValue;
- }
- }
- if (animation._tail === tween) {
- animation.targets.forEach(t => {
- if (t.getAttribute && t.getAttribute('style') === emptyString) {
- t.removeAttribute('style');
- } });
- }
- }
- });
- }
- return renderable;
-};
-
// Defines decomposed values target objects only once and mutate their properties later to avoid GC
// TODO: Maybe move the objects creation to values.js and use the decompose function to create the base object
const fromTargetObject = createDecomposedValueTargetObject();
@@ -3601,7 +3456,7 @@ class JSAnimation extends Timer {
length = 0
) {
- super(/** @type {TimerParams&AnimationParams} */(parameters), parent, parentPosition);
+ super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
const parsedTargets = registerTargets(targets);
const targetsLength = parsedTargets.length;
@@ -3623,7 +3478,7 @@ class JSAnimation extends Timer {
const animDefaults = parent ? parent.defaults : globals.defaults;
const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
- const animEase = animaPlaybackEase ? parseEasings(animaPlaybackEase) : null;
+ const animEase = animaPlaybackEase ? parseEase(animaPlaybackEase) : null;
const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease);
const tDuration = hasSpring ? /** @type {Spring} */(ease).duration : setValue(duration, animDefaults.duration);
@@ -3749,7 +3604,7 @@ class JSAnimation extends Timer {
const isFromToValue = isFromToArray || (hasFromvalue && hasToValue);
const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay;
// Rounding is necessary here to minimize floating point errors when working in seconds
- const absoluteStartTime = round(absoluteOffsetTime + tweenStartTime, 12);
+ const absoluteStartTime = round$1(absoluteOffsetTime + tweenStartTime, 12);
// Force a onRender callback if the animation contains at least one from value and autoplay is set to false
if (!shouldTriggerRender && (hasFromvalue || isFromToArray)) shouldTriggerRender = 1;
@@ -3871,14 +3726,14 @@ class JSAnimation extends Timer {
const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject;
const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject;
// TODO: Check if n should be used instead of 0 for default complex values
- shortestValue.d = longestValue.d.map((_, i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
+ shortestValue.d = longestValue.d.map((/** @type {Number} */_, /** @type {Number} */i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
shortestValue.s = cloneArray(longestValue.s);
}
// Tween factory
// Rounding is necessary here to minimize floating point errors when working in seconds
- const tweenUpdateDuration = round(+tweenDuration || minValue, 12);
+ const tweenUpdateDuration = round$1(+tweenDuration || minValue, 12);
/** @type {Tween} */
const tween = {
@@ -3888,7 +3743,7 @@ class JSAnimation extends Timer {
target: target,
_value: null,
_func: toFunctionStore.func,
- _ease: parseEasings(tweenEasing),
+ _ease: parseEase(tweenEasing),
_fromNumbers: cloneArray(fromTargetObject.d),
_toNumbers: cloneArray(toTargetObject.d),
_strings: cloneArray(toTargetObject.s),
@@ -3927,7 +3782,7 @@ class JSAnimation extends Timer {
firstTweenChangeStartTime = tween._startTime;
}
// Rounding is necessary here to minimize floating point errors when working in seconds
- lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12);
+ lastTweenChangeEndTime = round$1(tweenStartTime + tweenUpdateDuration, 12);
prevTween = tween;
animationAnimationLength++;
@@ -4089,82 +3944,6 @@ const animate = (targets, parameters) => new JSAnimation(targets, parameters, nu
-/**
- * Converts an easing function into a valid CSS linear() timing function string
- * @param {EasingFunction} fn
- * @param {number} [samples=100]
- * @returns {string} CSS linear() timing function
- */
-const easingToLinear = (fn, samples = 100) => {
- const points = [];
- for (let i = 0; i <= samples; i++) points.push(fn(i / samples));
- return `linear(${points.join(', ')})`;
-};
-
-const WAAPIEasesLookups = {
- in: 'ease-in',
- out: 'ease-out',
- inOut: 'ease-in-out',
-};
-
-const WAAPIeases = /*#__PURE__*/(() => {
- const list = {};
- for (let type in easeTypes) list[type] = (/** @type {String|Number} */p) => easeTypes[type](easeInPower(p));
- return /** @type {Record<String, EasingFunction>} */(list);
-})();
-
-/**
- * @param {EasingParam} ease
- * @return {String}
- */
-const parseWAAPIEasing = (ease) => {
- let parsedEase = WAAPIEasesLookups[ease];
- if (parsedEase) return parsedEase;
- parsedEase = 'linear';
- if (isStr(ease)) {
- if (
- stringStartsWith(ease, 'linear') ||
- stringStartsWith(ease, 'cubic-') ||
- stringStartsWith(ease, 'steps') ||
- stringStartsWith(ease, 'ease')
- ) {
- parsedEase = ease;
- } else if (stringStartsWith(ease, 'cubicB')) {
- parsedEase = toLowerCase(ease);
- } else {
- const parsed = parseEaseString(ease, WAAPIeases, WAAPIEasesLookups);
- if (isFnc(parsed)) parsedEase = parsed === none ? 'linear' : easingToLinear(parsed);
- }
- WAAPIEasesLookups[ease] = parsedEase;
- } else if (isFnc(ease)) {
- const easing = easingToLinear(ease);
- if (easing) parsedEase = easing;
- } else if (/** @type {Spring} */(ease).ease) {
- parsedEase = easingToLinear(/** @type {Spring} */(ease).ease);
- }
- return parsedEase;
-};
-
-const transformsShorthands = ['x', 'y', 'z'];
-const commonDefaultPXProperties = [
- 'perspective',
- 'width',
- 'height',
- 'margin',
- 'padding',
- 'top',
- 'right',
- 'bottom',
- 'left',
- 'borderWidth',
- 'fontSize',
- 'borderRadius',
- ...transformsShorthands
-];
-
-const validIndividualTransforms = /*#__PURE__*/ (() => [...transformsShorthands, ...validTransforms.filter(t => ['X', 'Y', 'Z'].some(axis => t.endsWith(axis)))])();
-
-let transformsPropertiesRegistered = null;
const WAAPIAnimationsLookups = {
_head: null,
@@ -4230,4137 +4009,4546 @@ const addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
return animation;
};
+
+
+
+
/**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
* @param {String} propName
- * @param {WAAPIKeyframeValue} value
- * @param {DOMTarget} $el
- * @param {Number} i
- * @param {Number} targetsLength
* @return {String}
- */
-const normalizeTweenValue = (propName, value, $el, i, targetsLength) => {
- let v = getFunctionValue(/** @type {any} */(value), $el, i, targetsLength);
- if (!isNum(v)) return v;
- if (commonDefaultPXProperties.includes(propName) || stringStartsWith(propName, 'translate')) return `${v}px`;
- if (stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew')) return `${v}deg`;
- return `${v}`;
-};
-
-/**
- * @param {DOMTarget} $el
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
* @param {String} propName
- * @param {WAAPIKeyframeValue} from
- * @param {WAAPIKeyframeValue} to
- * @param {Number} i
- * @param {Number} targetsLength
- * @return {WAAPITweenValue}
- */
-const parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => {
- /** @type {WAAPITweenValue} */
- let tweenValue = '0';
- const computedTo = !isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName];
- if (!isUnd(from)) {
- const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength);
- tweenValue = [computedFrom, computedTo];
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+function get(targetSelector, propName, unit) {
+ const targets = registerTargets(targetSelector);
+ if (!targets.length) return;
+ const [ target ] = targets;
+ const tweenType = getTweenType(target, propName);
+ const normalizePropName = sanitizePropertyName(propName, target, tweenType);
+ let originalValue = getOriginalAnimatableValue(target, normalizePropName);
+ if (isUnd(unit)) {
+ return originalValue;
} else {
- tweenValue = isArr(to) ? to.map((/** @type {any} */v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo;
+ decomposeRawValue(originalValue, decomposedOriginalValue);
+ if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) {
+ if (unit === false) {
+ return decomposedOriginalValue.n;
+ } else {
+ const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false);
+ return `${round$1(convertedValue.n, globals.precision)}${convertedValue.u}`;
+ }
+ }
}
- return tweenValue;
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @return {JSAnimation}
+ */
+const set = (targets, parameters) => {
+ if (isUnd(parameters)) return;
+ parameters.duration = minValue;
+ // Do not overrides currently active tweens by default
+ parameters.composition = setValue(parameters.composition, compositionTypes.none);
+ // Skip init() and force rendering by playing the animation
+ return new JSAnimation(targets, parameters, null, 0, true).resume();
};
-class WAAPIAnimation {
/**
- * @param {DOMTargetsParam} targets
- * @param {WAAPIAnimationParams} params
+ * @param {TargetsParam} targets
+ * @param {Renderable|WAAPIAnimation} [renderable]
+ * @param {String} [propertyName]
+ * @return {TargetsArray}
*/
- constructor(targets, params) {
+const remove = (targets, renderable, propertyName) => {
+ const targetsArray = parseTargets(targets);
+ for (let i = 0, l = targetsArray.length; i < l; i++) {
+ removeWAAPIAnimation(
+ /** @type {DOMTarget} */(targetsArray[i]),
+ propertyName,
+ renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable),
+ );
+ }
+ removeTargetsFromRenderable(
+ targetsArray,
+ /** @type {Renderable} */(renderable),
+ propertyName
+ );
+ return targetsArray;
+};
- if (scope.current) scope.current.register(this);
- // Skip the registration and fallback to no animation in case CSS.registerProperty is not supported
- if (isNil(transformsPropertiesRegistered)) {
- if (isBrowser && (isUnd(CSS) || !Object.hasOwnProperty.call(CSS, 'registerProperty'))) {
- transformsPropertiesRegistered = false;
- } else {
- validTransforms.forEach(t => {
- const isSkew = stringStartsWith(t, 'skew');
- const isScale = stringStartsWith(t, 'scale');
- const isRotate = stringStartsWith(t, 'rotate');
- const isTranslate = stringStartsWith(t, 'translate');
- const isAngle = isRotate || isSkew;
- const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*";
- try {
- CSS.registerProperty({
- name: '--' + t,
- syntax,
- inherits: false,
- initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0',
- });
- } catch {} });
- transformsPropertiesRegistered = true;
- }
- }
- const parsedTargets = registerTargets(targets);
- const targetsLength = parsedTargets.length;
- if (!targetsLength) {
- console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
- }
- const ease = setValue(params.ease, parseWAAPIEasing(globals.defaults.ease));
- const spring = /** @type {Spring} */(ease).ease && ease;
- const autoplay = setValue(params.autoplay, globals.defaults.autoplay);
- const scroll = autoplay && /** @type {ScrollObserver} */(autoplay).link ? autoplay : false;
- const alternate = params.alternate && /** @type {Boolean} */(params.alternate) === true;
- const reversed = params.reversed && /** @type {Boolean} */(params.reversed) === true;
- const loop = setValue(params.loop, globals.defaults.loop);
- const iterations = /** @type {Number} */((loop === true || loop === Infinity) ? Infinity : isNum(loop) ? loop + 1 : 1);
- /** @type {PlaybackDirection} */
- const direction = alternate ? reversed ? 'alternate-reverse' : 'alternate' : reversed ? 'reverse' : 'normal';
- /** @type {FillMode} */
- const fill = 'forwards';
- /** @type {String} */
- const easing = parseWAAPIEasing(ease);
- const timeScale = (globals.timeScale === 1 ? 1 : K);
+/**
+ * Timeline's children offsets positions parser
+ * @param {Timeline} timeline
+ * @param {String} timePosition
+ * @return {Number}
+ */
+const getPrevChildOffset = (timeline, timePosition) => {
+ if (stringStartsWith(timePosition, '<')) {
+ const goToPrevAnimationOffset = timePosition[1] === '<';
+ const prevAnimation = /** @type {Tickable} */(timeline._tail);
+ const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
+ return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
+ }
+};
- /** @type {DOMTargetsArray}] */
- this.targets = parsedTargets;
- /** @type {Array<globalThis.Animation>}] */
- this.animations = [];
- /** @type {globalThis.Animation}] */
- this.controlAnimation = null;
- /** @type {Callback<this>} */
- this.onComplete = params.onComplete || noop;
- /** @type {Number} */
- this.duration = 0;
- /** @type {Boolean} */
- this.muteCallbacks = false;
- /** @type {Boolean} */
- this.completed = false;
- /** @type {Boolean} */
- this.paused = !autoplay || scroll !== false;
- /** @type {Boolean} */
- this.reversed = reversed;
- /** @type {Boolean|ScrollObserver} */
- this.autoplay = autoplay;
- /** @type {Number} */
- this._speed = setValue(params.playbackRate, globals.defaults.playbackRate);
- /** @type {Function} */
- this._resolve = noop; // Used by .then()
- /** @type {Number} */
- this._completed = 0;
- /** @type {Array<Object>}] */
- this._inlineStyles = parsedTargets.map($el => $el.getAttribute('style'));
+/**
+ * @param {Timeline} timeline
+ * @param {TimelinePosition} [timePosition]
+ * @return {Number}
+ */
+const parseTimelinePosition = (timeline, timePosition) => {
+ let tlDuration = timeline.iterationDuration;
+ if (tlDuration === minValue) tlDuration = 0;
+ if (isUnd(timePosition)) return tlDuration;
+ if (isNum(+timePosition)) return +timePosition;
+ const timePosStr = /** @type {String} */(timePosition);
+ const tlLabels = timeline ? timeline.labels : null;
+ const hasLabels = !isNil(tlLabels);
+ const prevOffset = getPrevChildOffset(timeline, timePosStr);
+ const hasSibling = !isUnd(prevOffset);
+ const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
+ if (matchedRelativeOperator) {
+ const fullOperator = matchedRelativeOperator[0];
+ const split = timePosStr.split(fullOperator);
+ const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
+ const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
+ const parsedNumericalOffset = +split[1];
+ return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
+ } else {
+ return hasSibling ? prevOffset :
+ hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
+ tlDuration : tlDuration;
+ }
+};
- parsedTargets.forEach(($el, i) => {
- const cachedTransforms = $el[transformsSymbol];
- const hasIndividualTransforms = validIndividualTransforms.some(t => params.hasOwnProperty(t));
- /** @type {Number} */
- const duration = (spring ? /** @type {Spring} */(spring).duration : getFunctionValue(setValue(params.duration, globals.defaults.duration), $el, i, targetsLength)) * timeScale;
- /** @type {Number} */
- const delay = getFunctionValue(setValue(params.delay, globals.defaults.delay), $el, i, targetsLength) * timeScale;
- /** @type {CompositeOperation} */
- const composite = /** @type {CompositeOperation} */(setValue(params.composition, 'replace'));
- for (let name in params) {
- if (!isKey(name)) continue;
- /** @type {PropertyIndexedKeyframes} */
- const keyframes = {};
- /** @type {KeyframeAnimationOptions} */
- const tweenParams = { iterations, direction, fill, easing, duration, delay, composite };
- const propertyValue = params[name];
- const individualTransformProperty = hasIndividualTransforms ? validTransforms.includes(name) ? name : shortTransforms.get(name) : false;
- let parsedPropertyValue;
- if (isObj(propertyValue)) {
- const tweenOptions = /** @type {WAAPITweenOptions} */(propertyValue);
- const tweenOptionsEase = setValue(tweenOptions.ease, ease);
- const tweenOptionsSpring = /** @type {Spring} */(tweenOptionsEase).ease && tweenOptionsEase;
- const to = /** @type {WAAPITweenOptions} */(tweenOptions).to;
- const from = /** @type {WAAPITweenOptions} */(tweenOptions).from;
- /** @type {Number} */
- tweenParams.duration = (tweenOptionsSpring ? /** @type {Spring} */(tweenOptionsSpring).duration : getFunctionValue(setValue(tweenOptions.duration, duration), $el, i, targetsLength)) * timeScale;
- /** @type {Number} */
- tweenParams.delay = getFunctionValue(setValue(tweenOptions.delay, delay), $el, i, targetsLength) * timeScale;
- /** @type {CompositeOperation} */
- tweenParams.composite = /** @type {CompositeOperation} */(setValue(tweenOptions.composition, composite));
- /** @type {String} */
- tweenParams.easing = parseWAAPIEasing(tweenOptionsEase);
- parsedPropertyValue = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
- if (individualTransformProperty) {
- keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
- cachedTransforms[individualTransformProperty] = parsedPropertyValue;
- } else {
- keyframes[name] = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
- }
- addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
- if (!isUnd(from)) {
- if (!individualTransformProperty) {
- $el.style[name] = keyframes[name][0];
- } else {
- const key = `--${individualTransformProperty}`;
- $el.style.setProperty(key, keyframes[key][0]);
- }
- }
- } else {
- parsedPropertyValue = isArr(propertyValue) ?
- propertyValue.map((/** @type {any} */v) => normalizeTweenValue(name, v, $el, i, targetsLength)) :
- normalizeTweenValue(name, /** @type {any} */(propertyValue), $el, i, targetsLength);
- if (individualTransformProperty) {
- keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
- cachedTransforms[individualTransformProperty] = parsedPropertyValue;
- } else {
- keyframes[name] = parsedPropertyValue;
- }
- addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
- }
- }
- if (hasIndividualTransforms) {
- let transforms = emptyString;
- for (let t in cachedTransforms) {
- transforms += `${transformsFragmentStrings[t]}var(--${t})) `;
- }
- $el.style.transform = transforms;
- }
- });
+/**
+ * @param {Timeline} tl
+ * @return {Number}
+ */
+function getTimelineTotalDuration(tl) {
+ return clampInfinity(((tl.iterationDuration + tl._loopDelay) * tl.iterationCount) - tl._loopDelay) || minValue;
+}
- if (scroll) {
- /** @type {ScrollObserver} */(this.autoplay).link(this);
- }
+/**
+ * @overload
+ * @param {TimerParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @return {Timeline}
+ *
+ * @overload
+ * @param {AnimationParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @param {TargetsParam} targets
+ * @param {Number} [index]
+ * @param {Number} [length]
+ * @return {Timeline}
+ *
+ * @param {TimerParams|AnimationParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @param {TargetsParam} [targets]
+ * @param {Number} [index]
+ * @param {Number} [length]
+ */
+function addTlChild(childParams, tl, timePosition, targets, index, length) {
+ const isSetter = isNum(childParams.duration) && /** @type {Number} */(childParams.duration) <= minValue;
+ // Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position
+ const adjustedPosition = isSetter ? timePosition - minValue : timePosition;
+ tick(tl, adjustedPosition, 1, 1, tickModes.AUTO);
+ const tlChild = targets ?
+ new JSAnimation(targets,/** @type {AnimationParams} */(childParams), tl, adjustedPosition, false, index, length) :
+ new Timer(/** @type {TimerParams} */(childParams), tl, adjustedPosition);
+ tlChild.init(1);
+ // TODO: Might be better to insert at a position relative to startTime?
+ addChild(tl, tlChild);
+ forEachChildren(tl, (/** @type {Renderable} */child) => {
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > tl.iterationDuration) tl.iterationDuration = childDur;
+ });
+ tl.duration = getTimelineTotalDuration(tl);
+ return tl;
+}
+
+class Timeline extends Timer {
+
+ /**
+ * @param {TimelineParams} [parameters]
+ */
+ constructor(parameters = {}) {
+ super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0);
+ /** @type {Number} */
+ this.duration = 0; // TL duration starts at 0 and grows when adding children
+ /** @type {Record<String, Number>} */
+ this.labels = {};
+ const defaultsParams = parameters.defaults;
+ const globalDefaults = globals.defaults;
+ /** @type {DefaultsParams} */
+ this.defaults = defaultsParams ? mergeObjects(defaultsParams, globalDefaults) : globalDefaults;
+ /** @type {Callback<this>} */
+ this.onRender = parameters.onRender || globalDefaults.onRender;
+ const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase);
+ this._ease = tlPlaybackEase ? parseEase(tlPlaybackEase) : null;
+ /** @type {Number} */
+ this.iterationDuration = 0;
}
/**
- * @callback forEachCallback
- * @param {globalThis.Animation} animation
+ * @overload
+ * @param {TargetsParam} a1
+ * @param {AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ * @return {this}
+ *
+ * @overload
+ * @param {TimerParams} a1
+ * @param {TimelinePosition} [a2]
+ * @return {this}
+ *
+ * @param {TargetsParam|TimerParams} a1
+ * @param {TimelinePosition|AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
*/
+ add(a1, a2, a3) {
+ const isAnim = isObj(a2);
+ const isTimer = isObj(a1);
+ if (isAnim || isTimer) {
+ this._hasChildren = true;
+ if (isAnim) {
+ const childParams = /** @type {AnimationParams} */(a2);
+ // Check for function for children stagger positions
+ if (isFnc(a3)) {
+ const staggeredPosition = a3;
+ const parsedTargetsArray = parseTargets(/** @type {TargetsParam} */(a1));
+ // Store initial duration before adding new children that will change the duration
+ const tlDuration = this.duration;
+ // Store initial _iterationDuration before adding new children that will change the duration
+ const tlIterationDuration = this.iterationDuration;
+ // Store the original id in order to add specific indexes to the new animations ids
+ const id = childParams.id;
+ let i = 0;
+ /** @type {Number} */
+ const parsedLength = (parsedTargetsArray.length);
+ parsedTargetsArray.forEach((/** @type {Target} */target) => {
+ // Create a new parameter object for each staggered children
+ const staggeredChildParams = { ...childParams };
+ // Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation
+ this.duration = tlDuration;
+ this.iterationDuration = tlIterationDuration;
+ if (!isUnd(id)) staggeredChildParams.id = id + '-' + i;
+ addTlChild(
+ staggeredChildParams,
+ this,
+ parseTimelinePosition(this, staggeredPosition(target, i, parsedLength, this)),
+ target,
+ i,
+ parsedLength
+ );
+ i++;
+ });
+ } else {
+ addTlChild(
+ childParams,
+ this,
+ parseTimelinePosition(this, a3),
+ /** @type {TargetsParam} */(a1),
+ );
+ }
+ } else {
+ // It's a Timer
+ addTlChild(
+ /** @type TimerParams */(a1),
+ this,
+ parseTimelinePosition(this,a2),
+ );
+ }
+ return this.init(1); // 1 = internalRender
+ }
+ }
/**
- * @param {forEachCallback|String} callback
+ * @overload
+ * @param {Tickable} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {WAAPIAnimation} [synced]
+ * @param {TimelinePosition} [position]
* @return {this}
+ *
+ * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
*/
- forEach(callback) {
- const cb = isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback;
- this.animations.forEach(cb);
- return this;
+ sync(synced, position) {
+ if (isUnd(synced) || synced && isUnd(synced.pause)) return this;
+ synced.pause();
+ const duration = +(/** @type {globalThis.Animation} */(synced).effect ? /** @type {globalThis.Animation} */(synced).effect.getTiming().duration : /** @type {Tickable} */(synced).duration);
+ return this.add(synced, { currentTime: [0, duration], duration, ease: 'linear' }, position);
}
- get speed() {
- return this._speed;
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ set(targets, parameters, position) {
+ if (isUnd(parameters)) return this;
+ parameters.duration = minValue;
+ parameters.composition = compositionTypes.replace;
+ return this.add(targets, parameters, position);
}
- /** @param {Number} speed */
- set speed(speed) {
- this._speed = +speed;
- this.forEach(anim => anim.playbackRate = speed);
+ /**
+ * @param {Callback<Timer>} callback
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ call(callback, position) {
+ if (isUnd(callback) || callback && !isFnc(callback)) return this;
+ return this.add({ duration: 0, onComplete: () => callback(this) }, position);
}
- get currentTime() {
- const controlAnimation = this.controlAnimation;
- const timeScale = globals.timeScale;
- return this.completed ? this.duration : controlAnimation ? +controlAnimation.currentTime * (timeScale === 1 ? 1 : timeScale) : 0;
+ /**
+ * @param {String} labelName
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ */
+ label(labelName, position) {
+ if (isUnd(labelName) || labelName && !isStr(labelName)) return this;
+ this.labels[labelName] = parseTimelinePosition(this, position);
+ return this;
}
- /** @param {Number} time */
- set currentTime(time) {
- const t = time * (globals.timeScale === 1 ? 1 : K);
- this.forEach(anim => {
- // Make sure the animation playState is not 'paused' in order to properly trigger an onfinish callback.
- // The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported.
- // https://developer.mozilla.org/en-US/docs/Web/API/Animation/finish_event
- if (t >= this.duration) anim.play();
- anim.currentTime = t;
- });
+ /**
+ * @param {TargetsParam} targets
+ * @param {String} [propertyName]
+ * @return {this}
+ */
+ remove(targets, propertyName) {
+ removeTargetsFromRenderable(parseTargets(targets), this, propertyName);
+ return this;
}
- get progress() {
- return this.currentTime / this.duration;
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ if (currentDuration === normalizeTime(newDuration)) return this;
+ const timeScale = newDuration / currentDuration;
+ const labels = this.labels;
+ forEachChildren(this, (/** @type {JSAnimation} */child) => child.stretch(child.duration * timeScale));
+ for (let labelName in labels) labels[labelName] *= timeScale;
+ return super.stretch(newDuration);
}
- /** @param {Number} progress */
- set progress(progress) {
- this.forEach(anim => anim.currentTime = progress * this.duration || 0);
+ /**
+ * @return {this}
+ */
+ refresh() {
+ forEachChildren(this, (/** @type {JSAnimation} */child) => {
+ if (child.refresh) child.refresh();
+ });
+ return this;
}
- resume() {
- if (!this.paused) return this;
- this.paused = false;
- // TODO: Store the current time, and seek back to the last position
- return this.forEach('play');
+ /**
+ * @return {this}
+ */
+ revert() {
+ super.revert();
+ forEachChildren(this, (/** @type {JSAnimation} */child) => child.revert, true);
+ return cleanInlineStyles(this);
}
- pause() {
- if (this.paused) return this;
- this.paused = true;
- return this.forEach('pause');
- }
-
- alternate() {
- this.reversed = !this.reversed;
- this.forEach('reverse');
- if (this.paused) this.forEach('pause');
- return this;
- }
-
- play() {
- if (this.reversed) this.alternate();
- return this.resume();
- }
-
- reverse() {
- if (!this.reversed) this.alternate();
- return this.resume();
- }
-
- /**
- * @param {Number} time
- * @param {Boolean} muteCallbacks
- */
- seek(time, muteCallbacks = false) {
- if (muteCallbacks) this.muteCallbacks = true;
- if (time < this.duration) this.completed = false;
- this.currentTime = time;
- this.muteCallbacks = false;
- if (this.paused) this.pause();
- return this;
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback) {
+ return super.then(callback);
}
+}
- restart() {
- this.completed = false;
- return this.seek(0, true).resume();
- }
+/**
+ * @param {TimelineParams} [parameters]
+ * @return {Timeline}
+ */
+const createTimeline = parameters => new Timeline(parameters).init();
- commitStyles() {
- return this.forEach('commitStyles');
- }
- complete() {
- return this.seek(this.duration);
- }
- cancel() {
- this.forEach('cancel');
- return this.pause();
+class Animatable {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ */
+ constructor(targets, parameters) {
+ if (scope.current) scope.current.register(this);
+ const beginHandler = () => {
+ if (this.callbacks.completed) this.callbacks.reset();
+ this.callbacks.play();
+ };
+ const pauseHandler = () => {
+ if (this.callbacks.completed) return;
+ let paused = true;
+ for (let name in this.animations) {
+ const anim = this.animations[name];
+ if (!anim.paused && paused) {
+ paused = false;
+ break;
+ }
+ }
+ if (paused) {
+ this.callbacks.complete();
+ }
+ };
+ /** @type {AnimationParams} */
+ const globalParams = {
+ onBegin: beginHandler,
+ onComplete: pauseHandler,
+ onPause: pauseHandler,
+ };
+ /** @type {AnimationParams} */
+ const callbacksAnimationParams = { v: 1, autoplay: false };
+ const properties = {};
+ this.targets = [];
+ this.animations = {};
+ /** @type {JSAnimation|null} */
+ this.callbacks = null;
+ if (isUnd(targets) || isUnd(parameters)) return;
+ for (let propName in parameters) {
+ const paramValue = parameters[propName];
+ if (isKey(propName)) {
+ properties[propName] = paramValue;
+ } else if (stringStartsWith(propName, 'on')) {
+ callbacksAnimationParams[propName] = paramValue;
+ } else {
+ globalParams[propName] = paramValue;
+ }
+ }
+ this.callbacks = new JSAnimation({ v: 0 }, callbacksAnimationParams);
+ for (let propName in properties) {
+ const propValue = properties[propName];
+ const isObjValue = isObj(propValue);
+ /** @type {TweenParamsOptions} */
+ let propParams = {};
+ let to = '+=0';
+ if (isObjValue) {
+ const unit = propValue.unit;
+ if (isStr(unit)) to += unit;
+ } else {
+ propParams.duration = propValue;
+ }
+ propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to;
+ const animParams = mergeObjects(globalParams, propParams);
+ animParams.composition = compositionTypes.replace;
+ animParams.autoplay = false;
+ const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init();
+ if (!this.targets.length) this.targets.push(...animation.targets);
+ /** @type {AnimatableProperty} */
+ this[propName] = (to, duration, ease) => {
+ const tween = /** @type {Tween} */(animation._head);
+ if (isUnd(to) && tween) {
+ const numbers = tween._numbers;
+ if (numbers && numbers.length) {
+ return numbers;
+ } else {
+ return tween._modifier(tween._number);
+ }
+ } else {
+ forEachChildren(animation, (/** @type {Tween} */tween) => {
+ if (isArr(to)) {
+ for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) {
+ if (!isUnd(tween._numbers[i])) {
+ tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i]));
+ tween._toNumbers[i] = to[i];
+ }
+ }
+ } else {
+ tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number));
+ tween._toNumber = /** @type {Number} */(to);
+ }
+ if (!isUnd(ease)) tween._ease = parseEase(ease);
+ tween._currentTime = 0;
+ });
+ if (!isUnd(duration)) animation.stretch(duration);
+ animation.reset(1).resume();
+ return this;
+ }
+ };
+ }
}
revert() {
- this.cancel();
- this.targets.forEach(($el, i) => $el.setAttribute('style', this._inlineStyles[i]) );
+ for (let propName in this.animations) {
+ this[propName] = noop;
+ this.animations[propName].revert();
+ }
+ this.animations = {};
+ this.targets.length = 0;
+ if (this.callbacks) this.callbacks.revert();
return this;
}
-
- /**
- * @param {WAAPICallback} [callback]
- * @return {Promise}
- */
- then(callback = noop) {
- const then = this.then;
- const onResolve = () => {
- this.then = null;
- callback(this);
- this.then = then;
- this._resolve = noop;
- };
- return new Promise(r => {
- this._resolve = () => r(onResolve());
- if (this.completed) this._resolve();
- return this;
- });
- }
}
-const waapi = {
/**
- * @param {DOMTargetsParam} targets
- * @param {WAAPIAnimationParams} params
- * @return {WAAPIAnimation}
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ * @return {AnimatableObject}
*/
- animate: (targets, params) => new WAAPIAnimation(targets, params),
- convertEase: easingToLinear
-};
-
-
-
+const createAnimatable = (targets, parameters) => /** @type {AnimatableObject} */ (new Animatable(targets, parameters));
/**
- * @param {Callback<Timer>} [callback]
- * @return {Timer}
+ * Rounds a number to fixed decimal places
+ * @param {Number|String} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {String}
*/
-const sync = (callback = noop) => {
- return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
-};
+const roundPad$1 = (v, decimalLength) => (+v).toFixed(decimalLength);
/**
- * @overload
- * @param {DOMTargetSelector} targetSelector
- * @param {String} propName
+ * Pads the start of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
* @return {String}
- *
- * @overload
- * @param {JSTargetsParam} targetSelector
- * @param {String} propName
- * @return {Number|String}
- *
- * @overload
- * @param {DOMTargetsParam} targetSelector
- * @param {String} propName
- * @param {String} unit
+ */
+const padStart$1 = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString);
+
+/**
+ * Pads the end of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
* @return {String}
- *
- * @overload
- * @param {TargetsParam} targetSelector
- * @param {String} propName
- * @param {Boolean} unit
+ */
+const padEnd$1 = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString);
+
+/**
+ * Wraps a value within a range
+ * @param {Number} v - Value to wrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
* @return {Number}
- *
- * @param {TargetsParam} targetSelector
- * @param {String} propName
- * @param {String|Boolean} [unit]
*/
-function getTargetValue(targetSelector, propName, unit) {
- const targets = registerTargets(targetSelector);
- if (!targets.length) return;
- const [ target ] = targets;
- const tweenType = getTweenType(target, propName);
- const normalizePropName = sanitizePropertyName(propName, target, tweenType);
- let originalValue = getOriginalAnimatableValue(target, normalizePropName);
- if (isUnd(unit)) {
- return originalValue;
- } else {
- decomposeRawValue(originalValue, decomposedOriginalValue);
- if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) {
- if (unit === false) {
- return decomposedOriginalValue.n;
- } else {
- const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false);
- return `${round(convertedValue.n, globals.precision)}${convertedValue.u}`;
- }
- }
- }
-}
+const wrap$1 = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min;
/**
- * @param {TargetsParam} targets
- * @param {AnimationParams} parameters
- * @return {JSAnimation}
+ * Maps a value from one range to another
+ * @param {Number} value - Input value
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {Number}
*/
-const setTargetValues = (targets, parameters) => {
- if (isUnd(parameters)) return;
- parameters.duration = minValue;
- // Do not overrides currently active tweens by default
- parameters.composition = setValue(parameters.composition, compositionTypes.none);
- // Skip init() and force rendering by playing the animation
- return new JSAnimation(targets, parameters, null, 0, true).resume();
-};
+const mapRange$1 = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow);
/**
- * @param {TargetsArray} targetsArray
- * @param {JSAnimation} animation
- * @param {String} [propertyName]
- * @return {Boolean}
+ * Converts degrees to radians
+ * @param {Number} degrees - Angle in degrees
+ * @return {Number}
*/
-const removeTargetsFromAnimation = (targetsArray, animation, propertyName) => {
- let tweensMatchesTargets = false;
- forEachChildren(animation, (/**@type {Tween} */tween) => {
- const tweenTarget = tween.target;
- if (targetsArray.includes(tweenTarget)) {
- const tweenName = tween.property;
- const tweenType = tween._tweenType;
- const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
- if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
- // Make sure to flag the previous CSS transform tween to renderTransform
- if (tween.parent._tail === tween &&
- tween._tweenType === tweenTypes.TRANSFORM &&
- tween._prev &&
- tween._prev._tweenType === tweenTypes.TRANSFORM
- ) {
- tween._prev._renderTransforms = 1;
- }
- // Removes the tween from the selected animation
- removeChild(animation, tween);
- // Detach the tween from its siblings to make sure blended tweens are correctlly removed
- removeTweenSliblings(tween);
- tweensMatchesTargets = true;
- }
- }
- }, true);
- return tweensMatchesTargets;
-};
+const degToRad$1 = degrees => degrees * Math.PI / 180;
/**
- * @param {TargetsParam} targets
- * @param {Renderable|WAAPIAnimation} [renderable]
- * @param {String} [propertyName]
- * @return {TargetsArray}
+ * Converts radians to degrees
+ * @param {Number} radians - Angle in radians
+ * @return {Number}
*/
-const remove = (targets, renderable, propertyName) => {
- const targetsArray = parseTargets(targets);
- const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine);
- const waapiAnimation = renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable);
- for (let i = 0, l = targetsArray.length; i < l; i++) {
- const $el = /** @type {DOMTarget} */(targetsArray[i]);
- removeWAAPIAnimation($el, propertyName, waapiAnimation);
+const radToDeg$1 = radians => radians * 180 / Math.PI;
+
+/**
+ * Frame rate independent damped lerp
+ * Based on: https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
+ */
+const damp$1 = (start, end, deltaTime, factor) => {
+ return !factor ? start : factor === 1 ? end : lerp$1(start, end, 1 - Math.exp(-factor * deltaTime * .1));
+};
+
+var numberImports = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ clamp: clamp$1,
+ damp: damp$1,
+ degToRad: degToRad$1,
+ lerp: lerp$1,
+ mapRange: mapRange$1,
+ padEnd: padEnd$1,
+ padStart: padStart$1,
+ radToDeg: radToDeg$1,
+ round: round$1,
+ roundPad: roundPad$1,
+ snap: snap$1,
+ wrap: wrap$1
+});
+
+
+
+/*
+ * Spring ease solver adapted from https://webkit.org/demos/spring/spring.js
+ * (c) 2016 Webkit - Apple Inc
+ */
+
+const maxSpringParamValue = K * 10;
+
+class Spring {
+ /**
+ * @param {SpringParams} [parameters]
+ */
+ constructor(parameters = {}) {
+ this.timeStep = .02; // Interval fed to the solver to calculate duration
+ this.restThreshold = .0005; // Values below this threshold are considered resting position
+ this.restDuration = 200; // Duration in ms used to check if the spring is resting after reaching restThreshold
+ this.maxDuration = 60000; // The maximum allowed spring duration in ms (default 1 min)
+ this.maxRestSteps = this.restDuration / this.timeStep / K; // How many steps allowed after reaching restThreshold before stopping the duration calculation
+ this.maxIterations = this.maxDuration / this.timeStep / K; // Calculate the maximum iterations allowed based on maxDuration
+ this.m = clamp$1(setValue(parameters.mass, 1), 0, maxSpringParamValue);
+ this.s = clamp$1(setValue(parameters.stiffness, 100), 1, maxSpringParamValue);
+ this.d = clamp$1(setValue(parameters.damping, 10), .1, maxSpringParamValue);
+ this.v = clamp$1(setValue(parameters.velocity, 0), -maxSpringParamValue, maxSpringParamValue);
+ this.w0 = 0;
+ this.zeta = 0;
+ this.wd = 0;
+ this.b = 0;
+ this.solverDuration = 0;
+ this.duration = 0;
+ this.compute();
+ /** @type {EasingFunction} */
+ this.ease = t => t === 0 || t === 1 ? t : this.solve(t * this.solverDuration);
}
- let removeMatches;
- if (parent._hasChildren) {
- let iterationDuration = 0;
- forEachChildren(parent, (/** @type {Renderable} */child) => {
- if (!child._hasChildren) {
- removeMatches = removeTargetsFromAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName);
- // Remove the child from its parent if no tweens and no children left after the removal
- if (removeMatches && !child._head) {
- child.cancel();
- removeChild(parent, child);
- } else {
- // Calculate the new iterationDuration value to handle onComplete with last child in render()
- const childTLOffset = child._offset + child._delay;
- const childDur = childTLOffset + child.duration;
- if (childDur > iterationDuration) {
- iterationDuration = childDur;
- }
- }
- }
- // Make sure to also remove engine's children targets
- // NOTE: Avoid recursion?
- if (child._head) {
- remove(targets, child, propertyName);
+
+ /** @type {EasingFunction} */
+ solve(time) {
+ const { zeta, w0, wd, b } = this;
+ let t = time;
+ if (zeta < 1) {
+ t = exp(-t * zeta * w0) * (1 * cos(wd * t) + b * sin(wd * t));
+ } else {
+ t = (1 + b * t) * exp(-t * w0);
+ }
+ return 1 - t;
+ }
+
+ compute() {
+ const { maxRestSteps, maxIterations, restThreshold, timeStep, m, d, s, v } = this;
+ const w0 = this.w0 = clamp$1(sqrt(s / m), minValue, K);
+ const zeta = this.zeta = d / (2 * sqrt(s * m));
+ const wd = this.wd = zeta < 1 ? w0 * sqrt(1 - zeta * zeta) : 0;
+ this.b = zeta < 1 ? (zeta * w0 + -v) / wd : -v + w0;
+ let solverTime = 0;
+ let restSteps = 0;
+ let iterations = 0;
+ while (restSteps < maxRestSteps && iterations < maxIterations) {
+ if (abs(1 - this.solve(solverTime)) < restThreshold) {
+ restSteps++;
} else {
- child._hasChildren = false;
+ restSteps = 0;
}
- }, true);
- // Update iterationDuration value to handle onComplete with last child in render()
- if (!isUnd(/** @type {Renderable} */(parent).iterationDuration)) {
- /** @type {Renderable} */(parent).iterationDuration = iterationDuration;
+ this.solverDuration = solverTime;
+ solverTime += timeStep;
+ iterations++;
}
- } else {
- removeMatches = removeTargetsFromAnimation(
- targetsArray,
- /** @type {JSAnimation} */(parent),
- propertyName
- );
+ this.duration = round$1(this.solverDuration * K, 0) * globals.timeScale;
}
- if (removeMatches && !parent._head) {
- parent._hasChildren = false;
- // Cancel the parent if there are no tweens and no children left after the removal
- // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
- if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel();
+ get mass() {
+ return this.m;
}
- return targetsArray;
-};
+ set mass(v) {
+ this.m = clamp$1(setValue(v, 1), 0, maxSpringParamValue);
+ this.compute();
+ }
-/**
- * @param {(...args: any[]) => Tickable} constructor
- * @return {(...args: any[]) => Tickable}
- */
-const keepTime = createRefreshable;
+ get stiffness() {
+ return this.s;
+ }
-/**
- * @param {String|Array} items
- * @return {any}
- */
-const randomPick = items => items[random(0, items.length - 1)];
+ set stiffness(v) {
+ this.s = clamp$1(setValue(v, 100), 1, maxSpringParamValue);
+ this.compute();
+ }
-/**
- * @param {Number|String} v
- * @param {Number} decimalLength
- * @return {String}
- */
-const roundPad = (v, decimalLength) => (+v).toFixed(decimalLength);
+ get damping() {
+ return this.d;
+ }
-/**
- * @param {Number} v
- * @param {Number} totalLength
- * @param {String} padString
- * @return {String}
- */
-const padStart = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString);
+ set damping(v) {
+ this.d = clamp$1(setValue(v, 10), .1, maxSpringParamValue);
+ this.compute();
+ }
-/**
- * @param {Number} v
- * @param {Number} totalLength
- * @param {String} padString
- * @return {String}
- */
-const padEnd = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString);
+ get velocity() {
+ return this.v;
+ }
-/**
- * @param {Number} v
- * @param {Number} min
- * @param {Number} max
- * @return {Number}
- */
-const wrap = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min;
+ set velocity(v) {
+ this.v = clamp$1(setValue(v, 0), -maxSpringParamValue, maxSpringParamValue);
+ this.compute();
+ }
+}
/**
- * @param {Number} value
- * @param {Number} inLow
- * @param {Number} inHigh
- * @param {Number} outLow
- * @param {Number} outHigh
- * @return {Number}
+ * @param {SpringParams} [parameters]
+ * @returns {Spring}
*/
-const mapRange = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow);
+const createSpring = (parameters) => new Spring(parameters);
-/**
- * @param {Number} degrees
- * @return {Number}
- */
-const degToRad = degrees => degrees * PI / 180;
-/**
- * @param {Number} radians
- * @return {Number}
- */
-const radToDeg = radians => radians * 180 / PI;
-/**
- * https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
- * @param {Number} start
- * @param {Number} end
- * @param {Number} amount
- * @param {Renderable|Boolean} [renderable]
- * @return {Number}
- */
-const lerp = (start, end, amount, renderable) => {
- let dt = K / globals.defaults.frameRate;
- if (renderable !== false) {
- const ticker = /** @type Renderable */
- (renderable) ||
- (engine._hasChildren && engine);
- if (ticker && ticker.deltaTime) {
- dt = ticker.deltaTime;
- }
- }
- const t = 1 - Math.exp(-amount * dt * .1);
- return !amount ? start : amount === 1 ? end : (1 - t) * start + t * end;
-};
-// Chain-able utilities
/**
- * @callback UtilityFunction
- * @param {...*} args
- * @return {Number|String}
- *
- * @param {UtilityFunction} fn
- * @param {Number} [last=0]
- * @return {function(...(Number|String)): function(Number|String): (Number|String)}
+ * @param {Event} e
*/
-const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args);
+const preventDefault = e => {
+ if (e.cancelable) e.preventDefault();
+};
-/**
- * @param {Function} fn
- * @return {function(...(Number|String))}
- */
-const chain = fn => {
- return (...args) => {
- const result = fn(...args);
- return new Proxy(noop, {
- apply: (_, __, [v]) => result(v),
- get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => {
- const nextResult = utils[prop](...nextArgs);
- return (/**@type {Number|String} */v) => nextResult(result(v));
- })
- });
+class DOMProxy {
+ /** @param {Object} el */
+ constructor(el) {
+ this.el = el;
+ this.zIndex = 0;
+ this.parentElement = null;
+ this.classList = {
+ add: noop,
+ remove: noop,
+ };
}
-};
-/**
- * @param {UtilityFunction} fn
- * @param {Number} [right]
- * @return {function(...(Number|String)): UtilityFunction}
- */
-const makeChainable = (fn, right = 0) => (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args);
+ get x() { return this.el.x || 0 };
+ set x(v) { this.el.x = v; };
-/**
- * @callback ChainedUtilsResult
- * @param {Number} value
- * @return {Number}
- *
- * @typedef {Object} ChainableUtils
- * @property {ChainedClamp} clamp
- * @property {ChainedRound} round
- * @property {ChainedSnap} snap
- * @property {ChainedWrap} wrap
- * @property {ChainedInterpolate} interpolate
- * @property {ChainedMapRange} mapRange
- * @property {ChainedRoundPad} roundPad
- * @property {ChainedPadStart} padStart
- * @property {ChainedPadEnd} padEnd
- * @property {ChainedDegToRad} degToRad
- * @property {ChainedRadToDeg} radToDeg
- *
- * @typedef {ChainableUtils & ChainedUtilsResult} ChainableUtil
- *
- * @callback ChainedClamp
- * @param {Number} min
- * @param {Number} max
- * @return {ChainableUtil}
- *
- * @callback ChainedRound
- * @param {Number} decimalLength
- * @return {ChainableUtil}
- *
- * @callback ChainedSnap
- * @param {Number} increment
- * @return {ChainableUtil}
- *
- * @callback ChainedWrap
- * @param {Number} min
- * @param {Number} max
- * @return {ChainableUtil}
- *
- * @callback ChainedInterpolate
- * @param {Number} start
- * @param {Number} end
- * @return {ChainableUtil}
- *
- * @callback ChainedMapRange
- * @param {Number} inLow
- * @param {Number} inHigh
- * @param {Number} outLow
- * @param {Number} outHigh
- * @return {ChainableUtil}
- *
- * @callback ChainedRoundPad
- * @param {Number} decimalLength
- * @return {ChainableUtil}
- *
- * @callback ChainedPadStart
- * @param {Number} totalLength
- * @param {String} padString
- * @return {ChainableUtil}
- *
- * @callback ChainedPadEnd
- * @param {Number} totalLength
- * @param {String} padString
- * @return {ChainableUtil}
- *
- * @callback ChainedDegToRad
- * @return {ChainableUtil}
- *
- * @callback ChainedRadToDeg
- * @return {ChainableUtil}
- */
+ get y() { return this.el.y || 0 };
+ set y(v) { this.el.y = v; };
-const utils = {
- $: registerTargets,
- get: getTargetValue,
- set: setTargetValues,
- remove,
- cleanInlineStyles,
- random,
- randomPick,
- shuffle,
- lerp,
- sync,
- keepTime,
- clamp: /** @type {typeof clamp & ChainedClamp} */(makeChainable(clamp)),
- round: /** @type {typeof round & ChainedRound} */(makeChainable(round)),
- snap: /** @type {typeof snap & ChainedSnap} */(makeChainable(snap)),
- wrap: /** @type {typeof wrap & ChainedWrap} */(makeChainable(wrap)),
- interpolate: /** @type {typeof interpolate & ChainedInterpolate} */(makeChainable(interpolate, 1)),
- mapRange: /** @type {typeof mapRange & ChainedMapRange} */(makeChainable(mapRange)),
- roundPad: /** @type {typeof roundPad & ChainedRoundPad} */(makeChainable(roundPad)),
- padStart: /** @type {typeof padStart & ChainedPadStart} */(makeChainable(padStart)),
- padEnd: /** @type {typeof padEnd & ChainedPadEnd} */(makeChainable(padEnd)),
- degToRad: /** @type {typeof degToRad & ChainedDegToRad} */(makeChainable(degToRad)),
- radToDeg: /** @type {typeof radToDeg & ChainedRadToDeg} */(makeChainable(radToDeg)),
-};
+ get width() { return this.el.width || 0 };
+ set width(v) { this.el.width = v; };
+ get height() { return this.el.height || 0 };
+ set height(v) { this.el.height = v; };
+ getBoundingClientRect() {
+ return {
+ top: this.y,
+ right: this.x,
+ bottom: this.y + this.height,
+ left: this.x + this.width,
+ }
+ }
+}
+class Transforms {
+ /**
+ * @param {DOMTarget|DOMProxy} $el
+ */
+ constructor($el) {
+ this.$el = $el;
+ this.inlineTransforms = [];
+ this.point = new DOMPoint();
+ this.inversedMatrix = this.getMatrix().inverse();
+ }
-/**
- * Timeline's children offsets positions parser
- * @param {Timeline} timeline
- * @param {String} timePosition
- * @return {Number}
- */
-const getPrevChildOffset = (timeline, timePosition) => {
- if (stringStartsWith(timePosition, '<')) {
- const goToPrevAnimationOffset = timePosition[1] === '<';
- const prevAnimation = /** @type {Tickable} */(timeline._tail);
- const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
- return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
+ /**
+ * @param {Number} x
+ * @param {Number} y
+ * @return {DOMPoint}
+ */
+ normalizePoint(x, y) {
+ this.point.x = x;
+ this.point.y = y;
+ return this.point.matrixTransform(this.inversedMatrix);
}
-};
-/**
- * @param {Timeline} timeline
- * @param {TimelinePosition} [timePosition]
- * @return {Number}
- */
-const parseTimelinePosition = (timeline, timePosition) => {
- let tlDuration = timeline.iterationDuration;
- if (tlDuration === minValue) tlDuration = 0;
- if (isUnd(timePosition)) return tlDuration;
- if (isNum(+timePosition)) return +timePosition;
- const timePosStr = /** @type {String} */(timePosition);
- const tlLabels = timeline ? timeline.labels : null;
- const hasLabels = !isNil(tlLabels);
- const prevOffset = getPrevChildOffset(timeline, timePosStr);
- const hasSibling = !isUnd(prevOffset);
- const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
- if (matchedRelativeOperator) {
- const fullOperator = matchedRelativeOperator[0];
- const split = timePosStr.split(fullOperator);
- const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
- const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
- const parsedNumericalOffset = +split[1];
- return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
- } else {
- return hasSibling ? prevOffset :
- hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
- tlDuration : tlDuration;
+ /**
+ * @callback TraverseParentsCallback
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ */
+
+ /**
+ * @param {TraverseParentsCallback} cb
+ */
+ traverseUp(cb) {
+ let $el = /** @type {DOMTarget|Document} */(this.$el.parentElement), i = 0;
+ while ($el && $el !== doc) {
+ cb(/** @type {DOMTarget} */($el), i);
+ $el = /** @type {DOMTarget} */($el.parentElement);
+ i++;
+ }
}
-};
-/**
- * @param {Timeline} tl
- * @return {Number}
- */
-function getTimelineTotalDuration(tl) {
- return clampInfinity(((tl.iterationDuration + tl._loopDelay) * tl.iterationCount) - tl._loopDelay) || minValue;
+ getMatrix() {
+ const matrix = new DOMMatrix();
+ this.traverseUp($el => {
+ const transformValue = getComputedStyle($el).transform;
+ if (transformValue) {
+ const elMatrix = new DOMMatrix(transformValue);
+ matrix.preMultiplySelf(elMatrix);
+ }
+ });
+ return matrix;
+ }
+
+ remove() {
+ this.traverseUp(($el, i) => {
+ this.inlineTransforms[i] = $el.style.transform;
+ $el.style.transform = 'none';
+ });
+ }
+
+ revert() {
+ this.traverseUp(($el, i) => {
+ const ct = this.inlineTransforms[i];
+ if (ct === '') {
+ $el.style.removeProperty('transform');
+ } else {
+ $el.style.transform = ct;
+ }
+ });
+ }
}
/**
- * @overload
- * @param {TimerParams} childParams
- * @param {Timeline} tl
- * @param {Number} timePosition
- * @return {Timeline}
- *
- * @overload
- * @param {AnimationParams} childParams
- * @param {Timeline} tl
- * @param {Number} timePosition
- * @param {TargetsParam} targets
- * @param {Number} [index]
- * @param {Number} [length]
- * @return {Timeline}
- *
- * @param {TimerParams|AnimationParams} childParams
- * @param {Timeline} tl
- * @param {Number} timePosition
- * @param {TargetsParam} [targets]
- * @param {Number} [index]
- * @param {Number} [length]
+ * @template {Array<Number>|DOMTargetSelector|String|Number|Boolean|Function|DraggableCursorParams} T
+ * @param {T | ((draggable: Draggable) => T)} value
+ * @param {Draggable} draggable
+ * @return {T}
*/
-function addTlChild(childParams, tl, timePosition, targets, index, length) {
- const isSetter = isNum(childParams.duration) && /** @type {Number} */(childParams.duration) <= minValue;
- // Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position
- const adjustedPosition = isSetter ? timePosition - minValue : timePosition;
- tick(tl, adjustedPosition, 1, 1, tickModes.AUTO);
- const tlChild = targets ?
- new JSAnimation(targets,/** @type {AnimationParams} */(childParams), tl, adjustedPosition, false, index, length) :
- new Timer(/** @type {TimerParams} */(childParams), tl, adjustedPosition);
- tlChild.init(1);
- // TODO: Might be better to insert at a position relative to startTime?
- addChild(tl, tlChild);
- forEachChildren(tl, (/** @type {Renderable} */child) => {
- const childTLOffset = child._offset + child._delay;
- const childDur = childTLOffset + child.duration;
- if (childDur > tl.iterationDuration) tl.iterationDuration = childDur;
- });
- tl.duration = getTimelineTotalDuration(tl);
- return tl;
-}
+const parseDraggableFunctionParameter = (value, draggable) => value && isFnc(value) ? /** @type {Function} */(value)(draggable) : /** @type {T} */(value);
-class Timeline extends Timer {
+let zIndex = 0;
+class Draggable {
/**
- * @param {TimelineParams} [parameters]
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
*/
- constructor(parameters = {}) {
- super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0);
+ constructor(target, parameters = {}) {
+ if (!target) return;
+ if (scope.current) scope.current.register(this);
+ const paramX = parameters.x;
+ const paramY = parameters.y;
+ const trigger = parameters.trigger;
+ const modifier = parameters.modifier;
+ const ease = parameters.releaseEase;
+ const customEase = ease && parseEase(ease);
+ const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
+ const xProp = /** @type {String} */(isObj(paramX) && !isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX');
+ const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY');
+ const container = parseDraggableFunctionParameter(parameters.container, this);
+ this.containerArray = isArr(container) ? container : null;
+ this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body);
+ this.useWin = this.$container === doc.body;
+ /** @type {Window | HTMLElement} */
+ this.$scrollContainer = this.useWin ? win : this.$container;
+ this.$target = /** @type {HTMLElement} */(isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]);
+ this.$trigger = /** @type {HTMLElement} */(parseTargets(trigger ? trigger : target)[0]);
+ this.fixed = get(this.$target, 'position') === 'fixed';
+ // Refreshable parameters
+ this.isFinePointer = true;
+ /** @type {[Number, Number, Number, Number]} */
+ this.containerPadding = [0, 0, 0, 0];
/** @type {Number} */
- this.duration = 0; // TL duration starts at 0 and grows when adding children
- /** @type {Record<String, Number>} */
- this.labels = {};
- const defaultsParams = parameters.defaults;
- const globalDefaults = globals.defaults;
- /** @type {DefaultsParams} */
- this.defaults = defaultsParams ? mergeObjects(defaultsParams, globalDefaults) : globalDefaults;
- /** @type {Callback<this>} */
- this.onRender = parameters.onRender || globalDefaults.onRender;
- const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase);
- this._ease = tlPlaybackEase ? parseEasings(tlPlaybackEase) : null;
+ this.containerFriction = 0;
/** @type {Number} */
- this.iterationDuration = 0;
- }
-
- /**
- * @overload
- * @param {TargetsParam} a1
- * @param {AnimationParams} a2
- * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
- * @return {this}
- *
- * @overload
- * @param {TimerParams} a1
- * @param {TimelinePosition} [a2]
- * @return {this}
- *
- * @param {TargetsParam|TimerParams} a1
- * @param {TimelinePosition|AnimationParams} a2
- * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
- */
- add(a1, a2, a3) {
- const isAnim = isObj(a2);
- const isTimer = isObj(a1);
- if (isAnim || isTimer) {
- this._hasChildren = true;
- if (isAnim) {
- const childParams = /** @type {AnimationParams} */(a2);
- // Check for function for children stagger positions
- if (isFnc(a3)) {
- const staggeredPosition = a3;
- const parsedTargetsArray = parseTargets(/** @type {TargetsParam} */(a1));
- // Store initial duration before adding new children that will change the duration
- const tlDuration = this.duration;
- // Store initial _iterationDuration before adding new children that will change the duration
- const tlIterationDuration = this.iterationDuration;
- // Store the original id in order to add specific indexes to the new animations ids
- const id = childParams.id;
- let i = 0;
- /** @type {Number} */
- const parsedLength = (parsedTargetsArray.length);
- parsedTargetsArray.forEach((/** @type {Target} */target) => {
- // Create a new parameter object for each staggered children
- const staggeredChildParams = { ...childParams };
- // Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation
- this.duration = tlDuration;
- this.iterationDuration = tlIterationDuration;
- if (!isUnd(id)) staggeredChildParams.id = id + '-' + i;
- addTlChild(
- staggeredChildParams,
- this,
- parseTimelinePosition(this, staggeredPosition(target, i, parsedLength, this)),
- target,
- i,
- parsedLength
- );
- i++;
- });
- } else {
- addTlChild(
- childParams,
- this,
- parseTimelinePosition(this, a3),
- /** @type {TargetsParam} */(a1),
- );
- }
- } else {
- // It's a Timer
- addTlChild(
- /** @type TimerParams */(a1),
- this,
- parseTimelinePosition(this,a2),
- );
- }
- return this.init(1); // 1 = internalRender
- }
- }
-
- /**
- * @overload
- * @param {Tickable} [synced]
- * @param {TimelinePosition} [position]
- * @return {this}
- *
- * @overload
- * @param {globalThis.Animation} [synced]
- * @param {TimelinePosition} [position]
- * @return {this}
- *
- * @overload
- * @param {WAAPIAnimation} [synced]
- * @param {TimelinePosition} [position]
- * @return {this}
- *
- * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
- * @param {TimelinePosition} [position]
- */
- sync(synced, position) {
- if (isUnd(synced) || synced && isUnd(synced.pause)) return this;
- synced.pause();
- const duration = +(/** @type {globalThis.Animation} */(synced).effect ? /** @type {globalThis.Animation} */(synced).effect.getTiming().duration : /** @type {Tickable} */(synced).duration);
- return this.add(synced, { currentTime: [0, duration], duration, ease: 'linear' }, position);
- }
-
- /**
- * @param {TargetsParam} targets
- * @param {AnimationParams} parameters
- * @param {TimelinePosition} [position]
- * @return {this}
- */
- set(targets, parameters, position) {
- if (isUnd(parameters)) return this;
- parameters.duration = minValue;
- parameters.composition = compositionTypes.replace;
- return this.add(targets, parameters, position);
- }
-
- /**
- * @param {Callback<Timer>} callback
- * @param {TimelinePosition} [position]
- * @return {this}
- */
- call(callback, position) {
- if (isUnd(callback) || callback && !isFnc(callback)) return this;
- return this.add({ duration: 0, onComplete: () => callback(this) }, position);
- }
-
- /**
- * @param {String} labelName
- * @param {TimelinePosition} [position]
- * @return {this}
- *
- */
- label(labelName, position) {
- if (isUnd(labelName) || labelName && !isStr(labelName)) return this;
- this.labels[labelName] = parseTimelinePosition(this, position);
- return this;
- }
-
- /**
- * @param {TargetsParam} targets
- * @param {String} [propertyName]
- * @return {this}
- */
- remove(targets, propertyName) {
- remove(targets, this, propertyName);
- return this;
- }
-
- /**
- * @param {Number} newDuration
- * @return {this}
- */
- stretch(newDuration) {
- const currentDuration = this.duration;
- if (currentDuration === normalizeTime(newDuration)) return this;
- const timeScale = newDuration / currentDuration;
- const labels = this.labels;
- forEachChildren(this, (/** @type {JSAnimation} */child) => child.stretch(child.duration * timeScale));
- for (let labelName in labels) labels[labelName] *= timeScale;
- return super.stretch(newDuration);
- }
-
- /**
- * @return {this}
- */
- refresh() {
- forEachChildren(this, (/** @type {JSAnimation} */child) => {
- if (child.refresh) child.refresh();
- });
- return this;
- }
-
- /**
- * @return {this}
- */
- revert() {
- super.revert();
- forEachChildren(this, (/** @type {JSAnimation} */child) => child.revert, true);
- return cleanInlineStyles(this);
- }
-
- /**
- * @param {Callback<this>} [callback]
- * @return {Promise}
- */
- then(callback) {
- return super.then(callback);
- }
-}
-
-/**
- * @param {TimelineParams} [parameters]
- * @return {Timeline}
- */
-const createTimeline = parameters => new Timeline(parameters).init();
-
-
-
-
-class Animatable {
- /**
- * @param {TargetsParam} targets
- * @param {AnimatableParams} parameters
- */
- constructor(targets, parameters) {
- if (scope.current) scope.current.register(this);
- const beginHandler = () => {
- if (this.callbacks.completed) this.callbacks.reset();
- this.callbacks.play();
- };
- const pauseHandler = () => {
- if (this.callbacks.completed) return;
- let paused = true;
- for (let name in this.animations) {
- const anim = this.animations[name];
- if (!anim.paused && paused) {
- paused = false;
- break;
- }
- }
- if (paused) {
- this.callbacks.complete();
- }
- };
- /** @type {AnimationParams} */
- const globalParams = {
- onBegin: beginHandler,
- onComplete: pauseHandler,
- onPause: pauseHandler,
- };
- /** @type {AnimationParams} */
- const callbacksAnimationParams = { v: 1, autoplay: false };
- const properties = {};
- this.targets = [];
- this.animations = {};
- /** @type {JSAnimation|null} */
- this.callbacks = null;
- if (isUnd(targets) || isUnd(parameters)) return;
- for (let propName in parameters) {
- const paramValue = parameters[propName];
- if (isKey(propName)) {
- properties[propName] = paramValue;
- } else if (stringStartsWith(propName, 'on')) {
- callbacksAnimationParams[propName] = paramValue;
- } else {
- globalParams[propName] = paramValue;
- }
- }
- this.callbacks = new JSAnimation({ v: 0 }, callbacksAnimationParams);
- for (let propName in properties) {
- const propValue = properties[propName];
- const isObjValue = isObj(propValue);
- /** @type {TweenParamsOptions} */
- let propParams = {};
- let to = '+=0';
- if (isObjValue) {
- const unit = propValue.unit;
- if (isStr(unit)) to += unit;
- } else {
- propParams.duration = propValue;
- }
- propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to;
- const animParams = mergeObjects(globalParams, propParams);
- animParams.composition = compositionTypes.replace;
- animParams.autoplay = false;
- const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init();
- if (!this.targets.length) this.targets.push(...animation.targets);
- /** @type {AnimatableProperty} */
- this[propName] = (to, duration, ease) => {
- const tween = /** @type {Tween} */(animation._head);
- if (isUnd(to) && tween) {
- const numbers = tween._numbers;
- if (numbers && numbers.length) {
- return numbers;
- } else {
- return tween._modifier(tween._number);
- }
- } else {
- forEachChildren(animation, (/** @type {Tween} */tween) => {
- if (isArr(to)) {
- for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) {
- if (!isUnd(tween._numbers[i])) {
- tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i]));
- tween._toNumbers[i] = to[i];
- }
- }
- } else {
- tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number));
- tween._toNumber = /** @type {Number} */(to);
- }
- if (!isUnd(ease)) tween._ease = parseEasings(ease);
- tween._currentTime = 0;
- });
- if (!isUnd(duration)) animation.stretch(duration);
- animation.reset(1).resume();
- return this;
- }
- };
- }
- }
-
- revert() {
- for (let propName in this.animations) {
- this[propName] = noop;
- this.animations[propName].revert();
- }
- this.animations = {};
- this.targets.length = 0;
- if (this.callbacks) this.callbacks.revert();
- return this;
- }
-}
-
-/**
- * @param {TargetsParam} targets
- * @param {AnimatableParams} parameters
- * @return {AnimatableObject}
- */
-const createAnimatable = (targets, parameters) => /** @type {AnimatableObject} */ (new Animatable(targets, parameters));
-
-
-
-
-/*
- * Spring ease solver adapted from https://webkit.org/demos/spring/spring.js
- * Webkit Copyright © 2016 Apple Inc
- */
-
-const maxSpringParamValue = K * 10;
-
-/**
- * @typedef {Object} SpringParams
- * @property {Number} [mass=1] - Mass, default 1
- * @property {Number} [stiffness=100] - Stiffness, default 100
- * @property {Number} [damping=10] - Damping, default 10
- * @property {Number} [velocity=0] - Initial velocity, default 0
- */
-class Spring {
- /**
- * @param {SpringParams} [parameters]
- */
- constructor(parameters = {}) {
- this.timeStep = .02; // Interval fed to the solver to calculate duration
- this.restThreshold = .0005; // Values below this threshold are considered resting position
- this.restDuration = 200; // Duration in ms used to check if the spring is resting after reaching restThreshold
- this.maxDuration = 60000; // The maximum allowed spring duration in ms (default 1 min)
- this.maxRestSteps = this.restDuration / this.timeStep / K; // How many steps allowed after reaching restThreshold before stopping the duration calculation
- this.maxIterations = this.maxDuration / this.timeStep / K; // Calculate the maximum iterations allowed based on maxDuration
- this.m = clamp(setValue(parameters.mass, 1), 0, maxSpringParamValue);
- this.s = clamp(setValue(parameters.stiffness, 100), 1, maxSpringParamValue);
- this.d = clamp(setValue(parameters.damping, 10), .1, maxSpringParamValue);
- this.v = clamp(setValue(parameters.velocity, 0), -1e4, maxSpringParamValue);
- this.w0 = 0;
- this.zeta = 0;
- this.wd = 0;
- this.b = 0;
- this.solverDuration = 0;
- this.duration = 0;
- this.compute();
+ this.releaseContainerFriction = 0;
+ /** @type {Number|Array<Number>} */
+ this.snapX = 0;
+ /** @type {Number|Array<Number>} */
+ this.snapY = 0;
+ /** @type {Number} */
+ this.scrollSpeed = 0;
+ /** @type {Number} */
+ this.scrollThreshold = 0;
+ /** @type {Number} */
+ this.dragSpeed = 0;
+ /** @type {Number} */
+ this.maxVelocity = 0;
+ /** @type {Number} */
+ this.minVelocity = 0;
+ /** @type {Number} */
+ this.velocityMultiplier = 0;
+ /** @type {Boolean|DraggableCursorParams} */
+ this.cursor = false;
+ /** @type {Spring} */
+ this.releaseXSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({
+ mass: setValue(parameters.releaseMass, 1),
+ stiffness: setValue(parameters.releaseStiffness, 80),
+ damping: setValue(parameters.releaseDamping, 20),
+ });
+ /** @type {Spring} */
+ this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({
+ mass: setValue(parameters.releaseMass, 1),
+ stiffness: setValue(parameters.releaseStiffness, 80),
+ damping: setValue(parameters.releaseDamping, 20),
+ });
/** @type {EasingFunction} */
- this.ease = t => t === 0 || t === 1 ? t : this.solve(t * this.solverDuration);
- }
-
- /** @type {EasingFunction} */
- solve(time) {
- const { zeta, w0, wd, b } = this;
- let t = time;
- if (zeta < 1) {
- t = exp(-t * zeta * w0) * (1 * cos(wd * t) + b * sin(wd * t));
- } else {
- t = (1 + b * t) * exp(-t * w0);
+ this.releaseEase = customEase || eases.outQuint;
+ /** @type {Boolean} */
+ this.hasReleaseSpring = hasSpring;
+ /** @type {Callback<this>} */
+ this.onGrab = parameters.onGrab || noop;
+ /** @type {Callback<this>} */
+ this.onDrag = parameters.onDrag || noop;
+ /** @type {Callback<this>} */
+ this.onRelease = parameters.onRelease || noop;
+ /** @type {Callback<this>} */
+ this.onUpdate = parameters.onUpdate || noop;
+ /** @type {Callback<this>} */
+ this.onSettle = parameters.onSettle || noop;
+ /** @type {Callback<this>} */
+ this.onSnap = parameters.onSnap || noop;
+ /** @type {Callback<this>} */
+ this.onResize = parameters.onResize || noop;
+ /** @type {Callback<this>} */
+ this.onAfterResize = parameters.onAfterResize || noop;
+ /** @type {[Number, Number]} */
+ this.disabled = [0, 0];
+ /** @type {AnimatableParams} */
+ const animatableParams = {};
+ if (modifier) animatableParams.modifier = modifier;
+ if (isUnd(paramX) || paramX === true) {
+ animatableParams[xProp] = 0;
+ } else if (isObj(paramX)) {
+ const paramXObject = /** @type {DraggableAxisParam} */(paramX);
+ const animatableXParams = {};
+ if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier;
+ if (paramXObject.composition) animatableXParams.composition = paramXObject.composition;
+ animatableParams[xProp] = animatableXParams;
+ } else if (paramX === false) {
+ animatableParams[xProp] = 0;
+ this.disabled[0] = 1;
}
- return 1 - t;
- }
-
- compute() {
- const { maxRestSteps, maxIterations, restThreshold, timeStep, m, d, s, v } = this;
- const w0 = this.w0 = clamp(sqrt(s / m), minValue, K);
- const zeta = this.zeta = d / (2 * sqrt(s * m));
- const wd = this.wd = zeta < 1 ? w0 * sqrt(1 - zeta * zeta) : 0;
- this.b = zeta < 1 ? (zeta * w0 + -v) / wd : -v + w0;
- let solverTime = 0;
- let restSteps = 0;
- let iterations = 0;
- while (restSteps < maxRestSteps && iterations < maxIterations) {
- if (abs(1 - this.solve(solverTime)) < restThreshold) {
- restSteps++;
+ if (isUnd(paramY) || paramY === true) {
+ animatableParams[yProp] = 0;
+ } else if (isObj(paramY)) {
+ const paramYObject = /** @type {DraggableAxisParam} */(paramY);
+ const animatableYParams = {};
+ if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier;
+ if (paramYObject.composition) animatableYParams.composition = paramYObject.composition;
+ animatableParams[yProp] = animatableYParams;
+ } else if (paramY === false) {
+ animatableParams[yProp] = 0;
+ this.disabled[1] = 1;
+ }
+ /** @type {AnimatableObject} */
+ this.animate = /** @type {AnimatableObject} */(new Animatable(this.$target, animatableParams));
+ // Internal props
+ this.xProp = xProp;
+ this.yProp = yProp;
+ this.destX = 0;
+ this.destY = 0;
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.scroll = {x: 0, y: 0};
+ /** @type {[Number, Number, Number, Number]} */
+ this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y
+ /** @type {[Number, Number]} */
+ this.snapped = [0, 0]; // x, y
+ /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */
+ this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2
+ /** @type {[Number, Number]} */
+ this.scrollView = [0, 0]; // w, h
+ /** @type {[Number, Number, Number, Number]} */
+ this.dragArea = [0, 0, 0, 0]; // x, y, w, h
+ /** @type {[Number, Number, Number, Number]} */
+ this.containerBounds = [-maxValue, maxValue, maxValue, -maxValue]; // t, r, b, l
+ /** @type {[Number, Number, Number, Number]} */
+ this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l
+ /** @type {[Number, Number, Number, Number]} */
+ this.targetBounds = [0, 0, 0, 0]; // t, r, b, l
+ /** @type {[Number, Number]} */
+ this.window = [0, 0]; // w, h
+ /** @type {[Number, Number, Number]} */
+ this.velocityStack = [0, 0, 0];
+ /** @type {Number} */
+ this.velocityStackIndex = 0;
+ /** @type {Number} */
+ this.velocityTime = now();
+ /** @type {Number} */
+ this.velocity = 0;
+ /** @type {Number} */
+ this.angle = 0;
+ /** @type {JSAnimation} */
+ this.cursorStyles = null;
+ /** @type {JSAnimation} */
+ this.triggerStyles = null;
+ /** @type {JSAnimation} */
+ this.bodyStyles = null;
+ /** @type {JSAnimation} */
+ this.targetStyles = null;
+ /** @type {JSAnimation} */
+ this.touchActionStyles = null;
+ this.transforms = new Transforms(this.$target);
+ this.overshootCoords = { x: 0, y: 0 };
+ this.overshootTicker = new Timer({
+ autoplay: false,
+ onUpdate: () => {
+ this.updated = true;
+ this.manual = true;
+ // Use a duration of 1 to prevent the animatable from completing immediately to prevent issues with onSettle()
+ // https://github.com/juliangarnier/anime/issues/1045
+ if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 1);
+ if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 1);
+ },
+ onComplete: () => {
+ this.manual = false;
+ if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0);
+ if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0);
+ },
+ }, null, 0).init();
+ this.updateTicker = new Timer({ autoplay: false, onUpdate: () => this.update() }, null,0,).init();
+ this.contained = !isUnd(container);
+ this.manual = false;
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.enabled = false;
+ this.initialized = false;
+ this.activeProp = this.disabled[1] ? xProp : yProp;
+ this.animate.callbacks.onRender = () => {
+ const hasUpdated = this.updated;
+ const hasMoved = this.grabbed && hasUpdated;
+ const hasReleased = !hasMoved && this.released;
+ const x = this.x;
+ const y = this.y;
+ const dx = x - this.coords[2];
+ const dy = y - this.coords[3];
+ this.deltaX = dx;
+ this.deltaY = dy;
+ this.coords[2] = x;
+ this.coords[3] = y;
+ // Check if dx or dy are not 0 to check if the draggable has actually moved
+ // https://github.com/juliangarnier/anime/issues/1032
+ if (hasUpdated && (dx || dy)) {
+ this.onUpdate(this);
+ }
+ if (!hasReleased) {
+ this.updated = false;
} else {
- restSteps = 0;
+ this.computeVelocity(dx, dy);
+ this.angle = atan2(dy, dx);
}
- this.solverDuration = solverTime;
- solverTime += timeStep;
- iterations++;
- }
- this.duration = round(this.solverDuration * K, 0) * globals.timeScale;
- }
-
- get mass() {
- return this.m;
- }
-
- set mass(v) {
- this.m = clamp(setValue(v, 1), 0, maxSpringParamValue);
- this.compute();
- }
-
- get stiffness() {
- return this.s;
+ };
+ this.animate.callbacks.onComplete = () => {
+ if ((!this.grabbed && this.released)) {
+ // Set released to false before calling onSettle to avoid recursion
+ this.released = false;
+ }
+ if (!this.manual) {
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.onSettle(this);
+ }
+ };
+ this.resizeTicker = new Timer({
+ autoplay: false,
+ duration: 150 * globals.timeScale,
+ onComplete: () => {
+ this.onResize(this);
+ this.refresh();
+ this.onAfterResize(this);
+ },
+ }).init();
+ this.parameters = parameters;
+ this.resizeObserver = new ResizeObserver(() => {
+ if (this.initialized) {
+ this.resizeTicker.restart();
+ } else {
+ this.initialized = true;
+ }
+ });
+ this.enable();
+ this.refresh();
+ this.resizeObserver.observe(this.$container);
+ if (!isObj(target)) this.resizeObserver.observe(this.$target);
}
- set stiffness(v) {
- this.s = clamp(setValue(v, 100), 1, maxSpringParamValue);
- this.compute();
+ /**
+ * @param {Number} dx
+ * @param {Number} dy
+ * @return {Number}
+ */
+ computeVelocity(dx, dy) {
+ const prevTime = this.velocityTime;
+ const curTime = now();
+ const elapsed = curTime - prevTime;
+ if (elapsed < 17) return this.velocity;
+ this.velocityTime = curTime;
+ const velocityStack = this.velocityStack;
+ const vMul = this.velocityMultiplier;
+ const minV = this.minVelocity;
+ const maxV = this.maxVelocity;
+ const vi = this.velocityStackIndex;
+ velocityStack[vi] = round$1(clamp$1((sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5);
+ const velocity = max(velocityStack[0], velocityStack[1], velocityStack[2]);
+ this.velocity = velocity;
+ this.velocityStackIndex = (vi + 1) % 3;
+ return velocity;
}
- get damping() {
- return this.d;
+ /**
+ * @param {Number} x
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setX(x, muteUpdateCallback = false) {
+ if (this.disabled[0]) return;
+ const v = round$1(x, 5);
+ this.overshootTicker.pause();
+ this.manual = true;
+ this.updated = !muteUpdateCallback;
+ this.destX = v;
+ this.snapped[0] = snap$1(v, this.snapX);
+ this.animate[this.xProp](v, 0);
+ this.manual = false;
+ return this;
}
- set damping(v) {
- this.d = clamp(setValue(v, 10), .1, maxSpringParamValue);
- this.compute();
+ /**
+ * @param {Number} y
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setY(y, muteUpdateCallback = false) {
+ if (this.disabled[1]) return;
+ const v = round$1(y, 5);
+ this.overshootTicker.pause();
+ this.manual = true;
+ this.updated = !muteUpdateCallback;
+ this.destY = v;
+ this.snapped[1] = snap$1(v, this.snapY);
+ this.animate[this.yProp](v, 0);
+ this.manual = false;
+ return this;
}
- get velocity() {
- return this.v;
+ get x() {
+ return round$1(/** @type {Number} */(this.animate[this.xProp]()), globals.precision);
}
- set velocity(v) {
- this.v = clamp(setValue(v, 0), -1e4, maxSpringParamValue);
- this.compute();
+ set x(x) {
+ this.setX(x, false);
}
-}
-
-/**
- * @param {SpringParams} [parameters]
- * @returns {Spring}
- */
-const createSpring = (parameters) => new Spring(parameters);
-
-
-
-/**
- * @param {Event} e
- */
-const preventDefault = e => {
- if (e.cancelable) e.preventDefault();
-};
-
-class DOMProxy {
- /** @param {Object} el */
- constructor(el) {
- this.el = el;
- this.zIndex = 0;
- this.parentElement = null;
- this.classList = {
- add: noop,
- remove: noop,
- };
+ get y() {
+ return round$1(/** @type {Number} */(this.animate[this.yProp]()), globals.precision);
}
- get x() { return this.el.x || 0 };
- set x(v) { this.el.x = v; };
-
- get y() { return this.el.y || 0 };
- set y(v) { this.el.y = v; };
-
- get width() { return this.el.width || 0 };
- set width(v) { this.el.width = v; };
-
- get height() { return this.el.height || 0 };
- set height(v) { this.el.height = v; };
-
- getBoundingClientRect() {
- return {
- top: this.y,
- right: this.x,
- bottom: this.y + this.height,
- left: this.x + this.width,
- }
+ set y(y) {
+ this.setY(y, false);
}
-}
-class Transforms {
- /**
- * @param {DOMTarget|DOMProxy} $el
- */
- constructor($el) {
- this.$el = $el;
- this.inlineTransforms = [];
- this.point = new DOMPoint();
- this.inversedMatrix = this.getMatrix().inverse();
+ get progressX() {
+ return mapRange$1(this.x, this.containerBounds[3], this.containerBounds[1], 0, 1);
}
- /**
- * @param {Number} x
- * @param {Number} y
- * @return {DOMPoint}
- */
- normalizePoint(x, y) {
- this.point.x = x;
- this.point.y = y;
- return this.point.matrixTransform(this.inversedMatrix);
+ set progressX(x) {
+ this.setX(mapRange$1(x, 0, 1, this.containerBounds[3], this.containerBounds[1]), false);
}
- /**
- * @callback TraverseParentsCallback
- * @param {DOMTarget} $el
- * @param {Number} i
- */
-
- /**
- * @param {TraverseParentsCallback} cb
- */
- traverseUp(cb) {
- let $el = /** @type {DOMTarget|Document} */(this.$el.parentElement), i = 0;
- while ($el && $el !== doc) {
- cb(/** @type {DOMTarget} */($el), i);
- $el = /** @type {DOMTarget} */($el.parentElement);
- i++;
- }
+ get progressY() {
+ return mapRange$1(this.y, this.containerBounds[0], this.containerBounds[2], 0, 1);
}
- getMatrix() {
- const matrix = new DOMMatrix();
- this.traverseUp($el => {
- const transformValue = getComputedStyle($el).transform;
- if (transformValue) {
- const elMatrix = new DOMMatrix(transformValue);
- matrix.preMultiplySelf(elMatrix);
- }
- });
- return matrix;
+ set progressY(y) {
+ this.setY(mapRange$1(y, 0, 1, this.containerBounds[0], this.containerBounds[2]), false);
}
- remove() {
- this.traverseUp(($el, i) => {
- this.inlineTransforms[i] = $el.style.transform;
- $el.style.transform = 'none';
- });
+ updateScrollCoords() {
+ const sx = round$1(this.useWin ? win.scrollX : this.$container.scrollLeft, 0);
+ const sy = round$1(this.useWin ? win.scrollY : this.$container.scrollTop, 0);
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const threshold = this.scrollThreshold;
+ this.scroll.x = sx;
+ this.scroll.y = sy;
+ this.scrollBounds[0] = sy - this.targetBounds[0] + cpt - threshold;
+ this.scrollBounds[1] = sx - this.targetBounds[1] - cpr + threshold;
+ this.scrollBounds[2] = sy - this.targetBounds[2] - cpb + threshold;
+ this.scrollBounds[3] = sx - this.targetBounds[3] + cpl - threshold;
}
- revert() {
- this.traverseUp(($el, i) => {
- const ct = this.inlineTransforms[i];
- if (ct === '') {
- $el.style.removeProperty('transform');
+ updateBoundingValues() {
+ const $container = this.$container;
+ // Return early if no $container defined to prevents error when reading scrollWidth / scrollHeight
+ // https://github.com/juliangarnier/anime/issues/1064
+ if (!$container) return;
+ const cx = this.x;
+ const cy = this.y;
+ const cx2 = this.coords[2];
+ const cy2 = this.coords[3];
+ // Prevents interfering with the scroll area in cases the target is outside of the container
+ // Make sure the temp coords are also adjuset to prevents wrong delta calculation on updates
+ this.coords[2] = 0;
+ this.coords[3] = 0;
+ this.setX(0, true);
+ this.setY(0, true);
+ this.transforms.remove();
+ const iw = this.window[0] = win.innerWidth;
+ const ih = this.window[1] = win.innerHeight;
+ const uw = this.useWin;
+ const sw = $container.scrollWidth;
+ const sh = $container.scrollHeight;
+ const fx = this.fixed;
+ const transformContainerRect = $container.getBoundingClientRect();
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ this.dragArea[0] = uw ? 0 : transformContainerRect.left;
+ this.dragArea[1] = uw ? 0 : transformContainerRect.top;
+ this.scrollView[0] = uw ? clamp$1(sw, iw, sw) : sw;
+ this.scrollView[1] = uw ? clamp$1(sh, ih, sh) : sh;
+ this.updateScrollCoords();
+ const { width, height, left, top, right, bottom } = $container.getBoundingClientRect();
+ this.dragArea[2] = round$1(uw ? clamp$1(width, iw, iw) : width, 0);
+ this.dragArea[3] = round$1(uw ? clamp$1(height, ih, ih) : height, 0);
+ const containerOverflow = get($container, 'overflow');
+ const visibleOverflow = containerOverflow === 'visible';
+ const hiddenOverflow = containerOverflow === 'hidden';
+ this.canScroll = fx ? false :
+ this.contained &&
+ (($container === doc.body && visibleOverflow) || (!hiddenOverflow && !visibleOverflow)) &&
+ (sw > this.dragArea[2] + cpl - cpr || sh > this.dragArea[3] + cpt - cpb) &&
+ (!this.containerArray || (this.containerArray && !isArr(this.containerArray)));
+ if (this.contained) {
+ const sx = this.scroll.x;
+ const sy = this.scroll.y;
+ const canScroll = this.canScroll;
+ const targetRect = this.$target.getBoundingClientRect();
+ const hiddenLeft = canScroll ? uw ? 0 : $container.scrollLeft : 0;
+ const hiddenTop = canScroll ? uw ? 0 : $container.scrollTop : 0;
+ const hiddenRight = canScroll ? this.scrollView[0] - hiddenLeft - width : 0;
+ const hiddenBottom = canScroll ? this.scrollView[1] - hiddenTop - height : 0;
+ this.targetBounds[0] = round$1((targetRect.top + sy) - (uw ? 0 : top), 0);
+ this.targetBounds[1] = round$1((targetRect.right + sx) - (uw ? iw : right), 0);
+ this.targetBounds[2] = round$1((targetRect.bottom + sy) - (uw ? ih : bottom), 0);
+ this.targetBounds[3] = round$1((targetRect.left + sx) - (uw ? 0 : left), 0);
+ if (this.containerArray) {
+ this.containerBounds[0] = this.containerArray[0] + cpt;
+ this.containerBounds[1] = this.containerArray[1] - cpr;
+ this.containerBounds[2] = this.containerArray[2] - cpb;
+ this.containerBounds[3] = this.containerArray[3] + cpl;
} else {
- $el.style.transform = ct;
+ this.containerBounds[0] = -round$1(targetRect.top - (fx ? clamp$1(top, 0, ih) : top) + hiddenTop - cpt, 0);
+ this.containerBounds[1] = -round$1(targetRect.right - (fx ? clamp$1(right, 0, iw) : right) - hiddenRight + cpr, 0);
+ this.containerBounds[2] = -round$1(targetRect.bottom - (fx ? clamp$1(bottom, 0, ih) : bottom) - hiddenBottom + cpb, 0);
+ this.containerBounds[3] = -round$1(targetRect.left - (fx ? clamp$1(left, 0, iw) : left) + hiddenLeft - cpl, 0);
}
- });
+ }
+ this.transforms.revert();
+ // Restore coordinates
+ this.coords[2] = cx2;
+ this.coords[3] = cy2;
+ this.setX(cx, true);
+ this.setY(cy, true);
}
-}
-
-/**
- * @template {Array<Number>|DOMTargetSelector|String|Number|Boolean|Function|DraggableCursorParams} T
- * @param {T | ((draggable: Draggable) => T)} value
- * @param {Draggable} draggable
- * @return {T}
- */
-const parseDraggableFunctionParameter = (value, draggable) => value && isFnc(value) ? /** @type {Function} */(value)(draggable) : value;
-let zIndex = 0;
-
-class Draggable {
/**
- * @param {TargetsParam} target
- * @param {DraggableParams} [parameters]
+ * @param {Array} bounds
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number}
*/
- constructor(target, parameters = {}) {
- if (!target) return;
- if (scope.current) scope.current.register(this);
- const paramX = parameters.x;
- const paramY = parameters.y;
- const trigger = parameters.trigger;
- const modifier = parameters.modifier;
- const ease = parameters.releaseEase;
- const customEase = ease && parseEasings(ease);
- const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
- const xProp = /** @type {String} */(isObj(paramX) && !isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX');
- const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY');
- const container = parseDraggableFunctionParameter(parameters.container, this);
+ isOutOfBounds(bounds, x, y) {
+ // Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB
+ if (!this.contained) return 0;
+ const [ bt, br, bb, bl ] = bounds;
+ const [ dx, dy ] = this.disabled;
+ const obx = !dx && x < bl || !dx && x > br;
+ const oby = !dy && y < bt || !dy && y > bb;
+ return obx && !oby ? 1 : !obx && oby ? 2 : obx && oby ? 3 : 0;
+ }
+
+ refresh() {
+ const params = this.parameters;
+ const paramX = params.x;
+ const paramY = params.y;
+ const container = parseDraggableFunctionParameter(params.container, this);
+ const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0;
+ const containerPadding = /** @type {[Number, Number, Number, Number]} */(isArr(cp) ? cp : [cp, cp, cp, cp]);
+ const cx = this.x;
+ const cy = this.y;
+ const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this);
+ const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' };
+ if (parsedCursorStyles) {
+ const { onHover, onGrab } = /** @type {DraggableCursorParams} */(parsedCursorStyles);
+ if (onHover) cursorStyles.onHover = onHover;
+ if (onGrab) cursorStyles.onGrab = onGrab;
+ }
this.containerArray = isArr(container) ? container : null;
this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body);
this.useWin = this.$container === doc.body;
/** @type {Window | HTMLElement} */
this.$scrollContainer = this.useWin ? win : this.$container;
- this.$target = /** @type {HTMLElement} */(isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]);
- this.$trigger = /** @type {HTMLElement} */(parseTargets(trigger ? trigger : target)[0]);
- this.fixed = getTargetValue(this.$target, 'position') === 'fixed';
- // Refreshable parameters
- this.isFinePointer = true;
- /** @type {[Number, Number, Number, Number]} */
- this.containerPadding = [0, 0, 0, 0];
- /** @type {Number} */
- this.containerFriction = 0;
- /** @type {Number} */
- this.releaseContainerFriction = 0;
- /** @type {Number|Array<Number>} */
- this.snapX = 0;
- /** @type {Number|Array<Number>} */
- this.snapY = 0;
- /** @type {Number} */
- this.scrollSpeed = 0;
- /** @type {Number} */
- this.scrollThreshold = 0;
- /** @type {Number} */
- this.dragSpeed = 0;
- /** @type {Number} */
- this.maxVelocity = 0;
- /** @type {Number} */
- this.minVelocity = 0;
- /** @type {Number} */
- this.velocityMultiplier = 0;
- /** @type {Boolean|DraggableCursorParams} */
- this.cursor = false;
- /** @type {Spring} */
- this.releaseXSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({
- mass: setValue(parameters.releaseMass, 1),
- stiffness: setValue(parameters.releaseStiffness, 80),
- damping: setValue(parameters.releaseDamping, 20),
- });
- /** @type {Spring} */
- this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({
- mass: setValue(parameters.releaseMass, 1),
- stiffness: setValue(parameters.releaseStiffness, 80),
- damping: setValue(parameters.releaseDamping, 20),
- });
- /** @type {EasingFunction} */
- this.releaseEase = customEase || eases.outQuint;
- /** @type {Boolean} */
- this.hasReleaseSpring = hasSpring;
- /** @type {Callback<this>} */
- this.onGrab = parameters.onGrab || noop;
- /** @type {Callback<this>} */
- this.onDrag = parameters.onDrag || noop;
- /** @type {Callback<this>} */
- this.onRelease = parameters.onRelease || noop;
- /** @type {Callback<this>} */
- this.onUpdate = parameters.onUpdate || noop;
- /** @type {Callback<this>} */
- this.onSettle = parameters.onSettle || noop;
- /** @type {Callback<this>} */
- this.onSnap = parameters.onSnap || noop;
- /** @type {Callback<this>} */
- this.onResize = parameters.onResize || noop;
- /** @type {Callback<this>} */
- this.onAfterResize = parameters.onAfterResize || noop;
- /** @type {[Number, Number]} */
- this.disabled = [0, 0];
- /** @type {AnimatableParams} */
- const animatableParams = {};
- if (modifier) animatableParams.modifier = modifier;
- if (isUnd(paramX) || paramX === true) {
- animatableParams[xProp] = 0;
- } else if (isObj(paramX)) {
- const paramXObject = /** @type {DraggableAxisParam} */(paramX);
- const animatableXParams = {};
- if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier;
- if (paramXObject.composition) animatableXParams.composition = paramXObject.composition;
- animatableParams[xProp] = animatableXParams;
- } else if (paramX === false) {
- animatableParams[xProp] = 0;
- this.disabled[0] = 1;
+ this.isFinePointer = matchMedia('(pointer:fine)').matches;
+ this.containerPadding = setValue(containerPadding, [0, 0, 0, 0]);
+ this.containerFriction = clamp$1(setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1);
+ this.releaseContainerFriction = clamp$1(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1);
+ this.snapX = parseDraggableFunctionParameter(isObj(paramX) && !isUnd(paramX.snap) ? paramX.snap : params.snap, this);
+ this.snapY = parseDraggableFunctionParameter(isObj(paramY) && !isUnd(paramY.snap) ? paramY.snap : params.snap, this);
+ this.scrollSpeed = setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5);
+ this.scrollThreshold = setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20);
+ this.dragSpeed = setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1);
+ this.minVelocity = setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0);
+ this.maxVelocity = setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50);
+ this.velocityMultiplier = setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1);
+ this.cursor = parsedCursorStyles === false ? false : cursorStyles;
+ this.updateBoundingValues();
+
+ // const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y);
+ // if (ob === 1 || ob === 3) this.progressX = px;
+ // if (ob === 2 || ob === 3) this.progressY = py;
+
+ // if (this.initialized && this.contained) {
+ // if (this.progressX !== px) this.progressX = px;
+ // if (this.progressY !== py) this.progressY = py;
+ // }
+
+ const [ bt, br, bb, bl ] = this.containerBounds;
+ this.setX(clamp$1(cx, bl, br), true);
+ this.setY(clamp$1(cy, bt, bb), true);
+ }
+
+ update() {
+ this.updateScrollCoords();
+ if (this.canScroll) {
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const [ sw, sh ] = this.scrollView;
+ const daw = this.dragArea[2];
+ const dah = this.dragArea[3];
+ const csx = this.scroll.x;
+ const csy = this.scroll.y;
+ const nsw = this.$container.scrollWidth;
+ const nsh = this.$container.scrollHeight;
+ const csw = this.useWin ? clamp$1(nsw, this.window[0], nsw) : nsw;
+ const csh = this.useWin ? clamp$1(nsh, this.window[1], nsh) : nsh;
+ const swd = sw - csw;
+ const shd = sh - csh;
+ // Handle cases where the scrollarea dimensions changes during drag
+ if (this.dragged && swd > 0) {
+ this.coords[0] -= swd;
+ this.scrollView[0] = csw;
+ }
+ if (this.dragged && shd > 0) {
+ this.coords[1] -= shd;
+ this.scrollView[1] = csh;
+ }
+ // Handle autoscroll when target is at the edges of the scroll bounds
+ const s = this.scrollSpeed * 10;
+ const threshold = this.scrollThreshold;
+ const [ x, y ] = this.coords;
+ const [ st, sr, sb, sl ] = this.scrollBounds;
+ const t = round$1(clamp$1((y - st + cpt) / threshold, -1, 0) * s, 0);
+ const r = round$1(clamp$1((x - sr - cpr) / threshold, 0, 1) * s, 0);
+ const b = round$1(clamp$1((y - sb - cpb) / threshold, 0, 1) * s, 0);
+ const l = round$1(clamp$1((x - sl + cpl) / threshold, -1, 0) * s, 0);
+ if (t || b || l || r) {
+ const [nx, ny] = this.disabled;
+ let scrollX = csx;
+ let scrollY = csy;
+ if (!nx) {
+ scrollX = round$1(clamp$1(csx + (l || r), 0, sw - daw), 0);
+ this.coords[0] -= csx - scrollX;
+ }
+ if (!ny) {
+ scrollY = round$1(clamp$1(csy + (t || b), 0, sh - dah), 0);
+ this.coords[1] -= csy - scrollY;
+ }
+ // Note: Safari mobile requires to use different scroll methods depending if using the window or not
+ if (this.useWin) {
+ this.$scrollContainer.scrollBy(-(csx - scrollX), -(csy - scrollY));
+ } else {
+ this.$scrollContainer.scrollTo(scrollX, scrollY);
+ }
+ }
+ }
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
+ this.coords[0] += (px1 - px3) * this.dragSpeed;
+ this.coords[1] += (py1 - py3) * this.dragSpeed;
+ this.pointer[4] = px1;
+ this.pointer[5] = py1;
+ const [ cx, cy ] = this.coords;
+ const [ sx, sy ] = this.snapped;
+ const cf = (1 - this.containerFriction) * this.dragSpeed;
+ this.setX(cx > cr ? cr + (cx - cr) * cf : cx < cl ? cl + (cx - cl) * cf : cx, false);
+ this.setY(cy > cb ? cb + (cy - cb) * cf : cy < ct ? ct + (cy - ct) * cf : cy, false);
+ this.computeVelocity(px1 - px3, py1 - py3);
+ this.angle = atan2(py1 - py2, px1 - px2);
+ const [ nsx, nsy ] = this.snapped;
+ if (nsx !== sx && this.snapX || nsy !== sy && this.snapY) {
+ this.onSnap(this);
}
- if (isUnd(paramY) || paramY === true) {
- animatableParams[yProp] = 0;
- } else if (isObj(paramY)) {
- const paramYObject = /** @type {DraggableAxisParam} */(paramY);
- const animatableYParams = {};
- if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier;
- if (paramYObject.composition) animatableYParams.composition = paramYObject.composition;
- animatableParams[yProp] = animatableYParams;
- } else if (paramY === false) {
- animatableParams[yProp] = 0;
- this.disabled[1] = 1;
+ }
+
+ stop() {
+ this.updateTicker.pause();
+ this.overshootTicker.pause();
+ // Pauses the in bounds onRelease animations
+ for (let prop in this.animate.animations) this.animate.animations[prop].pause();
+ removeTargetsFromRenderable([this], null, 'x');
+ removeTargetsFromRenderable([this], null, 'y');
+ removeTargetsFromRenderable([this], null, 'progressX');
+ removeTargetsFromRenderable([this], null, 'progressY');
+ removeTargetsFromRenderable([this.scroll]); // Removes any active animations on the container scroll
+ removeTargetsFromRenderable([this.overshootCoords]); // Removes active overshoot animations
+ return this;
+ }
+
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ scrollInView(duration, gap = 0, ease = eases.inOutQuad) {
+ this.updateScrollCoords();
+ const x = this.destX;
+ const y = this.destY;
+ const scroll = this.scroll;
+ const scrollBounds = this.scrollBounds;
+ const canScroll = this.canScroll;
+ if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) {
+ const [ st, sr, sb, sl ] = scrollBounds;
+ const t = round$1(clamp$1(y - st, -maxValue, 0), 0);
+ const r = round$1(clamp$1(x - sr, 0, maxValue), 0);
+ const b = round$1(clamp$1(y - sb, 0, maxValue), 0);
+ const l = round$1(clamp$1(x - sl, -maxValue, 0), 0);
+ new JSAnimation(scroll, {
+ x: round$1(scroll.x + (l ? l - gap : r ? r + gap : 0), 0),
+ y: round$1(scroll.y + (t ? t - gap : b ? b + gap : 0), 0),
+ duration: isUnd(duration) ? 350 * globals.timeScale : duration,
+ ease,
+ onUpdate: () => {
+ this.canScroll = false;
+ this.$scrollContainer.scrollTo(scroll.x, scroll.y);
+ }
+ }).init().then(() => {
+ this.canScroll = canScroll;
+ });
}
- /** @type {AnimatableObject} */
- this.animate = /** @type {AnimatableObject} */(new Animatable(this.$target, animatableParams));
- // Internal props
- this.xProp = xProp;
- this.yProp = yProp;
- this.destX = 0;
- this.destY = 0;
+ return this;
+ }
+
+ handleHover() {
+ if (this.isFinePointer && this.cursor && !this.cursorStyles) {
+ this.cursorStyles = set(this.$trigger, {
+ cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover
+ });
+ }
+ }
+
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ animateInView(duration, gap = 0, ease = eases.inOutQuad) {
+ this.stop();
+ this.updateBoundingValues();
+ const x = this.x;
+ const y = this.y;
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const bt = this.scroll.y - this.targetBounds[0] + cpt + gap;
+ const br = this.scroll.x - this.targetBounds[1] - cpr - gap;
+ const bb = this.scroll.y - this.targetBounds[2] - cpb - gap;
+ const bl = this.scroll.x - this.targetBounds[3] + cpl + gap;
+ const ob = this.isOutOfBounds([bt, br, bb, bl], x, y);
+ if (ob) {
+ const [ disabledX, disabledY ] = this.disabled;
+ const destX = clamp$1(snap$1(x, this.snapX), bl, br);
+ const destY = clamp$1(snap$1(y, this.snapY), bt, bb);
+ const dur = isUnd(duration) ? 350 * globals.timeScale : duration;
+ if (!disabledX && (ob === 1 || ob === 3)) this.animate[this.xProp](destX, dur, ease);
+ if (!disabledY && (ob === 2 || ob === 3)) this.animate[this.yProp](destY, dur, ease);
+ }
+ return this;
+ }
+
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleDown(e) {
+ const $eTarget = /** @type {HTMLElement} */(e.target);
+ if (this.grabbed || /** @type {HTMLInputElement} */($eTarget).type === 'range') return;
+
+ e.stopPropagation();
+
+ this.grabbed = true;
+ this.released = false;
+ this.stop();
+ this.updateBoundingValues();
+ const touches = /** @type {TouchEvent} */(e).changedTouches;
+ const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
+ const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
+ const { x, y } = this.transforms.normalizePoint(eventX, eventY);
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const cf = (1 - this.containerFriction) * this.dragSpeed;
+ const cx = this.x;
+ const cy = this.y;
+ this.coords[0] = this.coords[2] = !cf ? cx : cx > cr ? cr + (cx - cr) / cf : cx < cl ? cl + (cx - cl) / cf : cx;
+ this.coords[1] = this.coords[3] = !cf ? cy : cy > cb ? cb + (cy - cb) / cf : cy < ct ? ct + (cy - ct) / cf : cy;
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.pointer[2] = x;
+ this.pointer[3] = y;
+ this.pointer[4] = x;
+ this.pointer[5] = y;
+ this.pointer[6] = x;
+ this.pointer[7] = y;
this.deltaX = 0;
this.deltaY = 0;
- this.scroll = {x: 0, y: 0};
- /** @type {[Number, Number, Number, Number]} */
- this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y
- /** @type {[Number, Number]} */
- this.snapped = [0, 0]; // x, y
- /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */
- this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2
- /** @type {[Number, Number]} */
- this.scrollView = [0, 0]; // w, h
- /** @type {[Number, Number, Number, Number]} */
- this.dragArea = [0, 0, 0, 0]; // x, y, w, h
- /** @type {[Number, Number, Number, Number]} */
- this.containerBounds = [-1e12, maxValue, maxValue, -1e12]; // t, r, b, l
- /** @type {[Number, Number, Number, Number]} */
- this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l
- /** @type {[Number, Number, Number, Number]} */
- this.targetBounds = [0, 0, 0, 0]; // t, r, b, l
- /** @type {[Number, Number]} */
- this.window = [0, 0]; // w, h
- /** @type {[Number, Number, Number]} */
- this.velocityStack = [0, 0, 0];
- /** @type {Number} */
- this.velocityStackIndex = 0;
- /** @type {Number} */
- this.velocityTime = now();
- /** @type {Number} */
this.velocity = 0;
- /** @type {Number} */
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
this.angle = 0;
- /** @type {JSAnimation} */
- this.cursorStyles = null;
- /** @type {JSAnimation} */
- this.triggerStyles = null;
- /** @type {JSAnimation} */
- this.bodyStyles = null;
- /** @type {JSAnimation} */
- this.targetStyles = null;
- /** @type {JSAnimation} */
- this.touchActionStyles = null;
- this.transforms = new Transforms(this.$target);
- this.overshootCoords = { x: 0, y: 0 };
- this.overshootTicker = new Timer({
- autoplay: false,
- onUpdate: () => {
- this.updated = true;
- this.manual = true;
- // Use a duration of 1 to prevent the animatable from completing immediately to prevent issues with onSettle()
- // https://github.com/juliangarnier/anime/issues/1045
- if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 1);
- if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 1);
- },
- onComplete: () => {
- this.manual = false;
- if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0);
- if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0);
- },
- }, null, 0).init();
- this.updateTicker = new Timer({ autoplay: false, onUpdate: () => this.update() }, null,0,).init();
- this.contained = !isUnd(container);
- this.manual = false;
- this.grabbed = false;
- this.dragged = false;
- this.updated = false;
- this.released = false;
- this.canScroll = false;
- this.enabled = false;
- this.initialized = false;
- this.activeProp = this.disabled[1] ? xProp : yProp;
- this.animate.callbacks.onRender = () => {
- const hasUpdated = this.updated;
- const hasMoved = this.grabbed && hasUpdated;
- const hasReleased = !hasMoved && this.released;
- const x = this.x;
- const y = this.y;
- const dx = x - this.coords[2];
- const dy = y - this.coords[3];
- this.deltaX = dx;
- this.deltaY = dy;
- this.coords[2] = x;
- this.coords[3] = y;
- // Check if dx or dy are not 0 to check if the draggable has actually moved
- // https://github.com/juliangarnier/anime/issues/1032
- if (hasUpdated && (dx || dy)) {
- this.onUpdate(this);
- }
- if (!hasReleased) {
- this.updated = false;
- } else {
- this.computeVelocity(dx, dy);
- this.angle = atan2(dy, dx);
- }
- };
- this.animate.callbacks.onComplete = () => {
- if ((!this.grabbed && this.released)) {
- // Set released to false before calling onSettle to avoid recursion
- this.released = false;
- }
- if (!this.manual) {
- this.deltaX = 0;
- this.deltaY = 0;
- this.velocity = 0;
- this.velocityStack[0] = 0;
- this.velocityStack[1] = 0;
- this.velocityStack[2] = 0;
- this.velocityStackIndex = 0;
- this.onSettle(this);
- }
- };
- this.resizeTicker = new Timer({
- autoplay: false,
- duration: 150 * globals.timeScale,
- onComplete: () => {
- this.onResize(this);
- this.refresh();
- this.onAfterResize(this);
- },
- }).init();
- this.parameters = parameters;
- this.resizeObserver = new ResizeObserver(() => {
- if (this.initialized) {
- this.resizeTicker.restart();
- } else {
- this.initialized = true;
- }
- });
- this.enable();
- this.refresh();
- this.resizeObserver.observe(this.$container);
- if (!isObj(target)) this.resizeObserver.observe(this.$target);
- }
+ if (this.targetStyles) {
+ this.targetStyles.revert();
+ this.targetStyles = null;
+ }
+ const z = /** @type {Number} */(get(this.$target, 'zIndex', false));
+ zIndex = (z > zIndex ? z : zIndex) + 1;
+ this.targetStyles = set(this.$target, { zIndex });
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+ if (this.cursorStyles) {
+ this.cursorStyles.revert();
+ this.cursorStyles = null;
+ }
+ if (this.isFinePointer && this.cursor) {
+ this.bodyStyles = set(doc.body, {
+ cursor: /** @type {DraggableCursorParams} */(this.cursor).onGrab
+ });
+ }
+ this.scrollInView(100, 0, eases.out(3));
+ this.onGrab(this);
- /**
- * @param {Number} dx
- * @param {Number} dy
- * @return {Number}
- */
- computeVelocity(dx, dy) {
- const prevTime = this.velocityTime;
- const curTime = now();
- const elapsed = curTime - prevTime;
- if (elapsed < 17) return this.velocity;
- this.velocityTime = curTime;
- const velocityStack = this.velocityStack;
- const vMul = this.velocityMultiplier;
- const minV = this.minVelocity;
- const maxV = this.maxVelocity;
- const vi = this.velocityStackIndex;
- velocityStack[vi] = round(clamp((sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5);
- const velocity = max(velocityStack[0], velocityStack[1], velocityStack[2]);
- this.velocity = velocity;
- this.velocityStackIndex = (vi + 1) % 3;
- return velocity;
+ doc.addEventListener('touchmove', this);
+ doc.addEventListener('touchend', this);
+ doc.addEventListener('touchcancel', this);
+ doc.addEventListener('mousemove', this);
+ doc.addEventListener('mouseup', this);
+ doc.addEventListener('selectstart', this);
}
/**
- * @param {Number} x
- * @param {Boolean} [muteUpdateCallback]
- * @return {this}
+ * @param {MouseEvent|TouchEvent} e
*/
- setX(x, muteUpdateCallback = false) {
- if (this.disabled[0]) return;
- const v = round(x, 5);
- this.overshootTicker.pause();
- this.manual = true;
- this.updated = !muteUpdateCallback;
- this.destX = v;
- this.snapped[0] = snap(v, this.snapX);
- this.animate[this.xProp](v, 0);
- this.manual = false;
- return this;
- }
+ handleMove(e) {
+ if (!this.grabbed) return;
+ const touches = /** @type {TouchEvent} */(e).changedTouches;
+ const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
+ const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
+ const { x, y } = this.transforms.normalizePoint(eventX, eventY);
+ const movedX = x - this.pointer[6];
+ const movedY = y - this.pointer[7];
- /**
- * @param {Number} y
- * @param {Boolean} [muteUpdateCallback]
- * @return {this}
- */
- setY(y, muteUpdateCallback = false) {
- if (this.disabled[1]) return;
- const v = round(y, 5);
- this.overshootTicker.pause();
- this.manual = true;
- this.updated = !muteUpdateCallback;
- this.destY = v;
- this.snapped[1] = snap(v, this.snapY);
- this.animate[this.yProp](v, 0);
- this.manual = false;
- return this;
- }
+ let $parent = /** @type {HTMLElement} */(e.target);
+ let isAtTop = false;
+ let isAtBottom = false;
+ let canTouchScroll = false;
- get x() {
- return round(/** @type {Number} */(this.animate[this.xProp]()), globals.precision);
- }
+ while (touches && $parent && $parent !== this.$trigger) {
+ const overflowY = get($parent, 'overflow-y');
+ if (overflowY !== 'hidden' && overflowY !== 'visible') {
+ const { scrollTop, scrollHeight, clientHeight } = $parent;
+ if (scrollHeight > clientHeight) {
+ canTouchScroll = true;
+ isAtTop = scrollTop <= 3;
+ isAtBottom = scrollTop >= (scrollHeight - clientHeight) - 3;
+ break;
+ }
+ }
+ $parent = $parent.parentElement;
+ }
- set x(x) {
- this.setX(x, false);
- }
+ if (canTouchScroll && ((!isAtTop && !isAtBottom) || (isAtTop && movedY < 0) || (isAtBottom && movedY > 0))) {
- get y() {
- return round(/** @type {Number} */(this.animate[this.yProp]()), globals.precision);
- }
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.pointer[2] = x;
+ this.pointer[3] = y;
+ this.pointer[4] = x;
+ this.pointer[5] = y;
+ this.pointer[6] = x;
+ this.pointer[7] = y;
- set y(y) {
- this.setY(y, false);
- }
+ } else {
- get progressX() {
- return mapRange(this.x, this.containerBounds[3], this.containerBounds[1], 0, 1);
- }
+ preventDefault(e);
- set progressX(x) {
- this.setX(mapRange(x, 0, 1, this.containerBounds[3], this.containerBounds[1]), false);
- }
+ // Needed to prevents click on handleUp
+ if (!this.triggerStyles) this.triggerStyles = set(this.$trigger, { pointerEvents: 'none' });
+ // Needed to prevent page scroll while dragging on touch devvice
+ this.$trigger.addEventListener('touchstart', preventDefault, { passive: false });
+ this.$trigger.addEventListener('touchmove', preventDefault, { passive: false });
+ this.$trigger.addEventListener('touchend', preventDefault);
- get progressY() {
- return mapRange(this.y, this.containerBounds[0], this.containerBounds[2], 0, 1);
- }
- set progressY(y) {
- this.setY(mapRange(y, 0, 1, this.containerBounds[0], this.containerBounds[2]), false);
- }
+ if ((!this.disabled[0] && abs(movedX) > 3) || (!this.disabled[1] && abs(movedY) > 3)) {
- updateScrollCoords() {
- const sx = round(this.useWin ? win.scrollX : this.$container.scrollLeft, 0);
- const sy = round(this.useWin ? win.scrollY : this.$container.scrollTop, 0);
- const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
- const threshold = this.scrollThreshold;
- this.scroll.x = sx;
- this.scroll.y = sy;
- this.scrollBounds[0] = sy - this.targetBounds[0] + cpt - threshold;
- this.scrollBounds[1] = sx - this.targetBounds[1] - cpr + threshold;
- this.scrollBounds[2] = sy - this.targetBounds[2] - cpb + threshold;
- this.scrollBounds[3] = sx - this.targetBounds[3] + cpl - threshold;
+ this.updateTicker.resume();
+ this.pointer[2] = this.pointer[0];
+ this.pointer[3] = this.pointer[1];
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.dragged = true;
+ this.released = false;
+ this.onDrag(this);
+ }
+ }
}
- updateBoundingValues() {
- const $container = this.$container;
- // Return early if no $container defined to prevents error when reading scrollWidth / scrollHeight
- // https://github.com/juliangarnier/anime/issues/1064
- if (!$container) return;
+ handleUp() {
+
+ if (!this.grabbed) return;
+
+ this.updateTicker.pause();
+
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+
+ if (this.bodyStyles) {
+ this.bodyStyles.revert();
+ this.bodyStyles = null;
+ }
+
+ const [ disabledX, disabledY ] = this.disabled;
+ const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const [ sx, sy ] = this.snapped;
+ const springX = this.releaseXSpring;
+ const springY = this.releaseYSpring;
+ const releaseEase = this.releaseEase;
+ const hasReleaseSpring = this.hasReleaseSpring;
+ const overshootCoords = this.overshootCoords;
const cx = this.x;
const cy = this.y;
- const cx2 = this.coords[2];
- const cy2 = this.coords[3];
- // Prevents interfering with the scroll area in cases the target is outside of the container
- // Make sure the temp coords are also adjuset to prevents wrong delta calculation on updates
- this.coords[2] = 0;
- this.coords[3] = 0;
- this.setX(0, true);
- this.setY(0, true);
- this.transforms.remove();
- const iw = this.window[0] = win.innerWidth;
- const ih = this.window[1] = win.innerHeight;
- const uw = this.useWin;
- const sw = $container.scrollWidth;
- const sh = $container.scrollHeight;
- const fx = this.fixed;
- const transformContainerRect = $container.getBoundingClientRect();
- const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
- this.dragArea[0] = uw ? 0 : transformContainerRect.left;
- this.dragArea[1] = uw ? 0 : transformContainerRect.top;
- this.scrollView[0] = uw ? clamp(sw, iw, sw) : sw;
- this.scrollView[1] = uw ? clamp(sh, ih, sh) : sh;
- this.updateScrollCoords();
- const { width, height, left, top, right, bottom } = $container.getBoundingClientRect();
- this.dragArea[2] = round(uw ? clamp(width, iw, iw) : width, 0);
- this.dragArea[3] = round(uw ? clamp(height, ih, ih) : height, 0);
- const containerOverflow = getTargetValue($container, 'overflow');
- const visibleOverflow = containerOverflow === 'visible';
- const hiddenOverflow = containerOverflow === 'hidden';
- this.canScroll = fx ? false :
- this.contained &&
- (($container === doc.body && visibleOverflow) || (!hiddenOverflow && !visibleOverflow)) &&
- (sw > this.dragArea[2] + cpl - cpr || sh > this.dragArea[3] + cpt - cpb) &&
- (!this.containerArray || (this.containerArray && !isArr(this.containerArray)));
- if (this.contained) {
- const sx = this.scroll.x;
- const sy = this.scroll.y;
- const canScroll = this.canScroll;
- const targetRect = this.$target.getBoundingClientRect();
- const hiddenLeft = canScroll ? uw ? 0 : $container.scrollLeft : 0;
- const hiddenTop = canScroll ? uw ? 0 : $container.scrollTop : 0;
- const hiddenRight = canScroll ? this.scrollView[0] - hiddenLeft - width : 0;
- const hiddenBottom = canScroll ? this.scrollView[1] - hiddenTop - height : 0;
- this.targetBounds[0] = round((targetRect.top + sy) - (uw ? 0 : top), 0);
- this.targetBounds[1] = round((targetRect.right + sx) - (uw ? iw : right), 0);
- this.targetBounds[2] = round((targetRect.bottom + sy) - (uw ? ih : bottom), 0);
- this.targetBounds[3] = round((targetRect.left + sx) - (uw ? 0 : left), 0);
- if (this.containerArray) {
- this.containerBounds[0] = this.containerArray[0] + cpt;
- this.containerBounds[1] = this.containerArray[1] - cpr;
- this.containerBounds[2] = this.containerArray[2] - cpb;
- this.containerBounds[3] = this.containerArray[3] + cpl;
- } else {
- this.containerBounds[0] = -round(targetRect.top - (fx ? clamp(top, 0, ih) : top) + hiddenTop - cpt, 0);
- this.containerBounds[1] = -round(targetRect.right - (fx ? clamp(right, 0, iw) : right) - hiddenRight + cpr, 0);
- this.containerBounds[2] = -round(targetRect.bottom - (fx ? clamp(bottom, 0, ih) : bottom) - hiddenBottom + cpb, 0);
- this.containerBounds[3] = -round(targetRect.left - (fx ? clamp(left, 0, iw) : left) + hiddenLeft - cpl, 0);
- }
+ const pv = this.computeVelocity(px1 - px3, py1 - py3);
+ const pa = this.angle = atan2(py1 - py2, px1 - px2);
+ const ds = pv * 150;
+ const cf = (1 - this.releaseContainerFriction) * this.dragSpeed;
+ const nx = cx + (cos(pa) * ds);
+ const ny = cy + (sin(pa) * ds);
+ const bx = nx > cr ? cr + (nx - cr) * cf : nx < cl ? cl + (nx - cl) * cf : nx;
+ const by = ny > cb ? cb + (ny - cb) * cf : ny < ct ? ct + (ny - ct) * cf : ny;
+ const dx = this.destX = clamp$1(round$1(snap$1(bx, this.snapX), 5), cl, cr);
+ const dy = this.destY = clamp$1(round$1(snap$1(by, this.snapY), 5), ct, cb);
+ const ob = this.isOutOfBounds(this.containerBounds, nx, ny);
+
+ let durationX = 0;
+ let durationY = 0;
+ let easeX = releaseEase;
+ let easeY = releaseEase;
+ let longestReleaseDuration = 0;
+
+ overshootCoords.x = cx;
+ overshootCoords.y = cy;
+
+ if (!disabledX) {
+ const directionX = dx === cr ? cx > cr ? -1 : 1 : cx < cl ? -1 : 1;
+ const distanceX = round$1(cx - dx, 0);
+ springX.velocity = disabledY && hasReleaseSpring ? distanceX ? (ds * directionX) / abs(distanceX) : 0 : pv;
+ const { ease, duration, restDuration } = springX;
+ durationX = cx === dx ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.timeScale);
+ if (hasReleaseSpring) easeX = ease;
+ if (durationX > longestReleaseDuration) longestReleaseDuration = durationX;
+ }
+
+ if (!disabledY) {
+ const directionY = dy === cb ? cy > cb ? -1 : 1 : cy < ct ? -1 : 1;
+ const distanceY = round$1(cy - dy, 0);
+ springY.velocity = disabledX && hasReleaseSpring ? distanceY ? (ds * directionY) / abs(distanceY) : 0 : pv;
+ const { ease, duration, restDuration } = springY;
+ durationY = cy === dy ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.timeScale);
+ if (hasReleaseSpring) easeY = ease;
+ if (durationY > longestReleaseDuration) longestReleaseDuration = durationY;
}
- this.transforms.revert();
- // Restore coordinates
- this.coords[2] = cx2;
- this.coords[3] = cy2;
- this.setX(cx, true);
- this.setY(cy, true);
- }
- /**
- * @param {Array} bounds
- * @param {Number} x
- * @param {Number} y
- * @return {Number}
- */
- isOutOfBounds(bounds, x, y) {
- // Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB
- if (!this.contained) return 0;
- const [ bt, br, bb, bl ] = bounds;
- const [ dx, dy ] = this.disabled;
- const obx = !dx && x < bl || !dx && x > br;
- const oby = !dy && y < bt || !dy && y > bb;
- return obx && !oby ? 1 : !obx && oby ? 2 : obx && oby ? 3 : 0;
- }
+ if (!hasReleaseSpring && ob && cf && (durationX || durationY)) {
- refresh() {
- const params = this.parameters;
- const paramX = params.x;
- const paramY = params.y;
- const container = parseDraggableFunctionParameter(params.container, this);
- const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0;
- const containerPadding = /** @type {[Number, Number, Number, Number]} */(isArr(cp) ? cp : [cp, cp, cp, cp]);
- const cx = this.x;
- const cy = this.y;
- const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this);
- const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' };
- if (parsedCursorStyles) {
- const { onHover, onGrab } = /** @type {DraggableCursorParams} */(parsedCursorStyles);
- if (onHover) cursorStyles.onHover = onHover;
- if (onGrab) cursorStyles.onGrab = onGrab;
- }
- this.containerArray = isArr(container) ? container : null;
- this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body);
- this.useWin = this.$container === doc.body;
- /** @type {Window | HTMLElement} */
- this.$scrollContainer = this.useWin ? win : this.$container;
- this.isFinePointer = matchMedia('(pointer:fine)').matches;
- this.containerPadding = setValue(containerPadding, [0, 0, 0, 0]);
- this.containerFriction = clamp(setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1);
- this.releaseContainerFriction = clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1);
- this.snapX = parseDraggableFunctionParameter(isObj(paramX) && !isUnd(paramX.snap) ? paramX.snap : params.snap, this);
- this.snapY = parseDraggableFunctionParameter(isObj(paramY) && !isUnd(paramY.snap) ? paramY.snap : params.snap, this);
- this.scrollSpeed = setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5);
- this.scrollThreshold = setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20);
- this.dragSpeed = setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1);
- this.minVelocity = setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0);
- this.maxVelocity = setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50);
- this.velocityMultiplier = setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1);
- this.cursor = parsedCursorStyles === false ? false : cursorStyles;
- this.updateBoundingValues();
+ const composition = compositionTypes.blend;
- // const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y);
- // if (ob === 1 || ob === 3) this.progressX = px;
- // if (ob === 2 || ob === 3) this.progressY = py;
+ new JSAnimation(overshootCoords, {
+ x: { to: bx, duration: durationX * .65 },
+ y: { to: by, duration: durationY * .65 },
+ ease: releaseEase,
+ composition,
+ }).init();
- // if (this.initialized && this.contained) {
- // if (this.progressX !== px) this.progressX = px;
- // if (this.progressY !== py) this.progressY = py;
- // }
+ new JSAnimation(overshootCoords, {
+ x: { to: dx, duration: durationX },
+ y: { to: dy, duration: durationY },
+ ease: releaseEase,
+ composition,
+ }).init();
- const [ bt, br, bb, bl ] = this.containerBounds;
- this.setX(clamp(cx, bl, br), true);
- this.setY(clamp(cy, bt, bb), true);
- }
+ this.overshootTicker.stretch(max(durationX, durationY)).restart();
+
+ } else {
+
+ if (!disabledX) this.animate[this.xProp](dx, durationX, easeX);
+ if (!disabledY) this.animate[this.yProp](dy, durationY, easeY);
- update() {
- this.updateScrollCoords();
- if (this.canScroll) {
- const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
- const [ sw, sh ] = this.scrollView;
- const daw = this.dragArea[2];
- const dah = this.dragArea[3];
- const csx = this.scroll.x;
- const csy = this.scroll.y;
- const nsw = this.$container.scrollWidth;
- const nsh = this.$container.scrollHeight;
- const csw = this.useWin ? clamp(nsw, this.window[0], nsw) : nsw;
- const csh = this.useWin ? clamp(nsh, this.window[1], nsh) : nsh;
- const swd = sw - csw;
- const shd = sh - csh;
- // Handle cases where the scrollarea dimensions changes during drag
- if (this.dragged && swd > 0) {
- this.coords[0] -= swd;
- this.scrollView[0] = csw;
- }
- if (this.dragged && shd > 0) {
- this.coords[1] -= shd;
- this.scrollView[1] = csh;
- }
- // Handle autoscroll when target is at the edges of the scroll bounds
- const s = this.scrollSpeed * 10;
- const threshold = this.scrollThreshold;
- const [ x, y ] = this.coords;
- const [ st, sr, sb, sl ] = this.scrollBounds;
- const t = round(clamp((y - st + cpt) / threshold, -1, 0) * s, 0);
- const r = round(clamp((x - sr - cpr) / threshold, 0, 1) * s, 0);
- const b = round(clamp((y - sb - cpb) / threshold, 0, 1) * s, 0);
- const l = round(clamp((x - sl + cpl) / threshold, -1, 0) * s, 0);
- if (t || b || l || r) {
- const [nx, ny] = this.disabled;
- let scrollX = csx;
- let scrollY = csy;
- if (!nx) {
- scrollX = round(clamp(csx + (l || r), 0, sw - daw), 0);
- this.coords[0] -= csx - scrollX;
- }
- if (!ny) {
- scrollY = round(clamp(csy + (t || b), 0, sh - dah), 0);
- this.coords[1] -= csy - scrollY;
- }
- // Note: Safari mobile requires to use different scroll methods depending if using the window or not
- if (this.useWin) {
- this.$scrollContainer.scrollBy(-(csx - scrollX), -(csy - scrollY));
- } else {
- this.$scrollContainer.scrollTo(scrollX, scrollY);
- }
- }
}
- const [ ct, cr, cb, cl ] = this.containerBounds;
- const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
- this.coords[0] += (px1 - px3) * this.dragSpeed;
- this.coords[1] += (py1 - py3) * this.dragSpeed;
- this.pointer[4] = px1;
- this.pointer[5] = py1;
- const [ cx, cy ] = this.coords;
- const [ sx, sy ] = this.snapped;
- const cf = (1 - this.containerFriction) * this.dragSpeed;
- this.setX(cx > cr ? cr + (cx - cr) * cf : cx < cl ? cl + (cx - cl) * cf : cx, false);
- this.setY(cy > cb ? cb + (cy - cb) * cf : cy < ct ? ct + (cy - ct) * cf : cy, false);
- this.computeVelocity(px1 - px3, py1 - py3);
- this.angle = atan2(py1 - py2, px1 - px2);
- const [ nsx, nsy ] = this.snapped;
- if (nsx !== sx && this.snapX || nsy !== sy && this.snapY) {
- this.onSnap(this);
+
+ this.scrollInView(longestReleaseDuration, this.scrollThreshold, releaseEase);
+
+ let hasSnapped = false;
+
+ if (dx !== sx) {
+ this.snapped[0] = dx;
+ if (this.snapX) hasSnapped = true;
+ }
+
+ if (dy !== sy && this.snapY) {
+ this.snapped[1] = dy;
+ if (this.snapY) hasSnapped = true;
}
+
+ if (hasSnapped) this.onSnap(this);
+
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = true;
+ this.released = true;
+
+ // It's important to trigger the callback after the release animations to be able to cancel them
+ this.onRelease(this);
+
+ this.$trigger.removeEventListener('touchstart', preventDefault);
+ this.$trigger.removeEventListener('touchmove', preventDefault);
+ this.$trigger.removeEventListener('touchend', preventDefault);
+
+ doc.removeEventListener('touchmove', this);
+ doc.removeEventListener('touchend', this);
+ doc.removeEventListener('touchcancel', this);
+ doc.removeEventListener('mousemove', this);
+ doc.removeEventListener('mouseup', this);
+ doc.removeEventListener('selectstart', this);
}
- stop() {
- this.updateTicker.pause();
- this.overshootTicker.pause();
- // Pauses the in bounds onRelease animations
- for (let prop in this.animate.animations) this.animate.animations[prop].pause();
- remove(this, null, 'x');
- remove(this, null, 'y');
- remove(this, null, 'progressX');
- remove(this, null, 'progressY');
- remove(this.scroll); // Removes any active animations on the container scroll
- remove(this.overshootCoords); // Removes active overshoot animations
+ reset() {
+ this.stop();
+ this.resizeTicker.pause();
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.setX(0, true);
+ this.setY(0, true);
+ this.coords[0] = 0;
+ this.coords[1] = 0;
+ this.pointer[0] = 0;
+ this.pointer[1] = 0;
+ this.pointer[2] = 0;
+ this.pointer[3] = 0;
+ this.pointer[4] = 0;
+ this.pointer[5] = 0;
+ this.pointer[6] = 0;
+ this.pointer[7] = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.angle = 0;
return this;
}
- /**
- * @param {Number} [duration]
- * @param {Number} [gap]
- * @param {EasingParam} [ease]
- * @return {this}
- */
- scrollInView(duration, gap = 0, ease = eases.inOutQuad) {
- this.updateScrollCoords();
- const x = this.destX;
- const y = this.destY;
- const scroll = this.scroll;
- const scrollBounds = this.scrollBounds;
- const canScroll = this.canScroll;
- if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) {
- const [ st, sr, sb, sl ] = scrollBounds;
- const t = round(clamp(y - st, -1e12, 0), 0);
- const r = round(clamp(x - sr, 0, maxValue), 0);
- const b = round(clamp(y - sb, 0, maxValue), 0);
- const l = round(clamp(x - sl, -1e12, 0), 0);
- new JSAnimation(scroll, {
- x: round(scroll.x + (l ? l - gap : r ? r + gap : 0), 0),
- y: round(scroll.y + (t ? t - gap : b ? b + gap : 0), 0),
- duration: isUnd(duration) ? 350 * globals.timeScale : duration,
- ease,
- onUpdate: () => {
- this.canScroll = false;
- this.$scrollContainer.scrollTo(scroll.x, scroll.y);
- }
- }).init().then(() => {
- this.canScroll = canScroll;
+ enable() {
+ if (!this.enabled) {
+ this.enabled = true;
+ this.$target.classList.remove('is-disabled');
+ this.touchActionStyles = set(this.$trigger, {
+ touchAction: this.disabled[0] ? 'pan-x' : this.disabled[1] ? 'pan-y' : 'none'
});
+ this.$trigger.addEventListener('touchstart', this, { passive: true });
+ this.$trigger.addEventListener('mousedown', this, { passive: true });
+ this.$trigger.addEventListener('mouseenter', this);
+ }
+ return this;
+ }
+
+ disable() {
+ this.enabled = false;
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.touchActionStyles.revert();
+ if (this.cursorStyles) {
+ this.cursorStyles.revert();
+ this.cursorStyles = null;
+ }
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+ if (this.bodyStyles) {
+ this.bodyStyles.revert();
+ this.bodyStyles = null;
+ }
+ if (this.targetStyles) {
+ this.targetStyles.revert();
+ this.targetStyles = null;
}
+ this.$target.classList.add('is-disabled');
+ this.$trigger.removeEventListener('touchstart', this);
+ this.$trigger.removeEventListener('mousedown', this);
+ this.$trigger.removeEventListener('mouseenter', this);
+ doc.removeEventListener('touchmove', this);
+ doc.removeEventListener('touchend', this);
+ doc.removeEventListener('touchcancel', this);
+ doc.removeEventListener('mousemove', this);
+ doc.removeEventListener('mouseup', this);
+ doc.removeEventListener('selectstart', this);
return this;
}
- handleHover() {
- if (this.isFinePointer && this.cursor && !this.cursorStyles) {
- this.cursorStyles = setTargetValues(this.$trigger, {
- cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover
- });
- }
+ revert() {
+ this.reset();
+ this.disable();
+ this.$target.classList.remove('is-disabled');
+ this.updateTicker.revert();
+ this.overshootTicker.revert();
+ this.resizeTicker.revert();
+ this.animate.revert();
+ this.resizeObserver.disconnect();
+ return this;
}
/**
- * @param {Number} [duration]
- * @param {Number} [gap]
- * @param {EasingParam} [ease]
- * @return {this}
+ * @param {Event} e
*/
- animateInView(duration, gap = 0, ease = eases.inOutQuad) {
- this.stop();
- this.updateBoundingValues();
- const x = this.x;
- const y = this.y;
- const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
- const bt = this.scroll.y - this.targetBounds[0] + cpt + gap;
- const br = this.scroll.x - this.targetBounds[1] - cpr - gap;
- const bb = this.scroll.y - this.targetBounds[2] - cpb - gap;
- const bl = this.scroll.x - this.targetBounds[3] + cpl + gap;
- const ob = this.isOutOfBounds([bt, br, bb, bl], x, y);
- if (ob) {
- const [ disabledX, disabledY ] = this.disabled;
- const destX = clamp(snap(x, this.snapX), bl, br);
- const destY = clamp(snap(y, this.snapY), bt, bb);
- const dur = isUnd(duration) ? 350 * globals.timeScale : duration;
- if (!disabledX && (ob === 1 || ob === 3)) this.animate[this.xProp](destX, dur, ease);
- if (!disabledY && (ob === 2 || ob === 3)) this.animate[this.yProp](destY, dur, ease);
+ handleEvent(e) {
+ switch (e.type) {
+ case 'mousedown':
+ this.handleDown(/** @type {MouseEvent} */(e));
+ break;
+ case 'touchstart':
+ this.handleDown(/** @type {TouchEvent} */(e));
+ break;
+ case 'mousemove':
+ this.handleMove(/** @type {MouseEvent} */(e));
+ break;
+ case 'touchmove':
+ this.handleMove(/** @type {TouchEvent} */(e));
+ break;
+ case 'mouseup':
+ this.handleUp();
+ break;
+ case 'touchend':
+ this.handleUp();
+ break;
+ case 'touchcancel':
+ this.handleUp();
+ break;
+ case 'mouseenter':
+ this.handleHover();
+ break;
+ case 'selectstart':
+ preventDefault(e);
+ break;
}
- return this;
}
+}
- /**
- * @param {MouseEvent|TouchEvent} e
- */
- handleDown(e) {
- const $eTarget = /** @type {HTMLElement} */(e.target);
- if (this.grabbed || /** @type {HTMLInputElement} */($eTarget).type === 'range') return;
+/**
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
+ * @return {Draggable}
+ */
+const createDraggable = (target, parameters) => new Draggable(target, parameters);
- e.stopPropagation();
- this.grabbed = true;
- this.released = false;
- this.stop();
- this.updateBoundingValues();
- const touches = /** @type {TouchEvent} */(e).changedTouches;
- const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
- const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
- const { x, y } = this.transforms.normalizePoint(eventX, eventY);
- const [ ct, cr, cb, cl ] = this.containerBounds;
- const cf = (1 - this.containerFriction) * this.dragSpeed;
- const cx = this.x;
- const cy = this.y;
- this.coords[0] = this.coords[2] = !cf ? cx : cx > cr ? cr + (cx - cr) / cf : cx < cl ? cl + (cx - cl) / cf : cx;
- this.coords[1] = this.coords[3] = !cf ? cy : cy > cb ? cb + (cy - cb) / cf : cy < ct ? ct + (cy - ct) / cf : cy;
- this.pointer[0] = x;
- this.pointer[1] = y;
- this.pointer[2] = x;
- this.pointer[3] = y;
- this.pointer[4] = x;
- this.pointer[5] = y;
- this.pointer[6] = x;
- this.pointer[7] = y;
- this.deltaX = 0;
- this.deltaY = 0;
- this.velocity = 0;
- this.velocityStack[0] = 0;
- this.velocityStack[1] = 0;
- this.velocityStack[2] = 0;
- this.velocityStackIndex = 0;
- this.angle = 0;
- if (this.targetStyles) {
- this.targetStyles.revert();
- this.targetStyles = null;
+
+/**
+ * @param {Callback<Timer>} [callback]
+ * @return {Timer}
+ */
+const sync = (callback = noop) => {
+ return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
+};
+
+/**
+ * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor
+ * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)}
+ */
+const keepTime = constructor => {
+ /** @type {Tickable} */
+ let tracked;
+ return (...args) => {
+ let currentIteration, currentIterationProgress, reversed, alternate;
+ if (tracked) {
+ currentIteration = tracked.currentIteration;
+ currentIterationProgress = tracked.iterationProgress;
+ reversed = tracked.reversed;
+ alternate = tracked._alternate;
+ tracked.revert();
}
- const z = /** @type {Number} */(getTargetValue(this.$target, 'zIndex', false));
- zIndex = (z > zIndex ? z : zIndex) + 1;
- this.targetStyles = setTargetValues(this.$target, { zIndex });
- if (this.triggerStyles) {
- this.triggerStyles.revert();
- this.triggerStyles = null;
+ const cleanup = constructor(...args);
+ if (cleanup && !isFnc(cleanup) && cleanup.revert) tracked = cleanup;
+ if (!isUnd(currentIterationProgress)) {
+ /** @type {Tickable} */(tracked).currentIteration = currentIteration;
+ /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress;
}
- if (this.cursorStyles) {
- this.cursorStyles.revert();
- this.cursorStyles = null;
+ return cleanup || noop;
+ }
+};
+
+
+
+class Scope {
+ /** @param {ScopeParams} [parameters] */
+ constructor(parameters = {}) {
+ if (scope.current) scope.current.register(this);
+ const rootParam = parameters.root;
+ /** @type {Document|DOMTarget} */
+ let root = doc;
+ if (rootParam) {
+ root = /** @type {ReactRef} */(rootParam).current ||
+ /** @type {AngularRef} */(rootParam).nativeElement ||
+ parseTargets(/** @type {DOMTargetSelector} */(rootParam))[0] ||
+ doc;
}
- if (this.isFinePointer && this.cursor) {
- this.bodyStyles = setTargetValues(doc.body, {
- cursor: /** @type {DraggableCursorParams} */(this.cursor).onGrab
- });
+ const scopeDefaults = parameters.defaults;
+ const globalDefault = globals.defaults;
+ const mediaQueries = parameters.mediaQueries;
+ /** @type {DefaultsParams} */
+ this.defaults = scopeDefaults ? mergeObjects(scopeDefaults, globalDefault) : globalDefault;
+ /** @type {Document|DOMTarget} */
+ this.root = root;
+ /** @type {Array<ScopeConstructorCallback>} */
+ this.constructors = [];
+ /** @type {Array<ScopeCleanupCallback>} */
+ this.revertConstructors = [];
+ /** @type {Array<Revertible>} */
+ this.revertibles = [];
+ /** @type {Array<ScopeConstructorCallback | ((scope: this) => Tickable)>} */
+ this.constructorsOnce = [];
+ /** @type {Array<ScopeCleanupCallback>} */
+ this.revertConstructorsOnce = [];
+ /** @type {Array<Revertible>} */
+ this.revertiblesOnce = [];
+ /** @type {Boolean} */
+ this.once = false;
+ /** @type {Number} */
+ this.onceIndex = 0;
+ /** @type {Record<String, ScopeMethod>} */
+ this.methods = {};
+ /** @type {Record<String, Boolean>} */
+ this.matches = {};
+ /** @type {Record<String, MediaQueryList>} */
+ this.mediaQueryLists = {};
+ /** @type {Record<String, any>} */
+ this.data = {};
+ if (mediaQueries) {
+ for (let mq in mediaQueries) {
+ const _mq = win.matchMedia(mediaQueries[mq]);
+ this.mediaQueryLists[mq] = _mq;
+ _mq.addEventListener('change', this);
+ }
}
- this.scrollInView(100, 0, eases.out(3));
- this.onGrab(this);
+ }
- doc.addEventListener('touchmove', this);
- doc.addEventListener('touchend', this);
- doc.addEventListener('touchcancel', this);
- doc.addEventListener('mousemove', this);
- doc.addEventListener('mouseup', this);
- doc.addEventListener('selectstart', this);
+ /**
+ * @param {Revertible} revertible
+ */
+ register(revertible) {
+ const store = this.once ? this.revertiblesOnce : this.revertibles;
+ store.push(revertible);
+ }
+
+ /**
+ * @template T
+ * @param {ScopedCallback<T>} cb
+ * @return {T}
+ */
+ execute(cb) {
+ let activeScope = scope.current;
+ let activeRoot = scope.root;
+ let activeDefaults = globals.defaults;
+ scope.current = this;
+ scope.root = this.root;
+ globals.defaults = this.defaults;
+ const mqs = this.mediaQueryLists;
+ for (let mq in mqs) this.matches[mq] = mqs[mq].matches;
+ const returned = cb(this);
+ scope.current = activeScope;
+ scope.root = activeRoot;
+ globals.defaults = activeDefaults;
+ return returned;
}
/**
- * @param {MouseEvent|TouchEvent} e
+ * @return {this}
*/
- handleMove(e) {
- if (!this.grabbed) return;
- const touches = /** @type {TouchEvent} */(e).changedTouches;
- const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
- const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
- const { x, y } = this.transforms.normalizePoint(eventX, eventY);
- const movedX = x - this.pointer[6];
- const movedY = y - this.pointer[7];
-
- let $parent = /** @type {HTMLElement} */(e.target);
- let isAtTop = false;
- let isAtBottom = false;
- let canTouchScroll = false;
-
- while (touches && $parent && $parent !== this.$trigger) {
- const overflowY = getTargetValue($parent, 'overflow-y');
- if (overflowY !== 'hidden' && overflowY !== 'visible') {
- const { scrollTop, scrollHeight, clientHeight } = $parent;
- if (scrollHeight > clientHeight) {
- canTouchScroll = true;
- isAtTop = scrollTop <= 3;
- isAtBottom = scrollTop >= (scrollHeight - clientHeight) - 3;
- break;
+ refresh() {
+ this.onceIndex = 0;
+ this.execute(() => {
+ let i = this.revertibles.length;
+ let y = this.revertConstructors.length;
+ while (i--) this.revertibles[i].revert();
+ while (y--) this.revertConstructors[y](this);
+ this.revertibles.length = 0;
+ this.revertConstructors.length = 0;
+ this.constructors.forEach((/** @type {ScopeConstructorCallback} */constructor) => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructors.push(revertConstructor);
}
- }
- $parent = $parent.parentElement;
- }
-
- if (canTouchScroll && ((!isAtTop && !isAtBottom) || (isAtTop && movedY < 0) || (isAtBottom && movedY > 0))) {
-
- this.pointer[0] = x;
- this.pointer[1] = y;
- this.pointer[2] = x;
- this.pointer[3] = y;
- this.pointer[4] = x;
- this.pointer[5] = y;
- this.pointer[6] = x;
- this.pointer[7] = y;
+ });
+ });
+ return this;
+ }
+ /**
+ * @overload
+ * @param {String} a1
+ * @param {ScopeMethod} a2
+ * @return {this}
+ *
+ * @overload
+ * @param {ScopeConstructorCallback} a1
+ * @return {this}
+ *
+ * @param {String|ScopeConstructorCallback} a1
+ * @param {ScopeMethod} [a2]
+ */
+ add(a1, a2) {
+ this.once = false;
+ if (isFnc(a1)) {
+ const constructor = /** @type {ScopeConstructorCallback} */(a1);
+ this.constructors.push(constructor);
+ this.execute(() => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructors.push(revertConstructor);
+ }
+ });
} else {
-
- preventDefault(e);
-
- // Needed to prevents click on handleUp
- if (!this.triggerStyles) this.triggerStyles = setTargetValues(this.$trigger, { pointerEvents: 'none' });
- // Needed to prevent page scroll while dragging on touch devvice
- this.$trigger.addEventListener('touchstart', preventDefault, { passive: false });
- this.$trigger.addEventListener('touchmove', preventDefault, { passive: false });
- this.$trigger.addEventListener('touchend', preventDefault);
-
-
- if ((!this.disabled[0] && abs(movedX) > 3) || (!this.disabled[1] && abs(movedY) > 3)) {
-
- this.updateTicker.resume();
- this.pointer[2] = this.pointer[0];
- this.pointer[3] = this.pointer[1];
- this.pointer[0] = x;
- this.pointer[1] = y;
- this.dragged = true;
- this.released = false;
- this.onDrag(this);
- }
+ this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args));
}
+ return this;
}
- handleUp() {
-
- if (!this.grabbed) return;
-
- this.updateTicker.pause();
-
- if (this.triggerStyles) {
- this.triggerStyles.revert();
- this.triggerStyles = null;
- }
-
- if (this.bodyStyles) {
- this.bodyStyles.revert();
- this.bodyStyles = null;
+ /**
+ * @param {ScopeConstructorCallback} scopeConstructorCallback
+ * @return {this}
+ */
+ addOnce(scopeConstructorCallback) {
+ this.once = true;
+ if (isFnc(scopeConstructorCallback)) {
+ const currentIndex = this.onceIndex++;
+ const tracked = this.constructorsOnce[currentIndex];
+ if (tracked) return this;
+ const constructor = /** @type {ScopeConstructorCallback} */(scopeConstructorCallback);
+ this.constructorsOnce[currentIndex] = constructor;
+ this.execute(() => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructorsOnce.push(revertConstructor);
+ }
+ });
}
+ return this;
+ }
- const [ disabledX, disabledY ] = this.disabled;
- const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
- const [ ct, cr, cb, cl ] = this.containerBounds;
- const [ sx, sy ] = this.snapped;
- const springX = this.releaseXSpring;
- const springY = this.releaseYSpring;
- const releaseEase = this.releaseEase;
- const hasReleaseSpring = this.hasReleaseSpring;
- const overshootCoords = this.overshootCoords;
- const cx = this.x;
- const cy = this.y;
- const pv = this.computeVelocity(px1 - px3, py1 - py3);
- const pa = this.angle = atan2(py1 - py2, px1 - px2);
- const ds = pv * 150;
- const cf = (1 - this.releaseContainerFriction) * this.dragSpeed;
- const nx = cx + (cos(pa) * ds);
- const ny = cy + (sin(pa) * ds);
- const bx = nx > cr ? cr + (nx - cr) * cf : nx < cl ? cl + (nx - cl) * cf : nx;
- const by = ny > cb ? cb + (ny - cb) * cf : ny < ct ? ct + (ny - ct) * cf : ny;
- const dx = this.destX = clamp(round(snap(bx, this.snapX), 5), cl, cr);
- const dy = this.destY = clamp(round(snap(by, this.snapY), 5), ct, cb);
- const ob = this.isOutOfBounds(this.containerBounds, nx, ny);
-
- let durationX = 0;
- let durationY = 0;
- let easeX = releaseEase;
- let easeY = releaseEase;
- let longestReleaseDuration = 0;
-
- overshootCoords.x = cx;
- overshootCoords.y = cy;
+ /**
+ * @param {(scope: this) => Tickable} cb
+ * @return {Tickable}
+ */
+ keepTime(cb) {
+ this.once = true;
+ const currentIndex = this.onceIndex++;
+ const tracked = /** @type {(scope: this) => Tickable} */(this.constructorsOnce[currentIndex]);
+ if (isFnc(tracked)) return tracked(this);
+ const constructor = /** @type {(scope: this) => Tickable} */(keepTime(cb));
+ this.constructorsOnce[currentIndex] = constructor;
+ let trackedTickable;
+ this.execute(() => {
+ trackedTickable = constructor(this);
+ });
+ return trackedTickable;
+ }
- if (!disabledX) {
- const directionX = dx === cr ? cx > cr ? -1 : 1 : cx < cl ? -1 : 1;
- const distanceX = round(cx - dx, 0);
- springX.velocity = disabledY && hasReleaseSpring ? distanceX ? (ds * directionX) / abs(distanceX) : 0 : pv;
- const { ease, duration, restDuration } = springX;
- durationX = cx === dx ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.timeScale);
- if (hasReleaseSpring) easeX = ease;
- if (durationX > longestReleaseDuration) longestReleaseDuration = durationX;
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'change':
+ this.refresh();
+ break;
}
+ }
- if (!disabledY) {
- const directionY = dy === cb ? cy > cb ? -1 : 1 : cy < ct ? -1 : 1;
- const distanceY = round(cy - dy, 0);
- springY.velocity = disabledX && hasReleaseSpring ? distanceY ? (ds * directionY) / abs(distanceY) : 0 : pv;
- const { ease, duration, restDuration } = springY;
- durationY = cy === dy ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.timeScale);
- if (hasReleaseSpring) easeY = ease;
- if (durationY > longestReleaseDuration) longestReleaseDuration = durationY;
- }
+ revert() {
+ const revertibles = this.revertibles;
+ const revertConstructors = this.revertConstructors;
+ const revertiblesOnce = this.revertiblesOnce;
+ const revertConstructorsOnce = this.revertConstructorsOnce;
+ const mqs = this.mediaQueryLists;
+ let i = revertibles.length;
+ let j = revertConstructors.length;
+ let k = revertiblesOnce.length;
+ let l = revertConstructorsOnce.length;
+ while (i--) revertibles[i].revert();
+ while (j--) revertConstructors[j](this);
+ while (k--) revertiblesOnce[k].revert();
+ while (l--) revertConstructorsOnce[l](this);
+ for (let mq in mqs) mqs[mq].removeEventListener('change', this);
+ revertibles.length = 0;
+ revertConstructors.length = 0;
+ this.constructors.length = 0;
+ revertiblesOnce.length = 0;
+ revertConstructorsOnce.length = 0;
+ this.constructorsOnce.length = 0;
+ this.onceIndex = 0;
+ this.matches = {};
+ this.methods = {};
+ this.mediaQueryLists = {};
+ this.data = {};
+ }
+}
+
+/**
+ * @param {ScopeParams} [params]
+ * @return {Scope}
+ */
+const createScope = params => new Scope(params);
- if (!hasReleaseSpring && ob && cf && (durationX || durationY)) {
- const composition = compositionTypes.blend;
- new JSAnimation(overshootCoords, {
- x: { to: bx, duration: durationX * .65 },
- y: { to: by, duration: durationY * .65 },
- ease: releaseEase,
- composition,
- }).init();
- new JSAnimation(overshootCoords, {
- x: { to: dx, duration: durationX },
- y: { to: dy, duration: durationY },
- ease: releaseEase,
- composition,
- }).init();
- this.overshootTicker.stretch(max(durationX, durationY)).restart();
- } else {
- if (!disabledX) this.animate[this.xProp](dx, durationX, easeX);
- if (!disabledY) this.animate[this.yProp](dy, durationY, easeY);
- }
- this.scrollInView(longestReleaseDuration, this.scrollThreshold, releaseEase);
+/**
+ * @return {Number}
+ */
+const getMaxViewHeight = () => {
+ const $el = doc.createElement('div');
+ doc.body.appendChild($el);
+ $el.style.height = '100lvh';
+ const height = $el.offsetHeight;
+ doc.body.removeChild($el);
+ return height;
+};
- let hasSnapped = false;
+/**
+ * @template {ScrollThresholdValue|String|Number|Boolean|Function|Object} T
+ * @param {T | ((observer: ScrollObserver) => T)} value
+ * @param {ScrollObserver} scroller
+ * @return {T}
+ */
+const parseScrollObserverFunctionParameter = (value, scroller) => value && isFnc(value) ? /** @type {Function} */(value)(scroller) : /** @type {T} */(value);
- if (dx !== sx) {
- this.snapped[0] = dx;
- if (this.snapX) hasSnapped = true;
- }
+const scrollContainers = new Map();
- if (dy !== sy && this.snapY) {
- this.snapped[1] = dy;
- if (this.snapY) hasSnapped = true;
+class ScrollContainer {
+ /**
+ * @param {HTMLElement} $el
+ */
+ constructor($el) {
+ /** @type {HTMLElement} */
+ this.element = $el;
+ /** @type {Boolean} */
+ this.useWin = this.element === doc.body;
+ /** @type {Number} */
+ this.winWidth = 0;
+ /** @type {Number} */
+ this.winHeight = 0;
+ /** @type {Number} */
+ this.width = 0;
+ /** @type {Number} */
+ this.height = 0;
+ /** @type {Number} */
+ this.left = 0;
+ /** @type {Number} */
+ this.top = 0;
+ /** @type {Number} */
+ this.zIndex = 0;
+ /** @type {Number} */
+ this.scrollX = 0;
+ /** @type {Number} */
+ this.scrollY = 0;
+ /** @type {Number} */
+ this.prevScrollX = 0;
+ /** @type {Number} */
+ this.prevScrollY = 0;
+ /** @type {Number} */
+ this.scrollWidth = 0;
+ /** @type {Number} */
+ this.scrollHeight = 0;
+ /** @type {Number} */
+ this.velocity = 0;
+ /** @type {Boolean} */
+ this.backwardX = false;
+ /** @type {Boolean} */
+ this.backwardY = false;
+ /** @type {Timer} */
+ this.scrollTicker = new Timer({
+ autoplay: false,
+ onBegin: () => this.dataTimer.resume(),
+ onUpdate: () => {
+ const backwards = this.backwardX || this.backwardY;
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => child.handleScroll(), backwards);
+ },
+ onComplete: () => this.dataTimer.pause()
+ }).init();
+ /** @type {Timer} */
+ this.dataTimer = new Timer({
+ autoplay: false,
+ frameRate: 30,
+ onUpdate: (/** @type {Timer} */self) => {
+ const dt = self.deltaTime;
+ const px = this.prevScrollX;
+ const py = this.prevScrollY;
+ const nx = this.scrollX;
+ const ny = this.scrollY;
+ const dx = px - nx;
+ const dy = py - ny;
+ this.prevScrollX = nx;
+ this.prevScrollY = ny;
+ if (dx) this.backwardX = px > nx;
+ if (dy) this.backwardY = py > ny;
+ this.velocity = round$1(dt > 0 ? Math.sqrt(dx * dx + dy * dy) / dt : 0, 5);
+ }
+ }).init();
+ /** @type {Timer} */
+ this.resizeTicker = new Timer({
+ autoplay: false,
+ duration: 250 * globals.timeScale,
+ onComplete: () => {
+ this.updateWindowBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ }
+ }).init();
+ /** @type {Timer} */
+ this.wakeTicker = new Timer({
+ autoplay: false,
+ duration: 500 * globals.timeScale,
+ onBegin: () => {
+ this.scrollTicker.resume();
+ },
+ onComplete: () => {
+ this.scrollTicker.pause();
+ }
+ }).init();
+ /** @type {ScrollObserver} */
+ this._head = null;
+ /** @type {ScrollObserver} */
+ this._tail = null;
+ this.updateScrollCoords();
+ this.updateWindowBounds();
+ this.updateBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ this.resizeObserver = new ResizeObserver(() => this.resizeTicker.restart());
+ this.resizeObserver.observe(this.element);
+ (this.useWin ? win : this.element).addEventListener('scroll', this, false);
+ }
+
+ updateScrollCoords() {
+ const useWin = this.useWin;
+ const $el = this.element;
+ this.scrollX = round$1(useWin ? win.scrollX : $el.scrollLeft, 0);
+ this.scrollY = round$1(useWin ? win.scrollY : $el.scrollTop, 0);
+ }
+
+ updateWindowBounds() {
+ this.winWidth = win.innerWidth;
+ this.winHeight = getMaxViewHeight();
+ }
+
+ updateBounds() {
+ const style = getComputedStyle(this.element);
+ const $el = this.element;
+ this.scrollWidth = $el.scrollWidth + parseFloat(style.marginLeft) + parseFloat(style.marginRight);
+ this.scrollHeight = $el.scrollHeight + parseFloat(style.marginTop) + parseFloat(style.marginBottom);
+ this.updateWindowBounds();
+ let width, height;
+ if (this.useWin) {
+ width = this.winWidth;
+ height = this.winHeight;
+ } else {
+ const elRect = $el.getBoundingClientRect();
+ width = $el.clientWidth;
+ height = $el.clientHeight;
+ this.top = elRect.top;
+ this.left = elRect.left;
}
+ this.width = width;
+ this.height = height;
+ }
- if (hasSnapped) this.onSnap(this);
+ refreshScrollObservers() {
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => {
+ if (child._debug) {
+ child.removeDebug();
+ }
+ });
+ this.updateBounds();
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => {
+ child.refresh();
+ if (child._debug) {
+ child.debug();
+ }
+ });
+ }
- this.grabbed = false;
- this.dragged = false;
- this.updated = true;
- this.released = true;
+ refresh() {
+ this.updateWindowBounds();
+ this.updateBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ }
- // It's important to trigger the callback after the release animations to be able to cancel them
- this.onRelease(this);
+ handleScroll() {
+ this.updateScrollCoords();
+ this.wakeTicker.restart();
+ }
- this.$trigger.removeEventListener('touchstart', preventDefault);
- this.$trigger.removeEventListener('touchmove', preventDefault);
- this.$trigger.removeEventListener('touchend', preventDefault);
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'scroll':
+ this.handleScroll();
+ break;
+ }
+ }
- doc.removeEventListener('touchmove', this);
- doc.removeEventListener('touchend', this);
- doc.removeEventListener('touchcancel', this);
- doc.removeEventListener('mousemove', this);
- doc.removeEventListener('mouseup', this);
- doc.removeEventListener('selectstart', this);
+ revert() {
+ this.scrollTicker.cancel();
+ this.dataTimer.cancel();
+ this.resizeTicker.cancel();
+ this.wakeTicker.cancel();
+ this.resizeObserver.disconnect();
+ (this.useWin ? win : this.element).removeEventListener('scroll', this);
+ scrollContainers.delete(this.element);
}
+}
- reset() {
- this.stop();
- this.resizeTicker.pause();
- this.grabbed = false;
- this.dragged = false;
- this.updated = false;
- this.released = false;
- this.canScroll = false;
- this.setX(0, true);
- this.setY(0, true);
- this.coords[0] = 0;
- this.coords[1] = 0;
- this.pointer[0] = 0;
- this.pointer[1] = 0;
- this.pointer[2] = 0;
- this.pointer[3] = 0;
- this.pointer[4] = 0;
- this.pointer[5] = 0;
- this.pointer[6] = 0;
- this.pointer[7] = 0;
- this.velocity = 0;
- this.velocityStack[0] = 0;
- this.velocityStack[1] = 0;
- this.velocityStack[2] = 0;
- this.velocityStackIndex = 0;
- this.angle = 0;
- return this;
+/**
+ * @param {TargetsParam} target
+ * @return {ScrollContainer}
+ */
+const registerAndGetScrollContainer = target => {
+ const $el = /** @type {HTMLElement} */(target ? parseTargets(target)[0] || doc.body : doc.body);
+ let scrollContainer = scrollContainers.get($el);
+ if (!scrollContainer) {
+ scrollContainer = new ScrollContainer($el);
+ scrollContainers.set($el, scrollContainer);
}
+ return scrollContainer;
+};
- enable() {
- if (!this.enabled) {
- this.enabled = true;
- this.$target.classList.remove('is-disabled');
- this.touchActionStyles = setTargetValues(this.$trigger, {
- touchAction: this.disabled[0] ? 'pan-x' : this.disabled[1] ? 'pan-y' : 'none'
- });
- this.$trigger.addEventListener('touchstart', this, { passive: true });
- this.$trigger.addEventListener('mousedown', this, { passive: true });
- this.$trigger.addEventListener('mouseenter', this);
- }
- return this;
+/**
+ * @param {HTMLElement} $el
+ * @param {Number|string} v
+ * @param {Number} size
+ * @param {Number} [under]
+ * @param {Number} [over]
+ * @return {Number}
+ */
+const convertValueToPx = ($el, v, size, under, over) => {
+ const clampMin = v === 'min';
+ const clampMax = v === 'max';
+ const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 :
+ v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' :
+ v === 'center' ? '50%' :
+ v;
+ const { n, u } = decomposeRawValue(value, decomposedOriginalValue);
+ let px = n;
+ if (u === '%') {
+ px = (n / 100) * size;
+ } else if (u) {
+ px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n;
}
+ if (clampMax && under < 0) px += under;
+ if (clampMin && over > 0) px += over;
+ return px;
+};
- disable() {
- this.enabled = false;
- this.grabbed = false;
- this.dragged = false;
- this.updated = false;
- this.released = false;
- this.canScroll = false;
- this.touchActionStyles.revert();
- if (this.cursorStyles) {
- this.cursorStyles.revert();
- this.cursorStyles = null;
- }
- if (this.triggerStyles) {
- this.triggerStyles.revert();
- this.triggerStyles = null;
- }
- if (this.bodyStyles) {
- this.bodyStyles.revert();
- this.bodyStyles = null;
+/**
+ * @param {HTMLElement} $el
+ * @param {ScrollThresholdValue} v
+ * @param {Number} size
+ * @param {Number} [under]
+ * @param {Number} [over]
+ * @return {Number}
+ */
+const parseBoundValue = ($el, v, size, under, over) => {
+ /** @type {Number} */
+ let value;
+ if (isStr(v)) {
+ const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v));
+ if (matchedOperator) {
+ const splitter = matchedOperator[0];
+ const operator = splitter[0];
+ const splitted = /** @type {String} */(v).split(splitter);
+ const clampMin = splitted[0] === 'min';
+ const clampMax = splitted[0] === 'max';
+ const valueAPx = convertValueToPx($el, splitted[0], size, under, over);
+ const valueBPx = convertValueToPx($el, splitted[1], size, under, over);
+ if (clampMin) {
+ const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator);
+ value = min < valueAPx ? valueAPx : min;
+ } else if (clampMax) {
+ const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator);
+ value = max > valueAPx ? valueAPx : max;
+ } else {
+ value = getRelativeValue(valueAPx, valueBPx, operator);
+ }
+ } else {
+ value = convertValueToPx($el, v, size, under, over);
}
- if (this.targetStyles) {
- this.targetStyles.revert();
- this.targetStyles = null;
+ } else {
+ value = /** @type {Number} */(v);
+ }
+ return round$1(value, 0);
+};
+
+/**
+ * @param {JSAnimation} linked
+ * @return {HTMLElement}
+ */
+const getAnimationDomTarget = linked => {
+ let $linkedTarget;
+ const linkedTargets = linked.targets;
+ for (let i = 0, l = linkedTargets.length; i < l; i++) {
+ const target = linkedTargets[i];
+ if (target[isDomSymbol]) {
+ $linkedTarget = /** @type {HTMLElement} */(target);
+ break;
}
- this.$target.classList.add('is-disabled');
- this.$trigger.removeEventListener('touchstart', this);
- this.$trigger.removeEventListener('mousedown', this);
- this.$trigger.removeEventListener('mouseenter', this);
- doc.removeEventListener('touchmove', this);
- doc.removeEventListener('touchend', this);
- doc.removeEventListener('touchcancel', this);
- doc.removeEventListener('mousemove', this);
- doc.removeEventListener('mouseup', this);
- doc.removeEventListener('selectstart', this);
- return this;
}
+ return $linkedTarget;
+};
- revert() {
- this.reset();
- this.disable();
- this.$target.classList.remove('is-disabled');
- this.updateTicker.revert();
- this.overshootTicker.revert();
- this.resizeTicker.revert();
- this.animate.revert();
- this.resizeObserver.disconnect();
- return this;
+let scrollerIndex = 0;
+
+const debugColors$1 = ['#FF4B4B','#FF971B','#FFC730','#F9F640','#7AFF5A','#18FF74','#17E09B','#3CFFEC','#05DBE9','#33B3F1','#638CF9','#C563FE','#FF4FCF','#F93F8A'];
+
+class ScrollObserver {
+ /**
+ * @param {ScrollObserverParams} parameters
+ */
+ constructor(parameters = {}) {
+ if (scope.current) scope.current.register(this);
+ const syncMode = setValue(parameters.sync, 'play pause');
+ const ease = syncMode ? parseEase(/** @type {EasingParam} */(syncMode)) : null;
+ const isLinear = syncMode && (syncMode === 'linear' || syncMode === none);
+ const isEase = syncMode && !(ease === none && !isLinear);
+ const isSmooth = syncMode && (isNum(syncMode) || syncMode === true || isLinear);
+ const isMethods = syncMode && (isStr(syncMode) && !isEase && !isSmooth);
+ const syncMethods = isMethods ? /** @type {String} */(syncMode).split(' ').map(
+ (/** @type {String} */m) => () => {
+ const linked = this.linked;
+ return linked && linked[m] ? linked[m]() : null;
+ }
+ ) : null;
+ const biDirSync = isMethods && syncMethods.length > 2;
+ /** @type {Number} */
+ this.index = scrollerIndex++;
+ /** @type {String|Number} */
+ this.id = !isUnd(parameters.id) ? parameters.id : this.index;
+ /** @type {ScrollContainer} */
+ this.container = registerAndGetScrollContainer(parameters.container);
+ /** @type {HTMLElement} */
+ this.target = null;
+ /** @type {Tickable|WAAPIAnimation} */
+ this.linked = null;
+ /** @type {Boolean} */
+ this.repeat = null;
+ /** @type {Boolean} */
+ this.horizontal = null;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ this.enter = null;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ this.leave = null;
+ /** @type {Boolean} */
+ this.sync = isEase || isSmooth || !!syncMethods;
+ /** @type {EasingFunction} */
+ this.syncEase = isEase ? ease : null;
+ /** @type {Number} */
+ this.syncSmooth = isSmooth ? syncMode === true || isLinear ? 1 : /** @type {Number} */(syncMode) : null;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnter = syncMethods && !biDirSync && syncMethods[0] ? syncMethods[0] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeave = syncMethods && !biDirSync && syncMethods[1] ? syncMethods[1] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnterForward = syncMethods && biDirSync && syncMethods[0] ? syncMethods[0] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeaveForward = syncMethods && biDirSync && syncMethods[1] ? syncMethods[1] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnterBackward = syncMethods && biDirSync && syncMethods[2] ? syncMethods[2] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeaveBackward = syncMethods && biDirSync && syncMethods[3] ? syncMethods[3] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnter = parameters.onEnter || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeave = parameters.onLeave || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnterForward = parameters.onEnterForward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeaveForward = parameters.onLeaveForward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnterBackward = parameters.onEnterBackward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeaveBackward = parameters.onLeaveBackward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onUpdate = parameters.onUpdate || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncComplete = parameters.onSyncComplete || noop;
+ /** @type {Boolean} */
+ this.reverted = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Boolean} */
+ this.began = false;
+ /** @type {Boolean} */
+ this.isInView = false;
+ /** @type {Boolean} */
+ this.forceEnter = false;
+ /** @type {Boolean} */
+ this.hasEntered = false;
+ // /** @type {Array.<Number>} */
+ // this.offsets = [];
+ /** @type {Number} */
+ this.offset = 0;
+ /** @type {Number} */
+ this.offsetStart = 0;
+ /** @type {Number} */
+ this.offsetEnd = 0;
+ /** @type {Number} */
+ this.distance = 0;
+ /** @type {Number} */
+ this.prevProgress = 0;
+ /** @type {Array} */
+ this.thresholds = ['start', 'end', 'end', 'start'];
+ /** @type {[Number, Number, Number, Number]} */
+ this.coords = [0, 0, 0, 0];
+ /** @type {JSAnimation} */
+ this.debugStyles = null;
+ /** @type {HTMLElement} */
+ this.$debug = null;
+ /** @type {ScrollObserverParams} */
+ this._params = parameters;
+ /** @type {Boolean} */
+ this._debug = setValue(parameters.debug, false);
+ /** @type {ScrollObserver} */
+ this._next = null;
+ /** @type {ScrollObserver} */
+ this._prev = null;
+ addChild(this.container, this);
+ // Wait for the next frame to add to the container in order to handle calls to link()
+ sync(() => {
+ if (this.reverted) return;
+ if (!this.target) {
+ const target = /** @type {HTMLElement} */(parseTargets(parameters.target)[0]);
+ this.target = target || doc.body;
+ this.refresh();
+ }
+ if (this._debug) this.debug();
+ });
}
/**
- * @param {Event} e
+ * @param {Tickable|WAAPIAnimation} linked
*/
- handleEvent(e) {
- switch (e.type) {
- case 'mousedown':
- this.handleDown(/** @type {MouseEvent} */(e));
- break;
- case 'touchstart':
- this.handleDown(/** @type {TouchEvent} */(e));
- break;
- case 'mousemove':
- this.handleMove(/** @type {MouseEvent} */(e));
- break;
- case 'touchmove':
- this.handleMove(/** @type {TouchEvent} */(e));
- break;
- case 'mouseup':
- this.handleUp();
- break;
- case 'touchend':
- this.handleUp();
- break;
- case 'touchcancel':
- this.handleUp();
- break;
- case 'mouseenter':
- this.handleHover();
- break;
- case 'selectstart':
- preventDefault(e);
- break;
+ link(linked) {
+ if (linked) {
+ // Make sure to pause the linked object in case it's added later
+ linked.pause();
+ this.linked = linked;
+ // Try to use a target of the linked object if no target parameters specified
+ if (!this._params.target) {
+ /** @type {HTMLElement} */
+ let $linkedTarget;
+ if (!isUnd(/** @type {JSAnimation} */(linked).targets)) {
+ $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(linked));
+ } else {
+ forEachChildren(/** @type {Timeline} */(linked), (/** @type {JSAnimation} */child) => {
+ if (child.targets && !$linkedTarget) {
+ $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(child));
+ }
+ });
+ }
+ // Fallback to body if no target found
+ this.target = $linkedTarget || doc.body;
+ this.refresh();
+ }
}
+ return this;
}
-}
-/**
- * @param {TargetsParam} target
- * @param {DraggableParams} [parameters]
- * @return {Draggable}
- */
-const createDraggable = (target, parameters) => new Draggable(target, parameters);
+ get velocity() {
+ return this.container.velocity;
+ }
+ get backward() {
+ return this.horizontal ? this.container.backwardX : this.container.backwardY;
+ }
+ get scroll() {
+ return this.horizontal ? this.container.scrollX : this.container.scrollY;
+ }
+ get progress() {
+ const p = (this.scroll - this.offsetStart) / this.distance;
+ return p === Infinity || isNaN(p) ? 0 : round$1(clamp$1(p, 0, 1), 6);
+ }
-class Scope {
- /** @param {ScopeParams} [parameters] */
- constructor(parameters = {}) {
- if (scope.current) scope.current.register(this);
- const rootParam = parameters.root;
- /** @type {Document|DOMTarget} */
- let root = doc;
- if (rootParam) {
- root = /** @type {ReactRef} */(rootParam).current ||
- /** @type {AngularRef} */(rootParam).nativeElement ||
- parseTargets(/** @type {DOMTargetSelector} */(rootParam))[0] ||
- doc;
+ refresh() {
+ this.reverted = false;
+ const params = this._params;
+ this.repeat = setValue(parseScrollObserverFunctionParameter(params.repeat, this), true);
+ this.horizontal = setValue(parseScrollObserverFunctionParameter(params.axis, this), 'y') === 'x';
+ this.enter = setValue(parseScrollObserverFunctionParameter(params.enter, this), 'end start');
+ this.leave = setValue(parseScrollObserverFunctionParameter(params.leave, this), 'start end');
+ this.updateBounds();
+ this.handleScroll();
+ return this;
+ }
+
+ removeDebug() {
+ if (this.$debug) {
+ this.$debug.parentNode.removeChild(this.$debug);
+ this.$debug = null;
}
- const scopeDefaults = parameters.defaults;
- const globalDefault = globals.defaults;
- const mediaQueries = parameters.mediaQueries;
- /** @type {DefaultsParams} */
- this.defaults = scopeDefaults ? mergeObjects(scopeDefaults, globalDefault) : globalDefault;
- /** @type {Document|DOMTarget} */
- this.root = root;
- /** @type {Array<ScopeConstructorCallback>} */
- this.constructors = [];
- /** @type {Array<ScopeCleanupCallback>} */
- this.revertConstructors = [];
- /** @type {Array<Revertible>} */
- this.revertibles = [];
- /** @type {Array<ScopeConstructorCallback | ((scope: this) => Tickable)>} */
- this.constructorsOnce = [];
- /** @type {Array<ScopeCleanupCallback>} */
- this.revertConstructorsOnce = [];
- /** @type {Array<Revertible>} */
- this.revertiblesOnce = [];
- /** @type {Boolean} */
- this.once = false;
- /** @type {Number} */
- this.onceIndex = 0;
- /** @type {Record<String, ScopeMethod>} */
- this.methods = {};
- /** @type {Record<String, Boolean>} */
- this.matches = {};
- /** @type {Record<String, MediaQueryList>} */
- this.mediaQueryLists = {};
- /** @type {Record<String, any>} */
- this.data = {};
- if (mediaQueries) {
- for (let mq in mediaQueries) {
- const _mq = win.matchMedia(mediaQueries[mq]);
- this.mediaQueryLists[mq] = _mq;
- _mq.addEventListener('change', this);
- }
+ if (this.debugStyles) {
+ this.debugStyles.revert();
+ this.$debug = null;
}
+ return this;
}
- /**
- * @param {Revertible} revertible
- */
- register(revertible) {
- const store = this.once ? this.revertiblesOnce : this.revertibles;
- store.push(revertible);
- }
+ debug() {
+ this.removeDebug();
+ const container = this.container;
+ const isHori = this.horizontal;
+ const $existingDebug = container.element.querySelector(':scope > .animejs-onscroll-debug');
+ const $debug = doc.createElement('div');
+ const $thresholds = doc.createElement('div');
+ const $triggers = doc.createElement('div');
+ const color = debugColors$1[this.index % debugColors$1.length];
+ const useWin = container.useWin;
+ const containerWidth = useWin ? container.winWidth : container.width;
+ const containerHeight = useWin ? container.winHeight : container.height;
+ const scrollWidth = container.scrollWidth;
+ const scrollHeight = container.scrollHeight;
+ const size = this.container.width > 360 ? 320 : 260;
+ const offLeft = isHori ? 0 : 10;
+ const offTop = isHori ? 10 : 0;
+ const half = isHori ? 24 : size / 2;
+ const labelHeight = isHori ? half : 15;
+ const labelWidth = isHori ? 60 : half;
+ const labelSize = isHori ? labelWidth : labelHeight;
+ const repeat = isHori ? 'repeat-x' : 'repeat-y';
+ /**
+ * @param {Number} v
+ * @return {String}
+ */
+ const gradientOffset = v => isHori ? '0px '+(v)+'px' : (v)+'px'+' 2px';
+ /**
+ * @param {String} c
+ * @return {String}
+ */
+ const lineCSS = (c) => `linear-gradient(${isHori ? 90 : 0}deg, ${c} 2px, transparent 1px)`;
+ /**
+ * @param {String} p
+ * @param {Number} l
+ * @param {Number} t
+ * @param {Number} w
+ * @param {Number} h
+ * @return {String}
+ */
+ const baseCSS = (p, l, t, w, h) => `position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`;
+ $debug.style.cssText = `${baseCSS('absolute', offLeft, offTop, isHori ? scrollWidth : size, isHori ? size : scrollHeight)}
+ pointer-events: none;
+ z-index: ${this.container.zIndex++};
+ display: flex;
+ flex-direction: ${isHori ? 'column' : 'row'};
+ filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));
+ `;
+ $thresholds.style.cssText = `${baseCSS('sticky', 0, 0, isHori ? containerWidth : half, isHori ? half : containerHeight)}`;
+ if (!$existingDebug) {
+ $thresholds.style.cssText += `background:
+ ${lineCSS('#FFFF')}${gradientOffset(half-10)} / ${isHori ? '100px 100px' : '100px 100px'} ${repeat},
+ ${lineCSS('#FFF8')}${gradientOffset(half-10)} / ${isHori ? '10px 10px' : '10px 10px'} ${repeat};
+ `;
+ }
+ $triggers.style.cssText = `${baseCSS('relative', 0, 0, isHori ? scrollWidth : half, isHori ? half : scrollHeight)}`;
+ if (!$existingDebug) {
+ $triggers.style.cssText += `background:
+ ${lineCSS('#FFFF')}${gradientOffset(0)} / ${isHori ? '100px 10px' : '10px 100px'} ${repeat},
+ ${lineCSS('#FFF8')}${gradientOffset(0)} / ${isHori ? '10px 0px' : '0px 10px'} ${repeat};
+ `;
+ }
+ const labels = [' enter: ', ' leave: '];
+ this.coords.forEach((v, i) => {
+ const isView = i > 1;
+ const value = (isView ? 0 : this.offset) + v;
+ const isTail = i % 2;
+ const isFirst = value < labelSize;
+ const isOver = value > (isView ? isHori ? containerWidth : containerHeight : isHori ? scrollWidth : scrollHeight) - labelSize;
+ const isFlip = (isView ? isTail && !isFirst : !isTail && !isFirst) || isOver;
+ const $label = doc.createElement('div');
+ const $text = doc.createElement('div');
+ const dirProp = isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top';
+ const flipOffset = isFlip ? (isHori ? labelWidth : labelHeight) + (!isView ? isHori ? -1 : -2 : isHori ? -1 : isOver ? 0 : -2) : !isView ? isHori ? 1 : 0 : isHori ? 1 : 0;
+ // $text.innerHTML = `${!isView ? '' : labels[isTail] + ' '}${this.id}: ${this.thresholds[i]} ${isView ? '' : labels[isTail]}`;
+ $text.innerHTML = `${this.id}${labels[isTail]}${this.thresholds[i]}`;
+ $label.style.cssText = `${baseCSS('absolute', 0, 0, labelWidth, labelHeight)}
+ display: flex;
+ flex-direction: ${isHori ? 'column' : 'row'};
+ justify-content: flex-${isView ? 'start' : 'end'};
+ align-items: flex-${isFlip ? 'end' : 'start'};
+ border-${dirProp}: 2px ${isTail ? 'solid' : 'solid'} ${color};
+ `;
+ $text.style.cssText = `
+ overflow: hidden;
+ max-width: ${(size / 2) - 10}px;
+ height: ${labelHeight};
+ margin-${isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'}: -2px;
+ padding: 1px;
+ font-family: ui-monospace, monospace;
+ font-size: 10px;
+ letter-spacing: -.025em;
+ line-height: 9px;
+ font-weight: 600;
+ text-align: ${isHori && isFlip || !isHori && !isView ? 'right' : 'left'};
+ white-space: pre;
+ text-overflow: ellipsis;
+ color: ${isTail ? color : 'rgba(0,0,0,.75)'};
+ background-color: ${isTail ? 'rgba(0,0,0,.65)' : color};
+ border: 2px solid ${isTail ? color : 'transparent'};
+ border-${isHori ? isFlip ? 'top-left' : 'top-right' : isFlip ? 'top-left' : 'bottom-left'}-radius: 5px;
+ border-${isHori ? isFlip ? 'bottom-left' : 'bottom-right' : isFlip ? 'top-right' : 'bottom-right'}-radius: 5px;
+ `;
+ $label.appendChild($text);
+ let position = value - flipOffset + (isHori ? 1 : 0);
+ $label.style[isHori ? 'left' : 'top'] = `${position}px`;
+ // $label.style[isHori ? 'left' : 'top'] = value - flipOffset + (!isFlip && isFirst && !isView ? 1 : isFlip ? 0 : -2) + 'px';
+ (isView ? $thresholds : $triggers).appendChild($label);
+ });
+
+ $debug.appendChild($thresholds);
+ $debug.appendChild($triggers);
+ container.element.appendChild($debug);
- /**
- * @template T
- * @param {ScopedCallback<T>} cb
- * @return {T}
- */
- execute(cb) {
- let activeScope = scope.current;
- let activeRoot = scope.root;
- let activeDefaults = globals.defaults;
- scope.current = this;
- scope.root = this.root;
- globals.defaults = this.defaults;
- const mqs = this.mediaQueryLists;
- for (let mq in mqs) this.matches[mq] = mqs[mq].matches;
- const returned = cb(this);
- scope.current = activeScope;
- scope.root = activeRoot;
- globals.defaults = activeDefaults;
- return returned;
- }
+ if (!$existingDebug) $debug.classList.add('animejs-onscroll-debug');
+ this.$debug = $debug;
+ const containerPosition = get(container.element, 'position');
+ if (containerPosition === 'static') {
+ this.debugStyles = set(container.element, { position: 'relative '});
+ }
- /**
- * @return {this}
- */
- refresh() {
- this.onceIndex = 0;
- this.execute(() => {
- let i = this.revertibles.length;
- let y = this.revertConstructors.length;
- while (i--) this.revertibles[i].revert();
- while (y--) this.revertConstructors[y](this);
- this.revertibles.length = 0;
- this.revertConstructors.length = 0;
- this.constructors.forEach((/** @type {ScopeConstructorCallback} */constructor) => {
- const revertConstructor = constructor(this);
- if (isFnc(revertConstructor)) {
- this.revertConstructors.push(revertConstructor);
- }
- });
- });
- return this;
}
- /**
- * @overload
- * @param {String} a1
- * @param {ScopeMethod} a2
- * @return {this}
- *
- * @overload
- * @param {ScopeConstructorCallback} a1
- * @return {this}
- *
- * @param {String|ScopeConstructorCallback} a1
- * @param {ScopeMethod} [a2]
- */
- add(a1, a2) {
- this.once = false;
- if (isFnc(a1)) {
- const constructor = /** @type {ScopeConstructorCallback} */(a1);
- this.constructors.push(constructor);
- this.execute(() => {
- const revertConstructor = constructor(this);
- if (isFnc(revertConstructor)) {
- this.revertConstructors.push(revertConstructor);
- }
- });
- } else {
- this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args));
+ updateBounds() {
+ if (this._debug) {
+ this.removeDebug();
}
- return this;
- }
+ let stickys;
+ const $target = this.target;
+ const container = this.container;
+ const isHori = this.horizontal;
+ const linked = this.linked;
+ let linkedTime;
+ let $el = $target;
+ // let offsetX = 0;
+ // let offsetY = 0;
+ // let $offsetParent = $el;
+ /** @type {Element} */
+ if (linked) {
+ linkedTime = linked.currentTime;
+ linked.seek(0, true);
+ }
+ /* Old implementation to get offset and targetSize before fixing https://github.com/juliangarnier/anime/issues/1021
+ // const isContainerStatic = get(container.element, 'position') === 'static' ? set(container.element, { position: 'relative '}) : false;
+ // while ($el && $el !== container.element && $el !== doc.body) {
+ // const isSticky = get($el, 'position') === 'sticky' ?
+ // set($el, { position: 'static' }) :
+ // false;
+ // if ($el === $offsetParent) {
+ // offsetX += $el.offsetLeft || 0;
+ // offsetY += $el.offsetTop || 0;
+ // $offsetParent = $el.offsetParent;
+ // }
+ // $el = /** @type {HTMLElement} */($el.parentElement);
+ // if (isSticky) {
+ // if (!stickys) stickys = [];
+ // stickys.push(isSticky);
+ // }
+ // }
+ // if (isContainerStatic) isContainerStatic.revert();
+ // const offset = isHori ? offsetX : offsetY;
+ // const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight;
- /**
- * @param {ScopeConstructorCallback} scopeConstructorCallback
- * @return {this}
- */
- addOnce(scopeConstructorCallback) {
- this.once = true;
- if (isFnc(scopeConstructorCallback)) {
- const currentIndex = this.onceIndex++;
- const tracked = this.constructorsOnce[currentIndex];
- if (tracked) return this;
- const constructor = /** @type {ScopeConstructorCallback} */(scopeConstructorCallback);
- this.constructorsOnce[currentIndex] = constructor;
- this.execute(() => {
- const revertConstructor = constructor(this);
- if (isFnc(revertConstructor)) {
- this.revertConstructorsOnce.push(revertConstructor);
- }
- });
+ while ($el && $el !== container.element && $el !== doc.body) {
+ const isSticky = get($el, 'position') === 'sticky' ? set($el, { position: 'static' }) : false;
+ $el = $el.parentElement;
+ if (isSticky) {
+ if (!stickys) stickys = [];
+ stickys.push(isSticky);
+ }
}
- return this;
- }
+ const rect = $target.getBoundingClientRect();
+ const offset = isHori ? rect.left + container.scrollX - container.left : rect.top + container.scrollY - container.top;
+ const targetSize = isHori ? rect.width : rect.height;
+ const containerSize = isHori ? container.width : container.height;
+ const scrollSize = isHori ? container.scrollWidth : container.scrollHeight;
+ const maxScroll = scrollSize - containerSize;
+ const enter = this.enter;
+ const leave = this.leave;
- /**
- * @param {(scope: this) => Tickable} cb
- * @return {Tickable}
- */
- keepTime(cb) {
- this.once = true;
- const currentIndex = this.onceIndex++;
- const tracked = /** @type {(scope: this) => Tickable} */(this.constructorsOnce[currentIndex]);
- if (isFnc(tracked)) return tracked(this);
- const constructor = /** @type {(scope: this) => Tickable} */(createRefreshable(cb));
- this.constructorsOnce[currentIndex] = constructor;
- let trackedTickable;
- this.execute(() => {
- trackedTickable = constructor(this);
- });
- return trackedTickable;
- }
+ /** @type {ScrollThresholdValue} */
+ let enterTarget = 'start';
+ /** @type {ScrollThresholdValue} */
+ let leaveTarget = 'end';
+ /** @type {ScrollThresholdValue} */
+ let enterContainer = 'end';
+ /** @type {ScrollThresholdValue} */
+ let leaveContainer = 'start';
- /**
- * @param {Event} e
- */
- handleEvent(e) {
- switch (e.type) {
- case 'change':
- this.refresh();
- break;
+ if (isStr(enter)) {
+ const splitted = /** @type {String} */(enter).split(' ');
+ enterContainer = splitted[0];
+ enterTarget = splitted.length > 1 ? splitted[1] : enterTarget;
+ } else if (isObj(enter)) {
+ const e = /** @type {ScrollThresholdParam} */(enter);
+ if (!isUnd(e.container)) enterContainer = e.container;
+ if (!isUnd(e.target)) enterTarget = e.target;
+ } else if (isNum(enter)) {
+ enterContainer = /** @type {Number} */(enter);
}
- }
- revert() {
- const revertibles = this.revertibles;
- const revertConstructors = this.revertConstructors;
- const revertiblesOnce = this.revertiblesOnce;
- const revertConstructorsOnce = this.revertConstructorsOnce;
- const mqs = this.mediaQueryLists;
- let i = revertibles.length;
- let j = revertConstructors.length;
- let k = revertiblesOnce.length;
- let l = revertConstructorsOnce.length;
- while (i--) revertibles[i].revert();
- while (j--) revertConstructors[j](this);
- while (k--) revertiblesOnce[k].revert();
- while (l--) revertConstructorsOnce[l](this);
- for (let mq in mqs) mqs[mq].removeEventListener('change', this);
- revertibles.length = 0;
- revertConstructors.length = 0;
- this.constructors.length = 0;
- revertiblesOnce.length = 0;
- revertConstructorsOnce.length = 0;
- this.constructorsOnce.length = 0;
- this.onceIndex = 0;
- this.matches = {};
- this.methods = {};
- this.mediaQueryLists = {};
- this.data = {};
+ if (isStr(leave)) {
+ const splitted = /** @type {String} */(leave).split(' ');
+ leaveContainer = splitted[0];
+ leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget;
+ } else if (isObj(leave)) {
+ const t = /** @type {ScrollThresholdParam} */(leave);
+ if (!isUnd(t.container)) leaveContainer = t.container;
+ if (!isUnd(t.target)) leaveTarget = t.target;
+ } else if (isNum(leave)) {
+ leaveContainer = /** @type {Number} */(leave);
+ }
+
+ const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize);
+ const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize);
+ const under = (parsedEnterTarget + offset) - containerSize;
+ const over = (parsedLeaveTarget + offset) - maxScroll;
+ const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over);
+ const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over);
+ const offsetStart = parsedEnterTarget + offset - parsedEnterContainer;
+ const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer;
+ const scrollDelta = offsetEnd - offsetStart;
+ // this.offsets[0] = offsetX;
+ // this.offsets[1] = offsetY;
+ this.offset = offset;
+ this.offsetStart = offsetStart;
+ this.offsetEnd = offsetEnd;
+ this.distance = scrollDelta <= 0 ? 0 : scrollDelta;
+ this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer];
+ this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer];
+ if (stickys) {
+ stickys.forEach(sticky => sticky.revert());
+ }
+ if (linked) {
+ linked.seek(linkedTime, true);
+ }
+ if (this._debug) {
+ this.debug();
+ }
}
-}
-
-/**
- * @param {ScopeParams} [params]
- * @return {Scope}
- */
-const createScope = params => new Scope(params);
-/**
- * @return {Number}
- */
-const getMaxViewHeight = () => {
- const $el = doc.createElement('div');
- doc.body.appendChild($el);
- $el.style.height = '100lvh';
- const height = $el.offsetHeight;
- doc.body.removeChild($el);
- return height;
-};
+ handleScroll() {
+ const linked = this.linked;
+ const sync = this.sync;
+ const syncEase = this.syncEase;
+ const syncSmooth = this.syncSmooth;
+ const shouldSeek = linked && (syncEase || syncSmooth);
+ const isHori = this.horizontal;
+ const container = this.container;
+ const scroll = this.scroll;
+ const isBefore = scroll <= this.offsetStart;
+ const isAfter = scroll >= this.offsetEnd;
+ const isInView = !isBefore && !isAfter;
+ const isOnTheEdge = scroll === this.offsetStart || scroll === this.offsetEnd;
+ const forceEnter = !this.hasEntered && isOnTheEdge;
+ const $debug = this._debug && this.$debug;
+ let hasUpdated = false;
+ let syncCompleted = false;
+ let p = this.progress;
-/**
- * @template {ScrollThresholdValue|String|Number|Boolean|Function|Object} T
- * @param {T | ((observer: ScrollObserver) => T)} value
- * @param {ScrollObserver} scroller
- * @return {T}
- */
-const parseScrollObserverFunctionParameter = (value, scroller) => value && isFnc(value) ? /** @type {Function} */(value)(scroller) : value;
+ if (isBefore && this.began) {
+ this.began = false;
+ }
-const scrollContainers = new Map();
+ if (p > 0 && !this.began) {
+ this.began = true;
+ }
-class ScrollContainer {
- /**
- * @param {HTMLElement} $el
- */
- constructor($el) {
- /** @type {HTMLElement} */
- this.element = $el;
- /** @type {Boolean} */
- this.useWin = this.element === doc.body;
- /** @type {Number} */
- this.winWidth = 0;
- /** @type {Number} */
- this.winHeight = 0;
- /** @type {Number} */
- this.width = 0;
- /** @type {Number} */
- this.height = 0;
- /** @type {Number} */
- this.left = 0;
- /** @type {Number} */
- this.top = 0;
- /** @type {Number} */
- this.zIndex = 0;
- /** @type {Number} */
- this.scrollX = 0;
- /** @type {Number} */
- this.scrollY = 0;
- /** @type {Number} */
- this.prevScrollX = 0;
- /** @type {Number} */
- this.prevScrollY = 0;
- /** @type {Number} */
- this.scrollWidth = 0;
- /** @type {Number} */
- this.scrollHeight = 0;
- /** @type {Number} */
- this.velocity = 0;
- /** @type {Boolean} */
- this.backwardX = false;
- /** @type {Boolean} */
- this.backwardY = false;
- /** @type {Timer} */
- this.scrollTicker = new Timer({
- autoplay: false,
- onBegin: () => this.dataTimer.resume(),
- onUpdate: () => {
- const backwards = this.backwardX || this.backwardY;
- forEachChildren(this, (/** @type {ScrollObserver} */child) => child.handleScroll(), backwards);
- },
- onComplete: () => this.dataTimer.pause()
- }).init();
- /** @type {Timer} */
- this.dataTimer = new Timer({
- autoplay: false,
- frameRate: 30,
- onUpdate: self => {
- const dt = self.deltaTime;
- const px = this.prevScrollX;
- const py = this.prevScrollY;
- const nx = this.scrollX;
- const ny = this.scrollY;
- const dx = px - nx;
- const dy = py - ny;
- this.prevScrollX = nx;
- this.prevScrollY = ny;
- if (dx) this.backwardX = px > nx;
- if (dy) this.backwardY = py > ny;
- this.velocity = round(dt > 0 ? Math.sqrt(dx * dx + dy * dy) / dt : 0, 5);
+ if (shouldSeek) {
+ const lp = linked.progress;
+ if (syncSmooth && isNum(syncSmooth)) {
+ if (/** @type {Number} */(syncSmooth) < 1) {
+ const step = 0.0001;
+ const snap = lp < p && p === 1 ? step : lp > p && !p ? -step : 0;
+ p = round$1(lerp$1(lp, p, lerp$1(.01, .2, /** @type {Number} */(syncSmooth))) + snap, 6);
+ }
+ } else if (syncEase) {
+ p = syncEase(p);
}
- }).init();
- /** @type {Timer} */
- this.resizeTicker = new Timer({
- autoplay: false,
- duration: 250 * globals.timeScale,
- onComplete: () => {
- this.updateWindowBounds();
- this.refreshScrollObservers();
- this.handleScroll();
+ hasUpdated = p !== this.prevProgress;
+ syncCompleted = lp === 1;
+ if (hasUpdated && !syncCompleted && (syncSmooth && lp)) {
+ container.wakeTicker.restart();
}
- }).init();
- /** @type {Timer} */
- this.wakeTicker = new Timer({
- autoplay: false,
- duration: 500 * globals.timeScale,
- onBegin: () => {
- this.scrollTicker.resume();
- },
- onComplete: () => {
- this.scrollTicker.pause();
+ }
+
+ if ($debug) {
+ const sticky = isHori ? container.scrollY : container.scrollX;
+ $debug.style[isHori ? 'top' : 'left'] = sticky + 10 + 'px';
+ }
+
+ // Trigger enter callbacks if already in view or when entering the view
+ if ((isInView && !this.isInView) || (forceEnter && !this.forceEnter && !this.hasEntered)) {
+ if (isInView) this.isInView = true;
+ if (!this.forceEnter || !this.hasEntered) {
+ if ($debug && isInView) $debug.style.zIndex = `${this.container.zIndex++}`;
+ this.onSyncEnter(this);
+ this.onEnter(this);
+ if (this.backward) {
+ this.onSyncEnterBackward(this);
+ this.onEnterBackward(this);
+ } else {
+ this.onSyncEnterForward(this);
+ this.onEnterForward(this);
+ }
+ this.hasEntered = true;
+ if (forceEnter) this.forceEnter = true;
+ } else if (isInView) {
+ this.forceEnter = false;
}
- }).init();
- /** @type {ScrollObserver} */
- this._head = null;
- /** @type {ScrollObserver} */
- this._tail = null;
- this.updateScrollCoords();
- this.updateWindowBounds();
- this.updateBounds();
- this.refreshScrollObservers();
- this.handleScroll();
- this.resizeObserver = new ResizeObserver(() => this.resizeTicker.restart());
- this.resizeObserver.observe(this.element);
- (this.useWin ? win : this.element).addEventListener('scroll', this, false);
- }
+ }
- updateScrollCoords() {
- const useWin = this.useWin;
- const $el = this.element;
- this.scrollX = round(useWin ? win.scrollX : $el.scrollLeft, 0);
- this.scrollY = round(useWin ? win.scrollY : $el.scrollTop, 0);
- }
+ if (isInView || !isInView && this.isInView) {
+ hasUpdated = true;
+ }
- updateWindowBounds() {
- this.winWidth = win.innerWidth;
- this.winHeight = getMaxViewHeight();
- }
+ if (hasUpdated) {
+ if (shouldSeek) linked.seek(linked.duration * p);
+ this.onUpdate(this);
+ }
- updateBounds() {
- const style = getComputedStyle(this.element);
- const $el = this.element;
- this.scrollWidth = $el.scrollWidth + parseFloat(style.marginLeft) + parseFloat(style.marginRight);
- this.scrollHeight = $el.scrollHeight + parseFloat(style.marginTop) + parseFloat(style.marginBottom);
- this.updateWindowBounds();
- let width, height;
- if (this.useWin) {
- width = this.winWidth;
- height = this.winHeight;
- } else {
- const elRect = $el.getBoundingClientRect();
- width = $el.clientWidth;
- height = $el.clientHeight;
- this.top = elRect.top;
- this.left = elRect.left;
+ if (!isInView && this.isInView) {
+ this.isInView = false;
+ this.onSyncLeave(this);
+ this.onLeave(this);
+ if (this.backward) {
+ this.onSyncLeaveBackward(this);
+ this.onLeaveBackward(this);
+ } else {
+ this.onSyncLeaveForward(this);
+ this.onLeaveForward(this);
+ }
+ if (sync && !syncSmooth) {
+ syncCompleted = true;
+ }
}
- this.width = width;
- this.height = height;
- }
- refreshScrollObservers() {
- forEachChildren(this, (/** @type {ScrollObserver} */child) => {
- if (child._debug) {
- child.removeDebug();
+ if (p >= 1 && this.began && !this.completed && (sync && syncCompleted || !sync)) {
+ if (sync) {
+ this.onSyncComplete(this);
}
- });
- this.updateBounds();
- forEachChildren(this, (/** @type {ScrollObserver} */child) => {
- child.refresh();
- if (child._debug) {
- child.debug();
+ this.completed = true;
+ if ((!this.repeat && !linked) || (!this.repeat && linked && linked.completed)) {
+ this.revert();
}
- });
- }
+ }
- refresh() {
- this.updateWindowBounds();
- this.updateBounds();
- this.refreshScrollObservers();
- this.handleScroll();
- }
+ if (p < 1 && this.completed) {
+ this.completed = false;
+ }
- handleScroll() {
- this.updateScrollCoords();
- this.wakeTicker.restart();
+ this.prevProgress = p;
}
- /**
- * @param {Event} e
- */
- handleEvent(e) {
- switch (e.type) {
- case 'scroll':
- this.handleScroll();
- break;
+ revert() {
+ if (this.reverted) return;
+ const container = this.container;
+ removeChild(container, this);
+ if (!container._head) {
+ container.revert();
+ }
+ if (this._debug) {
+ this.removeDebug();
}
+ this.reverted = true;
+ return this;
}
- revert() {
- this.scrollTicker.cancel();
- this.dataTimer.cancel();
- this.resizeTicker.cancel();
- this.wakeTicker.cancel();
- this.resizeObserver.disconnect();
- (this.useWin ? win : this.element).removeEventListener('scroll', this);
- scrollContainers.delete(this.element);
- }
}
/**
- * @param {TargetsParam} target
- * @return {ScrollContainer}
+ * @param {ScrollObserverParams} [parameters={}]
+ * @return {ScrollObserver}
*/
-const registerAndGetScrollContainer = target => {
- const $el = /** @type {HTMLElement} */(target ? parseTargets(target)[0] || doc.body : doc.body);
- let scrollContainer = scrollContainers.get($el);
- if (!scrollContainer) {
- scrollContainer = new ScrollContainer($el);
- scrollContainers.set($el, scrollContainer);
+const onScroll = (parameters = {}) => new ScrollObserver(parameters);
+
+var index$3 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ cubicBezier: cubicBezier,
+ eases: eases,
+ irregular: irregular,
+ linear: linear,
+ none: none,
+ steps: steps
+});
+
+// Chain-able utilities
+
+const numberUtils = numberImports; // Needed to keep the import when bundling
+
+const chainables = {};
+
+/**
+ * @callback UtilityFunction
+ * @param {...*} args
+ * @return {Number|String}
+ *
+ * @param {UtilityFunction} fn
+ * @param {Number} [last=0]
+ * @return {function(...(Number|String)): function(Number|String): (Number|String)}
+ */
+const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args);
+
+/**
+ * @param {Function} fn
+ * @return {function(...(Number|String))}
+ */
+const chain = fn => {
+ return (...args) => {
+ const result = fn(...args);
+ return new Proxy(noop, {
+ apply: (_, __, [v]) => result(v),
+ get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => {
+ const nextResult = chainables[prop](...nextArgs);
+ return (/**@type {Number|String} */v) => nextResult(result(v));
+ })
+ });
}
- return scrollContainer;
};
/**
- * @param {HTMLElement} $el
- * @param {Number|string} v
- * @param {Number} size
- * @param {Number} [under]
- * @param {Number} [over]
- * @return {Number}
+ * @param {UtilityFunction} fn
+ * @param {String} name
+ * @param {Number} [right]
+ * @return {function(...(Number|String)): UtilityFunction}
*/
-const convertValueToPx = ($el, v, size, under, over) => {
- const clampMin = v === 'min';
- const clampMax = v === 'max';
- const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 :
- v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' :
- v === 'center' ? '50%' :
- v;
- const { n, u } = decomposeRawValue(value, decomposedOriginalValue);
- let px = n;
- if (u === '%') {
- px = (n / 100) * size;
- } else if (u) {
- px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n;
+const makeChainable = (name, fn, right = 0) => {
+ const chained = (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args);
+ if (!chainables[name]) chainables[name] = chained;
+ return chained;
+};
+
+/**
+ * @typedef {Object} ChainablesMap
+ * @property {ChainedClamp} clamp
+ * @property {ChainedRound} round
+ * @property {ChainedSnap} snap
+ * @property {ChainedWrap} wrap
+ * @property {ChainedLerp} lerp
+ * @property {ChainedDamp} damp
+ * @property {ChainedMapRange} mapRange
+ * @property {ChainedRoundPad} roundPad
+ * @property {ChainedPadStart} padStart
+ * @property {ChainedPadEnd} padEnd
+ * @property {ChainedDegToRad} degToRad
+ * @property {ChainedRadToDeg} radToDeg
+ */
+
+/**
+ * @callback ChainedUtilsResult
+ * @param {Number} value - The value to process through the chained operations
+ * @return {Number} The processed result
+ */
+
+/**
+ * @typedef {ChainablesMap & ChainedUtilsResult} ChainableUtil
+ */
+
+// Chainable
+
+/**
+ * @callback ChainedRoundPad
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+const roundPad = /** @type {typeof numberUtils.roundPad & ChainedRoundPad} */(makeChainable('roundPad', numberUtils.roundPad));
+
+/**
+ * @callback ChainedPadStart
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+const padStart = /** @type {typeof numberUtils.padStart & ChainedPadStart} */(makeChainable('padStart', numberUtils.padStart));
+
+/**
+ * @callback ChainedPadEnd
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+const padEnd = /** @type {typeof numberUtils.padEnd & ChainedPadEnd} */(makeChainable('padEnd', numberUtils.padEnd));
+
+/**
+ * @callback ChainedWrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+const wrap = /** @type {typeof numberUtils.wrap & ChainedWrap} */(makeChainable('wrap', numberUtils.wrap));
+
+/**
+ * @callback ChainedMapRange
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {ChainableUtil}
+ */
+const mapRange = /** @type {typeof numberUtils.mapRange & ChainedMapRange} */(makeChainable('mapRange', numberUtils.mapRange));
+
+/**
+ * @callback ChainedDegToRad
+ * @return {ChainableUtil}
+ */
+const degToRad = /** @type {typeof numberUtils.degToRad & ChainedDegToRad} */(makeChainable('degToRad', numberUtils.degToRad));
+
+/**
+ * @callback ChainedRadToDeg
+ * @return {ChainableUtil}
+ */
+const radToDeg = /** @type {typeof numberUtils.radToDeg & ChainedRadToDeg} */(makeChainable('radToDeg', numberUtils.radToDeg));
+
+/**
+ * @callback ChainedSnap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {ChainableUtil}
+ */
+const snap = /** @type {typeof numberUtils.snap & ChainedSnap} */(makeChainable('snap', numberUtils.snap));
+
+/**
+ * @callback ChainedClamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+const clamp = /** @type {typeof numberUtils.clamp & ChainedClamp} */(makeChainable('clamp', numberUtils.clamp));
+
+/**
+ * @callback ChainedRound
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+const round = /** @type {typeof numberUtils.round & ChainedRound} */(makeChainable('round', numberUtils.round));
+
+/**
+ * @callback ChainedLerp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @return {ChainableUtil}
+ */
+const lerp = /** @type {typeof numberUtils.lerp & ChainedLerp} */(makeChainable('lerp', numberUtils.lerp, 1));
+
+/**
+ * @callback ChainedDamp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @return {ChainableUtil}
+ */
+const damp = /** @type {typeof numberUtils.damp & ChainedDamp} */(makeChainable('damp', numberUtils.damp, 1));
+
+/**
+ * Generate a random number between optional min and max (inclusive) and decimal precision
+ *
+ * @callback RandomNumberGenerator
+ * @param {Number} [min=0] - The minimum value (inclusive)
+ * @param {Number} [max=1] - The maximum value (inclusive)
+ * @param {Number} [decimalLength=0] - Number of decimal places to round to
+ * @return {Number} A random number between min and max
+ */
+
+/**
+ * Generates a random number between min and max (inclusive) with optional decimal precision
+ *
+ * @type {RandomNumberGenerator}
+ */
+const random = (min = 0, max = 1, decimalLength = 0) => {
+ const m = 10 ** decimalLength;
+ return Math.floor((Math.random() * (max - min + (1 / m)) + min) * m) / m;
+};
+
+let _seed = 0;
+
+/**
+ * Creates a seeded pseudorandom number generator function
+ *
+ * @param {Number} [seed] - The seed value for the random number generator
+ * @param {Number} [seededMin=0] - The minimum default value (inclusive) of the returned function
+ * @param {Number} [seededMax=1] - The maximum default value (inclusive) of the returned function
+ * @param {Number} [seededDecimalLength=0] - Default number of decimal places to round to of the returned function
+ * @return {RandomNumberGenerator} A function to generate a random number between optional min and max (inclusive) and decimal precision
+ */
+const createSeededRandom = (seed, seededMin = 0, seededMax = 1, seededDecimalLength = 0) => {
+ let t = seed === undefined ? _seed++ : seed;
+ return (min = seededMin, max = seededMax, decimalLength = seededDecimalLength) => {
+ t += 0x6D2B79F5;
+ t = Math.imul(t ^ t >>> 15, t | 1);
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
+ const m = 10 ** decimalLength;
+ return Math.floor(((((t ^ t >>> 14) >>> 0) / 4294967296) * (max - min + (1 / m)) + min) * m) / m;
}
- if (clampMax && under < 0) px += under;
- if (clampMin && over > 0) px += over;
- return px;
};
/**
- * @param {HTMLElement} $el
- * @param {ScrollThresholdValue} v
- * @param {Number} size
- * @param {Number} [under]
- * @param {Number} [over]
- * @return {Number}
+ * Picks a random element from an array or a string
+ *
+ * @template T
+ * @param {String|Array<T>} items - The array or string to pick from
+ * @return {String|T} A random element from the array or character from the string
+ */
+const randomPick = items => items[random(0, items.length - 1)];
+
+/**
+ * Shuffles an array in-place using the Fisher-Yates algorithm
+ * Adapted from https://bost.ocks.org/mike/shuffle/
+ *
+ * @param {Array} items - The array to shuffle (will be modified in-place)
+ * @return {Array} The same array reference, now shuffled
+ */
+const shuffle = items => {
+ let m = items.length, t, i;
+ while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; }
+ return items;
+};
+
+
+
+
+
+/**
+ * @overload
+ * @param {Number} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+/**
+ * @overload
+ * @param {String} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+/**
+ * @overload
+ * @param {[Number, Number]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+/**
+ * @overload
+ * @param {[String, String]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+/**
+ * @param {Number|String|[Number, Number]|[String, String]} val The staggered value or range
+ * @param {StaggerParams} [params] The stagger parameters
+ * @return {StaggerFunction<Number|String>}
*/
-const parseBoundValue = ($el, v, size, under, over) => {
- /** @type {Number} */
- let value;
- if (isStr(v)) {
- const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v));
- if (matchedOperator) {
- const splitter = matchedOperator[0];
- const operator = splitter[0];
- const splitted = /** @type {String} */(v).split(splitter);
- const clampMin = splitted[0] === 'min';
- const clampMax = splitted[0] === 'max';
- const valueAPx = convertValueToPx($el, splitted[0], size, under, over);
- const valueBPx = convertValueToPx($el, splitted[1], size, under, over);
- if (clampMin) {
- const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator);
- value = min < valueAPx ? valueAPx : min;
- } else if (clampMax) {
- const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator);
- value = max > valueAPx ? valueAPx : max;
- } else {
- value = getRelativeValue(valueAPx, valueBPx, operator);
+const stagger = (val, params = {}) => {
+ let values = [];
+ let maxValue = 0;
+ const from = params.from;
+ const reversed = params.reversed;
+ const ease = params.ease;
+ const hasEasing = !isUnd(ease);
+ const hasSpring = hasEasing && !isUnd(/** @type {Spring} */(ease).ease);
+ const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEase(ease) : null;
+ const grid = params.grid;
+ const axis = params.axis;
+ const customTotal = params.total;
+ const fromFirst = isUnd(from) || from === 0 || from === 'first';
+ const fromCenter = from === 'center';
+ const fromLast = from === 'last';
+ const fromRandom = from === 'random';
+ const isRange = isArr(val);
+ const useProp = params.use;
+ const val1 = isRange ? parseNumber(val[0]) : parseNumber(val);
+ const val2 = isRange ? parseNumber(val[1]) : 0;
+ const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString);
+ const start = params.start || 0 + (isRange ? val1 : 0);
+ let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0;
+ return (target, i, t, tl) => {
+ const [ registeredTarget ] = registerTargets(target);
+ const total = isUnd(customTotal) ? t : customTotal;
+ const customIndex = !isUnd(useProp) ? isFnc(useProp) ? useProp(registeredTarget, i, total) : getOriginalAnimatableValue(registeredTarget, useProp) : false;
+ const staggerIndex = isNum(customIndex) || isStr(customIndex) && isNum(+customIndex) ? +customIndex : i;
+ if (fromCenter) fromIndex = (total - 1) / 2;
+ if (fromLast) fromIndex = total - 1;
+ if (!values.length) {
+ for (let index = 0; index < total; index++) {
+ if (!grid) {
+ values.push(abs(fromIndex - index));
+ } else {
+ const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2;
+ const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2;
+ const toX = index % grid[0];
+ const toY = floor(index / grid[0]);
+ const distanceX = fromX - toX;
+ const distanceY = fromY - toY;
+ let value = sqrt(distanceX * distanceX + distanceY * distanceY);
+ if (axis === 'x') value = -distanceX;
+ if (axis === 'y') value = -distanceY;
+ values.push(value);
+ }
+ maxValue = max(...values);
}
- } else {
- value = convertValueToPx($el, v, size, under, over);
+ if (staggerEase) values = values.map(val => staggerEase(val / maxValue) * maxValue);
+ if (reversed) values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val));
+ if (fromRandom) values = shuffle(values);
}
- } else {
- value = /** @type {Number} */(v);
+ const spacing = isRange ? (val2 - val1) / maxValue : val1;
+ const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl.iterationDuration : start) : /** @type {Number} */(start);
+ /** @type {String|Number} */
+ let output = offset + ((spacing * round$1(values[staggerIndex], 2)) || 0);
+ if (params.modifier) output = params.modifier(output);
+ if (unitMatch) output = `${output}${unitMatch[2]}`;
+ return output;
}
- return round(value, 0);
};
+var index$2 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ $: registerTargets,
+ clamp: clamp,
+ cleanInlineStyles: cleanInlineStyles,
+ createSeededRandom: createSeededRandom,
+ damp: damp,
+ degToRad: degToRad,
+ get: get,
+ keepTime: keepTime,
+ lerp: lerp,
+ mapRange: mapRange,
+ padEnd: padEnd,
+ padStart: padStart,
+ radToDeg: radToDeg,
+ random: random,
+ randomPick: randomPick,
+ remove: remove,
+ round: round,
+ roundPad: roundPad,
+ set: set,
+ shuffle: shuffle,
+ snap: snap,
+ stagger: stagger,
+ sync: sync,
+ wrap: wrap
+});
+
+
+
/**
- * @param {JSAnimation} linked
- * @return {HTMLElement}
+ * @param {TargetsParam} path
+ * @return {SVGGeometryElement|void}
*/
-const getAnimationDomTarget = linked => {
- let $linkedTarget;
- const linkedTargets = linked.targets;
- for (let i = 0, l = linkedTargets.length; i < l; i++) {
- const target = linkedTargets[i];
- if (target[isDomSymbol]) {
- $linkedTarget = /** @type {HTMLElement} */(target);
- break;
- }
- }
- return $linkedTarget;
+const getPath = path => {
+ const parsedTargets = parseTargets(path);
+ const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
+ if (!$parsedSvg || !isSvg($parsedSvg)) return console.warn(`${path} is not a valid SVGGeometryElement`);
+ return $parsedSvg;
};
-let scrollerIndex = 0;
-const debugColors$1 = ['#FF4B4B','#FF971B','#FFC730','#F9F640','#7AFF5A','#18FF74','#17E09B','#3CFFEC','#05DBE9','#33B3F1','#638CF9','#C563FE','#FF4FCF','#F93F8A'];
-class ScrollObserver {
- /**
- * @param {ScrollObserverParams} parameters
- */
- constructor(parameters = {}) {
- if (scope.current) scope.current.register(this);
- const syncMode = setValue(parameters.sync, 'play pause');
- const ease = syncMode ? parseEasings(/** @type {EasingParam} */(syncMode)) : null;
- const isLinear = syncMode && (syncMode === 'linear' || syncMode === none);
- const isEase = syncMode && !(ease === none && !isLinear);
- const isSmooth = syncMode && (isNum(syncMode) || syncMode === true || isLinear);
- const isMethods = syncMode && (isStr(syncMode) && !isEase && !isSmooth);
- const syncMethods = isMethods ? /** @type {String} */(syncMode).split(' ').map(
- (/** @type {String} */m) => () => {
- const linked = this.linked;
- return linked && linked[m] ? linked[m]() : null;
- }
- ) : null;
- const biDirSync = isMethods && syncMethods.length > 2;
- /** @type {Number} */
- this.index = scrollerIndex++;
- /** @type {String|Number} */
- this.id = !isUnd(parameters.id) ? parameters.id : this.index;
- /** @type {ScrollContainer} */
- this.container = registerAndGetScrollContainer(parameters.container);
- /** @type {HTMLElement} */
- this.target = null;
- /** @type {Tickable|WAAPIAnimation} */
- this.linked = null;
- /** @type {Boolean} */
- this.repeat = null;
- /** @type {Boolean} */
- this.horizontal = null;
- /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
- this.enter = null;
- /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
- this.leave = null;
- /** @type {Boolean} */
- this.sync = isEase || isSmooth || !!syncMethods;
- /** @type {EasingFunction} */
- this.syncEase = isEase ? ease : null;
- /** @type {Number} */
- this.syncSmooth = isSmooth ? syncMode === true || isLinear ? 1 : /** @type {Number} */(syncMode) : null;
- /** @type {Callback<ScrollObserver>} */
- this.onSyncEnter = syncMethods && !biDirSync && syncMethods[0] ? syncMethods[0] : noop;
- /** @type {Callback<ScrollObserver>} */
- this.onSyncLeave = syncMethods && !biDirSync && syncMethods[1] ? syncMethods[1] : noop;
- /** @type {Callback<ScrollObserver>} */
- this.onSyncEnterForward = syncMethods && biDirSync && syncMethods[0] ? syncMethods[0] : noop;
- /** @type {Callback<ScrollObserver>} */
- this.onSyncLeaveForward = syncMethods && biDirSync && syncMethods[1] ? syncMethods[1] : noop;
- /** @type {Callback<ScrollObserver>} */
- this.onSyncEnterBackward = syncMethods && biDirSync && syncMethods[2] ? syncMethods[2] : noop;
- /** @type {Callback<ScrollObserver>} */
- this.onSyncLeaveBackward = syncMethods && biDirSync && syncMethods[3] ? syncMethods[3] : noop;
- /** @type {Callback<ScrollObserver>} */
- this.onEnter = parameters.onEnter || noop;
- /** @type {Callback<ScrollObserver>} */
- this.onLeave = parameters.onLeave || noop;
- /** @type {Callback<ScrollObserver>} */
- this.onEnterForward = parameters.onEnterForward || noop;
- /** @type {Callback<ScrollObserver>} */
- this.onLeaveForward = parameters.onLeaveForward || noop;
- /** @type {Callback<ScrollObserver>} */
- this.onEnterBackward = parameters.onEnterBackward || noop;
- /** @type {Callback<ScrollObserver>} */
- this.onLeaveBackward = parameters.onLeaveBackward || noop;
- /** @type {Callback<ScrollObserver>} */
- this.onUpdate = parameters.onUpdate || noop;
- /** @type {Callback<ScrollObserver>} */
- this.onSyncComplete = parameters.onSyncComplete || noop;
- /** @type {Boolean} */
- this.reverted = false;
- /** @type {Boolean} */
- this.completed = false;
- /** @type {Boolean} */
- this.began = false;
- /** @type {Boolean} */
- this.isInView = false;
- /** @type {Boolean} */
- this.forceEnter = false;
- /** @type {Boolean} */
- this.hasEntered = false;
- // /** @type {Array.<Number>} */
- // this.offsets = [];
- /** @type {Number} */
- this.offset = 0;
- /** @type {Number} */
- this.offsetStart = 0;
- /** @type {Number} */
- this.offsetEnd = 0;
- /** @type {Number} */
- this.distance = 0;
- /** @type {Number} */
- this.prevProgress = 0;
- /** @type {Array} */
- this.thresholds = ['start', 'end', 'end', 'start'];
- /** @type {[Number, Number, Number, Number]} */
- this.coords = [0, 0, 0, 0];
- /** @type {JSAnimation} */
- this.debugStyles = null;
- /** @type {HTMLElement} */
- this.$debug = null;
- /** @type {ScrollObserverParams} */
- this._params = parameters;
- /** @type {Boolean} */
- this._debug = setValue(parameters.debug, false);
- /** @type {ScrollObserver} */
- this._next = null;
- /** @type {ScrollObserver} */
- this._prev = null;
- addChild(this.container, this);
- // Wait for the next frame to add to the container in order to handle calls to link()
- sync(() => {
- if (this.reverted) return;
- if (!this.target) {
- const target = /** @type {HTMLElement} */(parseTargets(parameters.target)[0]);
- this.target = target || doc.body;
- this.refresh();
- }
- if (this._debug) this.debug();
- });
- }
+// Motion path animation
- /**
- * @param {Tickable|WAAPIAnimation} linked
- */
- link(linked) {
- if (linked) {
- // Make sure to pause the linked object in case it's added later
- linked.pause();
- this.linked = linked;
- // Try to use a target of the linked object if no target parameters specified
- if (!this._params.target) {
- /** @type {HTMLElement} */
- let $linkedTarget;
- if (!isUnd(/** @type {JSAnimation} */(linked).targets)) {
- $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(linked));
+/**
+ * @param {SVGGeometryElement} $path
+ * @param {Number} progress
+ * @param {Number}lookup
+ * @return {DOMPoint}
+ */
+const getPathPoint = ($path, progress, lookup = 0) => {
+ return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0);
+};
+
+/**
+ * @param {SVGGeometryElement} $path
+ * @param {String} pathProperty
+ * @return {FunctionValue}
+ */
+const getPathProgess = ($path, pathProperty) => {
+ return $el => {
+ const totalLength = +($path.getTotalLength());
+ const inSvg = $el[isSvgSymbol];
+ const ctm = $path.getCTM();
+ /** @type {TweenObjectValue} */
+ return {
+ from: 0,
+ to: totalLength,
+ /** @type {TweenModifier} */
+ modifier: progress => {
+ if (pathProperty === 'a') {
+ const p0 = getPathPoint($path, progress, -1);
+ const p1 = getPathPoint($path, progress, 1);
+ return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI;
} else {
- forEachChildren(/** @type {Timeline} */(linked), (/** @type {JSAnimation} */child) => {
- if (child.targets && !$linkedTarget) {
- $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(child));
- }
- });
+ const p = getPathPoint($path, progress, 0);
+ return pathProperty === 'x' ?
+ inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
+ inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
}
- // Fallback to body if no target found
- this.target = $linkedTarget || doc.body;
- this.refresh();
}
}
- return this;
- }
-
- get velocity() {
- return this.container.velocity;
- }
-
- get backward() {
- return this.horizontal ? this.container.backwardX : this.container.backwardY;
}
+};
- get scroll() {
- return this.horizontal ? this.container.scrollX : this.container.scrollY;
+/**
+ * @param {TargetsParam} path
+ */
+const createMotionPath = path => {
+ const $path = getPath(path);
+ if (!$path) return;
+ return {
+ translateX: getPathProgess($path, 'x'),
+ translateY: getPathProgess($path, 'y'),
+ rotate: getPathProgess($path, 'a'),
}
+};
- get progress() {
- const p = (this.scroll - this.offsetStart) / this.distance;
- return p === Infinity || isNaN(p) ? 0 : round(clamp(p, 0, 1), 6);
- }
- refresh() {
- this.reverted = false;
- const params = this._params;
- this.repeat = setValue(parseScrollObserverFunctionParameter(params.repeat, this), true);
- this.horizontal = setValue(parseScrollObserverFunctionParameter(params.axis, this), 'y') === 'x';
- this.enter = setValue(parseScrollObserverFunctionParameter(params.enter, this), 'end start');
- this.leave = setValue(parseScrollObserverFunctionParameter(params.leave, this), 'start end');
- this.updateBounds();
- this.handleScroll();
- return this;
- }
- removeDebug() {
- if (this.$debug) {
- this.$debug.parentNode.removeChild(this.$debug);
- this.$debug = null;
- }
- if (this.debugStyles) {
- this.debugStyles.revert();
- this.$debug = null;
+/**
+ * @param {SVGGeometryElement} [$el]
+ * @return {Number}
+ */
+const getScaleFactor = $el => {
+ let scaleFactor = 1;
+ if ($el && $el.getCTM) {
+ const ctm = $el.getCTM();
+ if (ctm) {
+ const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
+ const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
+ scaleFactor = (scaleX + scaleY) / 2;
}
- return this;
}
+ return scaleFactor;
+};
- debug() {
- this.removeDebug();
- const container = this.container;
- const isHori = this.horizontal;
- const $existingDebug = container.element.querySelector(':scope > .animejs-onscroll-debug');
- const $debug = doc.createElement('div');
- const $thresholds = doc.createElement('div');
- const $triggers = doc.createElement('div');
- const color = debugColors$1[this.index % debugColors$1.length];
- const useWin = container.useWin;
- const containerWidth = useWin ? container.winWidth : container.width;
- const containerHeight = useWin ? container.winHeight : container.height;
- const scrollWidth = container.scrollWidth;
- const scrollHeight = container.scrollHeight;
- const size = this.container.width > 360 ? 320 : 260;
- const offLeft = isHori ? 0 : 10;
- const offTop = isHori ? 10 : 0;
- const half = isHori ? 24 : size / 2;
- const labelHeight = isHori ? half : 15;
- const labelWidth = isHori ? 60 : half;
- const labelSize = isHori ? labelWidth : labelHeight;
- const repeat = isHori ? 'repeat-x' : 'repeat-y';
- /**
- * @param {Number} v
- * @return {String}
- */
- const gradientOffset = v => isHori ? '0px '+(v)+'px' : (v)+'px'+' 2px';
- /**
- * @param {String} c
- * @return {String}
- */
- const lineCSS = (c) => `linear-gradient(${isHori ? 90 : 0}deg, ${c} 2px, transparent 1px)`;
- /**
- * @param {String} p
- * @param {Number} l
- * @param {Number} t
- * @param {Number} w
- * @param {Number} h
- * @return {String}
- */
- const baseCSS = (p, l, t, w, h) => `position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`;
- $debug.style.cssText = `${baseCSS('absolute', offLeft, offTop, isHori ? scrollWidth : size, isHori ? size : scrollHeight)}
- pointer-events: none;
- z-index: ${this.container.zIndex++};
- display: flex;
- flex-direction: ${isHori ? 'column' : 'row'};
- filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));
- `;
- $thresholds.style.cssText = `${baseCSS('sticky', 0, 0, isHori ? containerWidth : half, isHori ? half : containerHeight)}`;
- if (!$existingDebug) {
- $thresholds.style.cssText += `background:
- ${lineCSS('#FFFF')}${gradientOffset(half-10)} / ${isHori ? '100px 100px' : '100px 100px'} ${repeat},
- ${lineCSS('#FFF8')}${gradientOffset(half-10)} / ${isHori ? '10px 10px' : '10px 10px'} ${repeat};
- `;
- }
- $triggers.style.cssText = `${baseCSS('relative', 0, 0, isHori ? scrollWidth : half, isHori ? half : scrollHeight)}`;
- if (!$existingDebug) {
- $triggers.style.cssText += `background:
- ${lineCSS('#FFFF')}${gradientOffset(0)} / ${isHori ? '100px 10px' : '10px 100px'} ${repeat},
- ${lineCSS('#FFF8')}${gradientOffset(0)} / ${isHori ? '10px 0px' : '0px 10px'} ${repeat};
- `;
- }
- const labels = [' enter: ', ' leave: '];
- this.coords.forEach((v, i) => {
- const isView = i > 1;
- const value = (isView ? 0 : this.offset) + v;
- const isTail = i % 2;
- const isFirst = value < labelSize;
- const isOver = value > (isView ? isHori ? containerWidth : containerHeight : isHori ? scrollWidth : scrollHeight) - labelSize;
- const isFlip = (isView ? isTail && !isFirst : !isTail && !isFirst) || isOver;
- const $label = doc.createElement('div');
- const $text = doc.createElement('div');
- const dirProp = isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top';
- const flipOffset = isFlip ? (isHori ? labelWidth : labelHeight) + (!isView ? isHori ? -1 : -2 : isHori ? -1 : isOver ? 0 : -2) : !isView ? isHori ? 1 : 0 : isHori ? 1 : 0;
- // $text.innerHTML = `${!isView ? '' : labels[isTail] + ' '}${this.id}: ${this.thresholds[i]} ${isView ? '' : labels[isTail]}`;
- $text.innerHTML = `${this.id}${labels[isTail]}${this.thresholds[i]}`;
- $label.style.cssText = `${baseCSS('absolute', 0, 0, labelWidth, labelHeight)}
- display: flex;
- flex-direction: ${isHori ? 'column' : 'row'};
- justify-content: flex-${isView ? 'start' : 'end'};
- align-items: flex-${isFlip ? 'end' : 'start'};
- border-${dirProp}: 2px ${isTail ? 'solid' : 'solid'} ${color};
- `;
- $text.style.cssText = `
- overflow: hidden;
- max-width: ${(size / 2) - 10}px;
- height: ${labelHeight};
- margin-${isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'}: -2px;
- padding: 1px;
- font-family: ui-monospace, monospace;
- font-size: 10px;
- letter-spacing: -.025em;
- line-height: 9px;
- font-weight: 600;
- text-align: ${isHori && isFlip || !isHori && !isView ? 'right' : 'left'};
- white-space: pre;
- text-overflow: ellipsis;
- color: ${isTail ? color : 'rgba(0,0,0,.75)'};
- background-color: ${isTail ? 'rgba(0,0,0,.65)' : color};
- border: 2px solid ${isTail ? color : 'transparent'};
- border-${isHori ? isFlip ? 'top-left' : 'top-right' : isFlip ? 'top-left' : 'bottom-left'}-radius: 5px;
- border-${isHori ? isFlip ? 'bottom-left' : 'bottom-right' : isFlip ? 'top-right' : 'bottom-right'}-radius: 5px;
- `;
- $label.appendChild($text);
- let position = value - flipOffset + (isHori ? 1 : 0);
- $label.style[isHori ? 'left' : 'top'] = `${position}px`;
- // $label.style[isHori ? 'left' : 'top'] = value - flipOffset + (!isFlip && isFirst && !isView ? 1 : isFlip ? 0 : -2) + 'px';
- (isView ? $thresholds : $triggers).appendChild($label);
- });
+/**
+ * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
+ * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
+ * @param {number} start - Starting position (0-1)
+ * @param {number} end - Ending position (0-1)
+ * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
+ */
+const createDrawableProxy = ($el, start, end) => {
+ const pathLength = K;
+ const computedStyles = getComputedStyle($el);
+ const strokeLineCap = computedStyles.strokeLinecap;
+ // @ts-ignore
+ const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
+ let currentCap = strokeLineCap;
- $debug.appendChild($thresholds);
- $debug.appendChild($triggers);
- container.element.appendChild($debug);
+ const proxy = new Proxy($el, {
+ get(target, property) {
+ const value = target[property];
+ if (property === proxyTargetSymbol) return target;
+ if (property === 'setAttribute') {
+ return (...args) => {
+ if (args[0] === 'draw') {
+ const value = args[1];
+ const values = value.split(' ');
+ const v1 = +values[0];
+ const v2 = +values[1];
+ // TOTO: Benchmark if performing two slices is more performant than one split
+ // const spaceIndex = value.indexOf(' ');
+ // const v1 = round(+value.slice(0, spaceIndex), precision);
+ // const v2 = round(+value.slice(spaceIndex + 1), precision);
+ const scaleFactor = getScaleFactor($scalled);
+ const os = v1 * -pathLength * scaleFactor;
+ const d1 = (v2 * pathLength * scaleFactor) + os;
+ const d2 = (pathLength * scaleFactor +
+ ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
+ if (strokeLineCap !== 'butt') {
+ const newCap = v1 === v2 ? 'butt' : strokeLineCap;
+ if (currentCap !== newCap) {
+ target.style.strokeLinecap = `${newCap}`;
+ currentCap = newCap;
+ }
+ }
+ target.setAttribute('stroke-dashoffset', `${os}`);
+ target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
+ }
+ return Reflect.apply(value, target, args);
+ };
+ }
- if (!$existingDebug) $debug.classList.add('animejs-onscroll-debug');
- this.$debug = $debug;
- const containerPosition = getTargetValue(container.element, 'position');
- if (containerPosition === 'static') {
- this.debugStyles = setTargetValues(container.element, { position: 'relative '});
+ if (isFnc(value)) {
+ return (...args) => Reflect.apply(value, target, args);
+ } else {
+ return value;
+ }
}
+ });
+ if ($el.getAttribute('pathLength') !== `${pathLength}`) {
+ $el.setAttribute('pathLength', `${pathLength}`);
+ proxy.setAttribute('draw', `${start} ${end}`);
}
- updateBounds() {
- if (this._debug) {
- this.removeDebug();
- }
- let stickys;
- const $target = this.target;
- const container = this.container;
- const isHori = this.horizontal;
- const linked = this.linked;
- let linkedTime;
- let $el = $target;
- // let offsetX = 0;
- // let offsetY = 0;
- // let $offsetParent = $el;
- /** @type {Element} */
- if (linked) {
- linkedTime = linked.currentTime;
- linked.seek(0, true);
- }
- /* Old implementation to get offset and targetSize before fixing https://github.com/juliangarnier/anime/issues/1021
- // const isContainerStatic = getTargetValue(container.element, 'position') === 'static' ? setTargetValues(container.element, { position: 'relative '}) : false;
- // while ($el && $el !== container.element && $el !== doc.body) {
- // const isSticky = getTargetValue($el, 'position') === 'sticky' ?
- // setTargetValues($el, { position: 'static' }) :
- // false;
- // if ($el === $offsetParent) {
- // offsetX += $el.offsetLeft || 0;
- // offsetY += $el.offsetTop || 0;
- // $offsetParent = $el.offsetParent;
- // }
- // $el = /** @type {HTMLElement} */($el.parentElement);
- // if (isSticky) {
- // if (!stickys) stickys = [];
- // stickys.push(isSticky);
- // }
- // }
- // if (isContainerStatic) isContainerStatic.revert();
- // const offset = isHori ? offsetX : offsetY;
- // const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight;
+ return /** @type {DrawableSVGGeometry} */(proxy);
+};
- while ($el && $el !== container.element && $el !== doc.body) {
- const isSticky = getTargetValue($el, 'position') === 'sticky' ? setTargetValues($el, { position: 'static' }) : false;
- $el = $el.parentElement;
- if (isSticky) {
- if (!stickys) stickys = [];
- stickys.push(isSticky);
- }
+/**
+ * Creates drawable proxies for multiple SVG elements.
+ * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
+ * @param {number} [start=0] - Starting position (0-1)
+ * @param {number} [end=0] - Ending position (0-1)
+ * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
+ */
+const createDrawable = (selector, start = 0, end = 0) => {
+ const els = parseTargets(selector);
+ return els.map($el => createDrawableProxy(
+ /** @type {SVGGeometryElement} */($el),
+ start,
+ end
+ ));
+};
+
+
+
+/**
+ * @param {TargetsParam} path2
+ * @param {Number} [precision]
+ * @return {FunctionValue}
+ */
+const morphTo = (path2, precision = .33) => ($path1) => {
+ const $path2 = /** @type {SVGGeometryElement} */(getPath(path2));
+ if (!$path2) return;
+ const isPath = $path1.tagName === 'path';
+ const separator = isPath ? ' ' : ',';
+ const previousPoints = $path1[morphPointsSymbol];
+ if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
+
+ let v1 = '', v2 = '';
+
+ if (!precision) {
+ v1 = $path1.getAttribute(isPath ? 'd' : 'points');
+ v2 = $path2.getAttribute(isPath ? 'd' : 'points');
+ } else {
+ const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
+ const length2 = $path2.getTotalLength();
+ const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
+ for (let i = 0; i < maxPoints; i++) {
+ const t = i / (maxPoints - 1);
+ const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
+ const pointOnPath2 = $path2.getPointAtLength(length2 * t);
+ const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
+ v1 += prefix + round$1(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
+ v2 += prefix + round$1(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
}
- const rect = $target.getBoundingClientRect();
- const offset = isHori ? rect.left + container.scrollX - container.left : rect.top + container.scrollY - container.top;
- const targetSize = isHori ? rect.width : rect.height;
- const containerSize = isHori ? container.width : container.height;
- const scrollSize = isHori ? container.scrollWidth : container.scrollHeight;
- const maxScroll = scrollSize - containerSize;
- const enter = this.enter;
- const leave = this.leave;
+ }
- /** @type {ScrollThresholdValue} */
- let enterTarget = 'start';
- /** @type {ScrollThresholdValue} */
- let leaveTarget = 'end';
- /** @type {ScrollThresholdValue} */
- let enterContainer = 'end';
- /** @type {ScrollThresholdValue} */
- let leaveContainer = 'start';
+ $path1[morphPointsSymbol] = v2;
- if (isStr(enter)) {
- const splitted = /** @type {String} */(enter).split(' ');
- enterContainer = splitted[0];
- enterTarget = splitted.length > 1 ? splitted[1] : enterTarget;
- } else if (isObj(enter)) {
- const e = /** @type {ScrollThresholdParam} */(enter);
- if (!isUnd(e.container)) enterContainer = e.container;
- if (!isUnd(e.target)) enterTarget = e.target;
- } else if (isNum(enter)) {
- enterContainer = /** @type {Number} */(enter);
+ return [v1, v2];
+};
+
+var index$1 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ createDrawable: createDrawable,
+ createMotionPath: createMotionPath,
+ morphTo: morphTo
+});
+
+
+
+const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter;
+const valueRgx = /\{value\}/g;
+const indexRgx = /\{i\}/g;
+const whiteSpaceGroupRgx = /(\s+)/;
+const whiteSpaceRgx = /^\s+$/;
+const lineType = 'line';
+const wordType = 'word';
+const charType = 'char';
+const dataLine = `data-line`;
+
+/**
+ * @typedef {Object} Segment
+ * @property {String} segment
+ * @property {Boolean} [isWordLike]
+ */
+
+/**
+ * @typedef {Object} Segmenter
+ * @property {function(String): Iterable<Segment>} segment
+ */
+
+/** @type {Segmenter} */
+let wordSegmenter = null;
+/** @type {Segmenter} */
+let graphemeSegmenter = null;
+let $splitTemplate = null;
+
+/**
+ * @param {Segment} seg
+ * @return {Boolean}
+ */
+const isSegmentWordLike = seg => {
+ return seg.isWordLike ||
+ seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later
+ isNum(+seg.segment); // Safari doesn't considers numbers as words
+};
+
+/**
+ * @param {HTMLElement} $el
+ */
+const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true');
+
+/**
+ * @param {DOMTarget} $el
+ * @param {String} type
+ * @return {Array<HTMLElement>}
+ */
+const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))];
+
+const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' };
+
+/**
+ * @param {HTMLElement} $el
+ */
+const filterEmptyElements = $el => {
+ if (!$el.childElementCount && !$el.textContent.trim()) {
+ const $parent = $el.parentElement;
+ $el.remove();
+ if ($parent) filterEmptyElements($parent);
+ }
+};
+
+/**
+ * @param {HTMLElement} $el
+ * @param {Number} lineIndex
+ * @param {Set<HTMLElement>} bin
+ * @returns {Set<HTMLElement>}
+ */
+const filterLineElements = ($el, lineIndex, bin) => {
+ const dataLineAttr = $el.getAttribute(dataLine);
+ if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') bin.add($el);
+ let i = $el.childElementCount;
+ while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin);
+ return bin;
+};
+
+/**
+ * @param {'line'|'word'|'char'} type
+ * @param {SplitTemplateParams} params
+ * @return {String}
+ */
+const generateTemplate = (type, params = {}) => {
+ let template = ``;
+ const classString = isStr(params.class) ? ` class="${params.class}"` : '';
+ const cloneType = setValue(params.clone, false);
+ const wrapType = setValue(params.wrap, false);
+ const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false;
+ if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`;
+ template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`;
+ if (cloneType) {
+ const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0';
+ const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0';
+ template += `<span>{value}</span>`;
+ template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`;
+ } else {
+ template += `{value}`;
+ }
+ template += `</span>`;
+ if (wrapType) template += `</span>`;
+ return template;
+};
+
+/**
+ * @param {String|SplitFunctionValue} htmlTemplate
+ * @param {Array<HTMLElement>} store
+ * @param {Node|HTMLElement} node
+ * @param {DocumentFragment} $parentFragment
+ * @param {'line'|'word'|'char'} type
+ * @param {Boolean} debug
+ * @param {Number} lineIndex
+ * @param {Number} [wordIndex]
+ * @param {Number} [charIndex]
+ * @return {HTMLElement}
+ */
+const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => {
+ const isLine = type === lineType;
+ const isChar = type === charType;
+ const className = `_${type}_`;
+ const template = isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate;
+ const displayStyle = isLine ? 'block' : 'inline-block';
+ $splitTemplate.innerHTML = template
+ .replace(valueRgx, `<i class="${className}"></i>`)
+ .replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`);
+ const $content = $splitTemplate.content;
+ const $highestParent = /** @type {HTMLElement} */($content.firstElementChild);
+ const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent;
+ const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`));
+ const replacablesLength = $replacables.length;
+ if (replacablesLength) {
+ $highestParent.style.display = displayStyle;
+ $split.style.display = displayStyle;
+ $split.setAttribute(dataLine, `${lineIndex}`);
+ if (!isLine) {
+ $split.setAttribute('data-word', `${wordIndex}`);
+ if (isChar) $split.setAttribute('data-char', `${charIndex}`);
}
-
- if (isStr(leave)) {
- const splitted = /** @type {String} */(leave).split(' ');
- leaveContainer = splitted[0];
- leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget;
- } else if (isObj(leave)) {
- const t = /** @type {ScrollThresholdParam} */(leave);
- if (!isUnd(t.container)) leaveContainer = t.container;
- if (!isUnd(t.target)) leaveTarget = t.target;
- } else if (isNum(leave)) {
- leaveContainer = /** @type {Number} */(leave);
+ let i = replacablesLength;
+ while (i--) {
+ const $replace = $replacables[i];
+ const $closestParent = $replace.parentElement;
+ $closestParent.style.display = displayStyle;
+ if (isLine) {
+ $closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML;
+ } else {
+ $closestParent.replaceChild(node.cloneNode(true), $replace);
+ }
}
+ store.push($split);
+ $parentFragment.appendChild($content);
+ } else {
+ console.warn(`The expression "{value}" is missing from the provided template.`);
+ }
+ if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`;
+ return $highestParent;
+};
- const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize);
- const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize);
- const under = (parsedEnterTarget + offset) - containerSize;
- const over = (parsedLeaveTarget + offset) - maxScroll;
- const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over);
- const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over);
- const offsetStart = parsedEnterTarget + offset - parsedEnterContainer;
- const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer;
- const scrollDelta = offsetEnd - offsetStart;
- // this.offsets[0] = offsetX;
- // this.offsets[1] = offsetY;
- this.offset = offset;
- this.offsetStart = offsetStart;
- this.offsetEnd = offsetEnd;
- this.distance = scrollDelta <= 0 ? 0 : scrollDelta;
- this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer];
- this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer];
- if (stickys) {
- stickys.forEach(sticky => sticky.revert());
- }
- if (linked) {
- linked.seek(linkedTime, true);
- }
- if (this._debug) {
- this.debug();
+/**
+ * A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
+ * @class
+ */
+class TextSplitter {
+ /**
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ */
+ constructor(target, parameters = {}) {
+ // Only init segmenters when needed
+ if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : {
+ segment: (text) => {
+ const segments = [];
+ const words = text.split(whiteSpaceGroupRgx);
+ for (let i = 0, l = words.length; i < l; i++) {
+ const segment = words[i];
+ segments.push({
+ segment,
+ isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like
+ });
+ }
+ return segments;
+ }
+ };
+ if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : {
+ segment: text => [...text].map(char => ({ segment: char }))
+ };
+ if (!$splitTemplate && isBrowser) $splitTemplate = doc.createElement('template');
+ if (scope.current) scope.current.register(this);
+ const { words, chars, lines, accessible, includeSpaces, debug } = parameters;
+ const $target = /** @type {HTMLElement} */((target = isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (getNodeList(target) || [])[0]);
+ const lineParams = lines === true ? {} : lines;
+ const wordParams = words === true || isUnd(words) ? {} : words;
+ const charParams = chars === true ? {} : chars;
+ this.debug = setValue(debug, false);
+ this.includeSpaces = setValue(includeSpaces, false);
+ this.accessible = setValue(accessible, true);
+ this.linesOnly = lineParams && (!wordParams && !charParams);
+ /** @type {String|false|SplitFunctionValue} */
+ this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams;
+ /** @type {String|false|SplitFunctionValue} */
+ this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams;
+ /** @type {String|false|SplitFunctionValue} */
+ this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams;
+ this.$target = $target;
+ this.html = $target && $target.innerHTML;
+ this.lines = [];
+ this.words = [];
+ this.chars = [];
+ this.effects = [];
+ this.effectsCleanups = [];
+ this.cache = null;
+ this.ready = false;
+ this.width = 0;
+ this.resizeTimeout = null;
+ const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split();
+ // Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback
+ this.resizeObserver = new ResizeObserver(() => {
+ // Use a setTimeout instead of a Timer for better tree shaking
+ clearTimeout(this.resizeTimeout);
+ this.resizeTimeout = setTimeout(() => {
+ const currentWidth = /** @type {HTMLElement} */($target).offsetWidth;
+ if (currentWidth === this.width) return;
+ this.width = currentWidth;
+ handleSplit();
+ }, 150);
+ });
+ // Only declare the font ready promise when splitting by lines and not alreay split
+ if (this.lineTemplate && !this.ready) {
+ doc.fonts.ready.then(handleSplit);
+ } else {
+ handleSplit();
}
+ $target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.');
}
- handleScroll() {
- const linked = this.linked;
- const sync = this.sync;
- const syncEase = this.syncEase;
- const syncSmooth = this.syncSmooth;
- const shouldSeek = linked && (syncEase || syncSmooth);
- const isHori = this.horizontal;
- const container = this.container;
- const scroll = this.scroll;
- const isBefore = scroll <= this.offsetStart;
- const isAfter = scroll >= this.offsetEnd;
- const isInView = !isBefore && !isAfter;
- const isOnTheEdge = scroll === this.offsetStart || scroll === this.offsetEnd;
- const forceEnter = !this.hasEntered && isOnTheEdge;
- const $debug = this._debug && this.$debug;
- let hasUpdated = false;
- let syncCompleted = false;
- let p = this.progress;
-
- if (isBefore && this.began) {
- this.began = false;
- }
+ /**
+ * @param {(...args: any[]) => Tickable | (() => void)} effect
+ * @return this
+ */
+ addEffect(effect) {
+ if (!isFnc(effect)) return console.warn('Effect must return a function.');
+ const refreshableEffect = keepTime(effect);
+ this.effects.push(refreshableEffect);
+ if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this);
+ return this;
+ }
- if (p > 0 && !this.began) {
- this.began = true;
- }
+ revert() {
+ clearTimeout(this.resizeTimeout);
+ this.lines.length = this.words.length = this.chars.length = 0;
+ this.resizeObserver.disconnect();
+ // Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process
+ this.effectsCleanups.forEach(cleanup => isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert());
+ this.$target.innerHTML = this.html;
+ return this;
+ }
- if (shouldSeek) {
- const lp = linked.progress;
- if (syncSmooth && isNum(syncSmooth)) {
- if (/** @type {Number} */(syncSmooth) < 1) {
- const step = 0.0001;
- const snap = lp < p && p === 1 ? step : lp > p && !p ? -1e-4 : 0;
- p = round(lerp(lp, p, interpolate(.01, .2, /** @type {Number} */(syncSmooth)), false) + snap, 6);
+ /**
+ * Recursively processes a node and its children
+ * @param {Node} node
+ */
+ splitNode(node) {
+ const wordTemplate = this.wordTemplate;
+ const charTemplate = this.charTemplate;
+ const includeSpaces = this.includeSpaces;
+ const debug = this.debug;
+ const nodeType = node.nodeType;
+ if (nodeType === 3) {
+ const nodeText = node.nodeValue;
+ // If the nodeText is only whitespace, leave it as is
+ if (nodeText.trim()) {
+ const tempWords = [];
+ const words = this.words;
+ const chars = this.chars;
+ const wordSegments = wordSegmenter.segment(nodeText);
+ const $wordsFragment = doc.createDocumentFragment();
+ let prevSeg = null;
+ for (const wordSegment of wordSegments) {
+ const segment = wordSegment.segment;
+ const isWordLike = isSegmentWordLike(wordSegment);
+ // Determine if this segment should be a new word, first segment always becomes a new word
+ if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) {
+ tempWords.push(segment);
+ } else {
+ // Only concatenate if both current and previous are non-word-like and don't contain spaces
+ const lastWordIndex = tempWords.length - 1;
+ const lastWord = tempWords[lastWordIndex];
+ if (!lastWord.includes(' ') && !segment.includes(' ')) {
+ tempWords[lastWordIndex] += segment;
+ } else {
+ tempWords.push(segment);
+ }
+ }
+ prevSeg = wordSegment;
}
- } else if (syncEase) {
- p = syncEase(p);
- }
- hasUpdated = p !== this.prevProgress;
- syncCompleted = lp === 1;
- if (hasUpdated && !syncCompleted && (syncSmooth && lp)) {
- container.wakeTicker.restart();
+
+ for (let i = 0, l = tempWords.length; i < l; i++) {
+ const word = tempWords[i];
+ if (!word.trim()) {
+ // Preserve whitespace only if includeSpaces is false and if the current space is not the first node
+ if (i && includeSpaces) continue;
+ $wordsFragment.appendChild(doc.createTextNode(word));
+ } else {
+ const nextWord = tempWords[i + 1];
+ const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim();
+ const wordToProcess = word;
+ const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null;
+ const $charsFragment = charTemplate ? doc.createDocumentFragment() : doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word);
+ if (charTemplate) {
+ const charSegmentsArray = [...charSegments];
+ for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) {
+ const charSegment = charSegmentsArray[j];
+ const isLastChar = j === jl - 1;
+ // If this is the last character and includeSpaces is true with a following space, append the space
+ const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment;
+ const $charNode = doc.createTextNode(charText);
+ processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length);
+ }
+ }
+ if (wordTemplate) {
+ processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length);
+ // Chars elements must be re-parsed in the split() method if both words and chars are parsed
+ } else if (charTemplate) {
+ $wordsFragment.appendChild($charsFragment);
+ } else {
+ $wordsFragment.appendChild(doc.createTextNode(word));
+ }
+ // Skip the next iteration if we included a space
+ if (hasWordFollowingSpace) i++;
+ }
+ }
+ node.parentNode.replaceChild($wordsFragment, node);
}
+ } else if (nodeType === 1) {
+ // Converting to an array is necessary to work around childNodes pottential mutation
+ const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]);
+ for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]);
}
+ }
- if ($debug) {
- const sticky = isHori ? container.scrollY : container.scrollX;
- $debug.style[isHori ? 'top' : 'left'] = sticky + 10 + 'px';
+ /**
+ * @param {Boolean} clearCache
+ * @return {this}
+ */
+ split(clearCache = false) {
+ const $el = this.$target;
+ const isCached = !!this.cache && !clearCache;
+ const lineTemplate = this.lineTemplate;
+ const wordTemplate = this.wordTemplate;
+ const charTemplate = this.charTemplate;
+ const fontsReady = doc.fonts.status !== 'loading';
+ const canSplitLines = lineTemplate && fontsReady;
+ this.ready = !lineTemplate || fontsReady;
+ if (canSplitLines || clearCache) {
+ // No need to revert effects animations here since it's already taken care by the refreshable
+ this.effectsCleanups.forEach(cleanup => isFnc(cleanup) && cleanup(this));
}
-
- // Trigger enter callbacks if already in view or when entering the view
- if ((isInView && !this.isInView) || (forceEnter && !this.forceEnter && !this.hasEntered)) {
- if (isInView) this.isInView = true;
- if (!this.forceEnter || !this.hasEntered) {
- if ($debug && isInView) $debug.style.zIndex = `${this.container.zIndex++}`;
- this.onSyncEnter(this);
- this.onEnter(this);
- if (this.backward) {
- this.onSyncEnterBackward(this);
- this.onEnterBackward(this);
- } else {
- this.onSyncEnterForward(this);
- this.onEnterForward(this);
- }
- this.hasEntered = true;
- if (forceEnter) this.forceEnter = true;
- } else if (isInView) {
- this.forceEnter = false;
+ if (!isCached) {
+ if (clearCache) {
+ $el.innerHTML = this.html;
+ this.words.length = this.chars.length = 0;
}
+ this.splitNode($el);
+ this.cache = $el.innerHTML;
}
-
- if (isInView || !isInView && this.isInView) {
- hasUpdated = true;
+ if (canSplitLines) {
+ if (isCached) $el.innerHTML = this.cache;
+ this.lines.length = 0;
+ if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
}
-
- if (hasUpdated) {
- if (shouldSeek) linked.seek(linked.duration * p);
- this.onUpdate(this);
+ // Always reparse characters after a line reset or if both words and chars are activated
+ if (charTemplate && (canSplitLines || wordTemplate)) {
+ this.chars = getAllTopLevelElements($el, charType);
}
-
- if (!isInView && this.isInView) {
- this.isInView = false;
- this.onSyncLeave(this);
- this.onLeave(this);
- if (this.backward) {
- this.onSyncLeaveBackward(this);
- this.onLeaveBackward(this);
- } else {
- this.onSyncLeaveForward(this);
- this.onLeaveForward(this);
- }
- if (sync && !syncSmooth) {
- syncCompleted = true;
- }
+ // Words are used when lines only and prioritized over chars
+ const elementsArray = this.words.length ? this.words : this.chars;
+ let y, linesCount = 0;
+ for (let i = 0, l = elementsArray.length; i < l; i++) {
+ const $el = elementsArray[i];
+ const { top, height } = $el.getBoundingClientRect();
+ if (y && top - y > height * .5) linesCount++;
+ $el.setAttribute(dataLine, `${linesCount}`);
+ const nested = $el.querySelectorAll(`[${dataLine}]`);
+ let c = nested.length;
+ while (c--) nested[c].setAttribute(dataLine, `${linesCount}`);
+ y = top;
}
-
- if (p >= 1 && this.began && !this.completed && (sync && syncCompleted || !sync)) {
- if (sync) {
- this.onSyncComplete(this);
+ if (canSplitLines) {
+ const linesFragment = doc.createDocumentFragment();
+ const parents = new Set();
+ const clones = [];
+ for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) {
+ const $clone = /** @type {HTMLElement} */($el.cloneNode(true));
+ filterLineElements($clone, lineIndex, new Set()).forEach($el => {
+ const $parent = $el.parentElement;
+ if ($parent) parents.add($parent);
+ $el.remove();
+ });
+ clones.push($clone);
}
- this.completed = true;
- if ((!this.repeat && !linked) || (!this.repeat && linked && linked.completed)) {
- this.revert();
+ parents.forEach(filterEmptyElements);
+ for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) {
+ processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex);
}
+ $el.innerHTML = '';
+ $el.appendChild(linesFragment);
+ if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
+ if (charTemplate) this.chars = getAllTopLevelElements($el, charType);
}
-
- if (p < 1 && this.completed) {
- this.completed = false;
+ // Remove the word wrappers and clear the words array if lines split only
+ if (this.linesOnly) {
+ const words = this.words;
+ let w = words.length;
+ while (w--) {
+ const $word = words[w];
+ $word.replaceWith($word.textContent);
+ }
+ words.length = 0;
}
-
- this.prevProgress = p;
- }
-
- revert() {
- if (this.reverted) return;
- const container = this.container;
- removeChild(container, this);
- if (!container._head) {
- container.revert();
+ if (this.accessible && (canSplitLines || !isCached)) {
+ const $accessible = doc.createElement('span');
+ // Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html)
+ $accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;
+ // $accessible.setAttribute('tabindex', '-1');
+ $accessible.innerHTML = this.html;
+ $el.insertBefore($accessible, $el.firstChild);
+ this.lines.forEach(setAriaHidden);
+ this.words.forEach(setAriaHidden);
+ this.chars.forEach(setAriaHidden);
}
- if (this._debug) {
- this.removeDebug();
+ this.width = /** @type {HTMLElement} */($el).offsetWidth;
+ if (canSplitLines || clearCache) {
+ this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this));
}
- this.reverted = true;
return this;
}
+ refresh() {
+ this.split(true);
+ }
}
/**
- * @param {ScrollObserverParams} [parameters={}]
- * @return {ScrollObserver}
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
*/
-const onScroll = (parameters = {}) => new ScrollObserver(parameters);
+const splitText = (target, parameters) => new TextSplitter(target, parameters);
+/**
+ * @deprecated text.split() is deprecated, import splitText() directly, or text.splitText()
+ *
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
+ */
+const split = (target, parameters) => {
+ console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()');
+ return new TextSplitter(target, parameters);
+};
+var index = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ TextSplitter: TextSplitter,
+ split: split,
+ splitText: splitText
+});
-const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter;
-const valueRgx = /\{value\}/g;
-const indexRgx = /\{i\}/g;
-const whiteSpaceGroupRgx = /(\s+)/;
-const whiteSpaceRgx = /^\s+$/;
-const lineType = 'line';
-const wordType = 'word';
-const charType = 'char';
-const dataLine = `data-line`;
-/**
- * @typedef {Object} Segment
- * @property {String} segment
- * @property {Boolean} [isWordLike]
- */
-/**
- * @typedef {Object} Segmenter
- * @property {function(String): Iterable<Segment>} segment
- */
-/** @type {Segmenter} */
-let wordSegmenter = null;
-/** @type {Segmenter} */
-let graphemeSegmenter = null;
-let $splitTemplate = null;
-/**
- * @param {Segment} seg
- * @return {Boolean}
- */
-const isSegmentWordLike = seg => {
- return seg.isWordLike ||
- seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later
- isNum(+seg.segment); // Safari doesn't considers numbers as words
-};
/**
- * @param {HTMLElement} $el
+ * Converts an easing function into a valid CSS linear() timing function string
+ * @param {EasingFunction} fn
+ * @param {number} [samples=100]
+ * @returns {string} CSS linear() timing function
*/
-const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true');
+const easingToLinear = (fn, samples = 100) => {
+ const points = [];
+ for (let i = 0; i <= samples; i++) points.push(fn(i / samples));
+ return `linear(${points.join(', ')})`;
+};
-/**
- * @param {DOMTarget} $el
- * @param {String} type
- * @return {Array<HTMLElement>}
- */
-const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))];
+const WAAPIEasesLookups = {
+ in: 'ease-in',
+ out: 'ease-out',
+ inOut: 'ease-in-out',
+};
-const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' };
+const WAAPIeases = /*#__PURE__*/(() => {
+ const list = {};
+ for (let type in easeTypes) list[type] = (/** @type {String|Number} */p) => easeTypes[type](easeInPower(p));
+ return /** @type {Record<String, EasingFunction>} */(list);
+})();
/**
- * @param {HTMLElement} $el
+ * @param {EasingParam} ease
+ * @return {String}
*/
-const filterEmptyElements = $el => {
- if (!$el.childElementCount && !$el.textContent.trim()) {
- const $parent = $el.parentElement;
- $el.remove();
- if ($parent) filterEmptyElements($parent);
+const parseWAAPIEasing = (ease) => {
+ let parsedEase = WAAPIEasesLookups[ease];
+ if (parsedEase) return parsedEase;
+ parsedEase = 'linear';
+ if (isStr(ease)) {
+ if (
+ stringStartsWith(ease, 'linear') ||
+ stringStartsWith(ease, 'cubic-') ||
+ stringStartsWith(ease, 'steps') ||
+ stringStartsWith(ease, 'ease')
+ ) {
+ parsedEase = ease;
+ } else if (stringStartsWith(ease, 'cubicB')) {
+ parsedEase = toLowerCase(ease);
+ } else {
+ const parsed = parseEaseString(ease, WAAPIeases, WAAPIEasesLookups);
+ if (isFnc(parsed)) parsedEase = parsed === none ? 'linear' : easingToLinear(parsed);
+ }
+ WAAPIEasesLookups[ease] = parsedEase;
+ } else if (isFnc(ease)) {
+ const easing = easingToLinear(ease);
+ if (easing) parsedEase = easing;
+ } else if (/** @type {Spring} */(ease).ease) {
+ parsedEase = easingToLinear(/** @type {Spring} */(ease).ease);
}
+ return parsedEase;
};
+const transformsShorthands = ['x', 'y', 'z'];
+const commonDefaultPXProperties = [
+ 'perspective',
+ 'width',
+ 'height',
+ 'margin',
+ 'padding',
+ 'top',
+ 'right',
+ 'bottom',
+ 'left',
+ 'borderWidth',
+ 'fontSize',
+ 'borderRadius',
+ ...transformsShorthands
+];
+
+const validIndividualTransforms = /*#__PURE__*/ (() => [...transformsShorthands, ...validTransforms.filter(t => ['X', 'Y', 'Z'].some(axis => t.endsWith(axis)))])();
+
+let transformsPropertiesRegistered = null;
+
/**
- * @param {HTMLElement} $el
- * @param {Number} lineIndex
- * @param {Set<HTMLElement>} bin
- * @returns {Set<HTMLElement>}
+ * @param {String} propName
+ * @param {WAAPIKeyframeValue} value
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ * @param {Number} targetsLength
+ * @return {String}
*/
-const filterLineElements = ($el, lineIndex, bin) => {
- const dataLineAttr = $el.getAttribute(dataLine);
- if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') bin.add($el);
- let i = $el.childElementCount;
- while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin);
- return bin;
+const normalizeTweenValue = (propName, value, $el, i, targetsLength) => {
+ let v = getFunctionValue(/** @type {any} */(value), $el, i, targetsLength);
+ if (!isNum(v)) return v;
+ if (commonDefaultPXProperties.includes(propName) || stringStartsWith(propName, 'translate')) return `${v}px`;
+ if (stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew')) return `${v}deg`;
+ return `${v}`;
};
/**
- * @param {'line'|'word'|'char'} type
- * @param {splitTemplateParams} params
- * @return {String}
+ * @param {DOMTarget} $el
+ * @param {String} propName
+ * @param {WAAPIKeyframeValue} from
+ * @param {WAAPIKeyframeValue} to
+ * @param {Number} i
+ * @param {Number} targetsLength
+ * @return {WAAPITweenValue}
*/
-const generateTemplate = (type, params = {}) => {
- let template = ``;
- const classString = isStr(params.class) ? ` class="${params.class}"` : '';
- const cloneType = setValue(params.clone, false);
- const wrapType = setValue(params.wrap, false);
- const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false;
- if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`;
- template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`;
- if (cloneType) {
- const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0';
- const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0';
- template += `<span>{value}</span>`;
- template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`;
+const parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => {
+ /** @type {WAAPITweenValue} */
+ let tweenValue = '0';
+ const computedTo = !isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName];
+ if (!isUnd(from)) {
+ const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength);
+ tweenValue = [computedFrom, computedTo];
} else {
- template += `{value}`;
+ tweenValue = isArr(to) ? to.map((/** @type {any} */v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo;
}
- template += `</span>`;
- if (wrapType) template += `</span>`;
- return template;
+ return tweenValue;
};
+class WAAPIAnimation {
/**
- * @param {String|SplitFunctionValue} htmlTemplate
- * @param {Array<HTMLElement>} store
- * @param {Node|HTMLElement} node
- * @param {DocumentFragment} $parentFragment
- * @param {'line'|'word'|'char'} type
- * @param {Boolean} debug
- * @param {Number} lineIndex
- * @param {Number} [wordIndex]
- * @param {Number} [charIndex]
- * @return {HTMLElement}
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
*/
-const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => {
- const isLine = type === lineType;
- const isChar = type === charType;
- const className = `_${type}_`;
- const template = isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate;
- const displayStyle = isLine ? 'block' : 'inline-block';
- $splitTemplate.innerHTML = template
- .replace(valueRgx, `<i class="${className}"></i>`)
- .replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`);
- const $content = $splitTemplate.content;
- const $highestParent = /** @type {HTMLElement} */($content.firstElementChild);
- const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent;
- const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`));
- const replacablesLength = $replacables.length;
- if (replacablesLength) {
- $highestParent.style.display = displayStyle;
- $split.style.display = displayStyle;
- $split.setAttribute(dataLine, `${lineIndex}`);
- if (!isLine) {
- $split.setAttribute('data-word', `${wordIndex}`);
- if (isChar) $split.setAttribute('data-char', `${charIndex}`);
- }
- let i = replacablesLength;
- while (i--) {
- const $replace = $replacables[i];
- const $closestParent = $replace.parentElement;
- $closestParent.style.display = displayStyle;
- if (isLine) {
- $closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML;
+ constructor(targets, params) {
+
+ if (scope.current) scope.current.register(this);
+
+ // Skip the registration and fallback to no animation in case CSS.registerProperty is not supported
+ if (isNil(transformsPropertiesRegistered)) {
+ if (isBrowser && (isUnd(CSS) || !Object.hasOwnProperty.call(CSS, 'registerProperty'))) {
+ transformsPropertiesRegistered = false;
} else {
- $closestParent.replaceChild(node.cloneNode(true), $replace);
+ validTransforms.forEach(t => {
+ const isSkew = stringStartsWith(t, 'skew');
+ const isScale = stringStartsWith(t, 'scale');
+ const isRotate = stringStartsWith(t, 'rotate');
+ const isTranslate = stringStartsWith(t, 'translate');
+ const isAngle = isRotate || isSkew;
+ const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*";
+ try {
+ CSS.registerProperty({
+ name: '--' + t,
+ syntax,
+ inherits: false,
+ initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0',
+ });
+ } catch {} });
+ transformsPropertiesRegistered = true;
}
}
- store.push($split);
- $parentFragment.appendChild($content);
- } else {
- console.warn(`The expression "{value}" is missing from the provided template.`);
- }
- if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`;
- return $highestParent;
-};
-/**
- * A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
- * @class
- */
-class TextSplitter {
- /**
- * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
- * @param {TextSplitterParams} [parameters]
- */
- constructor(target, parameters = {}) {
- // Only init segmenters when needed
- if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : {
- segment: (text) => {
- const segments = [];
- const words = text.split(whiteSpaceGroupRgx);
- for (let i = 0, l = words.length; i < l; i++) {
- const segment = words[i];
- segments.push({
- segment,
- isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like
- });
- }
- return segments;
- }
- };
- if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : {
- segment: text => [...text].map(char => ({ segment: char }))
- };
- if (!$splitTemplate && isBrowser) $splitTemplate = doc.createElement('template');
- if (scope.current) scope.current.register(this);
- const { words, chars, lines, accessible, includeSpaces, debug } = parameters;
- const $target = /** @type {HTMLElement} */((target = isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (getNodeList(target) || [])[0]);
- const lineParams = lines === true ? {} : lines;
- const wordParams = words === true || isUnd(words) ? {} : words;
- const charParams = chars === true ? {} : chars;
- this.debug = setValue(debug, false);
- this.includeSpaces = setValue(includeSpaces, false);
- this.accessible = setValue(accessible, true);
- this.linesOnly = lineParams && (!wordParams && !charParams);
- /** @type {String|false|SplitFunctionValue} */
- this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {splitTemplateParams} */(lineParams)) : lineParams;
- /** @type {String|false|SplitFunctionValue} */
- this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {splitTemplateParams} */(wordParams)) : wordParams;
- /** @type {String|false|SplitFunctionValue} */
- this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {splitTemplateParams} */(charParams)) : charParams;
- this.$target = $target;
- this.html = $target && $target.innerHTML;
- this.lines = [];
- this.words = [];
- this.chars = [];
- this.effects = [];
- this.effectsCleanups = [];
- this.cache = null;
- this.ready = false;
- this.width = 0;
- this.resizeTimeout = null;
- const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split();
- // Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback
- this.resizeObserver = new ResizeObserver(() => {
- // Use a setTimeout instead of a Timer for better tree shaking
- clearTimeout(this.resizeTimeout);
- this.resizeTimeout = setTimeout(() => {
- const currentWidth = /** @type {HTMLElement} */($target).offsetWidth;
- if (currentWidth === this.width) return;
- this.width = currentWidth;
- handleSplit();
- }, 150);
- });
- // Only declare the font ready promise when splitting by lines and not alreay split
- if (this.lineTemplate && !this.ready) {
- doc.fonts.ready.then(handleSplit);
- } else {
- handleSplit();
+ const parsedTargets = registerTargets(targets);
+ const targetsLength = parsedTargets.length;
+
+ if (!targetsLength) {
+ console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
}
- $target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.');
- }
- /**
- * @param {(...args: any[]) => Tickable | (() => void)} effect
- * @return this
- */
- addEffect(effect) {
- if (!isFnc(effect)) return console.warn('Effect must return a function.');
- const refreshableEffect = createRefreshable(effect);
- this.effects.push(refreshableEffect);
- if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this);
- return this;
- }
+ const ease = setValue(params.ease, parseWAAPIEasing(globals.defaults.ease));
+ const spring = /** @type {Spring} */(ease).ease && ease;
+ const autoplay = setValue(params.autoplay, globals.defaults.autoplay);
+ const scroll = autoplay && /** @type {ScrollObserver} */(autoplay).link ? autoplay : false;
+ const alternate = params.alternate && /** @type {Boolean} */(params.alternate) === true;
+ const reversed = params.reversed && /** @type {Boolean} */(params.reversed) === true;
+ const loop = setValue(params.loop, globals.defaults.loop);
+ const iterations = /** @type {Number} */((loop === true || loop === Infinity) ? Infinity : isNum(loop) ? loop + 1 : 1);
+ /** @type {PlaybackDirection} */
+ const direction = alternate ? reversed ? 'alternate-reverse' : 'alternate' : reversed ? 'reverse' : 'normal';
+ /** @type {FillMode} */
+ const fill = 'forwards';
+ /** @type {String} */
+ const easing = parseWAAPIEasing(ease);
+ const timeScale = (globals.timeScale === 1 ? 1 : K);
+
+ /** @type {DOMTargetsArray}] */
+ this.targets = parsedTargets;
+ /** @type {Array<globalThis.Animation>}] */
+ this.animations = [];
+ /** @type {globalThis.Animation}] */
+ this.controlAnimation = null;
+ /** @type {Callback<this>} */
+ this.onComplete = params.onComplete || noop;
+ /** @type {Number} */
+ this.duration = 0;
+ /** @type {Boolean} */
+ this.muteCallbacks = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Boolean} */
+ this.paused = !autoplay || scroll !== false;
+ /** @type {Boolean} */
+ this.reversed = reversed;
+ /** @type {Boolean|ScrollObserver} */
+ this.autoplay = autoplay;
+ /** @type {Number} */
+ this._speed = setValue(params.playbackRate, globals.defaults.playbackRate);
+ /** @type {Function} */
+ this._resolve = noop; // Used by .then()
+ /** @type {Number} */
+ this._completed = 0;
+ /** @type {Array<Object>}] */
+ this._inlineStyles = parsedTargets.map($el => $el.getAttribute('style'));
- revert() {
- clearTimeout(this.resizeTimeout);
- this.lines.length = this.words.length = this.chars.length = 0;
- this.resizeObserver.disconnect();
- // Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process
- this.effectsCleanups.forEach(cleanup => isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert());
- this.$target.innerHTML = this.html;
- return this;
- }
+ parsedTargets.forEach(($el, i) => {
- /**
- * Recursively processes a node and its children
- * @param {Node} node
- */
- splitNode(node) {
- const wordTemplate = this.wordTemplate;
- const charTemplate = this.charTemplate;
- const includeSpaces = this.includeSpaces;
- const debug = this.debug;
- const nodeType = node.nodeType;
- if (nodeType === 3) {
- const nodeText = node.nodeValue;
- // If the nodeText is only whitespace, leave it as is
- if (nodeText.trim()) {
- const tempWords = [];
- const words = this.words;
- const chars = this.chars;
- const wordSegments = wordSegmenter.segment(nodeText);
- const $wordsFragment = doc.createDocumentFragment();
- let prevSeg = null;
- for (const wordSegment of wordSegments) {
- const segment = wordSegment.segment;
- const isWordLike = isSegmentWordLike(wordSegment);
- // Determine if this segment should be a new word, first segment always becomes a new word
- if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) {
- tempWords.push(segment);
+ const cachedTransforms = $el[transformsSymbol];
+
+ const hasIndividualTransforms = validIndividualTransforms.some(t => params.hasOwnProperty(t));
+
+ /** @type {Number} */
+ const duration = (spring ? /** @type {Spring} */(spring).duration : getFunctionValue(setValue(params.duration, globals.defaults.duration), $el, i, targetsLength)) * timeScale;
+ /** @type {Number} */
+ const delay = getFunctionValue(setValue(params.delay, globals.defaults.delay), $el, i, targetsLength) * timeScale;
+ /** @type {CompositeOperation} */
+ const composite = /** @type {CompositeOperation} */(setValue(params.composition, 'replace'));
+
+ for (let name in params) {
+ if (!isKey(name)) continue;
+ /** @type {PropertyIndexedKeyframes} */
+ const keyframes = {};
+ /** @type {KeyframeAnimationOptions} */
+ const tweenParams = { iterations, direction, fill, easing, duration, delay, composite };
+ const propertyValue = params[name];
+ const individualTransformProperty = hasIndividualTransforms ? validTransforms.includes(name) ? name : shortTransforms.get(name) : false;
+ let parsedPropertyValue;
+ if (isObj(propertyValue)) {
+ const tweenOptions = /** @type {WAAPITweenOptions} */(propertyValue);
+ const tweenOptionsEase = setValue(tweenOptions.ease, ease);
+ const tweenOptionsSpring = /** @type {Spring} */(tweenOptionsEase).ease && tweenOptionsEase;
+ const to = /** @type {WAAPITweenOptions} */(tweenOptions).to;
+ const from = /** @type {WAAPITweenOptions} */(tweenOptions).from;
+ /** @type {Number} */
+ tweenParams.duration = (tweenOptionsSpring ? /** @type {Spring} */(tweenOptionsSpring).duration : getFunctionValue(setValue(tweenOptions.duration, duration), $el, i, targetsLength)) * timeScale;
+ /** @type {Number} */
+ tweenParams.delay = getFunctionValue(setValue(tweenOptions.delay, delay), $el, i, targetsLength) * timeScale;
+ /** @type {CompositeOperation} */
+ tweenParams.composite = /** @type {CompositeOperation} */(setValue(tweenOptions.composition, composite));
+ /** @type {String} */
+ tweenParams.easing = parseWAAPIEasing(tweenOptionsEase);
+ parsedPropertyValue = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
+ if (individualTransformProperty) {
+ keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
+ cachedTransforms[individualTransformProperty] = parsedPropertyValue;
} else {
- // Only concatenate if both current and previous are non-word-like and don't contain spaces
- const lastWordIndex = tempWords.length - 1;
- const lastWord = tempWords[lastWordIndex];
- if (!lastWord.includes(' ') && !segment.includes(' ')) {
- tempWords[lastWordIndex] += segment;
+ keyframes[name] = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
+ }
+ addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
+ if (!isUnd(from)) {
+ if (!individualTransformProperty) {
+ $el.style[name] = keyframes[name][0];
} else {
- tempWords.push(segment);
+ const key = `--${individualTransformProperty}`;
+ $el.style.setProperty(key, keyframes[key][0]);
}
}
- prevSeg = wordSegment;
- }
-
- for (let i = 0, l = tempWords.length; i < l; i++) {
- const word = tempWords[i];
- if (!word.trim()) {
- // Preserve whitespace only if includeSpaces is false and if the current space is not the first node
- if (i && includeSpaces) continue;
- $wordsFragment.appendChild(doc.createTextNode(word));
+ } else {
+ parsedPropertyValue = isArr(propertyValue) ?
+ propertyValue.map((/** @type {any} */v) => normalizeTweenValue(name, v, $el, i, targetsLength)) :
+ normalizeTweenValue(name, /** @type {any} */(propertyValue), $el, i, targetsLength);
+ if (individualTransformProperty) {
+ keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
+ cachedTransforms[individualTransformProperty] = parsedPropertyValue;
} else {
- const nextWord = tempWords[i + 1];
- const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim();
- const wordToProcess = word;
- const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null;
- const $charsFragment = charTemplate ? doc.createDocumentFragment() : doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word);
- if (charTemplate) {
- const charSegmentsArray = [...charSegments];
- for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) {
- const charSegment = charSegmentsArray[j];
- const isLastChar = j === jl - 1;
- // If this is the last character and includeSpaces is true with a following space, append the space
- const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment;
- const $charNode = doc.createTextNode(charText);
- processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length);
- }
- }
- if (wordTemplate) {
- processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length);
- // Chars elements must be re-parsed in the split() method if both words and chars are parsed
- } else if (charTemplate) {
- $wordsFragment.appendChild($charsFragment);
- } else {
- $wordsFragment.appendChild(doc.createTextNode(word));
- }
- // Skip the next iteration if we included a space
- if (hasWordFollowingSpace) i++;
+ keyframes[name] = parsedPropertyValue;
}
- }
- node.parentNode.replaceChild($wordsFragment, node);
- }
- } else if (nodeType === 1) {
- // Converting to an array is necessary to work around childNodes pottential mutation
- const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]);
- for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]);
- }
- }
-
- /**
- * @param {Boolean} clearCache
- * @return {this}
- */
- split(clearCache = false) {
- const $el = this.$target;
- const isCached = !!this.cache && !clearCache;
- const lineTemplate = this.lineTemplate;
- const wordTemplate = this.wordTemplate;
- const charTemplate = this.charTemplate;
- const fontsReady = doc.fonts.status !== 'loading';
- const canSplitLines = lineTemplate && fontsReady;
- this.ready = !lineTemplate || fontsReady;
- if (canSplitLines || clearCache) {
- // No need to revert effects animations here since it's already taken care by the refreshable
- this.effectsCleanups.forEach(cleanup => isFnc(cleanup) && cleanup(this));
- }
- if (!isCached) {
- if (clearCache) {
- $el.innerHTML = this.html;
- this.words.length = this.chars.length = 0;
- }
- this.splitNode($el);
- this.cache = $el.innerHTML;
- }
- if (canSplitLines) {
- if (isCached) $el.innerHTML = this.cache;
- this.lines.length = 0;
- if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
- }
- // Always reparse characters after a line reset or if both words and chars are activated
- if (charTemplate && (canSplitLines || wordTemplate)) {
- this.chars = getAllTopLevelElements($el, charType);
- }
- // Words are used when lines only and prioritized over chars
- const elementsArray = this.words.length ? this.words : this.chars;
- let y, linesCount = 0;
- for (let i = 0, l = elementsArray.length; i < l; i++) {
- const $el = elementsArray[i];
- const { top, height } = $el.getBoundingClientRect();
- if (y && top - y > height * .5) linesCount++;
- $el.setAttribute(dataLine, `${linesCount}`);
- const nested = $el.querySelectorAll(`[${dataLine}]`);
- let c = nested.length;
- while (c--) nested[c].setAttribute(dataLine, `${linesCount}`);
- y = top;
- }
- if (canSplitLines) {
- const linesFragment = doc.createDocumentFragment();
- const parents = new Set();
- const clones = [];
- for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) {
- const $clone = /** @type {HTMLElement} */($el.cloneNode(true));
- filterLineElements($clone, lineIndex, new Set()).forEach($el => {
- const $parent = $el.parentElement;
- if ($parent) parents.add($parent);
- $el.remove();
- });
- clones.push($clone);
- }
- parents.forEach(filterEmptyElements);
- for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) {
- processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex);
- }
- $el.innerHTML = '';
- $el.appendChild(linesFragment);
- if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
- if (charTemplate) this.chars = getAllTopLevelElements($el, charType);
- }
- // Remove the word wrappers and clear the words array if lines split only
- if (this.linesOnly) {
- const words = this.words;
- let w = words.length;
- while (w--) {
- const $word = words[w];
- $word.replaceWith($word.textContent);
+ addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
+ }
}
- words.length = 0;
- }
- if (this.accessible && (canSplitLines || !isCached)) {
- const $accessible = doc.createElement('span');
- // Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html)
- $accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;
- // $accessible.setAttribute('tabindex', '-1');
- $accessible.innerHTML = this.html;
- $el.insertBefore($accessible, $el.firstChild);
- this.lines.forEach(setAriaHidden);
- this.words.forEach(setAriaHidden);
- this.chars.forEach(setAriaHidden);
- }
- this.width = /** @type {HTMLElement} */($el).offsetWidth;
- if (canSplitLines || clearCache) {
- this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this));
+ if (hasIndividualTransforms) {
+ let transforms = emptyString;
+ for (let t in cachedTransforms) {
+ transforms += `${transformsFragmentStrings[t]}var(--${t})) `;
+ }
+ $el.style.transform = transforms;
+ }
+ });
+
+ if (scroll) {
+ /** @type {ScrollObserver} */(this.autoplay).link(this);
}
+ }
+
+ /**
+ * @callback forEachCallback
+ * @param {globalThis.Animation} animation
+ */
+
+ /**
+ * @param {forEachCallback|String} callback
+ * @return {this}
+ */
+ forEach(callback) {
+ const cb = isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback;
+ this.animations.forEach(cb);
return this;
}
- refresh() {
- this.split(true);
+ get speed() {
+ return this._speed;
}
-}
-/**
- * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
- * @param {TextSplitterParams} [parameters]
- * @return {TextSplitter}
- */
-const split = (target, parameters) => new TextSplitter(target, parameters);
+ set speed(speed) {
+ this._speed = +speed;
+ this.forEach(anim => anim.playbackRate = speed);
+ }
-const text = {
- split,
-};
+ get currentTime() {
+ const controlAnimation = this.controlAnimation;
+ const timeScale = globals.timeScale;
+ return this.completed ? this.duration : controlAnimation ? +controlAnimation.currentTime * (timeScale === 1 ? 1 : timeScale) : 0;
+ }
+
+ set currentTime(time) {
+ const t = time * (globals.timeScale === 1 ? 1 : K);
+ this.forEach(anim => {
+ // Make sure the animation playState is not 'paused' in order to properly trigger an onfinish callback.
+ // The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported.
+ // https://developer.mozilla.org/en-US/docs/Web/API/Animation/finish_event
+ if (t >= this.duration) anim.play();
+ anim.currentTime = t;
+ });
+ }
+ get progress() {
+ return this.currentTime / this.duration;
+ }
+ set progress(progress) {
+ this.forEach(anim => anim.currentTime = progress * this.duration || 0);
+ }
+ resume() {
+ if (!this.paused) return this;
+ this.paused = false;
+ // TODO: Store the current time, and seek back to the last position
+ return this.forEach('play');
+ }
+ pause() {
+ if (this.paused) return this;
+ this.paused = true;
+ return this.forEach('pause');
+ }
+
+ alternate() {
+ this.reversed = !this.reversed;
+ this.forEach('reverse');
+ if (this.paused) this.forEach('pause');
+ return this;
+ }
+
+ play() {
+ if (this.reversed) this.alternate();
+ return this.resume();
+ }
+
+ reverse() {
+ if (!this.reversed) this.alternate();
+ return this.resume();
+ }
+
+ /**
+ * @param {Number} time
+ * @param {Boolean} muteCallbacks
+ */
+ seek(time, muteCallbacks = false) {
+ if (muteCallbacks) this.muteCallbacks = true;
+ if (time < this.duration) this.completed = false;
+ this.currentTime = time;
+ this.muteCallbacks = false;
+ if (this.paused) this.pause();
+ return this;
+ }
+
+ restart() {
+ this.completed = false;
+ return this.seek(0, true).resume();
+ }
+
+ commitStyles() {
+ return this.forEach('commitStyles');
+ }
+
+ complete() {
+ return this.seek(this.duration);
+ }
+
+ cancel() {
+ this.forEach('cancel');
+ return this.pause();
+ }
+
+ revert() {
+ this.cancel();
+ this.targets.forEach(($el, i) => $el.setAttribute('style', this._inlineStyles[i]) );
+ return this;
+ }
+
+ /**
+ * @param {WAAPICallback} [callback]
+ * @return {Promise}
+ */
+ then(callback = noop) {
+ const then = this.then;
+ const onResolve = () => {
+ this.then = null;
+ callback(this);
+ this.then = then;
+ this._resolve = noop;
+ };
+ return new Promise(r => {
+ this._resolve = () => r(onResolve());
+ if (this.completed) this._resolve();
+ return this;
+ });
+ }
+}
+
+const waapi = {
/**
- * @overload
- * @param {Number} val
- * @param {StaggerParams} [params]
- * @return {StaggerFunction<Number>}
- */
-/**
- * @overload
- * @param {String} val
- * @param {StaggerParams} [params]
- * @return {StaggerFunction<String>}
- */
-/**
- * @overload
- * @param {[Number, Number]} val
- * @param {StaggerParams} [params]
- * @return {StaggerFunction<Number>}
- */
-/**
- * @overload
- * @param {[String, String]} val
- * @param {StaggerParams} [params]
- * @return {StaggerFunction<String>}
- */
-/**
- * @param {Number|String|[Number, Number]|[String, String]} val The staggered value or range
- * @param {StaggerParams} [params] The stagger parameters
- * @return {StaggerFunction<Number|String>}
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
+ * @return {WAAPIAnimation}
*/
-const stagger = (val, params = {}) => {
- let values = [];
- let maxValue = 0;
- const from = params.from;
- const reversed = params.reversed;
- const ease = params.ease;
- const hasEasing = !isUnd(ease);
- const hasSpring = hasEasing && !isUnd(/** @type {Spring} */(ease).ease);
- const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEasings(ease) : null;
- const grid = params.grid;
- const axis = params.axis;
- const customTotal = params.total;
- const fromFirst = isUnd(from) || from === 0 || from === 'first';
- const fromCenter = from === 'center';
- const fromLast = from === 'last';
- const fromRandom = from === 'random';
- const isRange = isArr(val);
- const useProp = params.use;
- const val1 = isRange ? parseNumber(val[0]) : parseNumber(val);
- const val2 = isRange ? parseNumber(val[1]) : 0;
- const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString);
- const start = params.start || 0 + (isRange ? val1 : 0);
- let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0;
- return (target, i, t, tl) => {
- const [ registeredTarget ] = registerTargets(target);
- const total = isUnd(customTotal) ? t : customTotal;
- const customIndex = !isUnd(useProp) ? isFnc(useProp) ? useProp(registeredTarget, i, total) : getOriginalAnimatableValue(registeredTarget, useProp) : false;
- const staggerIndex = isNum(customIndex) || isStr(customIndex) && isNum(+customIndex) ? +customIndex : i;
- if (fromCenter) fromIndex = (total - 1) / 2;
- if (fromLast) fromIndex = total - 1;
- if (!values.length) {
- for (let index = 0; index < total; index++) {
- if (!grid) {
- values.push(abs(fromIndex - index));
- } else {
- const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2;
- const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2;
- const toX = index % grid[0];
- const toY = floor(index / grid[0]);
- const distanceX = fromX - toX;
- const distanceY = fromY - toY;
- let value = sqrt(distanceX * distanceX + distanceY * distanceY);
- if (axis === 'x') value = -distanceX;
- if (axis === 'y') value = -distanceY;
- values.push(value);
- }
- maxValue = max(...values);
- }
- if (staggerEase) values = values.map(val => staggerEase(val / maxValue) * maxValue);
- if (reversed) values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val));
- if (fromRandom) values = shuffle(values);
- }
- const spacing = isRange ? (val2 - val1) / maxValue : val1;
- const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl.iterationDuration : start) : /** @type {Number} */(start);
- /** @type {String|Number} */
- let output = offset + ((spacing * round(values[staggerIndex], 2)) || 0);
- if (params.modifier) output = params.modifier(output);
- if (unitMatch) output = `${output}${unitMatch[2]}`;
- return output;
- }
+ animate: (targets, params) => new WAAPIAnimation(targets, params),
+ convertEase: easingToLinear
};
-export { Animatable, Draggable, JSAnimation, Scope, ScrollObserver, Spring, TextSplitter, Timeline, Timer, WAAPIAnimation, animate, createAnimatable, createDraggable, createScope, createSpring, createTimeline, createTimer, eases, engine, onScroll, scrollContainers, stagger, svg, text, utils, waapi };
+export { registerTargets as $, Animatable, Draggable, JSAnimation, Scope, ScrollObserver, Spring, TextSplitter, Timeline, Timer, WAAPIAnimation, animate, clamp, cleanInlineStyles, createAnimatable, createDraggable, createDrawable, createMotionPath, createScope, createSeededRandom, createSpring, createTimeline, createTimer, cubicBezier, damp, degToRad, eases, index$3 as easings, engine, get, irregular, keepTime, lerp, linear, mapRange, morphTo, none, onScroll, padEnd, padStart, radToDeg, random, randomPick, remove, round, roundPad, scrollContainers, set, shuffle, snap, split, splitText, stagger, steps, index$1 as svg, sync, index as text, index$2 as utils, waapi, wrap };
diff --git a/dist/bundles/anime.esm.min.js b/dist/bundles/anime.esm.min.js
new file mode 100644
index 00000000..7294cd59
--- /dev/null
+++ b/dist/bundles/anime.esm.min.js
@@ -0,0 +1,7 @@
+/**
+ * Anime.js - ESM minified bundle
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+const t="undefined"!=typeof window,e=t?window:null,s=t?document:null,i={OBJECT:0,ATTRIBUTE:1,CSS:2,TRANSFORM:3,CSS_VAR:4},r={NUMBER:0,UNIT:1,COLOR:2,COMPLEX:3},n={NONE:0,AUTO:1,FORCE:2},o={replace:0,none:1,blend:2},a=Symbol(),h=Symbol(),l=Symbol(),c=Symbol(),d=Symbol(),u=Symbol(),p=1e-11,m=1e12,f=1e3,g=120,_="",y=(()=>{const t=new Map;return t.set("x","translateX"),t.set("y","translateY"),t.set("z","translateZ"),t})(),v=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],b=v.reduce((t,e)=>({...t,[e]:e+"("}),{}),T=()=>{},S=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i,w=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i,x=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,E=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i,C=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,k=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi,$=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i,O=/([a-z])([A-Z])/g,B=/(\w+)(\([^)]+\)+)/g,N=/(\*=|\+=|-=)/,R={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:g,loop:0,reversed:!1,alternate:!1,autoplay:!0,duration:f,delay:0,loopDelay:0,ease:"out(2)",composition:o.replace,modifier:t=>t,onBegin:T,onBeforeUpdate:T,onUpdate:T,onLoop:T,onPause:T,onComplete:T,onRender:T},L={current:null,root:s},A={defaults:R,precision:4,timeScale:1,tickThreshold:200},D={version:"4.2.0",engine:null};t&&(e.AnimeJS||(e.AnimeJS=[]),e.AnimeJS.push(D));const M=t=>t.replace(O,"$1-$2").toLowerCase(),F=(t,e)=>0===t.indexOf(e),I=Date.now,P=Array.isArray,z=t=>t&&t.constructor===Object,X=t=>"number"==typeof t&&!isNaN(t),U=t=>"string"==typeof t,Y=t=>"function"==typeof t,W=t=>void 0===t,V=t=>W(t)||null===t,H=e=>t&&e instanceof SVGElement,q=t=>S.test(t),j=t=>F(t,"rgb"),Q=t=>F(t,"hsl"),G=t=>q(t)||j(t)||Q(t),J=t=>!A.defaults.hasOwnProperty(t),Z=["opacity","rotate","overflow","color"],K=(t,e)=>{if(Z.includes(e))return!1;if(t.getAttribute(e)||e in t){if("scale"===e){const e=t.parentNode;return e&&"filter"===e.tagName}return!0}},tt=t=>U(t)?parseFloat(t):t,et=Math.pow,st=Math.sqrt,it=Math.sin,rt=Math.cos,nt=Math.abs,ot=Math.exp,at=Math.ceil,ht=Math.floor,lt=Math.asin,ct=Math.max,dt=Math.atan2,ut=Math.PI,pt=Math.round,mt=(t,e,s)=>t<e?e:t>s?s:t,ft={},gt=(t,e)=>{if(e<0)return t;if(!e)return pt(t);let s=ft[e];return s||(s=ft[e]=10**e),pt(t*s)/s},_t=(t,e)=>P(e)?e.reduce((e,s)=>nt(s-t)<nt(e-t)?s:e):e?pt(t/e)*e:t,yt=(t,e,s)=>t+(e-t)*s,vt=t=>t===1/0?m:t===-1/0?-m:t,bt=t=>t<=p?p:vt(gt(t,11)),Tt=t=>P(t)?[...t]:t,St=(t,e)=>{const s={...t};for(let i in e){const r=t[i];s[i]=W(r)?e[i]:r}return s},wt=(t,e,s,i="_prev",r="_next")=>{let n=t._head,o=r;for(s&&(n=t._tail,o=i);n;){const t=n[o];e(n),n=t}},xt=(t,e,s="_prev",i="_next")=>{const r=e[s],n=e[i];r?r[i]=n:t._head=n,n?n[s]=r:t._tail=r,e[s]=null,e[i]=null},Et=(t,e,s,i="_prev",r="_next")=>{let n=t._tail;for(;n&&s&&s(n,e);)n=n[i];const o=n?n[r]:t._head;n?n[r]=e:t._head=e,o?o[i]=e:t._tail=e,e[i]=n,e[r]=o},Ct=(t,e,s)=>{const i=t.style.transform;let r;if(i){const n=t[c];let o;for(;o=B.exec(i);){const t=o[1],i=o[2].slice(1,-1);n[t]=i,t===e&&(r=i,s&&(s[e]=i))}}return i&&!W(r)?r:F(e,"scale")?"1":F(e,"rotate")||F(e,"skew")?"0deg":"0px"},kt=t=>{const e=w.exec(t)||x.exec(t),s=W(e[4])?1:+e[4];return[+e[1],+e[2],+e[3],s]},$t=t=>{const e=t.length,s=4===e||5===e;return[+("0x"+t[1]+t[s?1:2]),+("0x"+t[s?2:3]+t[s?2:4]),+("0x"+t[s?3:5]+t[s?3:6]),5===e||9===e?+(+("0x"+t[s?4:7]+t[s?4:8])/255).toFixed(3):1]},Ot=(t,e,s)=>(s<0&&(s+=1),s>1&&(s-=1),s<1/6?t+6*(e-t)*s:s<.5?e:s<2/3?t+(e-t)*(2/3-s)*6:t),Bt=t=>{const e=E.exec(t)||C.exec(t),s=+e[1]/360,i=+e[2]/100,r=+e[3]/100,n=W(e[4])?1:+e[4];let o,a,h;if(0===i)o=a=h=r;else{const t=r<.5?r*(1+i):r+i-r*i,e=2*r-t;o=gt(255*Ot(e,t,s+1/3),0),a=gt(255*Ot(e,t,s),0),h=gt(255*Ot(e,t,s-1/3),0)}return[o,a,h,n]},Nt=t=>j(t)?kt(t):q(t)?$t(t):Q(t)?Bt(t):[0,0,0,1],Rt=(t,e)=>W(t)?e:t,Lt=(t,e,s,i,r)=>{if(Y(t)){const n=()=>{const r=t(e,s,i);return isNaN(+r)?r||0:+r};return r&&(r.func=n),n()}return t},At=(t,e)=>t[h]?t[l]&&K(t,e)?i.ATTRIBUTE:v.includes(e)||y.get(e)?i.TRANSFORM:F(e,"--")?i.CSS_VAR:e in t.style?i.CSS:e in t?i.OBJECT:i.ATTRIBUTE:i.OBJECT,Dt=(t,e,s)=>{const i=t.style[e];i&&s&&(s[e]=i);const r=i||getComputedStyle(t[u]||t).getPropertyValue(e);return"auto"===r?"0":r},Mt=(t,e,s,r)=>{const n=W(s)?At(t,e):s;return n===i.OBJECT?t[e]||0:n===i.ATTRIBUTE?t.getAttribute(e):n===i.TRANSFORM?Ct(t,e,r):n===i.CSS_VAR?Dt(t,e,r).trimStart():Dt(t,e,r)},Ft=(t,e,s)=>"-"===s?t-e:"+"===s?t+e:t*e,It=()=>({t:r.NUMBER,n:0,u:null,o:null,d:null,s:null}),Pt=(t,e)=>{if(e.t=r.NUMBER,e.n=0,e.u=null,e.o=null,e.d=null,e.s=null,!t)return e;const s=+t;if(isNaN(s)){let s=t;"="===s[1]&&(e.o=s[0],s=s.slice(2));const i=!s.includes(" ")&&$.exec(s);if(i)return e.t=r.UNIT,e.n=+i[1],e.u=i[2],e;if(e.o)return e.n=+s,e;if(G(s))return e.t=r.COLOR,e.d=Nt(s),e;{const t=s.match(k);return e.t=r.COMPLEX,e.d=t?t.map(Number):[],e.s=s.split(k)||[],e}}return e.n=s,e},zt=(t,e)=>(e.t=t._valueType,e.n=t._toNumber,e.u=t._unit,e.o=null,e.d=Tt(t._toNumbers),e.s=Tt(t._strings),e),Xt=It(),Ut=(t,e,s,a,h)=>{const l=t.parent,d=t.duration,u=t.completed,m=t.iterationDuration,f=t.iterationCount,g=t._currentIteration,y=t._loopDelay,v=t._reversed,T=t._alternate,S=t._hasChildren,w=t._delay,x=t._currentTime,E=w+m,C=e-w,k=mt(x,-w,d),$=mt(C,-w,d),O=C-x,B=$>0,N=$>=d,R=d<=p,L=h===n.FORCE;let D=0,M=C,F=0;if(f>1){const e=~~($/(m+(N?0:y)));t._currentIteration=mt(e,0,f),N&&t._currentIteration--,D=t._currentIteration%2,M=$%(m+y)||0}const I=v^(T&&D),P=t._ease;let z=N?I?0:d:I?m-M:M;P&&(z=m*P(z/m)||0);const X=(l?l.backwards:C<x)?!I:!!I;if(t._currentTime=C,t._iterationTime=z,t.backwards=X,B&&!t.began?(t.began=!0,s||l&&(X||!l.began)||t.onBegin(t)):C<=0&&(t.began=!1),s||S||!B||t._currentIteration===g||t.onLoop(t),L||h===n.AUTO&&(e>=w&&e<=E||e<=w&&k>w||e>=E&&k!==d)||z>=E&&k!==d||z<=w&&k>0||e<=k&&k===d&&u||N&&!u&&R){if(B&&(t.computeDeltaTime(k),s||t.onBeforeUpdate(t)),!S){const e=L||(X?-1*O:O)>=A.tickThreshold,n=t._offset+(l?l._offset:0)+w+z;let h,d,u,p,m=t._head,f=0;for(;m;){const t=m._composition,s=m._currentTime,l=m._changeDuration,g=m._absoluteStartTime+m._changeDuration,y=m._nextRep,v=m._prevRep,T=t!==o.none;if((e||(s!==l||n<=g+(y?y._delay:0))&&(0!==s||n>=m._absoluteStartTime))&&(!T||!m._isOverridden&&(!m._isOverlapped||n<=g)&&(!y||y._isOverridden||n<=y._absoluteStartTime)&&(!v||v._isOverridden||n>=v._absoluteStartTime+v._changeDuration+m._delay))){const e=m._currentTime=mt(z-m._startTime,0,l),s=m._ease(e/m._updateDuration),n=m._modifier,g=m._valueType,_=m._tweenType,y=_===i.OBJECT,v=g===r.NUMBER,b=v&&y||0===s||1===s?-1:A.precision;let S,w;if(v)S=w=n(gt(yt(m._fromNumber,m._toNumber,s),b));else if(g===r.UNIT)w=n(gt(yt(m._fromNumber,m._toNumber,s),b)),S=`${w}${m._unit}`;else if(g===r.COLOR){const t=m._fromNumbers,e=m._toNumbers,i=gt(mt(n(yt(t[0],e[0],s)),0,255),0),r=gt(mt(n(yt(t[1],e[1],s)),0,255),0),o=gt(mt(n(yt(t[2],e[2],s)),0,255),0),a=mt(n(gt(yt(t[3],e[3],s),b)),0,1);if(S=`rgba(${i},${r},${o},${a})`,T){const t=m._numbers;t[0]=i,t[1]=r,t[2]=o,t[3]=a}}else if(g===r.COMPLEX){S=m._strings[0];for(let t=0,e=m._toNumbers.length;t<e;t++){const e=n(gt(yt(m._fromNumbers[t],m._toNumbers[t],s),b)),i=m._strings[t+1];S+=`${i?e+i:e}`,T&&(m._numbers[t]=e)}}if(T&&(m._number=w),a||t===o.blend)m._value=S;else{const t=m.property;h=m.target,y?h[t]=S:_===i.ATTRIBUTE?h.setAttribute(t,S):(d=h.style,_===i.TRANSFORM?(h!==u&&(u=h,p=h[c]),p[t]=S,f=1):_===i.CSS?d[t]=S:_===i.CSS_VAR&&d.setProperty(t,S)),B&&(F=1)}}if(f&&m._renderTransforms){let t=_;for(let e in p)t+=`${b[e]}${p[e]}) `;d.transform=t,f=0}m=m._next}!s&&F&&t.onRender(t)}!s&&B&&t.onUpdate(t)}return l&&R?!s&&(l.began&&!X&&C>=d&&!u||X&&C<=p&&u)&&(t.onComplete(t),t.completed=!X):B&&N?f===1/0?t._startTime+=t.duration:t._currentIteration>=f-1&&(t.paused=!0,u||S||(t.completed=!0,s||l&&(X||!l.began)||(t.onComplete(t),t._resolve(t)))):t.completed=!1,F},Yt=(t,e,s,i,r)=>{const o=t._currentIteration;if(Ut(t,e,s,i,r),t._hasChildren){const a=t,h=a.backwards,l=i?e:a._iterationTime,c=I();let d=0,u=!0;if(!i&&a._currentIteration!==o){const t=a.iterationDuration;wt(a,e=>{if(h){const i=e.duration,r=e._offset+e._delay;s||!(i<=p)||r&&r+i!==t||e.onComplete(e)}else!e.completed&&!e.backwards&&e._currentTime<e.iterationDuration&&Ut(e,t,s,1,n.FORCE),e.began=!1,e.completed=!1}),s||a.onLoop(a)}wt(a,t=>{const e=gt((l-t._offset)*t._speed,12),n=t._fps<a._fps?t.requestTick(c):r;d+=Ut(t,e,s,i,n),!t.completed&&u&&(u=!1)},h),!s&&d&&a.onRender(a),(u||h)&&a._currentTime>=a.duration&&(a.paused=!0,a.completed||(a.completed=!0,s||(a.onComplete(a),a._resolve(a))))}},Wt={},Vt=(t,e,s)=>{if(s===i.TRANSFORM)return y.get(t)||t;if(s===i.CSS||s===i.ATTRIBUTE&&H(e)&&t in e.style){const e=Wt[t];if(e)return e;{const e=t?M(t):t;return Wt[t]=e,e}}return t},Ht=t=>{if(t._hasChildren)wt(t,Ht,!0);else{const e=t;e.pause(),wt(e,t=>{const s=t.property,r=t.target;if(r[h]){const n=r.style,o=e._inlineStyles[s];if(t._tweenType===i.TRANSFORM){const e=r[c];if(W(o)||o===_?delete e[s]:e[s]=o,t._renderTransforms)if(Object.keys(e).length){let t=_;for(let s in e)t+=b[s]+e[s]+") ";n.transform=t}else n.removeProperty("transform")}else W(o)||o===_?n.removeProperty(s):n[s]=o;e._tail===t&&e.targets.forEach(t=>{t.getAttribute&&t.getAttribute("style")===_&&t.removeAttribute("style")})}})}return t};class qt{constructor(t=0){this.deltaTime=0,this._currentTime=t,this._elapsedTime=t,this._startTime=t,this._lastTime=t,this._scheduledTime=0,this._frameDuration=gt(f/g,0),this._fps=g,this._speed=1,this._hasChildren=!1,this._head=null,this._tail=null}get fps(){return this._fps}set fps(t){const e=this._frameDuration,s=+t,i=s<p?p:s,r=gt(f/i,0);this._fps=i,this._frameDuration=r,this._scheduledTime+=r-e}get speed(){return this._speed}set speed(t){const e=+t;this._speed=e<p?p:e}requestTick(t){const e=this._scheduledTime,s=this._elapsedTime;if(this._elapsedTime+=t-s,s<e)return n.NONE;const i=this._frameDuration,r=s-e;return this._scheduledTime+=r<i?i:r,n.AUTO}computeDeltaTime(t){const e=t-this._lastTime;return this.deltaTime=e,this._lastTime=t,e}}const jt={animation:null,update:T},Qt=t=>{let e=jt.animation;return e||(e={duration:p,computeDeltaTime:T,_offset:0,_delay:0,_head:null,_tail:null},jt.animation=e,jt.update=()=>{t.forEach(t=>{for(let e in t){const s=t[e],i=s._head;if(i){const t=i._valueType,e=t===r.COMPLEX||t===r.COLOR?Tt(i._fromNumbers):null;let n=i._fromNumber,o=s._tail;for(;o&&o!==i;){if(e)for(let t=0,s=o._numbers.length;t<s;t++)e[t]+=o._numbers[t];else n+=o._number;o=o._prevAdd}i._toNumber=n,i._toNumbers=e}}}),Ut(e,1,1,0,n.FORCE)}),e},Gt=(()=>t?requestAnimationFrame:setImmediate)(),Jt=(()=>t?cancelAnimationFrame:clearImmediate)();class Zt extends qt{constructor(t){super(t),this.useDefaultMainLoop=!0,this.pauseOnDocumentHidden=!0,this.defaults=R,this.paused=!0,this.reqId=0}update(){const t=this._currentTime=I();if(this.requestTick(t)){this.computeDeltaTime(t);const e=this._speed,s=this._fps;let i=this._head;for(;i;){const r=i._next;i.paused?(xt(this,i),this._hasChildren=!!this._tail,i._running=!1,i.completed&&!i._cancelled&&i.cancel()):Yt(i,(t-i._startTime)*i._speed*e,0,0,i._fps<s?i.requestTick(t):n.AUTO),i=r}jt.update()}}wake(){return this.useDefaultMainLoop&&!this.reqId&&(this.requestTick(I()),this.reqId=Gt(te)),this}pause(){if(this.reqId)return this.paused=!0,ee()}resume(){if(this.paused)return this.paused=!1,wt(this,t=>t.resetTime()),this.wake()}get speed(){return this._speed*(1===A.timeScale?1:f)}set speed(t){this._speed=t*A.timeScale,wt(this,t=>t.speed=t._speed)}get timeUnit(){return 1===A.timeScale?"ms":"s"}set timeUnit(t){const e="s"===t,s=e?.001:1;if(A.timeScale!==s){A.timeScale=s,A.tickThreshold=200*s;const t=e?.001:f;this.defaults.duration*=t,this._speed*=t}}get precision(){return A.precision}set precision(t){A.precision=t}}const Kt=(()=>{const e=new Zt(I());return t&&(D.engine=e,s.addEventListener("visibilitychange",()=>{e.pauseOnDocumentHidden&&(s.hidden?e.pause():e.resume())})),e})(),te=()=>{Kt._head?(Kt.reqId=Gt(te),Kt.update()):Kt.reqId=0},ee=()=>(Jt(Kt.reqId),Kt.reqId=0,Kt),se={_rep:new WeakMap,_add:new Map},ie=(t,e,s="_rep")=>{const i=se[s];let r=i.get(t);return r||(r={},i.set(t,r)),r[e]?r[e]:r[e]={_head:null,_tail:null}},re=(t,e)=>t._isOverridden||t._absoluteStartTime>e._absoluteStartTime,ne=t=>{t._isOverlapped=1,t._isOverridden=1,t._changeDuration=p,t._currentTime=p},oe=(t,e)=>{const s=t._composition;if(s===o.replace){const s=t._absoluteStartTime;Et(e,t,re,"_prevRep","_nextRep");const i=t._prevRep;if(i){const e=i.parent,r=i._absoluteStartTime+i._changeDuration;if(t.parent.id!==e.id&&e.iterationCount>1&&r+(e.duration-e.iterationDuration)>s){ne(i);let t=i._prevRep;for(;t&&t.parent.id===e.id;)ne(t),t=t._prevRep}const n=s-t._delay;if(r>n){const t=i._startTime,e=r-(t+i._updateDuration),s=gt(n-e-t,12);i._changeDuration=s,i._currentTime=s,i._isOverlapped=1,s<p&&ne(i)}let o=!0;if(wt(e,t=>{t._isOverlapped||(o=!1)}),o){const t=e.parent;if(t){let s=!0;wt(t,t=>{t!==e&&wt(t,t=>{t._isOverlapped||(s=!1)})}),s&&t.cancel()}else e.cancel()}}}else if(s===o.blend){const e=ie(t.target,t.property,"_add"),s=Qt(se._add);let i=e._head;i||(i={...t},i._composition=o.replace,i._updateDuration=p,i._startTime=0,i._numbers=Tt(t._fromNumbers),i._number=0,i._next=null,i._prev=null,Et(e,i),Et(s,i));const r=t._toNumber;if(t._fromNumber=i._fromNumber-r,t._toNumber=0,t._numbers=Tt(t._fromNumbers),t._number=0,i._fromNumber=r,t._toNumbers){const e=Tt(t._toNumbers);e&&e.forEach((e,s)=>{t._fromNumbers[s]=i._fromNumbers[s]-e,t._toNumbers[s]=0}),i._fromNumbers=e}Et(e,t,null,"_prevAdd","_nextAdd")}return t},ae=t=>{const e=t._composition;if(e!==o.none){const s=t.target,i=t.property,r=se._rep.get(s)[i];if(xt(r,t,"_prevRep","_nextRep"),e===o.blend){const e=se._add,r=e.get(s);if(!r)return;const n=r[i],o=jt.animation;xt(n,t,"_prevAdd","_nextAdd");const a=n._head;if(a&&a===n._tail){xt(n,a,"_prevAdd","_nextAdd"),xt(o,a);let t=!0;for(let e in r)if(r[e]._head){t=!1;break}t&&e.delete(s)}}}return t},he=(t,e,s)=>{let r=!1;return wt(e,n=>{const o=n.target;if(t.includes(o)){const t=n.property,a=n._tweenType,h=Vt(s,o,a);(!h||h&&h===t)&&(n.parent._tail===n&&n._tweenType===i.TRANSFORM&&n._prev&&n._prev._tweenType===i.TRANSFORM&&(n._prev._renderTransforms=1),xt(e,n),ae(n),r=!0)}},!0),r},le=(t,e,s)=>{const i=e||Kt;let r;if(i._hasChildren){let e=0;wt(i,n=>{if(!n._hasChildren)if(r=he(t,n,s),r&&!n._head)n.cancel(),xt(i,n);else{const t=n._offset+n._delay+n.duration;t>e&&(e=t)}n._head?le(t,n,s):n._hasChildren=!1},!0),W(i.iterationDuration)||(i.iterationDuration=e)}else r=he(t,i,s);r&&!i._head&&(i._hasChildren=!1,i.cancel&&i.cancel())},ce=t=>(t.paused=!0,t.began=!1,t.completed=!1,t),de=t=>t._cancelled?(t._hasChildren?wt(t,de):wt(t,t=>{t._composition!==o.none&&oe(t,ie(t.target,t.property))}),t._cancelled=0,t):t;let ue=0;class pe extends qt{constructor(t={},e=null,s=0){super(0);const{id:i,delay:r,duration:n,reversed:o,alternate:a,loop:h,loopDelay:l,autoplay:c,frameRate:d,playbackRate:u,onComplete:m,onLoop:f,onPause:g,onBegin:_,onBeforeUpdate:y,onUpdate:v}=t;L.current&&L.current.register(this);const b=e?0:Kt._elapsedTime,S=e?e.defaults:A.defaults,w=Y(r)||W(r)?S.delay:+r,x=Y(n)||W(n)?1/0:+n,E=Rt(h,S.loop),C=Rt(l,S.loopDelay),k=!0===E||E===1/0||E<0?1/0:E+1;let $=0;e?$=s:(Kt.reqId||Kt.requestTick(I()),$=(Kt._elapsedTime-Kt._startTime)*A.timeScale),this.id=W(i)?++ue:i,this.parent=e,this.duration=vt((x+C)*k-C)||p,this.backwards=!1,this.paused=!0,this.began=!1,this.completed=!1,this.onBegin=_||S.onBegin,this.onBeforeUpdate=y||S.onBeforeUpdate,this.onUpdate=v||S.onUpdate,this.onLoop=f||S.onLoop,this.onPause=g||S.onPause,this.onComplete=m||S.onComplete,this.iterationDuration=x,this.iterationCount=k,this._autoplay=!e&&Rt(c,S.autoplay),this._offset=$,this._delay=w,this._loopDelay=C,this._iterationTime=0,this._currentIteration=0,this._resolve=T,this._running=!1,this._reversed=+Rt(o,S.reversed),this._reverse=this._reversed,this._cancelled=0,this._alternate=Rt(a,S.alternate),this._prev=null,this._next=null,this._elapsedTime=b,this._startTime=b,this._lastTime=b,this._fps=Rt(d,S.frameRate),this._speed=Rt(u,S.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(t){t?this.cancel():this.reset(1).play()}get currentTime(){return mt(gt(this._currentTime,A.precision),-this._delay,this.duration)}set currentTime(t){const e=this.paused;this.pause().seek(+t),e||this.resume()}get iterationCurrentTime(){return gt(this._iterationTime,A.precision)}set iterationCurrentTime(t){this.currentTime=this.iterationDuration*this._currentIteration+t}get progress(){return mt(gt(this._currentTime/this.duration,10),0,1)}set progress(t){this.currentTime=this.duration*t}get iterationProgress(){return mt(gt(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(t){const e=this.iterationDuration;this.currentTime=e*this._currentIteration+e*t}get currentIteration(){return this._currentIteration}set currentIteration(t){this.currentTime=this.iterationDuration*mt(+t,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(t){t?this.reverse():this.play()}get speed(){return super.speed}set speed(t){super.speed=t,this.resetTime()}reset(t=0){return de(this),this._reversed&&!this._reverse&&(this.reversed=!1),this._iterationTime=this.iterationDuration,Yt(this,0,1,t,n.FORCE),ce(this),this._hasChildren&&wt(this,ce),this}init(t=0){this.fps=this._fps,this.speed=this._speed,!t&&this._hasChildren&&Yt(this,this.duration,1,t,n.FORCE),this.reset(t);const e=this._autoplay;return!0===e?this.resume():e&&!W(e.linked)&&e.link(this),this}resetTime(){const t=1/(this._speed*Kt._speed);return this._startTime=I()-(this._currentTime+this._delay)*t,this}pause(){return this.paused||(this.paused=!0,this.onPause(this)),this}resume(){return this.paused?(this.paused=!1,this.duration<=p&&!this._hasChildren?Yt(this,p,0,0,n.FORCE):(this._running||(Et(Kt,this),Kt._hasChildren=!0,this._running=!0),this.resetTime(),this._startTime-=12,Kt.wake()),this):this}restart(){return this.reset(0).resume()}seek(t,e=0,s=0){de(this),this.completed=!1;const i=this.paused;return this.paused=!0,Yt(this,t+this._delay,~~e,~~s,n.AUTO),i?this:this.resume()}alternate(){const t=this._reversed,e=this.iterationCount,s=this.iterationDuration,i=e===1/0?ht(m/s):e;return this._reversed=+(!this._alternate||i%2?!t:t),e===1/0?this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress:this.seek(s*i-this._currentTime),this.resetTime(),this}play(){return this._reversed&&this.alternate(),this.resume()}reverse(){return this._reversed||this.alternate(),this.resume()}cancel(){return this._hasChildren?wt(this,t=>t.cancel(),!0):wt(this,ae),this._cancelled=1,this.pause()}stretch(t){const e=this.duration,s=bt(t);if(e===s)return this;const i=t/e,r=t<=p;return this.duration=r?p:s,this.iterationDuration=r?p:bt(this.iterationDuration*i),this._offset*=i,this._delay*=i,this._loopDelay*=i,this}revert(){Yt(this,0,1,0,n.AUTO);const t=this._autoplay;return t&&t.linked&&t.linked===this&&t.revert(),this.cancel()}complete(){return this.seek(this.duration).cancel()}then(t=T){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=T};return new Promise(t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this))}}const me=t=>new pe(t,null,0).init();function fe(t){const e=U(t)?L.root.querySelectorAll(t):t;if(e instanceof NodeList||e instanceof HTMLCollection)return e}function ge(e){if(V(e))return[];if(!t)return P(e)&&e.flat(1/0)||[e];if(P(e)){const t=e.flat(1/0),s=[];for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!V(i)){const t=fe(i);if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!V(i)){let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}else{let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}}return s}const s=fe(e);return s?Array.from(s):[e]}function _e(t){const e=ge(t),s=e.length;if(s)for(let t=0;t<s;t++){const s=e[t];if(!s[a]){s[a]=!0;const t=H(s);(s.nodeType||t)&&(s[h]=!0,s[l]=t,s[c]={})}}return e}const ye={deg:1,rad:180/ut,turn:360},ve={},be=(t,e,i,n=!1)=>{const o=e.u,a=e.n;if(e.t===r.UNIT&&o===i)return e;const h=a+o+i,l=ve[h];if(W(l)||n){let r;if(o in ye)r=a*ye[o]/ye[i];else{const e=100,n=t.cloneNode(),h=t.parentNode,l=h&&h!==s?h:s.body;l.appendChild(n);const c=n.style;c.width=e+o;const d=n.offsetWidth||e;c.width=e+i;const u=d/(n.offsetWidth||e);l.removeChild(n),r=u*a}e.n=r,ve[h]=r}else e.n=l;return e.t,e.u=i,e},Te=t=>t,Se=(t=1.68)=>e=>et(e,+t),we={in:t=>e=>t(e),out:t=>e=>1-t(1-e),inOut:t=>e=>e<.5?t(2*e)/2:1-t(-2*e+2)/2,outIn:t=>e=>e<.5?(1-t(1-2*e))/2:(t(2*e-1)+1)/2},xe=(t,e,s)=>{if(s[t])return s[t];if(t.indexOf("(")<=-1){const i=we[t]||t.includes("Back")||t.includes("Elastic")?e[t]():e[t];return i?s[t]=i:Te}{const i=t.slice(0,-1).split("("),r=e[i[0]];return r?s[t]=r(...i[1].split(",")):Te}},Ee=(t,e,s)=>(((1-3*s+3*e)*t+(3*s-6*e))*t+3*e)*t,Ce=(t,e,s)=>{let i,r,n=0,o=1,a=0;do{r=n+(o-n)/2,i=Ee(r,e,s)-t,i>0?o=r:n=r}while(nt(i)>1e-7&&++a<100);return r},ke=(t=.5,e=0,s=.5,i=1)=>t===e&&s===i?Te:r=>0===r||1===r?r:Ee(Ce(r,t,s),e,i),$e=(t=10,e)=>{const s=e?at:ht;return e=>s(mt(e,0,1)*t)*(1/t)},Oe=(...t)=>{const e=t.length;if(!e)return Te;const s=e-1,i=t[0],r=t[s],n=[0],o=[tt(i)];for(let e=1;e<s;e++){const i=t[e],r=U(i)?i.trim().split(" "):[i],a=r[0],h=r[1];n.push(W(h)?e/s:tt(h)/100),o.push(tt(a))}return o.push(tt(r)),n.push(1),function(t){for(let e=1,s=n.length;e<s;e++){const s=n[e];if(t<=s){const i=n[e-1],r=o[e-1];return r+(o[e]-r)*(t-i)/(s-i)}}return o[o.length-1]}},Be=(t=10,e=1)=>{const s=[0],i=t-1;for(let t=1;t<i;t++){const r=s[t-1],n=t/i,o=n*(1-e)+(n+((t+1)/i-n)*Math.random())*e;s.push(mt(o,r,1))}return s.push(1),Oe(...s)},Ne=ut/2,Re=2*ut,Le={[_]:Se,Quad:Se(2),Cubic:Se(3),Quart:Se(4),Quint:Se(5),Sine:t=>1-rt(t*Ne),Circ:t=>1-st(1-t*t),Expo:t=>t?et(2,10*t-10):0,Bounce:t=>{let e,s=4;for(;t<((e=et(2,--s))-1)/11;);return 1/et(4,3-s)-7.5625*et((3*e-2)/22-t,2)},Back:(t=1.70158)=>e=>(+t+1)*e*e*e-+t*e*e,Elastic:(t=1,e=.3)=>{const s=mt(+t,1,10),i=mt(+e,p,2),r=i/Re*lt(1/s),n=Re/i;return t=>0===t||1===t?t:-s*et(2,-10*(1-t))*it((1-t-r)*n)}},Ae=(()=>{const t={linear:Oe,irregular:Be,steps:$e,cubicBezier:ke};for(let e in we)for(let s in Le){const i=Le[s],r=we[e];t[e+s]=s===_||"Back"===s||"Elastic"===s?(t,e)=>r(i(t,e)):r(i)}return t})(),De={linear:Te},Me=t=>Y(t)?t:U(t)?xe(t,Ae,De):Te,Fe=It(),Ie=It(),Pe={func:null},ze=[null],Xe=[null,null],Ue={to:null};let Ye,We,Ve=0;const He=(t,e)=>{const s={};if(P(t)){const e=[].concat(...t.map(t=>Object.keys(t))).filter(J);for(let i=0,r=e.length;i<r;i++){const r=e[i],n=t.map(t=>{const e={};for(let s in t){const i=t[s];J(s)?s===r&&(e.to=i):e[s]=i}return e});s[r]=n}}else{const i=Rt(e.duration,A.defaults.duration),r=Object.keys(t).map(e=>({o:parseFloat(e)/100,p:t[e]})).sort((t,e)=>t.o-e.o);r.forEach(t=>{const e=t.o,r=t.p;for(let t in r)if(J(t)){let n=s[t];n||(n=s[t]=[]);const o=e*i;let a=n.length,h=n[a-1];const l={to:r[t]};let c=0;for(let t=0;t<a;t++)c+=n[t].duration;1===a&&(l.from=h.to),r.ease&&(l.ease=r.ease),l.duration=o-(a?c:0),n.push(l)}return t});for(let t in s){const e=s[t];let i;for(let t=0,s=e.length;t<s;t++){const s=e[t],r=s.ease;s.ease=i||void 0,i=r}e[0].duration||e.shift()}}return s};class qe extends pe{constructor(t,e,s,n,a=!1,h=0,l=0){super(e,s,n);const c=_e(t),d=c.length,u=e.keyframes,m=u?St(He(u,e),e):e,{delay:g,duration:_,ease:y,playbackEase:v,modifier:b,composition:T,onRender:S}=m,w=s?s.defaults:A.defaults,x=Rt(v,w.playbackEase),E=x?Me(x):null,C=!W(y)&&!W(y.ease),k=C?y.ease:Rt(y,E?"linear":w.ease),$=C?y.duration:Rt(_,w.duration),O=Rt(g,w.delay),B=b||w.modifier,N=W(T)&&d>=f?o.none:W(T)?w.composition:T,R={},L=this._offset+(s?s._offset:0);let D=NaN,M=NaN,F=0,I=0;for(let t=0;t<d;t++){const e=c[t],n=h||t,u=l||d;let f=NaN,g=NaN;for(let t in m)if(J(t)){const h=At(e,t),l=Vt(t,e,h);let c=m[t];const d=P(c);if(a&&!d&&(Xe[0]=c,Xe[1]=c,c=Xe),d){const t=c.length,e=!z(c[0]);2===t&&e?(Ue.to=c,ze[0]=Ue,Ye=ze):t>2&&e?(Ye=[],c.forEach((t,e)=>{e?1===e?(Xe[1]=t,Ye.push(Xe)):Ye.push(t):Xe[0]=t})):Ye=c}else ze[0]=c,Ye=ze;let _=null,y=null,v=NaN,b=0,T=0;for(let t=Ye.length;T<t;T++){const i=Ye[T];z(i)?We=i:(Ue.to=i,We=Ue),Pe.func=null;const a=Lt(We.to,e,n,u,Pe);let c;z(a)&&!W(a.to)?(We=a,c=a.to):c=a;const d=Lt(We.from,e,n,u),m=We.ease,f=!W(m)&&!W(m.ease),g=f?m.ease:m||k,S=f?m.duration:Lt(Rt(We.duration,t>1?Lt($,e,n,u)/t:$),e,n,u),w=Lt(Rt(We.delay,T?0:O),e,n,u),x=Lt(Rt(We.composition,N),e,n,u),E=X(x)?x:o[x],C=We.modifier||B,A=!W(d),D=!W(c),M=P(c),U=M||A&&D,Y=y?b+w:w,V=gt(L+Y,12);I||!A&&!M||(I=1);let H=y;if(E!==o.none){_||(_=ie(e,l));let t=_._head;for(;t&&!t._isOverridden&&t._absoluteStartTime<=V;)if(H=t,t=t._nextRep,t&&t._absoluteStartTime>=V)for(;t;)ne(t),t=t._nextRep}if(U?(Pt(M?Lt(c[0],e,n,u):d,Fe),Pt(M?Lt(c[1],e,n,u,Pe):c,Ie),Fe.t===r.NUMBER&&(H?H._valueType===r.UNIT&&(Fe.t=r.UNIT,Fe.u=H._unit):(Pt(Mt(e,l,h,R),Xt),Xt.t===r.UNIT&&(Fe.t=r.UNIT,Fe.u=Xt.u)))):(D?Pt(c,Ie):y?zt(y,Ie):Pt(s&&H&&H.parent.parent===s?H._value:Mt(e,l,h,R),Ie),A?Pt(d,Fe):y?zt(y,Fe):Pt(s&&H&&H.parent.parent===s?H._value:Mt(e,l,h,R),Fe)),Fe.o&&(Fe.n=Ft(H?H._toNumber:Pt(Mt(e,l,h,R),Xt).n,Fe.n,Fe.o)),Ie.o&&(Ie.n=Ft(Fe.n,Ie.n,Ie.o)),Fe.t!==Ie.t)if(Fe.t===r.COMPLEX||Ie.t===r.COMPLEX){const t=Fe.t===r.COMPLEX?Fe:Ie,e=Fe.t===r.COMPLEX?Ie:Fe;e.t=r.COMPLEX,e.s=Tt(t.s),e.d=t.d.map(()=>e.n)}else if(Fe.t===r.UNIT||Ie.t===r.UNIT){const t=Fe.t===r.UNIT?Fe:Ie,e=Fe.t===r.UNIT?Ie:Fe;e.t=r.UNIT,e.u=t.u}else if(Fe.t===r.COLOR||Ie.t===r.COLOR){const t=Fe.t===r.COLOR?Fe:Ie,e=Fe.t===r.COLOR?Ie:Fe;e.t=r.COLOR,e.s=t.s,e.d=[0,0,0,1]}if(Fe.u!==Ie.u){let t=Ie.u?Fe:Ie;t=be(e,t,Ie.u?Ie.u:Fe.u,!1)}if(Ie.d&&Fe.d&&Ie.d.length!==Fe.d.length){const t=Fe.d.length>Ie.d.length?Fe:Ie,e=t===Fe?Ie:Fe;e.d=t.d.map((t,s)=>W(e.d[s])?0:e.d[s]),e.s=Tt(t.s)}const q=gt(+S||p,12),j={parent:this,id:Ve++,property:l,target:e,_value:null,_func:Pe.func,_ease:Me(g),_fromNumbers:Tt(Fe.d),_toNumbers:Tt(Ie.d),_strings:Tt(Ie.s),_fromNumber:Fe.n,_toNumber:Ie.n,_numbers:Tt(Fe.d),_number:Fe.n,_unit:Ie.u,_modifier:C,_currentTime:0,_startTime:Y,_delay:+w,_updateDuration:q,_changeDuration:q,_absoluteStartTime:V,_tweenType:h,_valueType:Ie.t,_composition:E,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};E!==o.none&&oe(j,_),isNaN(v)&&(v=j._startTime),b=gt(Y+q,12),y=j,F++,Et(this,j)}(isNaN(M)||v<M)&&(M=v),(isNaN(D)||b>D)&&(D=b),h===i.TRANSFORM&&(f=F-T,g=F)}if(!isNaN(f)){let t=0;wt(this,e=>{t>=f&&t<g&&(e._renderTransforms=1,e._composition===o.blend&&wt(jt.animation,t=>{t.id===e.id&&(t._renderTransforms=1)})),t++})}}d||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation."),M?(wt(this,t=>{t._startTime-t._delay||(t._delay-=M),t._startTime-=M}),D-=M):M=0,D||(D=p,this.iterationCount=0),this.targets=c,this.duration=D===p?p:vt((D+this._loopDelay)*this.iterationCount-this._loopDelay)||p,this.onRender=S||w.onRender,this._ease=E,this._delay=M,this.iterationDuration=D,this._inlineStyles=R,!this._autoplay&&I&&this.onRender(this)}stretch(t){const e=this.duration;if(e===bt(t))return this;const s=t/e;return wt(this,t=>{t._updateDuration=bt(t._updateDuration*s),t._changeDuration=bt(t._changeDuration*s),t._currentTime*=s,t._startTime*=s,t._absoluteStartTime*=s}),super.stretch(t)}refresh(){return wt(this,t=>{const e=t._func;if(e){const s=Mt(t.target,t.property,t._tweenType);Pt(s,Xt),Pt(e(),Ie),t._fromNumbers=Tt(Xt.d),t._fromNumber=Xt.n,t._toNumbers=Tt(Ie.d),t._strings=Tt(Ie.s),t._toNumber=Ie.o?Ft(Xt.n,Ie.n,Ie.o):Ie.n}}),this}revert(){return super.revert(),Ht(this)}then(t){return super.then(t)}}const je=(t,e)=>new qe(t,e,null,0,!1).init(),Qe={_head:null,_tail:null},Ge=(t,e,s)=>{let i=Qe._head;for(;i;){const r=i._next,n=i.$el===t,o=!e||i.property===e,a=!s||i.parent===s;if(n&&o&&a){const t=i.animation;try{t.commitStyles()}catch{}t.cancel(),xt(Qe,i);const e=i.parent;e&&(e._completed++,e.animations.length===e._completed&&(e.completed=!0,e.muteCallbacks||(e.paused=!0,e.onComplete(e),e._resolve(e))))}i=r}},Je=(t,e,s,i,r)=>{const n=e.animate(i,r),o=r.delay+ +r.duration*r.iterations;n.playbackRate=t._speed,t.paused&&n.pause(),t.duration<o&&(t.duration=o,t.controlAnimation=n),t.animations.push(n),Ge(e,s),Et(Qe,{parent:t,animation:n,$el:e,property:s,_next:null,_prev:null});const a=()=>{Ge(e,s,t)};return n.onremove=a,n.onfinish=a,n};function Ze(t,e,s){const i=_e(t);if(!i.length)return;const[n]=i,o=At(n,e),a=Vt(e,n,o);let h=Mt(n,a);if(W(s))return h;if(Pt(h,Xt),Xt.t===r.NUMBER||Xt.t===r.UNIT){if(!1===s)return Xt.n;{const t=be(n,Xt,s,!1);return`${gt(t.n,A.precision)}${t.u}`}}}const Ke=(t,e)=>{if(!W(e))return e.duration=p,e.composition=Rt(e.composition,o.none),new qe(t,e,null,0,!0).resume()},ts=(t,e,s)=>{const i=ge(t);for(let t=0,r=i.length;t<r;t++)Ge(i[t],s,e&&e.controlAnimation&&e);return le(i,e,s),i},es=(t,e)=>{if(F(e,"<")){const s="<"===e[1],i=t._tail,r=i?i._offset+i._delay:0;return s?r:r+i.duration}},ss=(t,e)=>{let s=t.iterationDuration;if(s===p&&(s=0),W(e))return s;if(X(+e))return+e;const i=e,r=t?t.labels:null,n=!V(r),o=es(t,i),a=!W(o),h=N.exec(i);if(h){const t=h[0],e=i.split(t),l=n&&e[0]?r[e[0]]:s,c=a?o:n?l:s,d=+e[1];return Ft(c,d,t[0])}return a?o:n?W(r[i])?s:r[i]:s};function is(t){return vt((t.iterationDuration+t._loopDelay)*t.iterationCount-t._loopDelay)||p}function rs(t,e,s,i,r,o){const a=X(t.duration)&&t.duration<=p?s-p:s;Yt(e,a,1,1,n.AUTO);const h=i?new qe(i,t,e,a,!1,r,o):new pe(t,e,a);return h.init(1),Et(e,h),wt(e,t=>{const s=t._offset+t._delay+t.duration;s>e.iterationDuration&&(e.iterationDuration=s)}),e.duration=is(e),e}class ns extends pe{constructor(t={}){super(t,null,0),this.duration=0,this.labels={};const e=t.defaults,s=A.defaults;this.defaults=e?St(e,s):s,this.onRender=t.onRender||s.onRender;const i=Rt(t.playbackEase,s.playbackEase);this._ease=i?Me(i):null,this.iterationDuration=0}add(t,e,s){const i=z(e),r=z(t);if(i||r){if(this._hasChildren=!0,i){const i=e;if(Y(s)){const e=s,r=ge(t),n=this.duration,o=this.iterationDuration,a=i.id;let h=0;const l=r.length;r.forEach(t=>{const s={...i};this.duration=n,this.iterationDuration=o,W(a)||(s.id=a+"-"+h),rs(s,this,ss(this,e(t,h,l,this)),t,h,l),h++})}else rs(i,this,ss(this,s),t)}else rs(t,this,ss(this,e));return this.init(1)}}sync(t,e){if(W(t)||t&&W(t.pause))return this;t.pause();const s=+(t.effect?t.effect.getTiming().duration:t.duration);return this.add(t,{currentTime:[0,s],duration:s,ease:"linear"},e)}set(t,e,s){return W(e)?this:(e.duration=p,e.composition=o.replace,this.add(t,e,s))}call(t,e){return W(t)||t&&!Y(t)?this:this.add({duration:0,onComplete:()=>t(this)},e)}label(t,e){return W(t)||t&&!U(t)||(this.labels[t]=ss(this,e)),this}remove(t,e){return le(ge(t),this,e),this}stretch(t){const e=this.duration;if(e===bt(t))return this;const s=t/e,i=this.labels;wt(this,t=>t.stretch(t.duration*s));for(let t in i)i[t]*=s;return super.stretch(t)}refresh(){return wt(this,t=>{t.refresh&&t.refresh()}),this}revert(){return super.revert(),wt(this,t=>t.revert,!0),Ht(this)}then(t){return super.then(t)}}const os=t=>new ns(t).init();class as{constructor(t,e){L.current&&L.current.register(this);const s=()=>{if(this.callbacks.completed)return;let t=!0;for(let e in this.animations)if(!this.animations[e].paused&&t){t=!1;break}t&&this.callbacks.complete()},i={onBegin:()=>{this.callbacks.completed&&this.callbacks.reset(),this.callbacks.play()},onComplete:s,onPause:s},r={v:1,autoplay:!1},n={};if(this.targets=[],this.animations={},this.callbacks=null,!W(t)&&!W(e)){for(let t in e){const s=e[t];J(t)?n[t]=s:F(t,"on")?r[t]=s:i[t]=s}this.callbacks=new qe({v:0},r);for(let e in n){const s=n[e],r=z(s);let a={},h="+=0";if(r){const t=s.unit;U(t)&&(h+=t)}else a.duration=s;a[e]=r?St({to:h},s):h;const l=St(i,a);l.composition=o.replace,l.autoplay=!1;const c=this.animations[e]=new qe(t,l,null,0,!1).init();this.targets.length||this.targets.push(...c.targets),this[e]=(t,e,s)=>{const i=c._head;if(W(t)&&i){const t=i._numbers;return t&&t.length?t:i._modifier(i._number)}return wt(c,e=>{if(P(t))for(let s=0,i=t.length;s<i;s++)W(e._numbers[s])||(e._fromNumbers[s]=e._modifier(e._numbers[s]),e._toNumbers[s]=t[s]);else e._fromNumber=e._modifier(e._number),e._toNumber=t;W(s)||(e._ease=Me(s)),e._currentTime=0}),W(e)||c.stretch(e),c.reset(1).resume(),this}}}}revert(){for(let t in this.animations)this[t]=T,this.animations[t].revert();return this.animations={},this.targets.length=0,this.callbacks&&this.callbacks.revert(),this}}const hs=(t,e)=>new as(t,e),ls=(t,e)=>(+t).toFixed(e),cs=(t,e,s)=>`${t}`.padStart(e,s),ds=(t,e,s)=>`${t}`.padEnd(e,s),us=(t,e,s)=>((t-e)%(s-e)+(s-e))%(s-e)+e,ps=(t,e,s,i,r)=>i+(t-e)/(s-e)*(r-i),ms=t=>t*Math.PI/180,fs=t=>180*t/Math.PI,gs=(t,e,s,i)=>i?1===i?e:yt(t,e,1-Math.exp(-i*s*.1)):t;var _s=Object.freeze({__proto__:null,clamp:mt,damp:gs,degToRad:ms,lerp:yt,mapRange:ps,padEnd:ds,padStart:cs,radToDeg:fs,round:gt,roundPad:ls,snap:_t,wrap:us});const ys=10*f;class vs{constructor(t={}){this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/f,this.maxIterations=this.maxDuration/this.timeStep/f,this.m=mt(Rt(t.mass,1),0,ys),this.s=mt(Rt(t.stiffness,100),1,ys),this.d=mt(Rt(t.damping,10),.1,ys),this.v=mt(Rt(t.velocity,0),-1e4,ys),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.solverDuration=0,this.duration=0,this.compute(),this.ease=t=>0===t||1===t?t:this.solve(t*this.solverDuration)}solve(t){const{zeta:e,w0:s,wd:i,b:r}=this;let n=t;return n=e<1?ot(-n*e*s)*(1*rt(i*n)+r*it(i*n)):(1+r*n)*ot(-n*s),1-n}compute(){const{maxRestSteps:t,maxIterations:e,restThreshold:s,timeStep:i,m:r,d:n,s:o,v:a}=this,h=this.w0=mt(st(o/r),p,f),l=this.zeta=n/(2*st(o*r)),c=this.wd=l<1?h*st(1-l*l):0;this.b=l<1?(l*h-a)/c:-a+h;let d=0,u=0,m=0;for(;u<t&&m<e;)nt(1-this.solve(d))<s?u++:u=0,this.solverDuration=d,d+=i,m++;this.duration=gt(this.solverDuration*f,0)*A.timeScale}get mass(){return this.m}set mass(t){this.m=mt(Rt(t,1),0,ys),this.compute()}get stiffness(){return this.s}set stiffness(t){this.s=mt(Rt(t,100),1,ys),this.compute()}get damping(){return this.d}set damping(t){this.d=mt(Rt(t,10),.1,ys),this.compute()}get velocity(){return this.v}set velocity(t){this.v=mt(Rt(t,0),-1e4,ys),this.compute()}}const bs=t=>new vs(t),Ts=t=>{t.cancelable&&t.preventDefault()};class Ss{constructor(t){this.el=t,this.zIndex=0,this.parentElement=null,this.classList={add:T,remove:T}}get x(){return this.el.x||0}set x(t){this.el.x=t}get y(){return this.el.y||0}set y(t){this.el.y=t}get width(){return this.el.width||0}set width(t){this.el.width=t}get height(){return this.el.height||0}set height(t){this.el.height=t}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class ws{constructor(t){this.$el=t,this.inlineTransforms=[],this.point=new DOMPoint,this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(t,e){return this.point.x=t,this.point.y=e,this.point.matrixTransform(this.inversedMatrix)}traverseUp(t){let e=this.$el.parentElement,i=0;for(;e&&e!==s;)t(e,i),e=e.parentElement,i++}getMatrix(){const t=new DOMMatrix;return this.traverseUp(e=>{const s=getComputedStyle(e).transform;if(s){const e=new DOMMatrix(s);t.preMultiplySelf(e)}}),t}remove(){this.traverseUp((t,e)=>{this.inlineTransforms[e]=t.style.transform,t.style.transform="none"})}revert(){this.traverseUp((t,e)=>{const s=this.inlineTransforms[e];""===s?t.style.removeProperty("transform"):t.style.transform=s})}}const xs=(t,e)=>t&&Y(t)?t(e):t;let Es=0;class Cs{constructor(t,i={}){if(!t)return;L.current&&L.current.register(this);const r=i.x,n=i.y,o=i.trigger,a=i.modifier,h=i.releaseEase,l=h&&Me(h),c=!W(h)&&!W(h.ease),d=z(r)&&!W(r.mapTo)?r.mapTo:"translateX",u=z(n)&&!W(n.mapTo)?n.mapTo:"translateY",p=xs(i.container,this);this.containerArray=P(p)?p:null,this.$container=p&&!this.containerArray?ge(p)[0]:s.body,this.useWin=this.$container===s.body,this.$scrollContainer=this.useWin?e:this.$container,this.$target=z(t)?new Ss(t):ge(t)[0],this.$trigger=ge(o||t)[0],this.fixed="fixed"===Ze(this.$target,"position"),this.isFinePointer=!0,this.containerPadding=[0,0,0,0],this.containerFriction=0,this.releaseContainerFriction=0,this.snapX=0,this.snapY=0,this.scrollSpeed=0,this.scrollThreshold=0,this.dragSpeed=0,this.maxVelocity=0,this.minVelocity=0,this.velocityMultiplier=0,this.cursor=!1,this.releaseXSpring=c?h:bs({mass:Rt(i.releaseMass,1),stiffness:Rt(i.releaseStiffness,80),damping:Rt(i.releaseDamping,20)}),this.releaseYSpring=c?h:bs({mass:Rt(i.releaseMass,1),stiffness:Rt(i.releaseStiffness,80),damping:Rt(i.releaseDamping,20)}),this.releaseEase=l||Ae.outQuint,this.hasReleaseSpring=c,this.onGrab=i.onGrab||T,this.onDrag=i.onDrag||T,this.onRelease=i.onRelease||T,this.onUpdate=i.onUpdate||T,this.onSettle=i.onSettle||T,this.onSnap=i.onSnap||T,this.onResize=i.onResize||T,this.onAfterResize=i.onAfterResize||T,this.disabled=[0,0];const f={};if(a&&(f.modifier=a),W(r)||!0===r)f[d]=0;else if(z(r)){const t=r,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[d]=e}else!1===r&&(f[d]=0,this.disabled[0]=1);if(W(n)||!0===n)f[u]=0;else if(z(n)){const t=n,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[u]=e}else!1===n&&(f[u]=0,this.disabled[1]=1);this.animate=new as(this.$target,f),this.xProp=d,this.yProp=u,this.destX=0,this.destY=0,this.deltaX=0,this.deltaY=0,this.scroll={x:0,y:0},this.coords=[this.x,this.y,0,0],this.snapped=[0,0],this.pointer=[0,0,0,0,0,0,0,0],this.scrollView=[0,0],this.dragArea=[0,0,0,0],this.containerBounds=[-m,m,m,-m],this.scrollBounds=[0,0,0,0],this.targetBounds=[0,0,0,0],this.window=[0,0],this.velocityStack=[0,0,0],this.velocityStackIndex=0,this.velocityTime=I(),this.velocity=0,this.angle=0,this.cursorStyles=null,this.triggerStyles=null,this.bodyStyles=null,this.targetStyles=null,this.touchActionStyles=null,this.transforms=new ws(this.$target),this.overshootCoords={x:0,y:0},this.overshootTicker=new pe({autoplay:!1,onUpdate:()=>{this.updated=!0,this.manual=!0,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,1),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=!1,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,0),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init(),this.updateTicker=new pe({autoplay:!1,onUpdate:()=>this.update()},null,0).init(),this.contained=!W(p),this.manual=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.enabled=!1,this.initialized=!1,this.activeProp=this.disabled[1]?d:u,this.animate.callbacks.onRender=()=>{const t=this.updated,e=!(this.grabbed&&t)&&this.released,s=this.x,i=this.y,r=s-this.coords[2],n=i-this.coords[3];this.deltaX=r,this.deltaY=n,this.coords[2]=s,this.coords[3]=i,t&&(r||n)&&this.onUpdate(this),e?(this.computeVelocity(r,n),this.angle=dt(n,r)):this.updated=!1},this.animate.callbacks.onComplete=()=>{!this.grabbed&&this.released&&(this.released=!1),this.manual||(this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.onSettle(this))},this.resizeTicker=new pe({autoplay:!1,duration:150*A.timeScale,onComplete:()=>{this.onResize(this),this.refresh(),this.onAfterResize(this)}}).init(),this.parameters=i,this.resizeObserver=new ResizeObserver(()=>{this.initialized?this.resizeTicker.restart():this.initialized=!0}),this.enable(),this.refresh(),this.resizeObserver.observe(this.$container),z(t)||this.resizeObserver.observe(this.$target)}computeVelocity(t,e){const s=this.velocityTime,i=I(),r=i-s;if(r<17)return this.velocity;this.velocityTime=i;const n=this.velocityStack,o=this.velocityMultiplier,a=this.minVelocity,h=this.maxVelocity,l=this.velocityStackIndex;n[l]=gt(mt(st(t*t+e*e)/r*o,a,h),5);const c=ct(n[0],n[1],n[2]);return this.velocity=c,this.velocityStackIndex=(l+1)%3,c}setX(t,e=!1){if(this.disabled[0])return;const s=gt(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destX=s,this.snapped[0]=_t(s,this.snapX),this.animate[this.xProp](s,0),this.manual=!1,this}setY(t,e=!1){if(this.disabled[1])return;const s=gt(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destY=s,this.snapped[1]=_t(s,this.snapY),this.animate[this.yProp](s,0),this.manual=!1,this}get x(){return gt(this.animate[this.xProp](),A.precision)}set x(t){this.setX(t,!1)}get y(){return gt(this.animate[this.yProp](),A.precision)}set y(t){this.setY(t,!1)}get progressX(){return ps(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(t){this.setX(ps(t,0,1,this.containerBounds[3],this.containerBounds[1]),!1)}get progressY(){return ps(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(t){this.setY(ps(t,0,1,this.containerBounds[0],this.containerBounds[2]),!1)}updateScrollCoords(){const t=gt(this.useWin?e.scrollX:this.$container.scrollLeft,0),s=gt(this.useWin?e.scrollY:this.$container.scrollTop,0),[i,r,n,o]=this.containerPadding,a=this.scrollThreshold;this.scroll.x=t,this.scroll.y=s,this.scrollBounds[0]=s-this.targetBounds[0]+i-a,this.scrollBounds[1]=t-this.targetBounds[1]-r+a,this.scrollBounds[2]=s-this.targetBounds[2]-n+a,this.scrollBounds[3]=t-this.targetBounds[3]+o-a}updateBoundingValues(){const t=this.$container;if(!t)return;const i=this.x,r=this.y,n=this.coords[2],o=this.coords[3];this.coords[2]=0,this.coords[3]=0,this.setX(0,!0),this.setY(0,!0),this.transforms.remove();const a=this.window[0]=e.innerWidth,h=this.window[1]=e.innerHeight,l=this.useWin,c=t.scrollWidth,d=t.scrollHeight,u=this.fixed,p=t.getBoundingClientRect(),[m,f,g,_]=this.containerPadding;this.dragArea[0]=l?0:p.left,this.dragArea[1]=l?0:p.top,this.scrollView[0]=l?mt(c,a,c):c,this.scrollView[1]=l?mt(d,h,d):d,this.updateScrollCoords();const{width:y,height:v,left:b,top:T,right:S,bottom:w}=t.getBoundingClientRect();this.dragArea[2]=gt(l?mt(y,a,a):y,0),this.dragArea[3]=gt(l?mt(v,h,h):v,0);const x=Ze(t,"overflow"),E="visible"===x,C="hidden"===x;if(this.canScroll=!u&&this.contained&&(t===s.body&&E||!C&&!E)&&(c>this.dragArea[2]+_-f||d>this.dragArea[3]+m-g)&&(!this.containerArray||this.containerArray&&!P(this.containerArray)),this.contained){const e=this.scroll.x,s=this.scroll.y,i=this.canScroll,r=this.$target.getBoundingClientRect(),n=i?l?0:t.scrollLeft:0,o=i?l?0:t.scrollTop:0,c=i?this.scrollView[0]-n-y:0,d=i?this.scrollView[1]-o-v:0;this.targetBounds[0]=gt(r.top+s-(l?0:T),0),this.targetBounds[1]=gt(r.right+e-(l?a:S),0),this.targetBounds[2]=gt(r.bottom+s-(l?h:w),0),this.targetBounds[3]=gt(r.left+e-(l?0:b),0),this.containerArray?(this.containerBounds[0]=this.containerArray[0]+m,this.containerBounds[1]=this.containerArray[1]-f,this.containerBounds[2]=this.containerArray[2]-g,this.containerBounds[3]=this.containerArray[3]+_):(this.containerBounds[0]=-gt(r.top-(u?mt(T,0,h):T)+o-m,0),this.containerBounds[1]=-gt(r.right-(u?mt(S,0,a):S)-c+f,0),this.containerBounds[2]=-gt(r.bottom-(u?mt(w,0,h):w)-d+g,0),this.containerBounds[3]=-gt(r.left-(u?mt(b,0,a):b)+n-_,0))}this.transforms.revert(),this.coords[2]=n,this.coords[3]=o,this.setX(i,!0),this.setY(r,!0)}isOutOfBounds(t,e,s){if(!this.contained)return 0;const[i,r,n,o]=t,[a,h]=this.disabled,l=!a&&e<o||!a&&e>r,c=!h&&s<i||!h&&s>n;return l&&!c?1:!l&&c?2:l&&c?3:0}refresh(){const t=this.parameters,i=t.x,r=t.y,n=xs(t.container,this),o=xs(t.containerPadding,this)||0,a=P(o)?o:[o,o,o,o],h=this.x,l=this.y,c=xs(t.cursor,this),d={onHover:"grab",onGrab:"grabbing"};if(c){const{onHover:t,onGrab:e}=c;t&&(d.onHover=t),e&&(d.onGrab=e)}this.containerArray=P(n)?n:null,this.$container=n&&!this.containerArray?ge(n)[0]:s.body,this.useWin=this.$container===s.body,this.$scrollContainer=this.useWin?e:this.$container,this.isFinePointer=matchMedia("(pointer:fine)").matches,this.containerPadding=Rt(a,[0,0,0,0]),this.containerFriction=mt(Rt(xs(t.containerFriction,this),.8),0,1),this.releaseContainerFriction=mt(Rt(xs(t.releaseContainerFriction,this),this.containerFriction),0,1),this.snapX=xs(z(i)&&!W(i.snap)?i.snap:t.snap,this),this.snapY=xs(z(r)&&!W(r.snap)?r.snap:t.snap,this),this.scrollSpeed=Rt(xs(t.scrollSpeed,this),1.5),this.scrollThreshold=Rt(xs(t.scrollThreshold,this),20),this.dragSpeed=Rt(xs(t.dragSpeed,this),1),this.minVelocity=Rt(xs(t.minVelocity,this),0),this.maxVelocity=Rt(xs(t.maxVelocity,this),50),this.velocityMultiplier=Rt(xs(t.velocityMultiplier,this),1),this.cursor=!1!==c&&d,this.updateBoundingValues();const[u,p,m,f]=this.containerBounds;this.setX(mt(h,f,p),!0),this.setY(mt(l,u,m),!0)}update(){if(this.updateScrollCoords(),this.canScroll){const[t,e,s,i]=this.containerPadding,[r,n]=this.scrollView,o=this.dragArea[2],a=this.dragArea[3],h=this.scroll.x,l=this.scroll.y,c=this.$container.scrollWidth,d=this.$container.scrollHeight,u=this.useWin?mt(c,this.window[0],c):c,p=this.useWin?mt(d,this.window[1],d):d,m=r-u,f=n-p;this.dragged&&m>0&&(this.coords[0]-=m,this.scrollView[0]=u),this.dragged&&f>0&&(this.coords[1]-=f,this.scrollView[1]=p);const g=10*this.scrollSpeed,_=this.scrollThreshold,[y,v]=this.coords,[b,T,S,w]=this.scrollBounds,x=gt(mt((v-b+t)/_,-1,0)*g,0),E=gt(mt((y-T-e)/_,0,1)*g,0),C=gt(mt((v-S-s)/_,0,1)*g,0),k=gt(mt((y-w+i)/_,-1,0)*g,0);if(x||C||k||E){const[t,e]=this.disabled;let s=h,i=l;t||(s=gt(mt(h+(k||E),0,r-o),0),this.coords[0]-=h-s),e||(i=gt(mt(l+(x||C),0,n-a),0),this.coords[1]-=l-i),this.useWin?this.$scrollContainer.scrollBy(-(h-s),-(l-i)):this.$scrollContainer.scrollTo(s,i)}}const[t,e,s,i]=this.containerBounds,[r,n,o,a,h,l]=this.pointer;this.coords[0]+=(r-h)*this.dragSpeed,this.coords[1]+=(n-l)*this.dragSpeed,this.pointer[4]=r,this.pointer[5]=n;const[c,d]=this.coords,[u,p]=this.snapped,m=(1-this.containerFriction)*this.dragSpeed;this.setX(c>e?e+(c-e)*m:c<i?i+(c-i)*m:c,!1),this.setY(d>s?s+(d-s)*m:d<t?t+(d-t)*m:d,!1),this.computeVelocity(r-h,n-l),this.angle=dt(n-a,r-o);const[f,g]=this.snapped;(f!==u&&this.snapX||g!==p&&this.snapY)&&this.onSnap(this)}stop(){this.updateTicker.pause(),this.overshootTicker.pause();for(let t in this.animate.animations)this.animate.animations[t].pause();return le([this],null,"x"),le([this],null,"y"),le([this],null,"progressX"),le([this],null,"progressY"),le([this.scroll]),le([this.overshootCoords]),this}scrollInView(t,e=0,s=Ae.inOutQuad){this.updateScrollCoords();const i=this.destX,r=this.destY,n=this.scroll,o=this.scrollBounds,a=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(o,i,r)){const[h,l,c,d]=o,u=gt(mt(r-h,-m,0),0),p=gt(mt(i-l,0,m),0),f=gt(mt(r-c,0,m),0),g=gt(mt(i-d,-m,0),0);new qe(n,{x:gt(n.x+(g?g-e:p?p+e:0),0),y:gt(n.y+(u?u-e:f?f+e:0),0),duration:W(t)?350*A.timeScale:t,ease:s,onUpdate:()=>{this.canScroll=!1,this.$scrollContainer.scrollTo(n.x,n.y)}}).init().then(()=>{this.canScroll=a})}return this}handleHover(){this.isFinePointer&&this.cursor&&!this.cursorStyles&&(this.cursorStyles=Ke(this.$trigger,{cursor:this.cursor.onHover}))}animateInView(t,e=0,s=Ae.inOutQuad){this.stop(),this.updateBoundingValues();const i=this.x,r=this.y,[n,o,a,h]=this.containerPadding,l=this.scroll.y-this.targetBounds[0]+n+e,c=this.scroll.x-this.targetBounds[1]-o-e,d=this.scroll.y-this.targetBounds[2]-a-e,u=this.scroll.x-this.targetBounds[3]+h+e,p=this.isOutOfBounds([l,c,d,u],i,r);if(p){const[e,n]=this.disabled,o=mt(_t(i,this.snapX),u,c),a=mt(_t(r,this.snapY),l,d),h=W(t)?350*A.timeScale:t;e||1!==p&&3!==p||this.animate[this.xProp](o,h,s),n||2!==p&&3!==p||this.animate[this.yProp](a,h,s)}return this}handleDown(t){const e=t.target;if(this.grabbed||"range"===e.type)return;t.stopPropagation(),this.grabbed=!0,this.released=!1,this.stop(),this.updateBoundingValues();const i=t.changedTouches,r=i?i[0].clientX:t.clientX,n=i?i[0].clientY:t.clientY,{x:o,y:a}=this.transforms.normalizePoint(r,n),[h,l,c,d]=this.containerBounds,u=(1-this.containerFriction)*this.dragSpeed,p=this.x,m=this.y;this.coords[0]=this.coords[2]=u?p>l?l+(p-l)/u:p<d?d+(p-d)/u:p:p,this.coords[1]=this.coords[3]=u?m>c?c+(m-c)/u:m<h?h+(m-h)/u:m:m,this.pointer[0]=o,this.pointer[1]=a,this.pointer[2]=o,this.pointer[3]=a,this.pointer[4]=o,this.pointer[5]=a,this.pointer[6]=o,this.pointer[7]=a,this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null);const f=Ze(this.$target,"zIndex",!1);Es=(f>Es?f:Es)+1,this.targetStyles=Ke(this.$target,{zIndex:Es}),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.isFinePointer&&this.cursor&&(this.bodyStyles=Ke(s.body,{cursor:this.cursor.onGrab})),this.scrollInView(100,0,Ae.out(3)),this.onGrab(this),s.addEventListener("touchmove",this),s.addEventListener("touchend",this),s.addEventListener("touchcancel",this),s.addEventListener("mousemove",this),s.addEventListener("mouseup",this),s.addEventListener("selectstart",this)}handleMove(t){if(!this.grabbed)return;const e=t.changedTouches,s=e?e[0].clientX:t.clientX,i=e?e[0].clientY:t.clientY,{x:r,y:n}=this.transforms.normalizePoint(s,i),o=r-this.pointer[6],a=n-this.pointer[7];let h=t.target,l=!1,c=!1,d=!1;for(;e&&h&&h!==this.$trigger;){const t=Ze(h,"overflow-y");if("hidden"!==t&&"visible"!==t){const{scrollTop:t,scrollHeight:e,clientHeight:s}=h;if(e>s){d=!0,l=t<=3,c=t>=e-s-3;break}}h=h.parentElement}d&&(!l&&!c||l&&a<0||c&&a>0)?(this.pointer[0]=r,this.pointer[1]=n,this.pointer[2]=r,this.pointer[3]=n,this.pointer[4]=r,this.pointer[5]=n,this.pointer[6]=r,this.pointer[7]=n):(Ts(t),this.triggerStyles||(this.triggerStyles=Ke(this.$trigger,{pointerEvents:"none"})),this.$trigger.addEventListener("touchstart",Ts,{passive:!1}),this.$trigger.addEventListener("touchmove",Ts,{passive:!1}),this.$trigger.addEventListener("touchend",Ts),(!this.disabled[0]&&nt(o)>3||!this.disabled[1]&&nt(a)>3)&&(this.updateTicker.resume(),this.pointer[2]=this.pointer[0],this.pointer[3]=this.pointer[1],this.pointer[0]=r,this.pointer[1]=n,this.dragged=!0,this.released=!1,this.onDrag(this)))}handleUp(){if(!this.grabbed)return;this.updateTicker.pause(),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null);const[t,e]=this.disabled,[i,r,n,a,h,l]=this.pointer,[c,d,u,p]=this.containerBounds,[m,f]=this.snapped,g=this.releaseXSpring,_=this.releaseYSpring,y=this.releaseEase,v=this.hasReleaseSpring,b=this.overshootCoords,T=this.x,S=this.y,w=this.computeVelocity(i-h,r-l),x=this.angle=dt(r-a,i-n),E=150*w,C=(1-this.releaseContainerFriction)*this.dragSpeed,k=T+rt(x)*E,$=S+it(x)*E,O=k>d?d+(k-d)*C:k<p?p+(k-p)*C:k,B=$>u?u+($-u)*C:$<c?c+($-c)*C:$,N=this.destX=mt(gt(_t(O,this.snapX),5),p,d),R=this.destY=mt(gt(_t(B,this.snapY),5),c,u),L=this.isOutOfBounds(this.containerBounds,k,$);let D=0,M=0,F=y,I=y,P=0;if(b.x=T,b.y=S,!t){const t=N===d?T>d?-1:1:T<p?-1:1,s=gt(T-N,0);g.velocity=e&&v?s?E*t/nt(s):0:w;const{ease:i,duration:r,restDuration:n}=g;D=T===N?0:v?r:r-n*A.timeScale,v&&(F=i),D>P&&(P=D)}if(!e){const e=R===u?S>u?-1:1:S<c?-1:1,s=gt(S-R,0);_.velocity=t&&v?s?E*e/nt(s):0:w;const{ease:i,duration:r,restDuration:n}=_;M=S===R?0:v?r:r-n*A.timeScale,v&&(I=i),M>P&&(P=M)}if(!v&&L&&C&&(D||M)){const t=o.blend;new qe(b,{x:{to:O,duration:.65*D},y:{to:B,duration:.65*M},ease:y,composition:t}).init(),new qe(b,{x:{to:N,duration:D},y:{to:R,duration:M},ease:y,composition:t}).init(),this.overshootTicker.stretch(ct(D,M)).restart()}else t||this.animate[this.xProp](N,D,F),e||this.animate[this.yProp](R,M,I);this.scrollInView(P,this.scrollThreshold,y);let z=!1;N!==m&&(this.snapped[0]=N,this.snapX&&(z=!0)),R!==f&&this.snapY&&(this.snapped[1]=R,this.snapY&&(z=!0)),z&&this.onSnap(this),this.grabbed=!1,this.dragged=!1,this.updated=!0,this.released=!0,this.onRelease(this),this.$trigger.removeEventListener("touchstart",Ts),this.$trigger.removeEventListener("touchmove",Ts),this.$trigger.removeEventListener("touchend",Ts),s.removeEventListener("touchmove",this),s.removeEventListener("touchend",this),s.removeEventListener("touchcancel",this),s.removeEventListener("mousemove",this),s.removeEventListener("mouseup",this),s.removeEventListener("selectstart",this)}reset(){return this.stop(),this.resizeTicker.pause(),this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.setX(0,!0),this.setY(0,!0),this.coords[0]=0,this.coords[1]=0,this.pointer[0]=0,this.pointer[1]=0,this.pointer[2]=0,this.pointer[3]=0,this.pointer[4]=0,this.pointer[5]=0,this.pointer[6]=0,this.pointer[7]=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this}enable(){return this.enabled||(this.enabled=!0,this.$target.classList.remove("is-disabled"),this.touchActionStyles=Ke(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"}),this.$trigger.addEventListener("touchstart",this,{passive:!0}),this.$trigger.addEventListener("mousedown",this,{passive:!0}),this.$trigger.addEventListener("mouseenter",this)),this}disable(){return this.enabled=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.touchActionStyles.revert(),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null),this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null),this.$target.classList.add("is-disabled"),this.$trigger.removeEventListener("touchstart",this),this.$trigger.removeEventListener("mousedown",this),this.$trigger.removeEventListener("mouseenter",this),s.removeEventListener("touchmove",this),s.removeEventListener("touchend",this),s.removeEventListener("touchcancel",this),s.removeEventListener("mousemove",this),s.removeEventListener("mouseup",this),s.removeEventListener("selectstart",this),this}revert(){return this.reset(),this.disable(),this.$target.classList.remove("is-disabled"),this.updateTicker.revert(),this.overshootTicker.revert(),this.resizeTicker.revert(),this.animate.revert(),this.resizeObserver.disconnect(),this}handleEvent(t){switch(t.type){case"mousedown":case"touchstart":this.handleDown(t);break;case"mousemove":case"touchmove":this.handleMove(t);break;case"mouseup":case"touchend":case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":Ts(t)}}}const ks=(t,e)=>new Cs(t,e),$s=(t=T)=>new pe({duration:1*A.timeScale,onComplete:t},null,0).resume(),Os=t=>{let e;return(...s)=>{let i,r,n,o;e&&(i=e.currentIteration,r=e.iterationProgress,n=e.reversed,o=e._alternate,e.revert());const a=t(...s);return a&&!Y(a)&&a.revert&&(e=a),W(r)||(e.currentIteration=i,e.iterationProgress=(o&&i%2?!n:n)?1-r:r),a||T}};class Bs{constructor(t={}){L.current&&L.current.register(this);const i=t.root;let r=s;i&&(r=i.current||i.nativeElement||ge(i)[0]||s);const n=t.defaults,o=A.defaults,a=t.mediaQueries;if(this.defaults=n?St(n,o):o,this.root=r,this.constructors=[],this.revertConstructors=[],this.revertibles=[],this.constructorsOnce=[],this.revertConstructorsOnce=[],this.revertiblesOnce=[],this.once=!1,this.onceIndex=0,this.methods={},this.matches={},this.mediaQueryLists={},this.data={},a)for(let t in a){const s=e.matchMedia(a[t]);this.mediaQueryLists[t]=s,s.addEventListener("change",this)}}register(t){(this.once?this.revertiblesOnce:this.revertibles).push(t)}execute(t){let e=L.current,s=L.root,i=A.defaults;L.current=this,L.root=this.root,A.defaults=this.defaults;const r=this.mediaQueryLists;for(let t in r)this.matches[t]=r[t].matches;const n=t(this);return L.current=e,L.root=s,A.defaults=i,n}refresh(){return this.onceIndex=0,this.execute(()=>{let t=this.revertibles.length,e=this.revertConstructors.length;for(;t--;)this.revertibles[t].revert();for(;e--;)this.revertConstructors[e](this);this.revertibles.length=0,this.revertConstructors.length=0,this.constructors.forEach(t=>{const e=t(this);Y(e)&&this.revertConstructors.push(e)})}),this}add(t,e){if(this.once=!1,Y(t)){const e=t;this.constructors.push(e),this.execute(()=>{const t=e(this);Y(t)&&this.revertConstructors.push(t)})}else this.methods[t]=(...t)=>this.execute(()=>e(...t));return this}addOnce(t){if(this.once=!0,Y(t)){const e=this.onceIndex++;if(this.constructorsOnce[e])return this;const s=t;this.constructorsOnce[e]=s,this.execute(()=>{const t=s(this);Y(t)&&this.revertConstructorsOnce.push(t)})}return this}keepTime(t){this.once=!0;const e=this.onceIndex++,s=this.constructorsOnce[e];if(Y(s))return s(this);const i=Os(t);let r;return this.constructorsOnce[e]=i,this.execute(()=>{r=i(this)}),r}handleEvent(t){"change"===t.type&&this.refresh()}revert(){const t=this.revertibles,e=this.revertConstructors,s=this.revertiblesOnce,i=this.revertConstructorsOnce,r=this.mediaQueryLists;let n=t.length,o=e.length,a=s.length,h=i.length;for(;n--;)t[n].revert();for(;o--;)e[o](this);for(;a--;)s[a].revert();for(;h--;)i[h](this);for(let t in r)r[t].removeEventListener("change",this);t.length=0,e.length=0,this.constructors.length=0,s.length=0,i.length=0,this.constructorsOnce.length=0,this.onceIndex=0,this.matches={},this.methods={},this.mediaQueryLists={},this.data={}}}const Ns=t=>new Bs(t),Rs=()=>{const t=s.createElement("div");s.body.appendChild(t),t.style.height="100lvh";const e=t.offsetHeight;return s.body.removeChild(t),e},Ls=(t,e)=>t&&Y(t)?t(e):t,As=new Map;class Ds{constructor(t){this.element=t,this.useWin=this.element===s.body,this.winWidth=0,this.winHeight=0,this.width=0,this.height=0,this.left=0,this.top=0,this.zIndex=0,this.scrollX=0,this.scrollY=0,this.prevScrollX=0,this.prevScrollY=0,this.scrollWidth=0,this.scrollHeight=0,this.velocity=0,this.backwardX=!1,this.backwardY=!1,this.scrollTicker=new pe({autoplay:!1,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const t=this.backwardX||this.backwardY;wt(this,t=>t.handleScroll(),t)},onComplete:()=>this.dataTimer.pause()}).init(),this.dataTimer=new pe({autoplay:!1,frameRate:30,onUpdate:t=>{const e=t.deltaTime,s=this.prevScrollX,i=this.prevScrollY,r=this.scrollX,n=this.scrollY,o=s-r,a=i-n;this.prevScrollX=r,this.prevScrollY=n,o&&(this.backwardX=s>r),a&&(this.backwardY=i>n),this.velocity=gt(e>0?Math.sqrt(o*o+a*a)/e:0,5)}}).init(),this.resizeTicker=new pe({autoplay:!1,duration:250*A.timeScale,onComplete:()=>{this.updateWindowBounds(),this.refreshScrollObservers(),this.handleScroll()}}).init(),this.wakeTicker=new pe({autoplay:!1,duration:500*A.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init(),this._head=null,this._tail=null,this.updateScrollCoords(),this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll(),this.resizeObserver=new ResizeObserver(()=>this.resizeTicker.restart()),this.resizeObserver.observe(this.element),(this.useWin?e:this.element).addEventListener("scroll",this,!1)}updateScrollCoords(){const t=this.useWin,s=this.element;this.scrollX=gt(t?e.scrollX:s.scrollLeft,0),this.scrollY=gt(t?e.scrollY:s.scrollTop,0)}updateWindowBounds(){this.winWidth=e.innerWidth,this.winHeight=Rs()}updateBounds(){const t=getComputedStyle(this.element),e=this.element;let s,i;if(this.scrollWidth=e.scrollWidth+parseFloat(t.marginLeft)+parseFloat(t.marginRight),this.scrollHeight=e.scrollHeight+parseFloat(t.marginTop)+parseFloat(t.marginBottom),this.updateWindowBounds(),this.useWin)s=this.winWidth,i=this.winHeight;else{const t=e.getBoundingClientRect();s=e.clientWidth,i=e.clientHeight,this.top=t.top,this.left=t.left}this.width=s,this.height=i}refreshScrollObservers(){wt(this,t=>{t._debug&&t.removeDebug()}),this.updateBounds(),wt(this,t=>{t.refresh(),t._debug&&t.debug()})}refresh(){this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll()}handleScroll(){this.updateScrollCoords(),this.wakeTicker.restart()}handleEvent(t){"scroll"===t.type&&this.handleScroll()}revert(){this.scrollTicker.cancel(),this.dataTimer.cancel(),this.resizeTicker.cancel(),this.wakeTicker.cancel(),this.resizeObserver.disconnect(),(this.useWin?e:this.element).removeEventListener("scroll",this),As.delete(this.element)}}const Ms=t=>{const e=t&&ge(t)[0]||s.body;let i=As.get(e);return i||(i=new Ds(e),As.set(e,i)),i},Fs=(t,e,s,i,r)=>{const n="min"===e,o="max"===e,a="top"===e||"left"===e||"start"===e||n?0:"bottom"===e||"right"===e||"end"===e||o?"100%":"center"===e?"50%":e,{n:h,u:l}=Pt(a,Xt);let c=h;return"%"===l?c=h/100*s:l&&(c=be(t,Xt,"px",!0).n),o&&i<0&&(c+=i),n&&r>0&&(c+=r),c},Is=(t,e,s,i,r)=>{let n;if(U(e)){const o=N.exec(e);if(o){const a=o[0],h=a[0],l=e.split(a),c="min"===l[0],d="max"===l[0],u=Fs(t,l[0],s,i,r),p=Fs(t,l[1],s,i,r);if(c){const e=Ft(Fs(t,"min",s),p,h);n=e<u?u:e}else if(d){const e=Ft(Fs(t,"max",s),p,h);n=e>u?u:e}else n=Ft(u,p,h)}else n=Fs(t,e,s,i,r)}else n=e;return gt(n,0)},Ps=t=>{let e;const s=t.targets;for(let t=0,i=s.length;t<i;t++){const i=s[t];if(i[h]){e=i;break}}return e};let zs=0;const Xs=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class Us{constructor(t={}){L.current&&L.current.register(this);const e=Rt(t.sync,"play pause"),i=e?Me(e):null,r=e&&("linear"===e||e===Te),n=e&&!(i===Te&&!r),o=e&&(X(e)||!0===e||r),a=e&&U(e)&&!n&&!o,h=a?e.split(" ").map(t=>()=>{const e=this.linked;return e&&e[t]?e[t]():null}):null,l=a&&h.length>2;this.index=zs++,this.id=W(t.id)?this.index:t.id,this.container=Ms(t.container),this.target=null,this.linked=null,this.repeat=null,this.horizontal=null,this.enter=null,this.leave=null,this.sync=n||o||!!h,this.syncEase=n?i:null,this.syncSmooth=o?!0===e||r?1:e:null,this.onSyncEnter=h&&!l&&h[0]?h[0]:T,this.onSyncLeave=h&&!l&&h[1]?h[1]:T,this.onSyncEnterForward=h&&l&&h[0]?h[0]:T,this.onSyncLeaveForward=h&&l&&h[1]?h[1]:T,this.onSyncEnterBackward=h&&l&&h[2]?h[2]:T,this.onSyncLeaveBackward=h&&l&&h[3]?h[3]:T,this.onEnter=t.onEnter||T,this.onLeave=t.onLeave||T,this.onEnterForward=t.onEnterForward||T,this.onLeaveForward=t.onLeaveForward||T,this.onEnterBackward=t.onEnterBackward||T,this.onLeaveBackward=t.onLeaveBackward||T,this.onUpdate=t.onUpdate||T,this.onSyncComplete=t.onSyncComplete||T,this.reverted=!1,this.completed=!1,this.began=!1,this.isInView=!1,this.forceEnter=!1,this.hasEntered=!1,this.offset=0,this.offsetStart=0,this.offsetEnd=0,this.distance=0,this.prevProgress=0,this.thresholds=["start","end","end","start"],this.coords=[0,0,0,0],this.debugStyles=null,this.$debug=null,this._params=t,this._debug=Rt(t.debug,!1),this._next=null,this._prev=null,Et(this.container,this),$s(()=>{if(!this.reverted){if(!this.target){const e=ge(t.target)[0];this.target=e||s.body,this.refresh()}this._debug&&this.debug()}})}link(t){if(t&&(t.pause(),this.linked=t,!this._params.target)){let e;W(t.targets)?wt(t,t=>{t.targets&&!e&&(e=Ps(t))}):e=Ps(t),this.target=e||s.body,this.refresh()}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const t=(this.scroll-this.offsetStart)/this.distance;return t===1/0||isNaN(t)?0:gt(mt(t,0,1),6)}refresh(){this.reverted=!1;const t=this._params;return this.repeat=Rt(Ls(t.repeat,this),!0),this.horizontal="x"===Rt(Ls(t.axis,this),"y"),this.enter=Rt(Ls(t.enter,this),"end start"),this.leave=Rt(Ls(t.leave,this),"start end"),this.updateBounds(),this.handleScroll(),this}removeDebug(){return this.$debug&&(this.$debug.parentNode.removeChild(this.$debug),this.$debug=null),this.debugStyles&&(this.debugStyles.revert(),this.$debug=null),this}debug(){this.removeDebug();const t=this.container,e=this.horizontal,i=t.element.querySelector(":scope > .animejs-onscroll-debug"),r=s.createElement("div"),n=s.createElement("div"),o=s.createElement("div"),a=Xs[this.index%Xs.length],h=t.useWin,l=h?t.winWidth:t.width,c=h?t.winHeight:t.height,d=t.scrollWidth,u=t.scrollHeight,p=this.container.width>360?320:260,m=e?0:10,f=e?10:0,g=e?24:p/2,_=e?g:15,y=e?60:g,v=e?y:_,b=e?"repeat-x":"repeat-y",T=t=>e?"0px "+t+"px":t+"px 2px",S=t=>`linear-gradient(${e?90:0}deg, ${t} 2px, transparent 1px)`,w=(t,e,s,i,r)=>`position:${t};left:${e}px;top:${s}px;width:${i}px;height:${r}px;`;r.style.cssText=`${w("absolute",m,f,e?d:p,e?p:u)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${e?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `,n.style.cssText=`${w("sticky",0,0,e?l:g,e?g:c)}`,i||(n.style.cssText+=`background:\n ${S("#FFFF")}${T(g-10)} / 100px 100px ${b},\n ${S("#FFF8")}${T(g-10)} / 10px 10px ${b};\n `),o.style.cssText=`${w("relative",0,0,e?d:g,e?g:u)}`,i||(o.style.cssText+=`background:\n ${S("#FFFF")}${T(0)} / ${e?"100px 10px":"10px 100px"} ${b},\n ${S("#FFF8")}${T(0)} / ${e?"10px 0px":"0px 10px"} ${b};\n `);const x=[" enter: "," leave: "];this.coords.forEach((t,i)=>{const r=i>1,h=(r?0:this.offset)+t,m=i%2,f=h<v,g=h>(r?e?l:c:e?d:u)-v,b=(r?m&&!f:!m&&!f)||g,T=s.createElement("div"),S=s.createElement("div"),E=e?b?"right":"left":b?"bottom":"top",C=b?(e?y:_)+(r?e?-1:g?0:-2:e?-1:-2):e?1:0;S.innerHTML=`${this.id}${x[m]}${this.thresholds[i]}`,T.style.cssText=`${w("absolute",0,0,y,_)}\n display: flex;\n flex-direction: ${e?"column":"row"};\n justify-content: flex-${r?"start":"end"};\n align-items: flex-${b?"end":"start"};\n border-${E}: 2px solid ${a};\n `,S.style.cssText=`\n overflow: hidden;\n max-width: ${p/2-10}px;\n height: ${_};\n margin-${e?b?"right":"left":b?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${e&&b||!e&&!r?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${m?a:"rgba(0,0,0,.75)"};\n background-color: ${m?"rgba(0,0,0,.65)":a};\n border: 2px solid ${m?a:"transparent"};\n border-${e?b?"top-left":"top-right":b?"top-left":"bottom-left"}-radius: 5px;\n border-${e?b?"bottom-left":"bottom-right":b?"top-right":"bottom-right"}-radius: 5px;\n `,T.appendChild(S);let k=h-C+(e?1:0);T.style[e?"left":"top"]=`${k}px`,(r?n:o).appendChild(T)}),r.appendChild(n),r.appendChild(o),t.element.appendChild(r),i||r.classList.add("animejs-onscroll-debug"),this.$debug=r,"static"===Ze(t.element,"position")&&(this.debugStyles=Ke(t.element,{position:"relative "}))}updateBounds(){let t;this._debug&&this.removeDebug();const e=this.target,i=this.container,r=this.horizontal,n=this.linked;let o,a=e;for(n&&(o=n.currentTime,n.seek(0,!0)),a.parentElement;a&&a!==i.element&&a!==s.body;){const e="sticky"===Ze(a,"position")&&Ke(a,{position:"static"});a=a.parentElement,e&&(t||(t=[]),t.push(e))}const h=e.getBoundingClientRect(),l=r?h.left+i.scrollX-i.left:h.top+i.scrollY-i.top,c=r?h.width:h.height,d=r?i.width:i.height,u=(r?i.scrollWidth:i.scrollHeight)-d,p=this.enter,m=this.leave;let f="start",g="end",_="end",y="start";if(U(p)){const t=p.split(" ");_=t[0],f=t.length>1?t[1]:f}else if(z(p)){const t=p;W(t.container)||(_=t.container),W(t.target)||(f=t.target)}else X(p)&&(_=p);if(U(m)){const t=m.split(" ");y=t[0],g=t.length>1?t[1]:g}else if(z(m)){const t=m;W(t.container)||(y=t.container),W(t.target)||(g=t.target)}else X(m)&&(y=m);const v=Is(e,f,c),b=Is(e,g,c),T=v+l-d,S=b+l-u,w=Is(e,_,d,T,S),x=Is(e,y,d,T,S),E=v+l-w,C=b+l-x,k=C-E;this.offset=l,this.offsetStart=E,this.offsetEnd=C,this.distance=k<=0?0:k,this.thresholds=[f,g,_,y],this.coords=[v,b,w,x],t&&t.forEach(t=>t.revert()),n&&n.seek(o,!0),this._debug&&this.debug()}handleScroll(){const t=this.linked,e=this.sync,s=this.syncEase,i=this.syncSmooth,r=t&&(s||i),n=this.horizontal,o=this.container,a=this.scroll,h=a<=this.offsetStart,l=a>=this.offsetEnd,c=!h&&!l,d=a===this.offsetStart||a===this.offsetEnd,u=!this.hasEntered&&d,p=this._debug&&this.$debug;let m=!1,f=!1,g=this.progress;if(h&&this.began&&(this.began=!1),g>0&&!this.began&&(this.began=!0),r){const e=t.progress;if(i&&X(i)){if(i<1){const t=1e-4,s=e<g&&1===g?t:e>g&&!g?-t:0;g=gt(yt(e,g,yt(.01,.2,i))+s,6)}}else s&&(g=s(g));m=g!==this.prevProgress,f=1===e,m&&!f&&i&&e&&o.wakeTicker.restart()}if(p){const t=n?o.scrollY:o.scrollX;p.style[n?"top":"left"]=t+10+"px"}(c&&!this.isInView||u&&!this.forceEnter&&!this.hasEntered)&&(c&&(this.isInView=!0),this.forceEnter&&this.hasEntered?c&&(this.forceEnter=!1):(p&&c&&(p.style.zIndex=""+this.container.zIndex++),this.onSyncEnter(this),this.onEnter(this),this.backward?(this.onSyncEnterBackward(this),this.onEnterBackward(this)):(this.onSyncEnterForward(this),this.onEnterForward(this)),this.hasEntered=!0,u&&(this.forceEnter=!0))),(c||!c&&this.isInView)&&(m=!0),m&&(r&&t.seek(t.duration*g),this.onUpdate(this)),!c&&this.isInView&&(this.isInView=!1,this.onSyncLeave(this),this.onLeave(this),this.backward?(this.onSyncLeaveBackward(this),this.onLeaveBackward(this)):(this.onSyncLeaveForward(this),this.onLeaveForward(this)),e&&!i&&(f=!0)),g>=1&&this.began&&!this.completed&&(e&&f||!e)&&(e&&this.onSyncComplete(this),this.completed=!0,(!this.repeat&&!t||!this.repeat&&t&&t.completed)&&this.revert()),g<1&&this.completed&&(this.completed=!1),this.prevProgress=g}revert(){if(this.reverted)return;const t=this.container;return xt(t,this),t._head||t.revert(),this._debug&&this.removeDebug(),this.reverted=!0,this}}const Ys=(t={})=>new Us(t);var Ws=Object.freeze({__proto__:null,cubicBezier:ke,eases:Ae,irregular:Be,linear:Oe,none:Te,steps:$e});const Vs=_s,Hs={},qs=(t,e=0)=>(...s)=>e?e=>t(...s,e):e=>t(e,...s),js=t=>(...e)=>{const s=t(...e);return new Proxy(T,{apply:(t,e,[i])=>s(i),get:(t,e)=>js((...t)=>{const i=Hs[e](...t);return t=>i(s(t))})})},Qs=(t,e,s=0)=>{const i=(...t)=>(t.length<e.length?js(qs(e,s)):e)(...t);return Hs[t]||(Hs[t]=i),i},Gs=Qs("roundPad",Vs.roundPad),Js=Qs("padStart",Vs.padStart),Zs=Qs("padEnd",Vs.padEnd),Ks=Qs("wrap",Vs.wrap),ti=Qs("mapRange",Vs.mapRange),ei=Qs("degToRad",Vs.degToRad),si=Qs("radToDeg",Vs.radToDeg),ii=Qs("snap",Vs.snap),ri=Qs("clamp",Vs.clamp),ni=Qs("round",Vs.round),oi=Qs("lerp",Vs.lerp,1),ai=Qs("damp",Vs.damp,1),hi=(t=0,e=1,s=0)=>{const i=10**s;return Math.floor((Math.random()*(e-t+1/i)+t)*i)/i};let li=0;const ci=(t,e=0,s=1,i=0)=>{let r=void 0===t?li++:t;return(t=e,n=s,o=i)=>{r+=1831565813,r=Math.imul(r^r>>>15,1|r),r^=r+Math.imul(r^r>>>7,61|r);const a=10**o;return Math.floor((((r^r>>>14)>>>0)/4294967296*(n-t+1/a)+t)*a)/a}},di=t=>t[hi(0,t.length-1)],ui=t=>{let e,s,i=t.length;for(;i;)s=hi(0,--i),e=t[i],t[i]=t[s],t[s]=e;return t},pi=(t,e={})=>{let s=[],i=0;const r=e.from,n=e.reversed,o=e.ease,a=!W(o),h=a&&!W(o.ease)?o.ease:a?Me(o):null,l=e.grid,c=e.axis,d=e.total,u=W(r)||0===r||"first"===r,p="center"===r,m="last"===r,f="random"===r,g=P(t),y=e.use,v=tt(g?t[0]:t),b=g?tt(t[1]):0,T=$.exec((g?t[1]:t)+_),S=e.start||0+(g?v:0);let w=u?0:X(r)?r:0;return(t,r,o,a)=>{const[u]=_e(t),_=W(d)?o:d,x=!W(y)&&(Y(y)?y(u,r,_):Mt(u,y)),E=X(x)||U(x)&&X(+x)?+x:r;if(p&&(w=(_-1)/2),m&&(w=_-1),!s.length){for(let t=0;t<_;t++){if(l){const e=p?(l[0]-1)/2:w%l[0],i=p?(l[1]-1)/2:ht(w/l[0]),r=e-t%l[0],n=i-ht(t/l[0]);let o=st(r*r+n*n);"x"===c&&(o=-r),"y"===c&&(o=-n),s.push(o)}else s.push(nt(w-t));i=ct(...s)}h&&(s=s.map(t=>h(t/i)*i)),n&&(s=s.map(t=>c?t<0?-1*t:-t:nt(i-t))),f&&(s=ui(s))}const C=g?(b-v)/i:v;let k=(a?ss(a,W(e.start)?a.iterationDuration:S):S)+(C*gt(s[E],2)||0);return e.modifier&&(k=e.modifier(k)),T&&(k=`${k}${T[2]}`),k}};var mi=Object.freeze({__proto__:null,$:_e,clamp:ri,cleanInlineStyles:Ht,createSeededRandom:ci,damp:ai,degToRad:ei,get:Ze,keepTime:Os,lerp:oi,mapRange:ti,padEnd:Zs,padStart:Js,radToDeg:si,random:hi,randomPick:di,remove:ts,round:ni,roundPad:Gs,set:Ke,shuffle:ui,snap:ii,stagger:pi,sync:$s,wrap:Ks});const fi=t=>{const e=ge(t)[0];return e&&H(e)?e:console.warn(`${t} is not a valid SVGGeometryElement`)},gi=(t,e,s=0)=>t.getPointAtLength(e+s>=1?e+s:0),_i=(t,e)=>s=>{const i=+t.getTotalLength(),r=s[l],n=t.getCTM();return{from:0,to:i,modifier:s=>{if("a"===e){const e=gi(t,s,-1),i=gi(t,s,1);return 180*dt(i.y-e.y,i.x-e.x)/ut}{const i=gi(t,s,0);return"x"===e?r||!n?i.x:i.x*n.a+i.y*n.c+n.e:r||!n?i.y:i.x*n.b+i.y*n.d+n.f}}}},yi=t=>{const e=fi(t);if(e)return{translateX:_i(e,"x"),translateY:_i(e,"y"),rotate:_i(e,"a")}},vi=t=>{let e=1;if(t&&t.getCTM){const s=t.getCTM();s&&(e=(st(s.a*s.a+s.b*s.b)+st(s.c*s.c+s.d*s.d))/2)}return e},bi=(t,e,s)=>{const i=f,r=getComputedStyle(t),n=r.strokeLinecap,o="non-scaling-stroke"===r.vectorEffect?t:null;let a=n;const h=new Proxy(t,{get(t,e){const s=t[e];return e===u?t:"setAttribute"===e?(...e)=>{if("draw"===e[0]){const s=e[1].split(" "),r=+s[0],h=+s[1],l=vi(o),c=-1e3*r*l,d=h*i*l+c,u=i*l+(0===r&&1===h||1===r&&0===h?0:10*l)-d;if("butt"!==n){const e=r===h?"butt":n;a!==e&&(t.style.strokeLinecap=`${e}`,a=e)}t.setAttribute("stroke-dashoffset",`${c}`),t.setAttribute("stroke-dasharray",`${d} ${u}`)}return Reflect.apply(s,t,e)}:Y(s)?(...e)=>Reflect.apply(s,t,e):s}});return"1000"!==t.getAttribute("pathLength")&&(t.setAttribute("pathLength","1000"),h.setAttribute("draw",`${e} ${s}`)),h},Ti=(t,e=0,s=0)=>ge(t).map(t=>bi(t,e,s)),Si=(t,e=.33)=>s=>{const i=fi(t);if(!i)return;const r="path"===s.tagName,n=r?" ":",",o=s[d];o&&s.setAttribute(r?"d":"points",o);let a="",h="";if(e){const t=s.getTotalLength(),o=i.getTotalLength(),l=Math.max(Math.ceil(t*e),Math.ceil(o*e));for(let e=0;e<l;e++){const c=e/(l-1),d=s.getPointAtLength(t*c),u=i.getPointAtLength(o*c),p=r?0===e?"M":"L":"";a+=p+gt(d.x,3)+n+d.y+" ",h+=p+gt(u.x,3)+n+u.y+" "}}else a=s.getAttribute(r?"d":"points"),h=i.getAttribute(r?"d":"points");return s[d]=h,[a,h]};var wi=Object.freeze({__proto__:null,createDrawable:Ti,createMotionPath:yi,morphTo:Si});const xi="undefined"!=typeof Intl&&Intl.Segmenter,Ei=/\{value\}/g,Ci=/\{i\}/g,ki=/(\s+)/,$i=/^\s+$/,Oi="line",Bi="word",Ni="char",Ri="data-line";let Li=null,Ai=null,Di=null;const Mi=t=>t.isWordLike||" "===t.segment||X(+t.segment),Fi=t=>t.setAttribute("aria-hidden","true"),Ii=(t,e)=>[...t.querySelectorAll(`[data-${e}]:not([data-${e}] [data-${e}])`)],Pi={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"},zi=t=>{if(!t.childElementCount&&!t.textContent.trim()){const e=t.parentElement;t.remove(),e&&zi(e)}},Xi=(t,e,s)=>{const i=t.getAttribute(Ri);(null!==i&&+i!==e||"BR"===t.tagName)&&s.add(t);let r=t.childElementCount;for(;r--;)Xi(t.children[r],e,s);return s},Ui=(t,e={})=>{let s="";const i=U(e.class)?` class="${e.class}"`:"",r=Rt(e.clone,!1),n=Rt(e.wrap,!1),o=n?!0===n?"clip":n:!!r&&"clip";return n&&(s+=`<span${o?` style="overflow:${o};"`:""}>`),s+=`<span${i}${r?' style="position:relative;"':""} data-${t}="{i}">`,r?(s+="<span>{value}</span>",s+=`<span inert style="position:absolute;top:${"top"===r?"-100%":"bottom"===r?"100%":"0"};left:${"left"===r?"-100%":"right"===r?"100%":"0"};white-space:nowrap;">{value}</span>`):s+="{value}",s+="</span>",n&&(s+="</span>"),s},Yi=(t,e,s,i,r,n,o,a,h)=>{const l=r===Oi,c=r===Ni,d=`_${r}_`,u=Y(t)?t(s):t,p=l?"block":"inline-block";Di.innerHTML=u.replace(Ei,`<i class="${d}"></i>`).replace(Ci,`${c?h:l?o:a}`);const m=Di.content,f=m.firstElementChild,g=m.querySelector(`[data-${r}]`)||f,_=m.querySelectorAll(`i.${d}`),y=_.length;if(y){f.style.display=p,g.style.display=p,g.setAttribute(Ri,`${o}`),l||(g.setAttribute("data-word",`${a}`),c&&g.setAttribute("data-char",`${h}`));let t=y;for(;t--;){const e=_[t],i=e.parentElement;i.style.display=p,l?i.innerHTML=s.innerHTML:i.replaceChild(s.cloneNode(!0),e)}e.push(g),i.appendChild(m)}else console.warn('The expression "{value}" is missing from the provided template.');return n&&(f.style.outline=`1px dotted ${Pi[r]}`),f};class Wi{constructor(e,i={}){Li||(Li=xi?new xi([],{granularity:Bi}):{segment:t=>{const e=[],s=t.split(ki);for(let t=0,i=s.length;t<i;t++){const i=s[t];e.push({segment:i,isWordLike:!$i.test(i)})}return e}}),Ai||(Ai=xi?new xi([],{granularity:"grapheme"}):{segment:t=>[...t].map(t=>({segment:t}))}),!Di&&t&&(Di=s.createElement("template")),L.current&&L.current.register(this);const{words:r,chars:n,lines:o,accessible:a,includeSpaces:h,debug:l}=i,c=(e=P(e)?e[0]:e)&&e.nodeType?e:(fe(e)||[])[0],d=!0===o?{}:o,u=!0===r||W(r)?{}:r,p=!0===n?{}:n;this.debug=Rt(l,!1),this.includeSpaces=Rt(h,!1),this.accessible=Rt(a,!0),this.linesOnly=d&&!u&&!p,this.lineTemplate=z(d)?Ui(Oi,d):d,this.wordTemplate=z(u)||this.linesOnly?Ui(Bi,u):u,this.charTemplate=z(p)?Ui(Ni,p):p,this.$target=c,this.html=c&&c.innerHTML,this.lines=[],this.words=[],this.chars=[],this.effects=[],this.effectsCleanups=[],this.cache=null,this.ready=!1,this.width=0,this.resizeTimeout=null;const m=()=>this.html&&(d||u||p)&&this.split();this.resizeObserver=new ResizeObserver(()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{const t=c.offsetWidth;t!==this.width&&(this.width=t,m())},150)}),this.lineTemplate&&!this.ready?s.fonts.ready.then(m):m(),c?this.resizeObserver.observe(c):console.warn("No Text Splitter target found.")}addEffect(t){if(!Y(t))return console.warn("Effect must return a function.");const e=Os(t);return this.effects.push(e),this.ready&&(this.effectsCleanups[this.effects.length-1]=e(this)),this}revert(){return clearTimeout(this.resizeTimeout),this.lines.length=this.words.length=this.chars.length=0,this.resizeObserver.disconnect(),this.effectsCleanups.forEach(t=>Y(t)?t(this):t.revert&&t.revert()),this.$target.innerHTML=this.html,this}splitNode(t){const e=this.wordTemplate,i=this.charTemplate,r=this.includeSpaces,n=this.debug,o=t.nodeType;if(3===o){const o=t.nodeValue;if(o.trim()){const a=[],h=this.words,l=this.chars,c=Li.segment(o),d=s.createDocumentFragment();let u=null;for(const t of c){const e=t.segment,s=Mi(t);if(!u||s&&u&&Mi(u))a.push(e);else{const t=a.length-1;a[t].includes(" ")||e.includes(" ")?a.push(e):a[t]+=e}u=t}for(let t=0,o=a.length;t<o;t++){const o=a[t];if(o.trim()){const c=a[t+1],u=r&&c&&!c.trim(),p=o,m=i?Ai.segment(p):null,f=i?s.createDocumentFragment():s.createTextNode(u?o+" ":o);if(i){const t=[...m];for(let e=0,r=t.length;e<r;e++){const o=t[e],a=e===r-1&&u?o.segment+" ":o.segment,c=s.createTextNode(a);Yi(i,l,c,f,Ni,n,-1,h.length,l.length)}}e?Yi(e,h,f,d,Bi,n,-1,h.length,l.length):i?d.appendChild(f):d.appendChild(s.createTextNode(o)),u&&t++}else{if(t&&r)continue;d.appendChild(s.createTextNode(o))}}t.parentNode.replaceChild(d,t)}}else if(1===o){const e=[...t.childNodes];for(let t=0,s=e.length;t<s;t++)this.splitNode(e[t])}}split(t=!1){const e=this.$target,i=!!this.cache&&!t,r=this.lineTemplate,n=this.wordTemplate,o=this.charTemplate,a="loading"!==s.fonts.status,h=r&&a;this.ready=!r||a,(h||t)&&this.effectsCleanups.forEach(t=>Y(t)&&t(this)),i||(t&&(e.innerHTML=this.html,this.words.length=this.chars.length=0),this.splitNode(e),this.cache=e.innerHTML),h&&(i&&(e.innerHTML=this.cache),this.lines.length=0,n&&(this.words=Ii(e,Bi))),o&&(h||n)&&(this.chars=Ii(e,Ni));const l=this.words.length?this.words:this.chars;let c,d=0;for(let t=0,e=l.length;t<e;t++){const e=l[t],{top:s,height:i}=e.getBoundingClientRect();c&&s-c>.5*i&&d++,e.setAttribute(Ri,`${d}`);const r=e.querySelectorAll(`[${Ri}]`);let n=r.length;for(;n--;)r[n].setAttribute(Ri,`${d}`);c=s}if(h){const t=s.createDocumentFragment(),i=new Set,a=[];for(let t=0;t<d+1;t++){const s=e.cloneNode(!0);Xi(s,t,new Set).forEach(t=>{const e=t.parentElement;e&&i.add(e),t.remove()}),a.push(s)}i.forEach(zi);for(let e=0,s=a.length;e<s;e++)Yi(r,this.lines,a[e],t,Oi,this.debug,e);e.innerHTML="",e.appendChild(t),n&&(this.words=Ii(e,Bi)),o&&(this.chars=Ii(e,Ni))}if(this.linesOnly){const t=this.words;let e=t.length;for(;e--;){const s=t[e];s.replaceWith(s.textContent)}t.length=0}if(this.accessible&&(h||!i)){const t=s.createElement("span");t.style.cssText="position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;",t.innerHTML=this.html,e.insertBefore(t,e.firstChild),this.lines.forEach(Fi),this.words.forEach(Fi),this.chars.forEach(Fi)}return this.width=e.offsetWidth,(h||t)&&this.effects.forEach((t,e)=>this.effectsCleanups[e]=t(this)),this}refresh(){this.split(!0)}}const Vi=(t,e)=>new Wi(t,e),Hi=(t,e)=>(console.warn("text.split() is deprecated, import splitText() directly, or text.splitText()"),new Wi(t,e));var qi=Object.freeze({__proto__:null,TextSplitter:Wi,split:Hi,splitText:Vi});const ji=(t,e=100)=>{const s=[];for(let i=0;i<=e;i++)s.push(t(i/e));return`linear(${s.join(", ")})`},Qi={in:"ease-in",out:"ease-out",inOut:"ease-in-out"},Gi=(()=>{const t={};for(let e in we)t[e]=t=>we[e](Se(t));return t})(),Ji=t=>{let e=Qi[t];if(e)return e;if(e="linear",U(t)){if(F(t,"linear")||F(t,"cubic-")||F(t,"steps")||F(t,"ease"))e=t;else if(F(t,"cubicB"))e=M(t);else{const s=xe(t,Gi,Qi);Y(s)&&(e=s===Te?"linear":ji(s))}Qi[t]=e}else if(Y(t)){const s=ji(t);s&&(e=s)}else t.ease&&(e=ji(t.ease));return e},Zi=["x","y","z"],Ki=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",...Zi],tr=(()=>[...Zi,...v.filter(t=>["X","Y","Z"].some(e=>t.endsWith(e)))])();let er=null;const sr=(t,e,s,i,r)=>{let n=Lt(e,s,i,r);return X(n)?Ki.includes(t)||F(t,"translate")?`${n}px`:F(t,"rotate")||F(t,"skew")?`${n}deg`:`${n}`:n},ir=(t,e,s,i,r,n)=>{let o="0";const a=W(i)?getComputedStyle(t)[e]:sr(e,i,t,r,n);return o=W(s)?P(i)?i.map(s=>sr(e,s,t,r,n)):a:[sr(e,s,t,r,n),a],o};class rr{constructor(e,s){L.current&&L.current.register(this),V(er)&&(!t||!W(CSS)&&Object.hasOwnProperty.call(CSS,"registerProperty")?(v.forEach(t=>{const e=F(t,"skew"),s=F(t,"scale"),i=F(t,"rotate"),r=F(t,"translate"),n=i||e,o=n?"<angle>":s?"<number>":r?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:o,inherits:!1,initialValue:r?"0px":n?"0deg":s?"1":"0"})}catch{}}),er=!0):er=!1);const i=_e(e),r=i.length;r||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation.");const n=Rt(s.ease,Ji(A.defaults.ease)),o=n.ease&&n,a=Rt(s.autoplay,A.defaults.autoplay),h=!(!a||!a.link)&&a,l=s.alternate&&!0===s.alternate,d=s.reversed&&!0===s.reversed,u=Rt(s.loop,A.defaults.loop),p=!0===u||u===1/0?1/0:X(u)?u+1:1,m=l?d?"alternate-reverse":"alternate":d?"reverse":"normal",g=Ji(n),S=1===A.timeScale?1:f;this.targets=i,this.animations=[],this.controlAnimation=null,this.onComplete=s.onComplete||T,this.duration=0,this.muteCallbacks=!1,this.completed=!1,this.paused=!a||!1!==h,this.reversed=d,this.autoplay=a,this._speed=Rt(s.playbackRate,A.defaults.playbackRate),this._resolve=T,this._completed=0,this._inlineStyles=i.map(t=>t.getAttribute("style")),i.forEach((t,e)=>{const i=t[c],a=tr.some(t=>s.hasOwnProperty(t)),h=(o?o.duration:Lt(Rt(s.duration,A.defaults.duration),t,e,r))*S,l=Lt(Rt(s.delay,A.defaults.delay),t,e,r)*S,d=Rt(s.composition,"replace");for(let o in s){if(!J(o))continue;const c={},u={iterations:p,direction:m,fill:"forwards",easing:g,duration:h,delay:l,composite:d},f=s[o],_=!!a&&(v.includes(o)?o:y.get(o));let b;if(z(f)){const s=f,a=Rt(s.ease,n),p=a.ease&&a,m=s.to,g=s.from;if(u.duration=(p?p.duration:Lt(Rt(s.duration,h),t,e,r))*S,u.delay=Lt(Rt(s.delay,l),t,e,r)*S,u.composite=Rt(s.composition,d),u.easing=Ji(a),b=ir(t,o,g,m,e,r),_?(c[`--${_}`]=b,i[_]=b):c[o]=ir(t,o,g,m,e,r),Je(this,t,o,c,u),!W(g))if(_){const e=`--${_}`;t.style.setProperty(e,c[e][0])}else t.style[o]=c[o][0]}else b=P(f)?f.map(s=>sr(o,s,t,e,r)):sr(o,f,t,e,r),_?(c[`--${_}`]=b,i[_]=b):c[o]=b,Je(this,t,o,c,u)}if(a){let e=_;for(let t in i)e+=`${b[t]}var(--${t})) `;t.style.transform=e}}),h&&this.autoplay.link(this)}forEach(t){const e=U(t)?e=>e[t]():t;return this.animations.forEach(e),this}get speed(){return this._speed}set speed(t){this._speed=+t,this.forEach(e=>e.playbackRate=t)}get currentTime(){const t=this.controlAnimation,e=A.timeScale;return this.completed?this.duration:t?+t.currentTime*(1===e?1:e):0}set currentTime(t){const e=t*(1===A.timeScale?1:f);this.forEach(t=>{e>=this.duration&&t.play(),t.currentTime=e})}get progress(){return this.currentTime/this.duration}set progress(t){this.forEach(e=>e.currentTime=t*this.duration||0)}resume(){return this.paused?(this.paused=!1,this.forEach("play")):this}pause(){return this.paused?this:(this.paused=!0,this.forEach("pause"))}alternate(){return this.reversed=!this.reversed,this.forEach("reverse"),this.paused&&this.forEach("pause"),this}play(){return this.reversed&&this.alternate(),this.resume()}reverse(){return this.reversed||this.alternate(),this.resume()}seek(t,e=!1){return e&&(this.muteCallbacks=!0),t<this.duration&&(this.completed=!1),this.currentTime=t,this.muteCallbacks=!1,this.paused&&this.pause(),this}restart(){return this.completed=!1,this.seek(0,!0).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){return this.forEach("cancel"),this.pause()}revert(){return this.cancel(),this.targets.forEach((t,e)=>t.setAttribute("style",this._inlineStyles[e])),this}then(t=T){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=T};return new Promise(t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this))}}const nr={animate:(t,e)=>new rr(t,e),convertEase:ji};export{_e as $,as as Animatable,Cs as Draggable,qe as JSAnimation,Bs as Scope,Us as ScrollObserver,vs as Spring,Wi as TextSplitter,ns as Timeline,pe as Timer,rr as WAAPIAnimation,je as animate,ri as clamp,Ht as cleanInlineStyles,hs as createAnimatable,ks as createDraggable,Ti as createDrawable,yi as createMotionPath,Ns as createScope,ci as createSeededRandom,bs as createSpring,os as createTimeline,me as createTimer,ke as cubicBezier,ai as damp,ei as degToRad,Ae as eases,Ws as easings,Kt as engine,Ze as get,Be as irregular,Os as keepTime,oi as lerp,Oe as linear,ti as mapRange,Si as morphTo,Te as none,Ys as onScroll,Zs as padEnd,Js as padStart,si as radToDeg,hi as random,di as randomPick,ts as remove,ni as round,Gs as roundPad,As as scrollContainers,Ke as set,ui as shuffle,ii as snap,Hi as split,Vi as splitText,pi as stagger,$e as steps,wi as svg,$s as sync,qi as text,mi as utils,nr as waapi,Ks as wrap};
diff --git a/dist/bundles/anime.umd.js b/dist/bundles/anime.umd.js
new file mode 100644
index 00000000..d84af67d
--- /dev/null
+++ b/dist/bundles/anime.umd.js
@@ -0,0 +1,8621 @@
+/**
+ * Anime.js - UMD bundle
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+// Global types
+
+/**
+ * @typedef {Object} DefaultsParams
+ * @property {Number|String} [id]
+ * @property {PercentageKeyframes|DurationKeyframes} [keyframes]
+ * @property {EasingParam} [playbackEase]
+ * @property {Number} [playbackRate]
+ * @property {Number} [frameRate]
+ * @property {Number|Boolean} [loop]
+ * @property {Boolean} [reversed]
+ * @property {Boolean} [alternate]
+ * @property {Boolean|ScrollObserver} [autoplay]
+ * @property {Number|FunctionValue} [duration]
+ * @property {Number|FunctionValue} [delay]
+ * @property {Number} [loopDelay]
+ * @property {EasingParam} [ease]
+ * @property {'none'|'replace'|'blend'|compositionTypes} [composition]
+ * @property {(v: any) => any} [modifier]
+ * @property {(tickable: Tickable) => void} [onBegin]
+ * @property {(tickable: Tickable) => void} [onBeforeUpdate]
+ * @property {(tickable: Tickable) => void} [onUpdate]
+ * @property {(tickable: Tickable) => void} [onLoop]
+ * @property {(tickable: Tickable) => void} [onPause]
+ * @property {(tickable: Tickable) => void} [onComplete]
+ * @property {(renderable: Renderable) => void} [onRender]
+ */
+
+/** @typedef {JSAnimation|Timeline} Renderable */
+/** @typedef {Timer|Renderable} Tickable */
+/** @typedef {Timer&JSAnimation&Timeline} CallbackArgument */
+/** @typedef {Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */
+
+// Stagger types
+
+/**
+ * @template T
+ * @callback StaggerFunction
+ * @param {Target} [target]
+ * @param {Number} [index]
+ * @param {Number} [length]
+ * @param {Timeline} [tl]
+ * @return {T}
+ */
+
+/**
+ * @typedef {Object} StaggerParams
+ * @property {Number|String} [start]
+ * @property {Number|'first'|'center'|'last'|'random'} [from]
+ * @property {Boolean} [reversed]
+ * @property {Array.<Number>} [grid]
+ * @property {('x'|'y')} [axis]
+ * @property {String|((target: Target, i: Number, length: Number) => Number)} [use]
+ * @property {Number} [total]
+ * @property {EasingParam} [ease]
+ * @property {TweenModifier} [modifier]
+ */
+
+// Targets types
+
+/** @typedef {HTMLElement|SVGElement} DOMTarget */
+/** @typedef {Record<String, any>} JSTarget */
+/** @typedef {DOMTarget|JSTarget} Target */
+/** @typedef {Target|NodeList|String} TargetSelector */
+/** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */
+/** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */
+/** @typedef {Array.<DOMTarget>} DOMTargetsArray */
+/** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */
+/** @typedef {Array.<JSTarget>} JSTargetsArray */
+/** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */
+/** @typedef {Array.<Target>} TargetsArray */
+
+// Eases types
+
+/**
+ * @callback EasingFunction
+ * @param {Number} time
+ * @return {Number}
+ */
+
+/**
+ * @typedef {('linear'|'linear(x1, x2 25%, x3)'|'in'|'out'|'inOut'|'inQuad'|'outQuad'|'inOutQuad'|'inCubic'|'outCubic'|'inOutCubic'|'inQuart'|'outQuart'|'inOutQuart'|'inQuint'|'outQuint'|'inOutQuint'|'inSine'|'outSine'|'inOutSine'|'inCirc'|'outCirc'|'inOutCirc'|'inExpo'|'outExpo'|'inOutExpo'|'inBounce'|'outBounce'|'inOutBounce'|'inBack'|'outBack'|'inOutBack'|'inElastic'|'outElastic'|'inOutElastic'|'irregular'|'cubicBezier'|'steps'|'in(p = 1.675)'|'out(p = 1.675)'|'inOut(p = 1.675)'|'inBack(overshoot = 1.70158)'|'outBack(overshoot = 1.70158)'|'inOutBack(overshoot = 1.70158)'|'inElastic(amplitude = 1, period = .3)'|'outElastic(amplitude = 1, period = .3)'|'inOutElastic(amplitude = 1, period = .3)'|'irregular(length = 10, randomness = 1)'|'cubicBezier(x1, y1, x2, y2)'|'steps(steps = 10)')} EaseStringParamNames
+ */
+
+/**
+ * @callback PowerEasing
+ * @param {Number|String} [power=1.675]
+ * @return {EasingFunction}
+ */
+
+/**
+ * @callback BackEasing
+ * @param {Number|String} [overshoot=1.70158]
+ * @return {EasingFunction}
+ */
+
+/**
+ * @callback ElasticEasing
+ * @param {Number|String} [amplitude=1]
+ * @param {Number|String} [period=.3]
+ * @return {EasingFunction}
+ */
+
+/** @typedef {PowerEasing|BackEasing|ElasticEasing} EasingFunctionWithParams */
+
+// A hack to get both ease names suggestions AND allow any strings
+// https://github.com/microsoft/TypeScript/issues/29729#issuecomment-460346421
+/** @typedef {(String & {})|EaseStringParamNames|EasingFunction|Spring} EasingParam */
+
+// Spring types
+
+/**
+ * @typedef {Object} SpringParams
+ * @property {Number} [mass=1] - Mass, default 1
+ * @property {Number} [stiffness=100] - Stiffness, default 100
+ * @property {Number} [damping=10] - Damping, default 10
+ * @property {Number} [velocity=0] - Initial velocity, default 0
+ */
+
+ // Callback types
+
+/**
+ * @template T
+ * @callback Callback
+ * @param {T} self - Returns itself
+ * @param {PointerEvent} [e]
+ * @return {*}
+ */
+
+/**
+ * @template {object} T
+ * @typedef {Object} TickableCallbacks
+ * @property {Callback<T>} [onBegin]
+ * @property {Callback<T>} [onBeforeUpdate]
+ * @property {Callback<T>} [onUpdate]
+ * @property {Callback<T>} [onLoop]
+ * @property {Callback<T>} [onPause]
+ * @property {Callback<T>} [onComplete]
+ */
+
+/**
+ * @template {object} T
+ * @typedef {Object} RenderableCallbacks
+ * @property {Callback<T>} [onRender]
+ */
+
+// Timer types
+
+/**
+ * @typedef {Object} TimerOptions
+ * @property {Number|String} [id]
+ * @property {TweenParamValue} [duration]
+ * @property {TweenParamValue} [delay]
+ * @property {Number} [loopDelay]
+ * @property {Boolean} [reversed]
+ * @property {Boolean} [alternate]
+ * @property {Boolean|Number} [loop]
+ * @property {Boolean|ScrollObserver} [autoplay]
+ * @property {Number} [frameRate]
+ * @property {Number} [playbackRate]
+ */
+
+/**
+ * @typedef {TimerOptions & TickableCallbacks<Timer>} TimerParams
+ */
+
+// Tween types
+
+/**
+ * @callback FunctionValue
+ * @param {Target} target - The animated target
+ * @param {Number} index - The target index
+ * @param {Number} length - The total number of animated targets
+ * @return {Number|String|TweenObjectValue|Array.<Number|String|TweenObjectValue>}
+ */
+
+/**
+ * @callback TweenModifier
+ * @param {Number} value - The animated value
+ * @return {Number|String}
+ */
+
+/** @typedef {[Number, Number, Number, Number]} ColorArray */
+
+/**
+ * @typedef {Object} Tween
+ * @property {Number} id
+ * @property {JSAnimation} parent
+ * @property {String} property
+ * @property {Target} target
+ * @property {String|Number} _value
+ * @property {Function|null} _func
+ * @property {EasingFunction} _ease
+ * @property {Array.<Number>} _fromNumbers
+ * @property {Array.<Number>} _toNumbers
+ * @property {Array.<String>} _strings
+ * @property {Number} _fromNumber
+ * @property {Number} _toNumber
+ * @property {Array.<Number>} _numbers
+ * @property {Number} _number
+ * @property {String} _unit
+ * @property {TweenModifier} _modifier
+ * @property {Number} _currentTime
+ * @property {Number} _delay
+ * @property {Number} _updateDuration
+ * @property {Number} _startTime
+ * @property {Number} _changeDuration
+ * @property {Number} _absoluteStartTime
+ * @property {tweenTypes} _tweenType
+ * @property {valueTypes} _valueType
+ * @property {Number} _composition
+ * @property {Number} _isOverlapped
+ * @property {Number} _isOverridden
+ * @property {Number} _renderTransforms
+ * @property {Tween} _prevRep
+ * @property {Tween} _nextRep
+ * @property {Tween} _prevAdd
+ * @property {Tween} _nextAdd
+ * @property {Tween} _prev
+ * @property {Tween} _next
+ */
+
+/**
+ * @typedef TweenDecomposedValue
+ * @property {Number} t - Type
+ * @property {Number} n - Single number value
+ * @property {String} u - Value unit
+ * @property {String} o - Value operator
+ * @property {Array.<Number>} d - Array of Numbers (in case of complex value type)
+ * @property {Array.<String>} s - Strings (in case of complex value type)
+ */
+
+/** @typedef {{_head: null|Tween, _tail: null|Tween}} TweenPropertySiblings */
+/** @typedef {Record<String, TweenPropertySiblings>} TweenLookups */
+/** @typedef {WeakMap.<Target, TweenLookups>} TweenReplaceLookups */
+/** @typedef {Map.<Target, TweenLookups>} TweenAdditiveLookups */
+
+// JSAnimation types
+
+/**
+ * @typedef {Number|String|FunctionValue} TweenParamValue
+ */
+
+/**
+ * @typedef {TweenParamValue|[TweenParamValue, TweenParamValue]} TweenPropValue
+ */
+
+/**
+ * @typedef {(String & {})|'none'|'replace'|'blend'|compositionTypes} TweenComposition
+ */
+
+/**
+ * @typedef {Object} TweenParamsOptions
+ * @property {TweenParamValue} [duration]
+ * @property {TweenParamValue} [delay]
+ * @property {EasingParam} [ease]
+ * @property {TweenModifier} [modifier]
+ * @property {TweenComposition} [composition]
+ */
+
+/**
+ * @typedef {Object} TweenValues
+ * @property {TweenParamValue} [from]
+ * @property {TweenPropValue} [to]
+ * @property {TweenPropValue} [fromTo]
+ */
+
+/**
+ * @typedef {TweenParamsOptions & TweenValues} TweenKeyValue
+ */
+
+/**
+ * @typedef {Array.<TweenKeyValue|TweenPropValue>} ArraySyntaxValue
+ */
+
+/**
+ * @typedef {TweenParamValue|ArraySyntaxValue|TweenKeyValue} TweenOptions
+ */
+
+/**
+ * @typedef {Partial<{to: TweenParamValue|Array.<TweenParamValue>; from: TweenParamValue|Array.<TweenParamValue>; fromTo: TweenParamValue|Array.<TweenParamValue>;}>} TweenObjectValue
+ */
+
+/**
+ * @typedef {Object} PercentageKeyframeOptions
+ * @property {EasingParam} [ease]
+ */
+
+/**
+ * @typedef {Record<String, TweenParamValue>} PercentageKeyframeParams
+ */
+
+/**
+ * @typedef {Record<String, PercentageKeyframeParams & PercentageKeyframeOptions>} PercentageKeyframes
+ */
+
+/**
+ * @typedef {Array<Record<String, TweenOptions | TweenModifier | boolean> & TweenParamsOptions>} DurationKeyframes
+ */
+
+/**
+ * @typedef {Object} AnimationOptions
+ * @property {PercentageKeyframes|DurationKeyframes} [keyframes]
+ * @property {EasingParam} [playbackEase]
+ */
+
+// TODO: Currently setting TweenModifier to the intersected Record<> makes the FunctionValue type target param any if only one parameter is set
+/**
+ * @typedef {Record<String, TweenOptions | Callback<JSAnimation> | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & TickableCallbacks<JSAnimation> & RenderableCallbacks<JSAnimation>} AnimationParams
+ */
+
+// Timeline types
+
+/**
+ * Accepts:<br>
+ * - `Number` - Absolute position in milliseconds (e.g., `500` places element at exactly 500ms)<br>
+ * - `'+=Number'` - Addition: Position element X ms after the last element (e.g., `'+=100'`)<br>
+ * - `'-=Number'` - Subtraction: Position element X ms before the last element's end (e.g., `'-=100'`)<br>
+ * - `'*=Number'` - Multiplier: Position element at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br>
+ * - `'<'` - Previous end: Position element at the end position of the previous element<br>
+ * - `'<<'` - Previous start: Position element at the start position of the previous element<br>
+ * - `'<<+=Number'` - Combined: Position element relative to previous element's start (e.g., `'<<+=250'`)<br>
+ * - `'label'` - Label: Position element at a named label position (e.g., `'My Label'`)
+ *
+ * @typedef {Number|`+=${Number}`|`-=${Number}`|`*=${Number}`|'<'|'<<'|`<<+=${Number}`|`<<-=${Number}`|String} TimelinePosition
+ */
+
+/**
+ * Accepts:<br>
+ * - `Number` - Absolute position in milliseconds (e.g., `500` places animation at exactly 500ms)<br>
+ * - `'+=Number'` - Addition: Position animation X ms after the last animation (e.g., `'+=100'`)<br>
+ * - `'-=Number'` - Subtraction: Position animation X ms before the last animation's end (e.g., `'-=100'`)<br>
+ * - `'*=Number'` - Multiplier: Position animation at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br>
+ * - `'<'` - Previous end: Position animation at the end position of the previous animation<br>
+ * - `'<<'` - Previous start: Position animation at the start position of the previous animation<br>
+ * - `'<<+=Number'` - Combined: Position animation relative to previous animation's start (e.g., `'<<+=250'`)<br>
+ * - `'label'` - Label: Position animation at a named label position (e.g., `'My Label'`)<br>
+ * - `stagger(String|Nummber)` - Stagger multi-elements animation positions (e.g., 10, 20, 30...)
+ *
+ * @typedef {TimelinePosition | StaggerFunction<Number|String>} TimelineAnimationPosition
+ */
+
+/**
+ * @typedef {Object} TimelineOptions
+ * @property {DefaultsParams} [defaults]
+ * @property {EasingParam} [playbackEase]
+ */
+
+/**
+ * @typedef {TimerOptions & TimelineOptions & TickableCallbacks<Timeline> & RenderableCallbacks<Timeline>} TimelineParams
+ */
+
+// WAAPIAnimation types
+
+/**
+ * @typedef {String|Number|Array<String>|Array<Number>} WAAPITweenValue
+ */
+
+/**
+ * @callback WAAPIFunctionValue
+ * @param {DOMTarget} target - The animated target
+ * @param {Number} index - The target index
+ * @param {Number} length - The total number of animated targets
+ * @return {WAAPITweenValue}
+ */
+
+/**
+ * @typedef {WAAPITweenValue|WAAPIFunctionValue|Array<String|Number|WAAPIFunctionValue>} WAAPIKeyframeValue
+ */
+
+/**
+ * @typedef {(animation: WAAPIAnimation) => void} WAAPICallback
+ */
+
+/**
+ * @typedef {Object} WAAPITweenOptions
+ * @property {WAAPIKeyframeValue} [to]
+ * @property {WAAPIKeyframeValue} [from]
+ * @property {Number|WAAPIFunctionValue} [duration]
+ * @property {Number|WAAPIFunctionValue} [delay]
+ * @property {EasingParam} [ease]
+ * @property {CompositeOperation} [composition]
+ */
+
+/**
+ * @typedef {Object} WAAPIAnimationOptions
+ * @property {Number|Boolean} [loop]
+ * @property {Boolean} [Reversed]
+ * @property {Boolean} [Alternate]
+ * @property {Boolean|ScrollObserver} [autoplay]
+ * @property {Number} [playbackRate]
+ * @property {Number|WAAPIFunctionValue} [duration]
+ * @property {Number|WAAPIFunctionValue} [delay]
+ * @property {EasingParam} [ease]
+ * @property {CompositeOperation} [composition]
+ * @property {WAAPICallback} [onComplete]
+ */
+
+/**
+ * @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | WAAPICallback | EasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams
+ */
+
+// Animatable types
+
+/**
+ * @callback AnimatablePropertySetter
+ * @param {Number|Array.<Number>} to
+ * @param {Number} [duration]
+ * @param {EasingParam} [ease]
+ * @return {AnimatableObject}
+ */
+
+/**
+ * @callback AnimatablePropertyGetter
+ * @return {Number|Array.<Number>}
+ */
+
+/**
+ * @typedef {AnimatablePropertySetter & AnimatablePropertyGetter} AnimatableProperty
+ */
+
+/**
+ * @typedef {Animatable & Record<String, AnimatableProperty>} AnimatableObject
+ */
+
+/**
+ * @typedef {Object} AnimatablePropertyParamsOptions
+ * @property {String} [unit]
+ * @property {TweenParamValue} [duration]
+ * @property {EasingParam} [ease]
+ * @property {TweenModifier} [modifier]
+ * @property {TweenComposition} [composition]
+ */
+
+/**
+ * @typedef {Record<String, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions} AnimatableParams
+ */
+
+// Scope types
+
+/**
+ * @typedef {Object} ReactRef
+ * @property {HTMLElement|SVGElement|null} [current]
+ */
+
+/**
+ * @typedef {Object} AngularRef
+ * @property {HTMLElement|SVGElement} [nativeElement]
+ */
+
+/**
+ * @typedef {Object} ScopeParams
+ * @property {DOMTargetSelector|ReactRef|AngularRef} [root]
+ * @property {DefaultsParams} [defaults]
+ * @property {Record<String, String>} [mediaQueries]
+ */
+
+/**
+ * @template T
+ * @callback ScopedCallback
+ * @param {Scope} scope
+ * @return {T}
+ */
+
+/**
+ * @callback ScopeCleanupCallback
+ * @param {Scope} [scope]
+ */
+
+/**
+ * @callback ScopeConstructorCallback
+ * @param {Scope} [scope]
+ * @return {ScopeCleanupCallback|void}
+ */
+
+/**
+ * @callback ScopeMethod
+ * @param {...*} args
+ * @return {ScopeCleanupCallback|void}
+ */
+
+// Scroll types
+
+/**
+ * @typedef {String|Number} ScrollThresholdValue
+ */
+
+/**
+ * @typedef {Object} ScrollThresholdParam
+ * @property {ScrollThresholdValue} [target]
+ * @property {ScrollThresholdValue} [container]
+ */
+
+/**
+ * @callback ScrollObserverAxisCallback
+ * @param {ScrollObserver} self
+ * @return {'x'|'y'}
+ */
+
+/**
+ * @callback ScrollThresholdCallback
+ * @param {ScrollObserver} self
+ * @return {ScrollThresholdValue|ScrollThresholdParam}
+ */
+
+/**
+ * @typedef {Object} ScrollObserverParams
+ * @property {Number|String} [id]
+ * @property {Boolean|Number|String|EasingParam} [sync]
+ * @property {TargetsParam} [container]
+ * @property {TargetsParam} [target]
+ * @property {'x'|'y'|ScrollObserverAxisCallback|((observer: ScrollObserver) => 'x'|'y'|ScrollObserverAxisCallback)} [axis]
+ * @property {ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback|((observer: ScrollObserver) => ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback)} [enter]
+ * @property {ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback|((observer: ScrollObserver) => ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback)} [leave]
+ * @property {Boolean|((observer: ScrollObserver) => Boolean)} [repeat]
+ * @property {Boolean} [debug]
+ * @property {Callback<ScrollObserver>} [onEnter]
+ * @property {Callback<ScrollObserver>} [onLeave]
+ * @property {Callback<ScrollObserver>} [onEnterForward]
+ * @property {Callback<ScrollObserver>} [onLeaveForward]
+ * @property {Callback<ScrollObserver>} [onEnterBackward]
+ * @property {Callback<ScrollObserver>} [onLeaveBackward]
+ * @property {Callback<ScrollObserver>} [onUpdate]
+ * @property {Callback<ScrollObserver>} [onSyncComplete]
+ */
+
+// Draggable types
+
+/**
+ * @typedef {Object} DraggableAxisParam
+ * @property {String} [mapTo]
+ * @property {TweenModifier} [modifier]
+ * @property {TweenComposition} [composition]
+ * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap]
+ */
+
+/**
+ * @typedef {Object} DraggableCursorParams
+ * @property {String} [onHover]
+ * @property {String} [onGrab]
+ */
+
+/**
+ * @typedef {Object} DraggableParams
+ * @property {DOMTargetSelector} [trigger]
+ * @property {DOMTargetSelector|Array<Number>|((draggable: Draggable) => DOMTargetSelector|Array<Number>)} [container]
+ * @property {Boolean|DraggableAxisParam} [x]
+ * @property {Boolean|DraggableAxisParam} [y]
+ * @property {TweenModifier} [modifier]
+ * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap]
+ * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [containerPadding]
+ * @property {Number|((draggable: Draggable) => Number)} [containerFriction]
+ * @property {Number|((draggable: Draggable) => Number)} [releaseContainerFriction]
+ * @property {Number|((draggable: Draggable) => Number)} [dragSpeed]
+ * @property {Number|((draggable: Draggable) => Number)} [scrollSpeed]
+ * @property {Number|((draggable: Draggable) => Number)} [scrollThreshold]
+ * @property {Number|((draggable: Draggable) => Number)} [minVelocity]
+ * @property {Number|((draggable: Draggable) => Number)} [maxVelocity]
+ * @property {Number|((draggable: Draggable) => Number)} [velocityMultiplier]
+ * @property {Number} [releaseMass]
+ * @property {Number} [releaseStiffness]
+ * @property {Number} [releaseDamping]
+ * @property {Boolean} [releaseDamping]
+ * @property {EasingParam} [releaseEase]
+ * @property {Boolean|DraggableCursorParams|((draggable: Draggable) => Boolean|DraggableCursorParams)} [cursor]
+ * @property {Callback<Draggable>} [onGrab]
+ * @property {Callback<Draggable>} [onDrag]
+ * @property {Callback<Draggable>} [onRelease]
+ * @property {Callback<Draggable>} [onUpdate]
+ * @property {Callback<Draggable>} [onSettle]
+ * @property {Callback<Draggable>} [onSnap]
+ * @property {Callback<Draggable>} [onResize]
+ * @property {Callback<Draggable>} [onAfterResize]
+ */
+
+// Text types
+
+/**
+ * @typedef {Object} SplitTemplateParams
+ * @property {false|String} [class]
+ * @property {Boolean|'hidden'|'clip'|'visible'|'scroll'|'auto'} [wrap]
+ * @property {Boolean|'top'|'right'|'bottom'|'left'|'center'} [clone]
+ */
+
+/**
+ * @typedef {Boolean|String} SplitValue
+ */
+
+/**
+ * @callback SplitFunctionValue
+ * @param {Node|HTMLElement} [value]
+ * @return String
+ */
+
+/**
+ * @typedef {Object} TextSplitterParams
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [lines]
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [words]
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [chars]
+ * @property {Boolean} [accessible]
+ * @property {Boolean} [includeSpaces]
+ * @property {Boolean} [debug]
+ */
+
+// SVG types
+
+/**
+ * @typedef {SVGGeometryElement & {
+ * setAttribute(name: 'draw', value: `${number} ${number}`): void;
+ * draw: `${number} ${number}`;
+ * }} DrawableSVGGeometry
+ */
+
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.anime = {}));
+})(this, (function (exports) { 'use strict';
+
+ // Environments
+
+ // TODO: Do we need to check if we're running inside a worker ?
+ const isBrowser = typeof window !== 'undefined';
+
+ /** @type {Window & {AnimeJS: Array}|null} */
+ const win = isBrowser ? /** @type {Window & {AnimeJS: Array}} */(/** @type {unknown} */(window)) : null;
+
+ /** @type {Document|null} */
+ const doc = isBrowser ? document : null;
+
+ // Enums
+
+ /** @enum {Number} */
+ const tweenTypes = {
+ OBJECT: 0,
+ ATTRIBUTE: 1,
+ CSS: 2,
+ TRANSFORM: 3,
+ CSS_VAR: 4,
+ };
+
+ /** @enum {Number} */
+ const valueTypes = {
+ NUMBER: 0,
+ UNIT: 1,
+ COLOR: 2,
+ COMPLEX: 3,
+ };
+
+ /** @enum {Number} */
+ const tickModes = {
+ NONE: 0,
+ AUTO: 1,
+ FORCE: 2,
+ };
+
+ /** @enum {Number} */
+ const compositionTypes = {
+ replace: 0,
+ none: 1,
+ blend: 2,
+ };
+
+ // Cache symbols
+
+ const isRegisteredTargetSymbol = Symbol();
+ const isDomSymbol = Symbol();
+ const isSvgSymbol = Symbol();
+ const transformsSymbol = Symbol();
+ const morphPointsSymbol = Symbol();
+ const proxyTargetSymbol = Symbol();
+
+ // Numbers
+
+ const minValue = 1e-11;
+ const maxValue = 1e12;
+ const K = 1e3;
+ const maxFps = 120;
+
+ // Strings
+
+ const emptyString = '';
+ const shortTransforms = /*#__PURE__*/ (() => {
+ const map = new Map();
+ map.set('x', 'translateX');
+ map.set('y', 'translateY');
+ map.set('z', 'translateZ');
+ return map;
+ })();
+
+ const validTransforms = [
+ 'translateX',
+ 'translateY',
+ 'translateZ',
+ 'rotate',
+ 'rotateX',
+ 'rotateY',
+ 'rotateZ',
+ 'scale',
+ 'scaleX',
+ 'scaleY',
+ 'scaleZ',
+ 'skew',
+ 'skewX',
+ 'skewY',
+ 'perspective',
+ 'matrix',
+ 'matrix3d',
+ ];
+
+ const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {});
+
+ // Functions
+
+ /** @return {void} */
+ const noop = () => {};
+
+ // Regex
+
+ const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;
+ const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;
+ const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
+ const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;
+ const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
+ // export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g;
+ const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;
+ // export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i;
+ const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;
+ const lowerCaseRgx = /([a-z])([A-Z])/g;
+ const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in ()
+ const relativeValuesExecRgx = /(\*=|\+=|-=)/;
+
+
+
+ /** @type {DefaultsParams} */
+ const defaults = {
+ id: null,
+ keyframes: null,
+ playbackEase: null,
+ playbackRate: 1,
+ frameRate: maxFps,
+ loop: 0,
+ reversed: false,
+ alternate: false,
+ autoplay: true,
+ duration: K,
+ delay: 0,
+ loopDelay: 0,
+ ease: 'out(2)',
+ composition: compositionTypes.replace,
+ modifier: v => v,
+ onBegin: noop,
+ onBeforeUpdate: noop,
+ onUpdate: noop,
+ onLoop: noop,
+ onPause: noop,
+ onComplete: noop,
+ onRender: noop,
+ };
+
+ const scope = {
+ /** @type {Scope} */
+ current: null,
+ /** @type {Document|DOMTarget} */
+ root: doc,
+ };
+
+ const globals = {
+ /** @type {DefaultsParams} */
+ defaults,
+ /** @type {Number} */
+ precision: 4,
+ /** @type {Number} equals 1 in ms mode, 0.001 in s mode */
+ timeScale: 1,
+ /** @type {Number} */
+ tickThreshold: 200,
+ };
+
+ const globalVersions = { version: '4.2.0', engine: null };
+
+ if (isBrowser) {
+ if (!win.AnimeJS) win.AnimeJS = [];
+ win.AnimeJS.push(globalVersions);
+ }
+
+
+
+ // Strings
+
+ /**
+ * @param {String} str
+ * @return {String}
+ */
+ const toLowerCase = str => str.replace(lowerCaseRgx, '$1-$2').toLowerCase();
+
+ /**
+ * Prioritize this method instead of regex when possible
+ * @param {String} str
+ * @param {String} sub
+ * @return {Boolean}
+ */
+ const stringStartsWith = (str, sub) => str.indexOf(sub) === 0;
+
+ // Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement.
+ const now = Date.now;
+
+ // Types checkers
+
+ const isArr = Array.isArray;
+ /**@param {any} a @return {a is Record<String, any>} */
+ const isObj = a => a && a.constructor === Object;
+ /**@param {any} a @return {a is Number} */
+ const isNum = a => typeof a === 'number' && !isNaN(a);
+ /**@param {any} a @return {a is String} */
+ const isStr = a => typeof a === 'string';
+ /**@param {any} a @return {a is Function} */
+ const isFnc = a => typeof a === 'function';
+ /**@param {any} a @return {a is undefined} */
+ const isUnd = a => typeof a === 'undefined';
+ /**@param {any} a @return {a is null | undefined} */
+ const isNil = a => isUnd(a) || a === null;
+ /**@param {any} a @return {a is SVGElement} */
+ const isSvg = a => isBrowser && a instanceof SVGElement;
+ /**@param {any} a @return {Boolean} */
+ const isHex = a => hexTestRgx.test(a);
+ /**@param {any} a @return {Boolean} */
+ const isRgb = a => stringStartsWith(a, 'rgb');
+ /**@param {any} a @return {Boolean} */
+ const isHsl = a => stringStartsWith(a, 'hsl');
+ /**@param {any} a @return {Boolean} */
+ const isCol = a => isHex(a) || isRgb(a) || isHsl(a);
+ /**@param {any} a @return {Boolean} */
+ const isKey = a => !globals.defaults.hasOwnProperty(a);
+
+ // SVG
+
+ // Consider the following as CSS animation
+ // CSS opacity animation has better default values (opacity: 1 instead of 0))
+ // rotate is more commonly intended to be used as a transform
+ const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
+
+ /**
+ * @param {Target} el
+ * @param {String} propertyName
+ * @return {Boolean}
+ */
+ const isValidSVGAttribute = (el, propertyName) => {
+ if (svgCssReservedProperties.includes(propertyName)) return false;
+ if (el.getAttribute(propertyName) || propertyName in el) {
+ if (propertyName === 'scale') { // Scale
+ const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
+ // Only consider scale as a valid SVG attribute on filter element
+ return elParentNode && elParentNode.tagName === 'filter';
+ }
+ return true;
+ }
+ };
+
+ // Number
+
+ /**
+ * @param {Number|String} str
+ * @return {Number}
+ */
+ const parseNumber = str => isStr(str) ?
+ parseFloat(/** @type {String} */(str)) :
+ /** @type {Number} */(str);
+
+ // Math
+
+ const pow = Math.pow;
+ const sqrt = Math.sqrt;
+ const sin = Math.sin;
+ const cos = Math.cos;
+ const abs = Math.abs;
+ const exp = Math.exp;
+ const ceil = Math.ceil;
+ const floor = Math.floor;
+ const asin = Math.asin;
+ const max = Math.max;
+ const atan2 = Math.atan2;
+ const PI = Math.PI;
+ const _round = Math.round;
+
+ /**
+ * Clamps a value between min and max bounds
+ *
+ * @param {Number} v - Value to clamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {Number}
+ */
+ const clamp$1 = (v, min, max) => v < min ? min : v > max ? max : v;
+
+ const powCache = {};
+
+ /**
+ * Rounds a number to specified decimal places
+ *
+ * @param {Number} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {Number}
+ */
+ const round$1 = (v, decimalLength) => {
+ if (decimalLength < 0) return v;
+ if (!decimalLength) return _round(v);
+ let p = powCache[decimalLength];
+ if (!p) p = powCache[decimalLength] = 10 ** decimalLength;
+ return _round(v * p) / p;
+ };
+
+ /**
+ * Snaps a value to nearest increment or array value
+ *
+ * @param {Number} v - Value to snap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {Number}
+ */
+ const snap$1 = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
+
+ /**
+ * Linear interpolation between two values
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
+ */
+ const lerp$1 = (start, end, factor) => start + (end - start) * factor;
+
+ /**
+ * Replaces infinity with maximum safe value
+ *
+ * @param {Number} v - Value to check
+ * @return {Number}
+ */
+ const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v;
+
+ /**
+ * Normalizes time value with minimum threshold
+ *
+ * @param {Number} v - Time value to normalize
+ * @return {Number}
+ */
+ const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round$1(v, 11));
+
+ // Arrays
+
+ /**
+ * @template T
+ * @param {T[]} a
+ * @return {T[]}
+ */
+ const cloneArray = a => isArr(a) ? [ ...a ] : a;
+
+ // Objects
+
+ /**
+ * @template T
+ * @template U
+ * @param {T} o1
+ * @param {U} o2
+ * @return {T & U}
+ */
+ const mergeObjects = (o1, o2) => {
+ const merged = /** @type {T & U} */({ ...o1 });
+ for (let p in o2) {
+ const o1p = /** @type {T & U} */(o1)[p];
+ merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p;
+ } return merged;
+ };
+
+ // Linked lists
+
+ /**
+ * @param {Object} parent
+ * @param {Function} callback
+ * @param {Boolean} [reverse]
+ * @param {String} [prevProp]
+ * @param {String} [nextProp]
+ * @return {void}
+ */
+ const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => {
+ let next = parent._head;
+ let adjustedNextProp = nextProp;
+ if (reverse) {
+ next = parent._tail;
+ adjustedNextProp = prevProp;
+ }
+ while (next) {
+ const currentNext = next[adjustedNextProp];
+ callback(next);
+ next = currentNext;
+ }
+ };
+
+ /**
+ * @param {Object} parent
+ * @param {Object} child
+ * @param {String} [prevProp]
+ * @param {String} [nextProp]
+ * @return {void}
+ */
+ const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => {
+ const prev = child[prevProp];
+ const next = child[nextProp];
+ prev ? prev[nextProp] = next : parent._head = next;
+ next ? next[prevProp] = prev : parent._tail = prev;
+ child[prevProp] = null;
+ child[nextProp] = null;
+ };
+
+ /**
+ * @param {Object} parent
+ * @param {Object} child
+ * @param {Function} [sortMethod]
+ * @param {String} prevProp
+ * @param {String} nextProp
+ * @return {void}
+ */
+ const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => {
+ let prev = parent._tail;
+ while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp];
+ const next = prev ? prev[nextProp] : parent._head;
+ prev ? prev[nextProp] = child : parent._head = child;
+ next ? next[prevProp] = child : parent._tail = child;
+ child[prevProp] = prev;
+ child[nextProp] = next;
+ };
+
+
+
+ /**
+ * @param {DOMTarget} target
+ * @param {String} propName
+ * @param {Object} animationInlineStyles
+ * @return {String}
+ */
+ const parseInlineTransforms = (target, propName, animationInlineStyles) => {
+ const inlineTransforms = target.style.transform;
+ let inlinedStylesPropertyValue;
+ if (inlineTransforms) {
+ const cachedTransforms = target[transformsSymbol];
+ let t; while (t = transformsExecRgx.exec(inlineTransforms)) {
+ const inlinePropertyName = t[1];
+ // const inlinePropertyValue = t[2];
+ const inlinePropertyValue = t[2].slice(1, -1);
+ cachedTransforms[inlinePropertyName] = inlinePropertyValue;
+ if (inlinePropertyName === propName) {
+ inlinedStylesPropertyValue = inlinePropertyValue;
+ // Store the new parsed inline styles if animationInlineStyles is provided
+ if (animationInlineStyles) {
+ animationInlineStyles[propName] = inlinePropertyValue;
+ }
+ }
+ }
+ }
+ return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue :
+ stringStartsWith(propName, 'scale') ? '1' :
+ stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px';
+ };
+
+
+
+ /**
+ * RGB / RGBA Color value string -> RGBA values array
+ * @param {String} rgbValue
+ * @return {ColorArray}
+ */
+ const rgbToRgba = rgbValue => {
+ const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue);
+ const a = !isUnd(rgba[4]) ? +rgba[4] : 1;
+ return [
+ +rgba[1],
+ +rgba[2],
+ +rgba[3],
+ a
+ ]
+ };
+
+ /**
+ * HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array
+ * @param {String} hexValue
+ * @return {ColorArray}
+ */
+ const hexToRgba = hexValue => {
+ const hexLength = hexValue.length;
+ const isShort = hexLength === 4 || hexLength === 5;
+ return [
+ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]),
+ +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]),
+ +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]),
+ ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1)
+ ]
+ };
+
+ /**
+ * @param {Number} p
+ * @param {Number} q
+ * @param {Number} t
+ * @return {Number}
+ */
+ const hue2rgb = (p, q, t) => {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ return t < 1 / 6 ? p + (q - p) * 6 * t :
+ t < 1 / 2 ? q :
+ t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 :
+ p;
+ };
+
+ /**
+ * HSL / HSLA Color value string -> RGBA values array
+ * @param {String} hslValue
+ * @return {ColorArray}
+ */
+ const hslToRgba = hslValue => {
+ const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue);
+ const h = +hsla[1] / 360;
+ const s = +hsla[2] / 100;
+ const l = +hsla[3] / 100;
+ const a = !isUnd(hsla[4]) ? +hsla[4] : 1;
+ let r, g, b;
+ if (s === 0) {
+ r = g = b = l;
+ } else {
+ const q = l < .5 ? l * (1 + s) : l + s - l * s;
+ const p = 2 * l - q;
+ r = round$1(hue2rgb(p, q, h + 1 / 3) * 255, 0);
+ g = round$1(hue2rgb(p, q, h) * 255, 0);
+ b = round$1(hue2rgb(p, q, h - 1 / 3) * 255, 0);
+ }
+ return [r, g, b, a];
+ };
+
+ /**
+ * All in one color converter that converts a color string value into an array of RGBA values
+ * @param {String} colorString
+ * @return {ColorArray}
+ */
+ const convertColorStringValuesToRgbaArray = colorString => {
+ return isRgb(colorString) ? rgbToRgba(colorString) :
+ isHex(colorString) ? hexToRgba(colorString) :
+ isHsl(colorString) ? hslToRgba(colorString) :
+ [0, 0, 0, 1];
+ };
+
+
+
+ /**
+ * @template T, D
+ * @param {T|undefined} targetValue
+ * @param {D} defaultValue
+ * @return {T|D}
+ */
+ const setValue = (targetValue, defaultValue) => {
+ return isUnd(targetValue) ? defaultValue : targetValue;
+ };
+
+ /**
+ * @param {TweenPropValue} value
+ * @param {Target} target
+ * @param {Number} index
+ * @param {Number} total
+ * @param {Object} [store]
+ * @return {any}
+ */
+ const getFunctionValue = (value, target, index, total, store) => {
+ if (isFnc(value)) {
+ const func = () => {
+ const computed = /** @type {Function} */(value)(target, index, total);
+ // Fallback to 0 if the function returns undefined / NaN / null / false / 0
+ return !isNaN(+computed) ? +computed : computed || 0;
+ };
+ if (store) {
+ store.func = func;
+ }
+ return func();
+ } else {
+ return value;
+ }
+ };
+
+ /**
+ * @param {Target} target
+ * @param {String} prop
+ * @return {tweenTypes}
+ */
+ const getTweenType = (target, prop) => {
+ return !target[isDomSymbol] ? tweenTypes.OBJECT :
+ // Handle SVG attributes
+ target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE :
+ // Handle CSS Transform properties differently than CSS to allow individual animations
+ validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM :
+ // CSS variables
+ stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR :
+ // All other CSS properties
+ prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS :
+ // Handle other DOM Attributes
+ prop in target ? tweenTypes.OBJECT :
+ tweenTypes.ATTRIBUTE;
+ };
+
+ /**
+ * @param {DOMTarget} target
+ * @param {String} propName
+ * @param {Object} animationInlineStyles
+ * @return {String}
+ */
+ const getCSSValue = (target, propName, animationInlineStyles) => {
+ const inlineStyles = target.style[propName];
+ if (inlineStyles && animationInlineStyles) {
+ animationInlineStyles[propName] = inlineStyles;
+ }
+ const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName);
+ return value === 'auto' ? '0' : value;
+ };
+
+ /**
+ * @param {Target} target
+ * @param {String} propName
+ * @param {tweenTypes} [tweenType]
+ * @param {Object|void} [animationInlineStyles]
+ * @return {String|Number}
+ */
+ const getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => {
+ const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName);
+ return type === tweenTypes.OBJECT ? target[propName] || 0 :
+ type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) :
+ type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) :
+ type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() :
+ getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles);
+ };
+
+ /**
+ * @param {Number} x
+ * @param {Number} y
+ * @param {String} operator
+ * @return {Number}
+ */
+ const getRelativeValue = (x, y, operator) => {
+ return operator === '-' ? x - y :
+ operator === '+' ? x + y :
+ x * y;
+ };
+
+ /** @return {TweenDecomposedValue} */
+ const createDecomposedValueTargetObject = () => {
+ return {
+ /** @type {valueTypes} */
+ t: valueTypes.NUMBER,
+ n: 0,
+ u: null,
+ o: null,
+ d: null,
+ s: null,
+ }
+ };
+
+ /**
+ * @param {String|Number} rawValue
+ * @param {TweenDecomposedValue} targetObject
+ * @return {TweenDecomposedValue}
+ */
+ const decomposeRawValue = (rawValue, targetObject) => {
+ /** @type {valueTypes} */
+ targetObject.t = valueTypes.NUMBER;
+ targetObject.n = 0;
+ targetObject.u = null;
+ targetObject.o = null;
+ targetObject.d = null;
+ targetObject.s = null;
+ if (!rawValue) return targetObject;
+ const num = +rawValue;
+ if (!isNaN(num)) {
+ // It's a number
+ targetObject.n = num;
+ return targetObject;
+ } else {
+ // let str = /** @type {String} */(rawValue).trim();
+ let str = /** @type {String} */(rawValue);
+ // Parsing operators (+=, -=, *=) manually is much faster than using regex here
+ if (str[1] === '=') {
+ targetObject.o = str[0];
+ str = str.slice(2);
+ }
+ // Skip exec regex if the value type is complex or color to avoid long regex backtracking
+ const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str);
+ if (unitMatch) {
+ // Has a number and a unit
+ targetObject.t = valueTypes.UNIT;
+ targetObject.n = +unitMatch[1];
+ targetObject.u = unitMatch[2];
+ return targetObject;
+ } else if (targetObject.o) {
+ // Has an operator (+=, -=, *=)
+ targetObject.n = +str;
+ return targetObject;
+ } else if (isCol(str)) {
+ // Is a color
+ targetObject.t = valueTypes.COLOR;
+ targetObject.d = convertColorStringValuesToRgbaArray(str);
+ return targetObject;
+ } else {
+ // Is a more complex string (generally svg coords, calc() or filters CSS values)
+ const matchedNumbers = str.match(digitWithExponentRgx);
+ targetObject.t = valueTypes.COMPLEX;
+ targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : [];
+ targetObject.s = str.split(digitWithExponentRgx) || [];
+ return targetObject;
+ }
+ }
+ };
+
+ /**
+ * @param {Tween} tween
+ * @param {TweenDecomposedValue} targetObject
+ * @return {TweenDecomposedValue}
+ */
+ const decomposeTweenValue = (tween, targetObject) => {
+ targetObject.t = tween._valueType;
+ targetObject.n = tween._toNumber;
+ targetObject.u = tween._unit;
+ targetObject.o = null;
+ targetObject.d = cloneArray(tween._toNumbers);
+ targetObject.s = cloneArray(tween._strings);
+ return targetObject;
+ };
+
+ const decomposedOriginalValue = createDecomposedValueTargetObject();
+
+
+
+
+
+
+
+ /**
+ * @param {Tickable} tickable
+ * @param {Number} time
+ * @param {Number} muteCallbacks
+ * @param {Number} internalRender
+ * @param {tickModes} tickMode
+ * @return {Number}
+ */
+ const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
+
+ const parent = tickable.parent;
+ const duration = tickable.duration;
+ const completed = tickable.completed;
+ const iterationDuration = tickable.iterationDuration;
+ const iterationCount = tickable.iterationCount;
+ const _currentIteration = tickable._currentIteration;
+ const _loopDelay = tickable._loopDelay;
+ const _reversed = tickable._reversed;
+ const _alternate = tickable._alternate;
+ const _hasChildren = tickable._hasChildren;
+ const tickableDelay = tickable._delay;
+ const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime
+
+ const tickableEndTime = tickableDelay + iterationDuration;
+ const tickableAbsoluteTime = time - tickableDelay;
+ const tickablePrevTime = clamp$1(tickablePrevAbsoluteTime, -tickableDelay, duration);
+ const tickableCurrentTime = clamp$1(tickableAbsoluteTime, -tickableDelay, duration);
+ const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime;
+ const isCurrentTimeAboveZero = tickableCurrentTime > 0;
+ const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration;
+ const isSetter = duration <= minValue;
+ const forcedTick = tickMode === tickModes.FORCE;
+
+ let isOdd = 0;
+ let iterationElapsedTime = tickableAbsoluteTime;
+ // Render checks
+ // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer
+ let hasRendered = 0;
+
+ // Execute the "expensive" iterations calculations only when necessary
+ if (iterationCount > 1) {
+ // bitwise NOT operator seems to be generally faster than Math.floor() across browsers
+ const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay)));
+ tickable._currentIteration = clamp$1(currentIteration, 0, iterationCount);
+ // Prevent the iteration count to go above the max iterations when reaching the end of the animation
+ if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--;
+ isOdd = tickable._currentIteration % 2;
+ iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0;
+ }
+
+ // Checks if exactly one of _reversed and (_alternate && isOdd) is true
+ const isReversed = _reversed ^ (_alternate && isOdd);
+ const _ease = /** @type {Renderable} */(tickable)._ease;
+ let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime;
+ if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0;
+ const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed;
+
+ tickable._currentTime = tickableAbsoluteTime;
+ tickable._iterationTime = iterationTime;
+ tickable.backwards = isRunningBackwards;
+
+ if (isCurrentTimeAboveZero && !tickable.began) {
+ tickable.began = true;
+ if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) {
+ tickable.onBegin(/** @type {CallbackArgument} */(tickable));
+ }
+ } else if (tickableAbsoluteTime <= 0) {
+ tickable.began = false;
+ }
+
+ // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function
+ // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values
+ if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) {
+ tickable.onLoop(/** @type {CallbackArgument} */(tickable));
+ }
+
+ if (
+ forcedTick ||
+ tickMode === tickModes.AUTO && (
+ time >= tickableDelay && time <= tickableEndTime || // Normal render
+ time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state
+ time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state
+ ) ||
+ iterationTime >= tickableEndTime && tickablePrevTime !== duration ||
+ iterationTime <= tickableDelay && tickablePrevTime > 0 ||
+ time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation
+ isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped
+ ) {
+
+ if (isCurrentTimeAboveZero) {
+ // Trigger onUpdate callback before rendering
+ tickable.computeDeltaTime(tickablePrevTime);
+ if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable));
+ }
+
+ // Start tweens rendering
+ if (!_hasChildren) {
+
+ // Time has jumped more than globals.tickThreshold so consider this tick manual
+ const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold;
+ const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime;
+
+ // Only Animation can have tweens, Timer returns undefined
+ let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head);
+ let tweenTarget;
+ let tweenStyle;
+ let tweenTargetTransforms;
+ let tweenTargetTransformsProperties;
+ let tweenTransformsNeedUpdate = 0;
+
+ while (tween) {
+
+ const tweenComposition = tween._composition;
+ const tweenCurrentTime = tween._currentTime;
+ const tweenChangeDuration = tween._changeDuration;
+ const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration;
+ const tweenNextRep = tween._nextRep;
+ const tweenPrevRep = tween._prevRep;
+ const tweenHasComposition = tweenComposition !== compositionTypes.none;
+
+ if ((forcedRender || (
+ (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) &&
+ (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime)
+ )) && (!tweenHasComposition || (
+ !tween._isOverridden &&
+ (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) &&
+ (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) &&
+ (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay)))
+ ))
+ ) {
+
+ const tweenNewTime = tween._currentTime = clamp$1(iterationTime - tween._startTime, 0, tweenChangeDuration);
+ const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration);
+ const tweenModifier = tween._modifier;
+ const tweenValueType = tween._valueType;
+ const tweenType = tween._tweenType;
+ const tweenIsObject = tweenType === tweenTypes.OBJECT;
+ const tweenIsNumber = tweenValueType === valueTypes.NUMBER;
+ // Only round the in-between frames values if the final value is a string
+ const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision;
+
+ // Recompose tween value
+ /** @type {String|Number} */
+ let value;
+ /** @type {Number} */
+ let number;
+
+ if (tweenIsNumber) {
+ value = number = /** @type {Number} */(tweenModifier(round$1(lerp$1(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
+ } else if (tweenValueType === valueTypes.UNIT) {
+ // Rounding the values speed up string composition
+ number = /** @type {Number} */(tweenModifier(round$1(lerp$1(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
+ value = `${number}${tween._unit}`;
+ } else if (tweenValueType === valueTypes.COLOR) {
+ const fn = tween._fromNumbers;
+ const tn = tween._toNumbers;
+ const r = round$1(clamp$1(/** @type {Number} */(tweenModifier(lerp$1(fn[0], tn[0], tweenProgress))), 0, 255), 0);
+ const g = round$1(clamp$1(/** @type {Number} */(tweenModifier(lerp$1(fn[1], tn[1], tweenProgress))), 0, 255), 0);
+ const b = round$1(clamp$1(/** @type {Number} */(tweenModifier(lerp$1(fn[2], tn[2], tweenProgress))), 0, 255), 0);
+ const a = clamp$1(/** @type {Number} */(tweenModifier(round$1(lerp$1(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
+ value = `rgba(${r},${g},${b},${a})`;
+ if (tweenHasComposition) {
+ const ns = tween._numbers;
+ ns[0] = r;
+ ns[1] = g;
+ ns[2] = b;
+ ns[3] = a;
+ }
+ } else if (tweenValueType === valueTypes.COMPLEX) {
+ value = tween._strings[0];
+ for (let j = 0, l = tween._toNumbers.length; j < l; j++) {
+ const n = /** @type {Number} */(tweenModifier(round$1(lerp$1(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
+ const s = tween._strings[j + 1];
+ value += `${s ? n + s : n}`;
+ if (tweenHasComposition) {
+ tween._numbers[j] = n;
+ }
+ }
+ }
+
+ // For additive tweens and Animatables
+ if (tweenHasComposition) {
+ tween._number = number;
+ }
+
+ if (!internalRender && tweenComposition !== compositionTypes.blend) {
+
+ const tweenProperty = tween.property;
+ tweenTarget = tween.target;
+
+ if (tweenIsObject) {
+ tweenTarget[tweenProperty] = value;
+ } else if (tweenType === tweenTypes.ATTRIBUTE) {
+ /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value));
+ } else {
+ tweenStyle = /** @type {DOMTarget} */(tweenTarget).style;
+ if (tweenType === tweenTypes.TRANSFORM) {
+ if (tweenTarget !== tweenTargetTransforms) {
+ tweenTargetTransforms = tweenTarget;
+ // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage.
+ tweenTargetTransformsProperties = tweenTarget[transformsSymbol];
+ }
+ tweenTargetTransformsProperties[tweenProperty] = value;
+ tweenTransformsNeedUpdate = 1;
+ } else if (tweenType === tweenTypes.CSS) {
+ tweenStyle[tweenProperty] = value;
+ } else if (tweenType === tweenTypes.CSS_VAR) {
+ tweenStyle.setProperty(tweenProperty,/** @type {String} */(value));
+ }
+ }
+
+ if (isCurrentTimeAboveZero) hasRendered = 1;
+
+ } else {
+ // Used for composing timeline tweens without having to do a real render
+ tween._value = value;
+ }
+
+ }
+
+ // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax
+ // to reduce memory usage on string composition
+ if (tweenTransformsNeedUpdate && tween._renderTransforms) {
+ let str = emptyString;
+ for (let key in tweenTargetTransformsProperties) {
+ str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `;
+ }
+ tweenStyle.transform = str;
+ tweenTransformsNeedUpdate = 0;
+ }
+
+ tween = tween._next;
+ }
+
+ if (!muteCallbacks && hasRendered) {
+ /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable));
+ }
+ }
+
+ if (!muteCallbacks && isCurrentTimeAboveZero) {
+ tickable.onUpdate(/** @type {CallbackArgument} */(tickable));
+ }
+
+ }
+
+ // End tweens rendering
+
+ // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards
+ if (parent && isSetter) {
+ if (!muteCallbacks && (
+ (parent.began && !isRunningBackwards && tickableAbsoluteTime >= duration && !completed) ||
+ (isRunningBackwards && tickableAbsoluteTime <= minValue && completed)
+ )) {
+ tickable.onComplete(/** @type {CallbackArgument} */(tickable));
+ tickable.completed = !isRunningBackwards;
+ }
+ // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops
+ } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) {
+ if (iterationCount === Infinity) {
+ // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer
+ tickable._startTime += tickable.duration;
+ } else if (tickable._currentIteration >= iterationCount - 1) {
+ // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick
+ tickable.paused = true;
+ if (!completed && !_hasChildren) {
+ // If the tickable has children, triggers onComplete() only when all children have completed in the tick function
+ tickable.completed = true;
+ if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) {
+ tickable.onComplete(/** @type {CallbackArgument} */(tickable));
+ tickable._resolve(/** @type {CallbackArgument} */(tickable));
+ }
+ }
+ }
+ // Otherwise set the completed flag to false
+ } else {
+ tickable.completed = false;
+ }
+
+ // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ?
+ return hasRendered;
+ };
+
+ /**
+ * @param {Tickable} tickable
+ * @param {Number} time
+ * @param {Number} muteCallbacks
+ * @param {Number} internalRender
+ * @param {Number} tickMode
+ * @return {void}
+ */
+ const tick = (tickable, time, muteCallbacks, internalRender, tickMode) => {
+ const _currentIteration = tickable._currentIteration;
+ render(tickable, time, muteCallbacks, internalRender, tickMode);
+ if (tickable._hasChildren) {
+ const tl = /** @type {Timeline} */(tickable);
+ const tlIsRunningBackwards = tl.backwards;
+ const tlChildrenTime = internalRender ? time : tl._iterationTime;
+ const tlCildrenTickTime = now();
+
+ let tlChildrenHasRendered = 0;
+ let tlChildrenHaveCompleted = true;
+
+ // If the timeline has looped forward, we need to manually triggers children skipped callbacks
+ if (!internalRender && tl._currentIteration !== _currentIteration) {
+ const tlIterationDuration = tl.iterationDuration;
+ forEachChildren(tl, (/** @type {JSAnimation} */child) => {
+ if (!tlIsRunningBackwards) {
+ // Force an internal render to trigger the callbacks if the child has not completed on loop
+ if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) {
+ render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE);
+ }
+ // Reset their began and completed flags to allow retrigering callbacks on the next iteration
+ child.began = false;
+ child.completed = false;
+ } else {
+ const childDuration = child.duration;
+ const childStartTime = child._offset + child._delay;
+ const childEndTime = childStartTime + childDuration;
+ // Triggers the onComplete callback on reverse for children on the edges of the timeline
+ if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) {
+ child.onComplete(child);
+ }
+ }
+ });
+ if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl));
+ }
+
+ forEachChildren(tl, (/** @type {JSAnimation} */child) => {
+ const childTime = round$1((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds
+ const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode;
+ tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode);
+ if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false;
+ }, tlIsRunningBackwards);
+
+ // Renders on timeline are triggered by its children so it needs to be set after rendering the children
+ if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl));
+
+ // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end
+ if ((tlChildrenHaveCompleted || tlIsRunningBackwards) && tl._currentTime >= tl.duration) {
+ // Make sure the paused flag is false in case it has been skipped in the render function
+ tl.paused = true;
+ if (!tl.completed) {
+ tl.completed = true;
+ if (!muteCallbacks) {
+ tl.onComplete(/** @type {CallbackArgument} */(tl));
+ tl._resolve(/** @type {CallbackArgument} */(tl));
+ }
+ }
+ }
+ }
+ };
+
+ const propertyNamesCache = {};
+
+
+
+
+
+
+ /**
+ * @param {String} propertyName
+ * @param {Target} target
+ * @param {tweenTypes} tweenType
+ * @return {String}
+ */
+ const sanitizePropertyName = (propertyName, target, tweenType) => {
+ if (tweenType === tweenTypes.TRANSFORM) {
+ const t = shortTransforms.get(propertyName);
+ return t ? t : propertyName;
+ } else if (
+ tweenType === tweenTypes.CSS ||
+ // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
+ // but properties like "baseFrequency" should stay in lowerCamelCase
+ (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
+ ) {
+ const cachedPropertyName = propertyNamesCache[propertyName];
+ if (cachedPropertyName) {
+ return cachedPropertyName;
+ } else {
+ const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
+ propertyNamesCache[propertyName] = lowerCaseName;
+ return lowerCaseName;
+ }
+ } else {
+ return propertyName;
+ }
+ };
+
+ /**
+ * @template {Renderable} T
+ * @param {T} renderable
+ * @return {T}
+ */
+ const cleanInlineStyles = renderable => {
+ // Allow cleanInlineStyles() to be called on timelines
+ if (renderable._hasChildren) {
+ forEachChildren(renderable, cleanInlineStyles, true);
+ } else {
+ const animation = /** @type {JSAnimation} */(renderable);
+ animation.pause();
+ forEachChildren(animation, (/** @type {Tween} */tween) => {
+ const tweenProperty = tween.property;
+ const tweenTarget = tween.target;
+ if (tweenTarget[isDomSymbol]) {
+ const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
+ const originalInlinedValue = animation._inlineStyles[tweenProperty];
+ if (tween._tweenType === tweenTypes.TRANSFORM) {
+ const cachedTransforms = tweenTarget[transformsSymbol];
+ if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
+ delete cachedTransforms[tweenProperty];
+ } else {
+ cachedTransforms[tweenProperty] = originalInlinedValue;
+ }
+ if (tween._renderTransforms) {
+ if (!Object.keys(cachedTransforms).length) {
+ targetStyle.removeProperty('transform');
+ } else {
+ let str = emptyString;
+ for (let key in cachedTransforms) {
+ str += transformsFragmentStrings[key] + cachedTransforms[key] + ') ';
+ }
+ targetStyle.transform = str;
+ }
+ }
+ } else {
+ if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
+ targetStyle.removeProperty(tweenProperty);
+ } else {
+ targetStyle[tweenProperty] = originalInlinedValue;
+ }
+ }
+ if (animation._tail === tween) {
+ animation.targets.forEach(t => {
+ if (t.getAttribute && t.getAttribute('style') === emptyString) {
+ t.removeAttribute('style');
+ } });
+ }
+ }
+ });
+ }
+ return renderable;
+ };
+
+
+
+ /*
+ * Base class to control framerate and playback rate.
+ * Inherited by Engine, Timer, Animation and Timeline.
+ */
+ class Clock {
+
+ /** @param {Number} [initTime] */
+ constructor(initTime = 0) {
+ /** @type {Number} */
+ this.deltaTime = 0;
+ /** @type {Number} */
+ this._currentTime = initTime;
+ /** @type {Number} */
+ this._elapsedTime = initTime;
+ /** @type {Number} */
+ this._startTime = initTime;
+ /** @type {Number} */
+ this._lastTime = initTime;
+ /** @type {Number} */
+ this._scheduledTime = 0;
+ /** @type {Number} */
+ this._frameDuration = round$1(K / maxFps, 0);
+ /** @type {Number} */
+ this._fps = maxFps;
+ /** @type {Number} */
+ this._speed = 1;
+ /** @type {Boolean} */
+ this._hasChildren = false;
+ /** @type {Tickable|Tween} */
+ this._head = null;
+ /** @type {Tickable|Tween} */
+ this._tail = null;
+ }
+
+ get fps() {
+ return this._fps;
+ }
+
+ set fps(frameRate) {
+ const previousFrameDuration = this._frameDuration;
+ const fr = +frameRate;
+ const fps = fr < minValue ? minValue : fr;
+ const frameDuration = round$1(K / fps, 0);
+ this._fps = fps;
+ this._frameDuration = frameDuration;
+ this._scheduledTime += frameDuration - previousFrameDuration;
+ }
+
+ get speed() {
+ return this._speed;
+ }
+
+ set speed(playbackRate) {
+ const pbr = +playbackRate;
+ this._speed = pbr < minValue ? minValue : pbr;
+ }
+
+ /**
+ * @param {Number} time
+ * @return {tickModes}
+ */
+ requestTick(time) {
+ const scheduledTime = this._scheduledTime;
+ const elapsedTime = this._elapsedTime;
+ this._elapsedTime += (time - elapsedTime);
+ // If the elapsed time is lower than the scheduled time
+ // this means not enough time has passed to hit one frameDuration
+ // so skip that frame
+ if (elapsedTime < scheduledTime) return tickModes.NONE;
+ const frameDuration = this._frameDuration;
+ const frameDelta = elapsedTime - scheduledTime;
+ // Ensures that _scheduledTime progresses in steps of at least 1 frameDuration.
+ // Skips ahead if the actual elapsed time is higher.
+ this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta;
+ return tickModes.AUTO;
+ }
+
+ /**
+ * @param {Number} time
+ * @return {Number}
+ */
+ computeDeltaTime(time) {
+ const delta = time - this._lastTime;
+ this.deltaTime = delta;
+ this._lastTime = time;
+ return delta;
+ }
+
+ }
+
+ const additive = {
+ animation: null,
+ update: noop,
+ };
+
+
+
+ /**
+ * @typedef AdditiveAnimation
+ * @property {Number} duration
+ * @property {Number} _offset
+ * @property {Number} _delay
+ * @property {Tween} _head
+ * @property {Tween} _tail
+ */
+
+ /**
+ * @param {TweenAdditiveLookups} lookups
+ * @return {AdditiveAnimation}
+ */
+ const addAdditiveAnimation = lookups => {
+ let animation = additive.animation;
+ if (!animation) {
+ animation = {
+ duration: minValue,
+ computeDeltaTime: noop,
+ _offset: 0,
+ _delay: 0,
+ _head: null,
+ _tail: null,
+ };
+ additive.animation = animation;
+ additive.update = () => {
+ lookups.forEach(propertyAnimation => {
+ for (let propertyName in propertyAnimation) {
+ const tweens = propertyAnimation[propertyName];
+ const lookupTween = tweens._head;
+ if (lookupTween) {
+ const valueType = lookupTween._valueType;
+ const additiveValues = valueType === valueTypes.COMPLEX || valueType === valueTypes.COLOR ? cloneArray(lookupTween._fromNumbers) : null;
+ let additiveValue = lookupTween._fromNumber;
+ let tween = tweens._tail;
+ while (tween && tween !== lookupTween) {
+ if (additiveValues) {
+ for (let i = 0, l = tween._numbers.length; i < l; i++) additiveValues[i] += tween._numbers[i];
+ } else {
+ additiveValue += tween._number;
+ }
+ tween = tween._prevAdd;
+ }
+ lookupTween._toNumber = additiveValue;
+ lookupTween._toNumbers = additiveValues;
+ }
+ }
+ });
+ // TODO: Avoid polymorphism here, idealy the additive animation should be a regular animation with a higher priority in the render loop
+ render(animation, 1, 1, 0, tickModes.FORCE);
+ };
+ }
+ return animation;
+ };
+
+
+
+
+
+ const engineTickMethod = /*#__PURE__*/ (() => isBrowser ? requestAnimationFrame : setImmediate)();
+ const engineCancelMethod = /*#__PURE__*/ (() => isBrowser ? cancelAnimationFrame : clearImmediate)();
+
+ class Engine extends Clock {
+
+ /** @param {Number} [initTime] */
+ constructor(initTime) {
+ super(initTime);
+ this.useDefaultMainLoop = true;
+ this.pauseOnDocumentHidden = true;
+ /** @type {DefaultsParams} */
+ this.defaults = defaults;
+ // this.paused = isBrowser && doc.hidden ? true : false;
+ this.paused = true;
+ /** @type {Number|NodeJS.Immediate} */
+ this.reqId = 0;
+ }
+
+ update() {
+ const time = this._currentTime = now();
+ if (this.requestTick(time)) {
+ this.computeDeltaTime(time);
+ const engineSpeed = this._speed;
+ const engineFps = this._fps;
+ let activeTickable = /** @type {Tickable} */(this._head);
+ while (activeTickable) {
+ const nextTickable = activeTickable._next;
+ if (!activeTickable.paused) {
+ tick(
+ activeTickable,
+ (time - activeTickable._startTime) * activeTickable._speed * engineSpeed,
+ 0, // !muteCallbacks
+ 0, // !internalRender
+ activeTickable._fps < engineFps ? activeTickable.requestTick(time) : tickModes.AUTO
+ );
+ } else {
+ removeChild(this, activeTickable);
+ this._hasChildren = !!this._tail;
+ activeTickable._running = false;
+ if (activeTickable.completed && !activeTickable._cancelled) {
+ activeTickable.cancel();
+ }
+ }
+ activeTickable = nextTickable;
+ }
+ additive.update();
+ }
+ }
+
+ wake() {
+ if (this.useDefaultMainLoop && !this.reqId) {
+ // Imediatly request a tick to update engine._elapsedTime and get accurate offsetPosition calculation in timer.js
+ this.requestTick(now());
+ this.reqId = engineTickMethod(tickEngine);
+ }
+ return this;
+ }
+
+ pause() {
+ if (!this.reqId) return;
+ this.paused = true;
+ return killEngine();
+ }
+
+ resume() {
+ if (!this.paused) return;
+ this.paused = false;
+ forEachChildren(this, (/** @type {Tickable} */child) => child.resetTime());
+ return this.wake();
+ }
+
+ // Getter and setter for speed
+ get speed() {
+ return this._speed * (globals.timeScale === 1 ? 1 : K);
+ }
+
+ set speed(playbackRate) {
+ this._speed = playbackRate * globals.timeScale;
+ forEachChildren(this, (/** @type {Tickable} */child) => child.speed = child._speed);
+ }
+
+ // Getter and setter for timeUnit
+ get timeUnit() {
+ return globals.timeScale === 1 ? 'ms' : 's';
+ }
+
+ set timeUnit(unit) {
+ const secondsScale = 0.001;
+ const isSecond = unit === 's';
+ const newScale = isSecond ? secondsScale : 1;
+ if (globals.timeScale !== newScale) {
+ globals.timeScale = newScale;
+ globals.tickThreshold = 200 * newScale;
+ const scaleFactor = isSecond ? secondsScale : K;
+ /** @type {Number} */
+ (this.defaults.duration) *= scaleFactor;
+ this._speed *= scaleFactor;
+ }
+ }
+
+ // Getter and setter for precision
+ get precision() {
+ return globals.precision;
+ }
+
+ set precision(precision) {
+ globals.precision = precision;
+ }
+
+ }
+
+ const engine = /*#__PURE__*/(() => {
+ const engine = new Engine(now());
+ if (isBrowser) {
+ globalVersions.engine = engine;
+ doc.addEventListener('visibilitychange', () => {
+ if (!engine.pauseOnDocumentHidden) return;
+ doc.hidden ? engine.pause() : engine.resume();
+ });
+ }
+ return engine;
+ })();
+
+
+ const tickEngine = () => {
+ if (engine._head) {
+ engine.reqId = engineTickMethod(tickEngine);
+ engine.update();
+ } else {
+ engine.reqId = 0;
+ }
+ };
+
+ const killEngine = () => {
+ engineCancelMethod(/** @type {NodeJS.Immediate & Number} */(engine.reqId));
+ engine.reqId = 0;
+ return engine;
+ };
+
+
+
+ const lookups = {
+ /** @type {TweenReplaceLookups} */
+ _rep: new WeakMap(),
+ /** @type {TweenAdditiveLookups} */
+ _add: new Map(),
+ };
+
+ /**
+ * @param {Target} target
+ * @param {String} property
+ * @param {String} lookup
+ * @return {TweenPropertySiblings}
+ */
+ const getTweenSiblings = (target, property, lookup = '_rep') => {
+ const lookupMap = lookups[lookup];
+ let targetLookup = lookupMap.get(target);
+ if (!targetLookup) {
+ targetLookup = {};
+ lookupMap.set(target, targetLookup);
+ }
+ return targetLookup[property] ? targetLookup[property] : targetLookup[property] = {
+ _head: null,
+ _tail: null,
+ }
+ };
+
+ /**
+ * @param {Tween} p
+ * @param {Tween} c
+ * @return {Number|Boolean}
+ */
+ const addTweenSortMethod = (p, c) => {
+ return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime;
+ };
+
+ /**
+ * @param {Tween} tween
+ */
+ const overrideTween = tween => {
+ tween._isOverlapped = 1;
+ tween._isOverridden = 1;
+ tween._changeDuration = minValue;
+ tween._currentTime = minValue;
+ };
+
+ /**
+ * @param {Tween} tween
+ * @param {TweenPropertySiblings} siblings
+ * @return {Tween}
+ */
+ const composeTween = (tween, siblings) => {
+
+ const tweenCompositionType = tween._composition;
+
+ // Handle replaced tweens
+
+ if (tweenCompositionType === compositionTypes.replace) {
+
+ const tweenAbsStartTime = tween._absoluteStartTime;
+
+ addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep');
+
+ const prevSibling = tween._prevRep;
+
+ // Update the previous siblings for composition replace tweens
+
+ if (prevSibling) {
+
+ const prevParent = prevSibling.parent;
+ const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration;
+
+ // Handle looped animations tween
+
+ if (
+ // Check if the previous tween is from a different animation
+ tween.parent.id !== prevParent.id &&
+ // Check if the animation has loops
+ prevParent.iterationCount> 1 &&
+ // Check if _absoluteChangeEndTime of last loop overlaps the current tween
+ prevAbsEndTime + (prevParent.duration - prevParent.iterationDuration) > tweenAbsStartTime
+ ) {
+
+ // TODO: Find a way to only override the iterations overlapping with the tween
+ overrideTween(prevSibling);
+
+ let prevPrevSibling = prevSibling._prevRep;
+
+ // If the tween was part of a set of keyframes, override its siblings
+ while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) {
+ overrideTween(prevPrevSibling);
+ prevPrevSibling = prevPrevSibling._prevRep;
+ }
+
+ }
+
+ const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay;
+
+ if (prevAbsEndTime > absoluteUpdateStartTime) {
+
+ const prevChangeStartTime = prevSibling._startTime;
+ const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration);
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const updatedPrevChangeDuration = round$1(absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime, 12);
+
+ prevSibling._changeDuration = updatedPrevChangeDuration;
+ prevSibling._currentTime = updatedPrevChangeDuration;
+ prevSibling._isOverlapped = 1;
+
+ // Override the previous tween if its new _changeDuration is lower than minValue
+ // TODO: See if it's even neceseeary to test against minValue, checking for 0 might be enough
+ if (updatedPrevChangeDuration < minValue) {
+ overrideTween(prevSibling);
+ }
+ }
+
+ // Pause (and cancel) the parent if it only contains overlapped tweens
+
+ let pausePrevParentAnimation = true;
+
+ forEachChildren(prevParent, (/** @type Tween */t) => {
+ if (!t._isOverlapped) pausePrevParentAnimation = false;
+ });
+
+ if (pausePrevParentAnimation) {
+ const prevParentTL = prevParent.parent;
+ if (prevParentTL) {
+ let pausePrevParentTL = true;
+ forEachChildren(prevParentTL, (/** @type JSAnimation */a) => {
+ if (a !== prevParent) {
+ forEachChildren(a, (/** @type Tween */t) => {
+ if (!t._isOverlapped) pausePrevParentTL = false;
+ });
+ }
+ });
+ if (pausePrevParentTL) {
+ prevParentTL.cancel();
+ }
+ } else {
+ prevParent.cancel();
+ // Previously, calling .cancel() on a timeline child would affect the render order of other children
+ // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop
+ // This is no longer needed since timeline tween composition is now handled separately
+ // Keeping this here for reference
+ // prevParent.completed = true;
+ // prevParent.pause();
+ }
+ }
+
+ }
+
+ // let nextSibling = tween._nextRep;
+
+ // // All the next siblings are automatically overridden
+
+ // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) {
+ // while (nextSibling) {
+ // overrideTween(nextSibling);
+ // nextSibling = nextSibling._nextRep;
+ // }
+ // }
+
+ // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) {
+ // while (nextSibling) {
+ // overrideTween(nextSibling);
+ // console.log(tween.id, nextSibling.id);
+ // nextSibling = nextSibling._nextRep;
+ // }
+ // }
+
+ // Handle additive tweens composition
+
+ } else if (tweenCompositionType === compositionTypes.blend) {
+
+ const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add');
+ const additiveAnimation = addAdditiveAnimation(lookups._add);
+
+ let lookupTween = additiveTweenSiblings._head;
+
+ if (!lookupTween) {
+ lookupTween = { ...tween };
+ lookupTween._composition = compositionTypes.replace;
+ lookupTween._updateDuration = minValue;
+ lookupTween._startTime = 0;
+ lookupTween._numbers = cloneArray(tween._fromNumbers);
+ lookupTween._number = 0;
+ lookupTween._next = null;
+ lookupTween._prev = null;
+ addChild(additiveTweenSiblings, lookupTween);
+ addChild(additiveAnimation, lookupTween);
+ }
+
+ // Convert the values of TO to FROM and set TO to 0
+
+ const toNumber = tween._toNumber;
+ tween._fromNumber = lookupTween._fromNumber - toNumber;
+ tween._toNumber = 0;
+ tween._numbers = cloneArray(tween._fromNumbers);
+ tween._number = 0;
+ lookupTween._fromNumber = toNumber;
+
+ if (tween._toNumbers) {
+ const toNumbers = cloneArray(tween._toNumbers);
+ if (toNumbers) {
+ toNumbers.forEach((value, i) => {
+ tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value;
+ tween._toNumbers[i] = 0;
+ });
+ }
+ lookupTween._fromNumbers = toNumbers;
+ }
+
+ addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd');
+
+ }
+
+ return tween;
+
+ };
+
+ /**
+ * @param {Tween} tween
+ * @return {Tween}
+ */
+ const removeTweenSliblings = tween => {
+ const tweenComposition = tween._composition;
+ if (tweenComposition !== compositionTypes.none) {
+ const tweenTarget = tween.target;
+ const tweenProperty = tween.property;
+ const replaceTweensLookup = lookups._rep;
+ const replaceTargetProps = replaceTweensLookup.get(tweenTarget);
+ const tweenReplaceSiblings = replaceTargetProps[tweenProperty];
+ removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep');
+ if (tweenComposition === compositionTypes.blend) {
+ const addTweensLookup = lookups._add;
+ const addTargetProps = addTweensLookup.get(tweenTarget);
+ if (!addTargetProps) return;
+ const additiveTweenSiblings = addTargetProps[tweenProperty];
+ const additiveAnimation = additive.animation;
+ removeChild(additiveTweenSiblings, tween, '_prevAdd', '_nextAdd');
+ // If only one tween is left in the additive lookup, it's the tween lookup
+ const lookupTween = additiveTweenSiblings._head;
+ if (lookupTween && lookupTween === additiveTweenSiblings._tail) {
+ removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd');
+ removeChild(additiveAnimation, lookupTween);
+ let shouldClean = true;
+ for (let prop in addTargetProps) {
+ if (addTargetProps[prop]._head) {
+ shouldClean = false;
+ break;
+ }
+ }
+ if (shouldClean) {
+ addTweensLookup.delete(tweenTarget);
+ }
+ }
+ }
+ }
+ return tween;
+ };
+
+ /**
+ * @param {TargetsArray} targetsArray
+ * @param {JSAnimation} animation
+ * @param {String} [propertyName]
+ * @return {Boolean}
+ */
+ const removeTargetsFromJSAnimation = (targetsArray, animation, propertyName) => {
+ let tweensMatchesTargets = false;
+ forEachChildren(animation, (/**@type {Tween} */tween) => {
+ const tweenTarget = tween.target;
+ if (targetsArray.includes(tweenTarget)) {
+ const tweenName = tween.property;
+ const tweenType = tween._tweenType;
+ const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
+ if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
+ // Make sure to flag the previous CSS transform tween to renderTransform
+ if (tween.parent._tail === tween &&
+ tween._tweenType === tweenTypes.TRANSFORM &&
+ tween._prev &&
+ tween._prev._tweenType === tweenTypes.TRANSFORM
+ ) {
+ tween._prev._renderTransforms = 1;
+ }
+ // Removes the tween from the selected animation
+ removeChild(animation, tween);
+ // Detach the tween from its siblings to make sure blended tweens are correctlly removed
+ removeTweenSliblings(tween);
+ tweensMatchesTargets = true;
+ }
+ }
+ }, true);
+ return tweensMatchesTargets;
+ };
+
+ /**
+ * @param {TargetsArray} targetsArray
+ * @param {Renderable} [renderable]
+ * @param {String} [propertyName]
+ */
+ const removeTargetsFromRenderable = (targetsArray, renderable, propertyName) => {
+ const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine);
+ let removeMatches;
+ if (parent._hasChildren) {
+ let iterationDuration = 0;
+ forEachChildren(parent, (/** @type {Renderable} */child) => {
+ if (!child._hasChildren) {
+ removeMatches = removeTargetsFromJSAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName);
+ // Remove the child from its parent if no tweens and no children left after the removal
+ if (removeMatches && !child._head) {
+ child.cancel();
+ removeChild(parent, child);
+ } else {
+ // Calculate the new iterationDuration value to handle onComplete with last child in render()
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > iterationDuration) {
+ iterationDuration = childDur;
+ }
+ }
+ }
+ // Make sure to also remove engine's children targets
+ // NOTE: Avoid recursion?
+ if (child._head) {
+ removeTargetsFromRenderable(targetsArray, child, propertyName);
+ } else {
+ child._hasChildren = false;
+ }
+ }, true);
+ // Update iterationDuration value to handle onComplete with last child in render()
+ if (!isUnd(/** @type {Renderable} */(parent).iterationDuration)) {
+ /** @type {Renderable} */(parent).iterationDuration = iterationDuration;
+ }
+ } else {
+ removeMatches = removeTargetsFromJSAnimation(
+ targetsArray,
+ /** @type {JSAnimation} */(parent),
+ propertyName
+ );
+ }
+ if (removeMatches && !parent._head) {
+ parent._hasChildren = false;
+ // Cancel the parent if there are no tweens and no children left after the removal
+ // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
+ if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel();
+ }
+ };
+
+
+
+
+
+
+
+ /**
+ * @param {Timer} timer
+ * @return {Timer}
+ */
+ const resetTimerProperties = timer => {
+ timer.paused = true;
+ timer.began = false;
+ timer.completed = false;
+ return timer;
+ };
+
+ /**
+ * @param {Timer} timer
+ * @return {Timer}
+ */
+ const reviveTimer = timer => {
+ if (!timer._cancelled) return timer;
+ if (timer._hasChildren) {
+ forEachChildren(timer, reviveTimer);
+ } else {
+ forEachChildren(timer, (/** @type {Tween} tween*/tween) => {
+ if (tween._composition !== compositionTypes.none) {
+ composeTween(tween, getTweenSiblings(tween.target, tween.property));
+ }
+ });
+ }
+ timer._cancelled = 0;
+ return timer;
+ };
+
+ let timerId = 0;
+
+ /**
+ * Base class used to create Timers, Animations and Timelines
+ */
+ class Timer extends Clock {
+ /**
+ * @param {TimerParams} [parameters]
+ * @param {Timeline} [parent]
+ * @param {Number} [parentPosition]
+ */
+ constructor(parameters = {}, parent = null, parentPosition = 0) {
+
+ super(0);
+
+ const {
+ id,
+ delay,
+ duration,
+ reversed,
+ alternate,
+ loop,
+ loopDelay,
+ autoplay,
+ frameRate,
+ playbackRate,
+ onComplete,
+ onLoop,
+ onPause,
+ onBegin,
+ onBeforeUpdate,
+ onUpdate,
+ } = parameters;
+
+ if (scope.current) scope.current.register(this);
+
+ const timerInitTime = parent ? 0 : engine._elapsedTime;
+ const timerDefaults = parent ? parent.defaults : globals.defaults;
+ const timerDelay = /** @type {Number} */(isFnc(delay) || isUnd(delay) ? timerDefaults.delay : +delay);
+ const timerDuration = isFnc(duration) || isUnd(duration) ? Infinity : +duration;
+ const timerLoop = setValue(loop, timerDefaults.loop);
+ const timerLoopDelay = setValue(loopDelay, timerDefaults.loopDelay);
+ const timerIterationCount = timerLoop === true ||
+ timerLoop === Infinity ||
+ /** @type {Number} */(timerLoop) < 0 ? Infinity :
+ /** @type {Number} */(timerLoop) + 1;
+
+
+ let offsetPosition = 0;
+
+ if (parent) {
+ offsetPosition = parentPosition;
+ } else {
+ // Make sure to tick the engine once if not currently running to get up to date engine._elapsedTime
+ // to avoid big gaps with the following offsetPosition calculation
+ if (!engine.reqId) engine.requestTick(now());
+ // Make sure to scale the offset position with globals.timeScale to properly handle seconds unit
+ offsetPosition = (engine._elapsedTime - engine._startTime) * globals.timeScale;
+ }
+
+ // Timer's parameters
+ this.id = !isUnd(id) ? id : ++timerId;
+ /** @type {Timeline} */
+ this.parent = parent;
+ // Total duration of the timer
+ this.duration = clampInfinity(((timerDuration + timerLoopDelay) * timerIterationCount) - timerLoopDelay) || minValue;
+ /** @type {Boolean} */
+ this.backwards = false;
+ /** @type {Boolean} */
+ this.paused = true;
+ /** @type {Boolean} */
+ this.began = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Callback<this>} */
+ this.onBegin = onBegin || timerDefaults.onBegin;
+ /** @type {Callback<this>} */
+ this.onBeforeUpdate = onBeforeUpdate || timerDefaults.onBeforeUpdate;
+ /** @type {Callback<this>} */
+ this.onUpdate = onUpdate || timerDefaults.onUpdate;
+ /** @type {Callback<this>} */
+ this.onLoop = onLoop || timerDefaults.onLoop;
+ /** @type {Callback<this>} */
+ this.onPause = onPause || timerDefaults.onPause;
+ /** @type {Callback<this>} */
+ this.onComplete = onComplete || timerDefaults.onComplete;
+ /** @type {Number} */
+ this.iterationDuration = timerDuration; // Duration of one loop
+ /** @type {Number} */
+ this.iterationCount = timerIterationCount; // Number of loops
+ /** @type {Boolean|ScrollObserver} */
+ this._autoplay = parent ? false : setValue(autoplay, timerDefaults.autoplay);
+ /** @type {Number} */
+ this._offset = offsetPosition;
+ /** @type {Number} */
+ this._delay = timerDelay;
+ /** @type {Number} */
+ this._loopDelay = timerLoopDelay;
+ /** @type {Number} */
+ this._iterationTime = 0;
+ /** @type {Number} */
+ this._currentIteration = 0; // Current loop index
+ /** @type {Function} */
+ this._resolve = noop; // Used by .then()
+ /** @type {Boolean} */
+ this._running = false;
+ /** @type {Number} */
+ this._reversed = +setValue(reversed, timerDefaults.reversed);
+ /** @type {Number} */
+ this._reverse = this._reversed;
+ /** @type {Number} */
+ this._cancelled = 0;
+ /** @type {Boolean} */
+ this._alternate = setValue(alternate, timerDefaults.alternate);
+ /** @type {Renderable} */
+ this._prev = null;
+ /** @type {Renderable} */
+ this._next = null;
+
+ // Clock's parameters
+ /** @type {Number} */
+ this._elapsedTime = timerInitTime;
+ /** @type {Number} */
+ this._startTime = timerInitTime;
+ /** @type {Number} */
+ this._lastTime = timerInitTime;
+ /** @type {Number} */
+ this._fps = setValue(frameRate, timerDefaults.frameRate);
+ /** @type {Number} */
+ this._speed = setValue(playbackRate, timerDefaults.playbackRate);
+ }
+
+ get cancelled() {
+ return !!this._cancelled;
+ }
+
+ set cancelled(cancelled) {
+ cancelled ? this.cancel() : this.reset(1).play();
+ }
+
+ get currentTime() {
+ return clamp$1(round$1(this._currentTime, globals.precision), -this._delay, this.duration);
+ }
+
+ set currentTime(time) {
+ const paused = this.paused;
+ // Pausing the timer is necessary to avoid time jumps on a running instance
+ this.pause().seek(+time);
+ if (!paused) this.resume();
+ }
+
+ get iterationCurrentTime() {
+ return round$1(this._iterationTime, globals.precision);
+ }
+
+ set iterationCurrentTime(time) {
+ this.currentTime = (this.iterationDuration * this._currentIteration) + time;
+ }
+
+ get progress() {
+ return clamp$1(round$1(this._currentTime / this.duration, 10), 0, 1);
+ }
+
+ set progress(progress) {
+ this.currentTime = this.duration * progress;
+ }
+
+ get iterationProgress() {
+ return clamp$1(round$1(this._iterationTime / this.iterationDuration, 10), 0, 1);
+ }
+
+ set iterationProgress(progress) {
+ const iterationDuration = this.iterationDuration;
+ this.currentTime = (iterationDuration * this._currentIteration) + (iterationDuration * progress);
+ }
+
+ get currentIteration() {
+ return this._currentIteration;
+ }
+
+ set currentIteration(iterationCount) {
+ this.currentTime = (this.iterationDuration * clamp$1(+iterationCount, 0, this.iterationCount - 1));
+ }
+
+ get reversed() {
+ return !!this._reversed;
+ }
+
+ set reversed(reverse) {
+ reverse ? this.reverse() : this.play();
+ }
+
+ get speed() {
+ return super.speed;
+ }
+
+ set speed(playbackRate) {
+ super.speed = playbackRate;
+ this.resetTime();
+ }
+
+ /**
+ * @param {Number} internalRender
+ * @return {this}
+ */
+ reset(internalRender = 0) {
+ // If cancelled, revive the timer before rendering in order to have propertly composed tweens siblings
+ reviveTimer(this);
+ if (this._reversed && !this._reverse) this.reversed = false;
+ // Rendering before updating the completed flag to prevent skips and to make sure the properties are not overridden
+ // Setting the iterationTime at the end to force the rendering to happend backwards, otherwise calling .reset() on Timelines might not render children in the right order
+ // NOTE: This is only required for Timelines and might be better to move to the Timeline class?
+ this._iterationTime = this.iterationDuration;
+ // Set tickMode to tickModes.FORCE to force rendering
+ tick(this, 0, 1, internalRender, tickModes.FORCE);
+ // Reset timer properties after revive / render to make sure the props are not updated again
+ resetTimerProperties(this);
+ // Also reset children properties
+ if (this._hasChildren) {
+ forEachChildren(this, resetTimerProperties);
+ }
+ return this;
+ }
+
+ /**
+ * @param {Number} internalRender
+ * @return {this}
+ */
+ init(internalRender = 0) {
+ this.fps = this._fps;
+ this.speed = this._speed;
+ // Manually calling .init() on timelines should render all children intial state
+ // Forces all children to render once then render to 0 when reseted
+ if (!internalRender && this._hasChildren) {
+ tick(this, this.duration, 1, internalRender, tickModes.FORCE);
+ }
+ this.reset(internalRender);
+ // Make sure to set autoplay to false to child timers so it doesn't attempt to autoplay / link
+ const autoplay = this._autoplay;
+ if (autoplay === true) {
+ this.resume();
+ } else if (autoplay && !isUnd(/** @type {ScrollObserver} */(autoplay).linked)) {
+ /** @type {ScrollObserver} */(autoplay).link(this);
+ }
+ return this;
+ }
+
+ /** @return {this} */
+ resetTime() {
+ const timeScale = 1 / (this._speed * engine._speed);
+ // TODO: See if we can safely use engine._elapsedTime here
+ // if (!engine.reqId) engine.requestTick(now())
+ // this._startTime = engine._elapsedTime - (this._currentTime + this._delay) * timeScale;
+ this._startTime = now() - (this._currentTime + this._delay) * timeScale;
+ return this;
+ }
+
+ /** @return {this} */
+ pause() {
+ if (this.paused) return this;
+ this.paused = true;
+ this.onPause(this);
+ return this;
+ }
+
+ /** @return {this} */
+ resume() {
+ if (!this.paused) return this;
+ this.paused = false;
+ // We can safely imediatly render a timer that has no duration and no children
+ if (this.duration <= minValue && !this._hasChildren) {
+ tick(this, minValue, 0, 0, tickModes.FORCE);
+ } else {
+ if (!this._running) {
+ addChild(engine, this);
+ engine._hasChildren = true;
+ this._running = true;
+ }
+ this.resetTime();
+ // Forces the timer to advance by at least one frame when the next tick occurs
+ this._startTime -= 12;
+ engine.wake();
+ }
+ return this;
+ }
+
+ /** @return {this} */
+ restart() {
+ return this.reset(0).resume();
+ }
+
+ /**
+ * @param {Number} time
+ * @param {Boolean|Number} [muteCallbacks]
+ * @param {Boolean|Number} [internalRender]
+ * @return {this}
+ */
+ seek(time, muteCallbacks = 0, internalRender = 0) {
+ // Recompose the tween siblings in case the timer has been cancelled
+ reviveTimer(this);
+ // If you seek a completed animation, otherwise the next play will starts at 0
+ this.completed = false;
+ const isPaused = this.paused;
+ this.paused = true;
+ // timer, time, muteCallbacks, internalRender, tickMode
+ tick(this, time + this._delay, ~~muteCallbacks, ~~internalRender, tickModes.AUTO);
+ return isPaused ? this : this.resume();
+ }
+
+ /** @return {this} */
+ alternate() {
+ const reversed = this._reversed;
+ const count = this.iterationCount;
+ const duration = this.iterationDuration;
+ // Calculate the maximum iterations possible given the iteration duration
+ const iterations = count === Infinity ? floor(maxValue / duration) : count;
+ this._reversed = +(this._alternate && !(iterations % 2) ? reversed : !reversed);
+ if (count === Infinity) {
+ // Handle infinite loops to loop on themself
+ this.iterationProgress = this._reversed ? 1 - this.iterationProgress : this.iterationProgress;
+ } else {
+ this.seek((duration * iterations) - this._currentTime);
+ }
+ this.resetTime();
+ return this;
+ }
+
+ /** @return {this} */
+ play() {
+ if (this._reversed) this.alternate();
+ return this.resume();
+ }
+
+ /** @return {this} */
+ reverse() {
+ if (!this._reversed) this.alternate();
+ return this.resume();
+ }
+
+ // TODO: Move all the animation / tweens / children related code to Animation / Timeline
+
+ /** @return {this} */
+ cancel() {
+ if (this._hasChildren) {
+ forEachChildren(this, (/** @type {Renderable} */child) => child.cancel(), true);
+ } else {
+ forEachChildren(this, removeTweenSliblings);
+ }
+ this._cancelled = 1;
+ // Pausing the timer removes it from the engine
+ return this.pause();
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ const normlizedDuration = normalizeTime(newDuration);
+ if (currentDuration === normlizedDuration) return this;
+ const timeScale = newDuration / currentDuration;
+ const isSetter = newDuration <= minValue;
+ this.duration = isSetter ? minValue : normlizedDuration;
+ this.iterationDuration = isSetter ? minValue : normalizeTime(this.iterationDuration * timeScale);
+ this._offset *= timeScale;
+ this._delay *= timeScale;
+ this._loopDelay *= timeScale;
+ return this;
+ }
+
+ /**
+ * Cancels the timer by seeking it back to 0 and reverting the attached scroller if necessary
+ * @return {this}
+ */
+ revert() {
+ tick(this, 0, 1, 0, tickModes.AUTO);
+ const ap = /** @type {ScrollObserver} */(this._autoplay);
+ if (ap && ap.linked && ap.linked === this) ap.revert();
+ return this.cancel();
+ }
+
+ /**
+ * Imediatly completes the timer, cancels it and triggers the onComplete callback
+ * @return {this}
+ */
+ complete() {
+ return this.seek(this.duration).cancel();
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback = noop) {
+ const then = this.then;
+ const onResolve = () => {
+ // this.then = null prevents infinite recursion if returned by an async function
+ // https://github.com/juliangarnierorg/anime-beta/issues/26
+ this.then = null;
+ callback(this);
+ this.then = then;
+ this._resolve = noop;
+ };
+ return new Promise(r => {
+ this._resolve = () => r(onResolve());
+ // Make sure to resolve imediatly if the timer has already completed
+ if (this.completed) this._resolve();
+ return this;
+ });
+ }
+
+ }
+
+ /**
+ * @param {TimerParams} [parameters]
+ * @return {Timer}
+ */
+ const createTimer = parameters => new Timer(parameters, null, 0).init();
+
+
+
+ /**
+ * @param {DOMTargetsParam|TargetsParam} v
+ * @return {NodeList|HTMLCollection}
+ */
+ function getNodeList(v) {
+ const n = isStr(v) ? scope.root.querySelectorAll(v) : v;
+ if (n instanceof NodeList || n instanceof HTMLCollection) return n;
+ }
+
+ /**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+ function parseTargets(targets) {
+ if (isNil(targets)) return /** @type {TargetsArray} */([]);
+ if (!isBrowser) return /** @type {JSTargetsArray} */(isArr(targets) && targets.flat(Infinity) || [targets]);
+ if (isArr(targets)) {
+ const flattened = targets.flat(Infinity);
+ /** @type {TargetsArray} */
+ const parsed = [];
+ for (let i = 0, l = flattened.length; i < l; i++) {
+ const item = flattened[i];
+ if (!isNil(item)) {
+ const nodeList = getNodeList(item);
+ if (nodeList) {
+ for (let j = 0, jl = nodeList.length; j < jl; j++) {
+ const subItem = nodeList[j];
+ if (!isNil(subItem)) {
+ let isDuplicate = false;
+ for (let k = 0, kl = parsed.length; k < kl; k++) {
+ if (parsed[k] === subItem) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ parsed.push(subItem);
+ }
+ }
+ }
+ } else {
+ let isDuplicate = false;
+ for (let j = 0, jl = parsed.length; j < jl; j++) {
+ if (parsed[j] === item) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ parsed.push(item);
+ }
+ }
+ }
+ }
+ return parsed;
+ }
+ const nodeList = getNodeList(targets);
+ if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList));
+ return /** @type {TargetsArray} */([targets]);
+ }
+
+ /**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+ function registerTargets(targets) {
+ const parsedTargetsArray = parseTargets(targets);
+ const parsedTargetsLength = parsedTargetsArray.length;
+ if (parsedTargetsLength) {
+ for (let i = 0; i < parsedTargetsLength; i++) {
+ const target = parsedTargetsArray[i];
+ if (!target[isRegisteredTargetSymbol]) {
+ target[isRegisteredTargetSymbol] = true;
+ const isSvgType = isSvg(target);
+ const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType;
+ if (isDom) {
+ target[isDomSymbol] = true;
+ target[isSvgSymbol] = isSvgType;
+ target[transformsSymbol] = {};
+ }
+ }
+ }
+ }
+ return parsedTargetsArray;
+ }
+
+ const angleUnitsMap = { 'deg': 1, 'rad': 180 / PI, 'turn': 360 };
+ const convertedValuesCache = {};
+
+
+
+ /**
+ * @param {DOMTarget} el
+ * @param {TweenDecomposedValue} decomposedValue
+ * @param {String} unit
+ * @param {Boolean} [force]
+ * @return {TweenDecomposedValue}
+ */
+ const convertValueUnit = (el, decomposedValue, unit, force = false) => {
+ const currentUnit = decomposedValue.u;
+ const currentNumber = decomposedValue.n;
+ if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary
+ return decomposedValue;
+ }
+ const cachedKey = currentNumber + currentUnit + unit;
+ const cached = convertedValuesCache[cachedKey];
+ if (!isUnd(cached) && !force) {
+ decomposedValue.n = cached;
+ } else {
+ let convertedValue;
+ if (currentUnit in angleUnitsMap) {
+ convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit];
+ } else {
+ const baseline = 100;
+ const tempEl = /** @type {DOMTarget} */(el.cloneNode());
+ const parentNode = el.parentNode;
+ const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body;
+ parentEl.appendChild(tempEl);
+ const elStyle = tempEl.style;
+ elStyle.width = baseline + currentUnit;
+ const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
+ elStyle.width = baseline + unit;
+ const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
+ const factor = currentUnitWidth / newUnitWidth;
+ parentEl.removeChild(tempEl);
+ convertedValue = factor * currentNumber;
+ }
+ decomposedValue.n = convertedValue;
+ convertedValuesCache[cachedKey] = convertedValue;
+ }
+ decomposedValue.t === valueTypes.UNIT;
+ decomposedValue.u = unit;
+ return decomposedValue;
+ };
+
+
+
+ /** @type {EasingFunction} */
+ const none = t => t;
+
+
+
+ /** @type {PowerEasing} */
+ const easeInPower = (p = 1.68) => t => pow(t, +p);
+
+ /**
+ * @callback EaseType
+ * @param {EasingFunction} Ease
+ * @return {EasingFunction}
+ */
+
+ /** @type {Record<String, EaseType>} */
+ const easeTypes = {
+ in: easeIn => t => easeIn(t),
+ out: easeIn => t => 1 - easeIn(1 - t),
+ inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2,
+ outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2,
+ };
+
+ /**
+ * @param {String} string
+ * @param {Record<String, EasingFunctionWithParams|EasingFunction>} easesFunctions
+ * @param {Object} easesLookups
+ * @return {EasingFunction}
+ */
+ const parseEaseString = (string, easesFunctions, easesLookups) => {
+ if (easesLookups[string]) return easesLookups[string];
+ if (string.indexOf('(') <= -1) {
+ const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic');
+ const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasingFunctionWithParams} */(easesFunctions[string])() : easesFunctions[string]);
+ return parsedFn ? easesLookups[string] = parsedFn : none;
+ } else {
+ const split = string.slice(0, -1).split('(');
+ const parsedFn = /** @type {EasingFunctionWithParams} */(easesFunctions[split[0]]);
+ return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none;
+ }
+ };
+
+
+
+ /**
+ * Cubic Bezier solver adapted from https://github.com/gre/bezier-easing
+ * (c) 2014 Gaëtan Renaudeau
+ */
+
+ /**
+ * @param {Number} aT
+ * @param {Number} aA1
+ * @param {Number} aA2
+ * @return {Number}
+ */
+ const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT;
+
+ /**
+ * @param {Number} aX
+ * @param {Number} mX1
+ * @param {Number} mX2
+ * @return {Number}
+ */
+ const binarySubdivide = (aX, mX1, mX2) => {
+ let aA = 0, aB = 1, currentX, currentT, i = 0;
+ do {
+ currentT = aA + (aB - aA) / 2;
+ currentX = calcBezier(currentT, mX1, mX2) - aX;
+ if (currentX > 0) {
+ aB = currentT;
+ } else {
+ aA = currentT;
+ }
+ } while (abs(currentX) > .0000001 && ++i < 100);
+ return currentT;
+ };
+
+ /**
+ * @param {Number} [mX1] The x coordinate of the first point
+ * @param {Number} [mY1] The y coordinate of the first point
+ * @param {Number} [mX2] The x coordinate of the second point
+ * @param {Number} [mY2] The y coordinate of the second point
+ * @return {EasingFunction}
+ */
+
+ const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none :
+ t => t === 0 || t === 1 ? t :
+ calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
+
+
+
+ /**
+ * Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
+ * Only covers 'end' and 'start' jumpterms
+ * @param {Number} steps
+ * @param {Boolean} [fromStart]
+ * @return {EasingFunction}
+ */
+ const steps = (steps = 10, fromStart) => {
+ const roundMethod = fromStart ? ceil : floor;
+ return t => roundMethod(clamp$1(t, 0, 1) * steps) * (1 / steps);
+ };
+
+
+
+ /**
+ * Without parameters, the linear function creates a non-eased transition.
+ * Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points.
+ *
+ * @param {...(String|Number)} args - Points
+ * @return {EasingFunction}
+ */
+ const linear = (...args) => {
+ const argsLength = args.length;
+ if (!argsLength) return none;
+ const totalPoints = argsLength - 1;
+ const firstArg = args[0];
+ const lastArg = args[totalPoints];
+ const xPoints = [0];
+ const yPoints = [parseNumber(firstArg)];
+ for (let i = 1; i < totalPoints; i++) {
+ const arg = args[i];
+ const splitValue = isStr(arg) ?
+ /** @type {String} */(arg).trim().split(' ') :
+ [arg];
+ const value = splitValue[0];
+ const percent = splitValue[1];
+ xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints);
+ yPoints.push(parseNumber(value));
+ }
+ yPoints.push(parseNumber(lastArg));
+ xPoints.push(1);
+ return function easeLinear(t) {
+ for (let i = 1, l = xPoints.length; i < l; i++) {
+ const currentX = xPoints[i];
+ if (t <= currentX) {
+ const prevX = xPoints[i - 1];
+ const prevY = yPoints[i - 1];
+ return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX);
+ }
+ }
+ return yPoints[yPoints.length - 1];
+ }
+ };
+
+
+
+ /**
+ * Generate random steps
+ * @param {Number} [length] - The number of steps
+ * @param {Number} [randomness] - How strong the randomness is
+ * @return {EasingFunction}
+ */
+ const irregular = (length = 10, randomness = 1) => {
+ const values = [0];
+ const total = length - 1;
+ for (let i = 1; i < total; i++) {
+ const previousValue = values[i - 1];
+ const spacing = i / total;
+ const segmentEnd = (i + 1) / total;
+ const randomVariation = spacing + (segmentEnd - spacing) * Math.random();
+ // Mix the even spacing and random variation based on the randomness parameter
+ const randomValue = spacing * (1 - randomness) + randomVariation * randomness;
+ values.push(clamp$1(randomValue, previousValue, 1));
+ }
+ values.push(1);
+ return linear(...values);
+ };
+
+
+
+ /**
+ * Easing functions adapted and simplified from https://robertpenner.com/easing/
+ * (c) 2001 Robert Penner
+ */
+
+ const halfPI = PI / 2;
+ const doublePI = PI * 2;
+
+ /** @type {Record<String, EasingFunctionWithParams|EasingFunction>} */
+ const easeInFunctions = {
+ [emptyString]: easeInPower,
+ Quad: easeInPower(2),
+ Cubic: easeInPower(3),
+ Quart: easeInPower(4),
+ Quint: easeInPower(5),
+ /** @type {EasingFunction} */
+ Sine: t => 1 - cos(t * halfPI),
+ /** @type {EasingFunction} */
+ Circ: t => 1 - sqrt(1 - t * t),
+ /** @type {EasingFunction} */
+ Expo: t => t ? pow(2, 10 * t - 10) : 0,
+ /** @type {EasingFunction} */
+ Bounce: t => {
+ let pow2, b = 4;
+ while (t < ((pow2 = pow(2, --b)) - 1) / 11);
+ return 1 / pow(4, 3 - b) - 7.5625 * pow((pow2 * 3 - 2) / 22 - t, 2);
+ },
+ /** @type {BackEasing} */
+ Back: (overshoot = 1.70158) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t,
+ /** @type {ElasticEasing} */
+ Elastic: (amplitude = 1, period = .3) => {
+ const a = clamp$1(+amplitude, 1, 10);
+ const p = clamp$1(+period, minValue, 2);
+ const s = (p / doublePI) * asin(1 / a);
+ const e = doublePI / p;
+ return t => t === 0 || t === 1 ? t : -a * pow(2, -10 * (1 - t)) * sin(((1 - t) - s) * e);
+ }
+ };
+
+ /**
+ * @typedef {Object} EasesFunctions
+ * @property {typeof linear} linear
+ * @property {typeof irregular} irregular
+ * @property {typeof steps} steps
+ * @property {typeof cubicBezier} cubicBezier
+ * @property {PowerEasing} in
+ * @property {PowerEasing} out
+ * @property {PowerEasing} inOut
+ * @property {PowerEasing} outIn
+ * @property {EasingFunction} inQuad
+ * @property {EasingFunction} outQuad
+ * @property {EasingFunction} inOutQuad
+ * @property {EasingFunction} outInQuad
+ * @property {EasingFunction} inCubic
+ * @property {EasingFunction} outCubic
+ * @property {EasingFunction} inOutCubic
+ * @property {EasingFunction} outInCubic
+ * @property {EasingFunction} inQuart
+ * @property {EasingFunction} outQuart
+ * @property {EasingFunction} inOutQuart
+ * @property {EasingFunction} outInQuart
+ * @property {EasingFunction} inQuint
+ * @property {EasingFunction} outQuint
+ * @property {EasingFunction} inOutQuint
+ * @property {EasingFunction} outInQuint
+ * @property {EasingFunction} inSine
+ * @property {EasingFunction} outSine
+ * @property {EasingFunction} inOutSine
+ * @property {EasingFunction} outInSine
+ * @property {EasingFunction} inCirc
+ * @property {EasingFunction} outCirc
+ * @property {EasingFunction} inOutCirc
+ * @property {EasingFunction} outInCirc
+ * @property {EasingFunction} inExpo
+ * @property {EasingFunction} outExpo
+ * @property {EasingFunction} inOutExpo
+ * @property {EasingFunction} outInExpo
+ * @property {EasingFunction} inBounce
+ * @property {EasingFunction} outBounce
+ * @property {EasingFunction} inOutBounce
+ * @property {EasingFunction} outInBounce
+ * @property {BackEasing} inBack
+ * @property {BackEasing} outBack
+ * @property {BackEasing} inOutBack
+ * @property {BackEasing} outInBack
+ * @property {ElasticEasing} inElastic
+ * @property {ElasticEasing} outElastic
+ * @property {ElasticEasing} inOutElastic
+ * @property {ElasticEasing} outInElastic
+ */
+
+ const eases = (/*#__PURE__ */ (() => {
+ const list = { linear, irregular, steps, cubicBezier };
+ for (let type in easeTypes) {
+ for (let name in easeInFunctions) {
+ const easeIn = easeInFunctions[name];
+ const easeType = easeTypes[type];
+ list[type + name] = /** @type {EasingFunctionWithParams|EasingFunction} */(
+ name === emptyString || name === 'Back' || name === 'Elastic' ?
+ (a, b) => easeType(/** @type {EasingFunctionWithParams} */(easeIn)(a, b)) :
+ easeType(/** @type {EasingFunction} */(easeIn))
+ );
+ }
+ }
+ return /** @type {EasesFunctions} */(list);
+ })());
+
+ /** @type {Record<String, EasingFunction>} */
+ const JSEasesLookups = { linear: none };
+
+ /**
+ * @param {EasingParam} ease
+ * @return {EasingFunction}
+ */
+ const parseEase = ease => isFnc(ease) ? ease :
+ isStr(ease) ? parseEaseString(/** @type {String} */(ease), eases, JSEasesLookups) :
+ none;
+
+
+
+ // Defines decomposed values target objects only once and mutate their properties later to avoid GC
+ // TODO: Maybe move the objects creation to values.js and use the decompose function to create the base object
+ const fromTargetObject = createDecomposedValueTargetObject();
+ const toTargetObject = createDecomposedValueTargetObject();
+ const toFunctionStore = { func: null };
+ const keyframesTargetArray = [null];
+ const fastSetValuesArray = [null, null];
+ /** @type {TweenKeyValue} */
+ const keyObjectTarget = { to: null };
+
+ let tweenId = 0;
+ let keyframes;
+ /** @type {TweenParamsOptions & TweenValues} */
+ let key;
+
+ /**
+ * @param {DurationKeyframes | PercentageKeyframes} keyframes
+ * @param {AnimationParams} parameters
+ * @return {AnimationParams}
+ */
+ const generateKeyframes = (keyframes, parameters) => {
+ /** @type {AnimationParams} */
+ const properties = {};
+ if (isArr(keyframes)) {
+ const propertyNames = [].concat(.../** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(isKey);
+ for (let i = 0, l = propertyNames.length; i < l; i++) {
+ const propName = propertyNames[i];
+ const propArray = /** @type {DurationKeyframes} */(keyframes).map(key => {
+ /** @type {TweenKeyValue} */
+ const newKey = {};
+ for (let p in key) {
+ const keyValue = /** @type {TweenPropValue} */(key[p]);
+ if (isKey(p)) {
+ if (p === propName) {
+ newKey.to = keyValue;
+ }
+ } else {
+ newKey[p] = keyValue;
+ }
+ }
+ return newKey;
+ });
+ properties[propName] = /** @type {ArraySyntaxValue} */(propArray);
+ }
+
+ } else {
+ const totalDuration = /** @type {Number} */(setValue(parameters.duration, globals.defaults.duration));
+ const keys = Object.keys(keyframes)
+ .map(key => { return {o: parseFloat(key) / 100, p: keyframes[key]} })
+ .sort((a, b) => a.o - b.o);
+ keys.forEach(key => {
+ const offset = key.o;
+ const prop = key.p;
+ for (let name in prop) {
+ if (isKey(name)) {
+ let propArray = /** @type {Array} */(properties[name]);
+ if (!propArray) propArray = properties[name] = [];
+ const duration = offset * totalDuration;
+ let length = propArray.length;
+ let prevKey = propArray[length - 1];
+ const keyObj = { to: prop[name] };
+ let durProgress = 0;
+ for (let i = 0; i < length; i++) {
+ durProgress += propArray[i].duration;
+ }
+ if (length === 1) {
+ keyObj.from = prevKey.to;
+ }
+ if (prop.ease) {
+ keyObj.ease = prop.ease;
+ }
+ keyObj.duration = duration - (length ? durProgress : 0);
+ propArray.push(keyObj);
+ }
+ }
+ return key;
+ });
+
+ for (let name in properties) {
+ const propArray = /** @type {Array} */(properties[name]);
+ let prevEase;
+ // let durProgress = 0
+ for (let i = 0, l = propArray.length; i < l; i++) {
+ const prop = propArray[i];
+ // Emulate WAPPI easing parameter position
+ const currentEase = prop.ease;
+ prop.ease = prevEase ? prevEase : undefined;
+ prevEase = currentEase;
+ // durProgress += prop.duration;
+ // if (i === l - 1 && durProgress !== totalDuration) {
+ // propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress })
+ // }
+ }
+ if (!propArray[0].duration) {
+ propArray.shift();
+ }
+ }
+
+ }
+
+ return properties;
+ };
+
+ class JSAnimation extends Timer {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {Timeline} [parent]
+ * @param {Number} [parentPosition]
+ * @param {Boolean} [fastSet=false]
+ * @param {Number} [index=0]
+ * @param {Number} [length=0]
+ */
+ constructor(
+ targets,
+ parameters,
+ parent,
+ parentPosition,
+ fastSet = false,
+ index = 0,
+ length = 0
+ ) {
+
+ super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
+
+ const parsedTargets = registerTargets(targets);
+ const targetsLength = parsedTargets.length;
+
+ // If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties
+
+ const kfParams = /** @type {AnimationParams} */(parameters).keyframes;
+ const params = /** @type {AnimationParams} */(kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters);
+
+ const {
+ delay,
+ duration,
+ ease,
+ playbackEase,
+ modifier,
+ composition,
+ onRender,
+ } = params;
+
+ const animDefaults = parent ? parent.defaults : globals.defaults;
+ const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
+ const animEase = animaPlaybackEase ? parseEase(animaPlaybackEase) : null;
+ const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
+ const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease);
+ const tDuration = hasSpring ? /** @type {Spring} */(ease).duration : setValue(duration, animDefaults.duration);
+ const tDelay = setValue(delay, animDefaults.delay);
+ const tModifier = modifier || animDefaults.modifier;
+ // If no composition is defined and the targets length is high (>= 1000) set the composition to 'none' (0) for faster tween creation
+ const tComposition = isUnd(composition) && targetsLength >= K ? compositionTypes.none : !isUnd(composition) ? composition : animDefaults.composition;
+ // TODO: Do not create an empty object until we know the animation will generate inline styles
+ const animInlineStyles = {};
+ // const absoluteOffsetTime = this._offset;
+ const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0);
+
+ let iterationDuration = NaN;
+ let iterationDelay = NaN;
+ let animationAnimationLength = 0;
+ let shouldTriggerRender = 0;
+
+ for (let targetIndex = 0; targetIndex < targetsLength; targetIndex++) {
+
+ const target = parsedTargets[targetIndex];
+ const ti = index || targetIndex;
+ const tl = length || targetsLength;
+
+ let lastTransformGroupIndex = NaN;
+ let lastTransformGroupLength = NaN;
+
+ for (let p in params) {
+
+ if (isKey(p)) {
+
+ const tweenType = getTweenType(target, p);
+
+ const propName = sanitizePropertyName(p, target, tweenType);
+
+ let propValue = params[p];
+
+ const isPropValueArray = isArr(propValue);
+
+ if (fastSet && !isPropValueArray) {
+ fastSetValuesArray[0] = propValue;
+ fastSetValuesArray[1] = propValue;
+ propValue = fastSetValuesArray;
+ }
+
+ // TODO: Allow nested keyframes inside ObjectValue value (prop: { to: [.5, 1, .75, 2, 3] })
+ // Normalize property values to valid keyframe syntax:
+ // [x, y] to [{to: [x, y]}] or {to: x} to [{to: x}] or keep keys syntax [{}, {}, {}...]
+ // const keyframes = isArr(propValue) ? propValue.length === 2 && !isObj(propValue[0]) ? [{ to: propValue }] : propValue : [propValue];
+ if (isPropValueArray) {
+ const arrayLength = /** @type {Array} */(propValue).length;
+ const isNotObjectValue = !isObj(propValue[0]);
+ // Convert [x, y] to [{to: [x, y]}]
+ if (arrayLength === 2 && isNotObjectValue) {
+ keyObjectTarget.to = /** @type {TweenParamValue} */(/** @type {unknown} */(propValue));
+ keyframesTargetArray[0] = keyObjectTarget;
+ keyframes = keyframesTargetArray;
+ // Convert [x, y, z] to [[x, y], z]
+ } else if (arrayLength > 2 && isNotObjectValue) {
+ keyframes = [];
+ /** @type {Array.<Number>} */(propValue).forEach((v, i) => {
+ if (!i) {
+ fastSetValuesArray[0] = v;
+ } else if (i === 1) {
+ fastSetValuesArray[1] = v;
+ keyframes.push(fastSetValuesArray);
+ } else {
+ keyframes.push(v);
+ }
+ });
+ } else {
+ keyframes = /** @type {Array.<TweenKeyValue>} */(propValue);
+ }
+ } else {
+ keyframesTargetArray[0] = propValue;
+ keyframes = keyframesTargetArray;
+ }
+
+ let siblings = null;
+ let prevTween = null;
+ let firstTweenChangeStartTime = NaN;
+ let lastTweenChangeEndTime = 0;
+ let tweenIndex = 0;
+
+ for (let l = keyframes.length; tweenIndex < l; tweenIndex++) {
+
+ const keyframe = keyframes[tweenIndex];
+
+ if (isObj(keyframe)) {
+ key = keyframe;
+ } else {
+ keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe);
+ key = keyObjectTarget;
+ }
+
+ toFunctionStore.func = null;
+
+ const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore);
+
+ let tweenToValue;
+ // Allows function based values to return an object syntax value ({to: v})
+ if (isObj(computedToValue) && !isUnd(computedToValue.to)) {
+ key = computedToValue;
+ tweenToValue = computedToValue.to;
+ } else {
+ tweenToValue = computedToValue;
+ }
+ const tweenFromValue = getFunctionValue(key.from, target, ti, tl);
+ const keyEasing = key.ease;
+ const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */(keyEasing).ease);
+ // Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time
+ const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing || tEasing;
+ // Calculate default individual keyframe duration by dividing the tl of keyframes
+ const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).duration : getFunctionValue(setValue(key.duration, (l > 1 ? getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl);
+ // Default delay value should only be applied to the first tween
+ const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl);
+ const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl);
+ const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition];
+ // Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper
+ const tweenModifier = key.modifier || tModifier;
+ const hasFromvalue = !isUnd(tweenFromValue);
+ const hasToValue = !isUnd(tweenToValue);
+ const isFromToArray = isArr(tweenToValue);
+ const isFromToValue = isFromToArray || (hasFromvalue && hasToValue);
+ const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay;
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const absoluteStartTime = round$1(absoluteOffsetTime + tweenStartTime, 12);
+
+ // Force a onRender callback if the animation contains at least one from value and autoplay is set to false
+ if (!shouldTriggerRender && (hasFromvalue || isFromToArray)) shouldTriggerRender = 1;
+
+ let prevSibling = prevTween;
+
+ if (tweenComposition !== compositionTypes.none) {
+ if (!siblings) siblings = getTweenSiblings(target, propName);
+ let nextSibling = siblings._head;
+ // Iterate trough all the next siblings until we find a sibling with an equal or inferior start time
+ while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) {
+ prevSibling = nextSibling;
+ nextSibling = nextSibling._nextRep;
+ // Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time
+ if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) {
+ while (nextSibling) {
+ overrideTween(nextSibling);
+ // This will ends both the current while loop and the upper one once all the next sibllings have been overriden
+ nextSibling = nextSibling._nextRep;
+ }
+ }
+ }
+ }
+
+ // Decompose values
+ if (isFromToValue) {
+ decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject);
+ decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject);
+ if (fromTargetObject.t === valueTypes.NUMBER) {
+ if (prevSibling) {
+ if (prevSibling._valueType === valueTypes.UNIT) {
+ fromTargetObject.t = valueTypes.UNIT;
+ fromTargetObject.u = prevSibling._unit;
+ }
+ } else {
+ decomposeRawValue(
+ getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles),
+ decomposedOriginalValue
+ );
+ if (decomposedOriginalValue.t === valueTypes.UNIT) {
+ fromTargetObject.t = valueTypes.UNIT;
+ fromTargetObject.u = decomposedOriginalValue.u;
+ }
+ }
+ }
+ } else {
+ if (hasToValue) {
+ decomposeRawValue(tweenToValue, toTargetObject);
+ } else {
+ if (prevTween) {
+ decomposeTweenValue(prevTween, toTargetObject);
+ } else {
+ // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
+ decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
+ getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), toTargetObject);
+ }
+ }
+ if (hasFromvalue) {
+ decomposeRawValue(tweenFromValue, fromTargetObject);
+ } else {
+ if (prevTween) {
+ decomposeTweenValue(prevTween, fromTargetObject);
+ } else {
+ decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
+ // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
+ getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), fromTargetObject);
+ }
+ }
+ }
+
+ // Apply operators
+ if (fromTargetObject.o) {
+ fromTargetObject.n = getRelativeValue(
+ !prevSibling ? decomposeRawValue(
+ getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles),
+ decomposedOriginalValue
+ ).n : prevSibling._toNumber,
+ fromTargetObject.n,
+ fromTargetObject.o
+ );
+ }
+
+ if (toTargetObject.o) {
+ toTargetObject.n = getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o);
+ }
+
+ // Values omogenisation in cases of type difference between "from" and "to"
+ if (fromTargetObject.t !== toTargetObject.t) {
+ if (fromTargetObject.t === valueTypes.COMPLEX || toTargetObject.t === valueTypes.COMPLEX) {
+ const complexValue = fromTargetObject.t === valueTypes.COMPLEX ? fromTargetObject : toTargetObject;
+ const notComplexValue = fromTargetObject.t === valueTypes.COMPLEX ? toTargetObject : fromTargetObject;
+ notComplexValue.t = valueTypes.COMPLEX;
+ notComplexValue.s = cloneArray(complexValue.s);
+ notComplexValue.d = complexValue.d.map(() => notComplexValue.n);
+ } else if (fromTargetObject.t === valueTypes.UNIT || toTargetObject.t === valueTypes.UNIT) {
+ const unitValue = fromTargetObject.t === valueTypes.UNIT ? fromTargetObject : toTargetObject;
+ const notUnitValue = fromTargetObject.t === valueTypes.UNIT ? toTargetObject : fromTargetObject;
+ notUnitValue.t = valueTypes.UNIT;
+ notUnitValue.u = unitValue.u;
+ } else if (fromTargetObject.t === valueTypes.COLOR || toTargetObject.t === valueTypes.COLOR) {
+ const colorValue = fromTargetObject.t === valueTypes.COLOR ? fromTargetObject : toTargetObject;
+ const notColorValue = fromTargetObject.t === valueTypes.COLOR ? toTargetObject : fromTargetObject;
+ notColorValue.t = valueTypes.COLOR;
+ notColorValue.s = colorValue.s;
+ notColorValue.d = [0, 0, 0, 1];
+ }
+ }
+
+ // Unit conversion
+ if (fromTargetObject.u !== toTargetObject.u) {
+ let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject;
+ valueToConvert = convertValueUnit(/** @type {DOMTarget} */(target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false);
+ // TODO:
+ // convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u);
+ }
+
+ // Fill in non existing complex values
+ if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) {
+ const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject;
+ const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject;
+ // TODO: Check if n should be used instead of 0 for default complex values
+ shortestValue.d = longestValue.d.map((/** @type {Number} */_, /** @type {Number} */i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
+ shortestValue.s = cloneArray(longestValue.s);
+ }
+
+ // Tween factory
+
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const tweenUpdateDuration = round$1(+tweenDuration || minValue, 12);
+
+ /** @type {Tween} */
+ const tween = {
+ parent: this,
+ id: tweenId++,
+ property: propName,
+ target: target,
+ _value: null,
+ _func: toFunctionStore.func,
+ _ease: parseEase(tweenEasing),
+ _fromNumbers: cloneArray(fromTargetObject.d),
+ _toNumbers: cloneArray(toTargetObject.d),
+ _strings: cloneArray(toTargetObject.s),
+ _fromNumber: fromTargetObject.n,
+ _toNumber: toTargetObject.n,
+ _numbers: cloneArray(fromTargetObject.d), // For additive tween and animatables
+ _number: fromTargetObject.n, // For additive tween and animatables
+ _unit: toTargetObject.u,
+ _modifier: tweenModifier,
+ _currentTime: 0,
+ _startTime: tweenStartTime,
+ _delay: +tweenDelay,
+ _updateDuration: tweenUpdateDuration,
+ _changeDuration: tweenUpdateDuration,
+ _absoluteStartTime: absoluteStartTime,
+ // NOTE: Investigate bit packing to stores ENUM / BOOL
+ _tweenType: tweenType,
+ _valueType: toTargetObject.t,
+ _composition: tweenComposition,
+ _isOverlapped: 0,
+ _isOverridden: 0,
+ _renderTransforms: 0,
+ _prevRep: null, // For replaced tween
+ _nextRep: null, // For replaced tween
+ _prevAdd: null, // For additive tween
+ _nextAdd: null, // For additive tween
+ _prev: null,
+ _next: null,
+ };
+
+ if (tweenComposition !== compositionTypes.none) {
+ composeTween(tween, siblings);
+ }
+
+ if (isNaN(firstTweenChangeStartTime)) {
+ firstTweenChangeStartTime = tween._startTime;
+ }
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ lastTweenChangeEndTime = round$1(tweenStartTime + tweenUpdateDuration, 12);
+ prevTween = tween;
+ animationAnimationLength++;
+
+ addChild(this, tween);
+
+ }
+
+ // Update animation timings with the added tweens properties
+
+ if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) {
+ iterationDelay = firstTweenChangeStartTime;
+ }
+
+ if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) {
+ iterationDuration = lastTweenChangeEndTime;
+ }
+
+ // TODO: Find a way to inline tween._renderTransforms = 1 here
+ if (tweenType === tweenTypes.TRANSFORM) {
+ lastTransformGroupIndex = animationAnimationLength - tweenIndex;
+ lastTransformGroupLength = animationAnimationLength;
+ }
+
+ }
+
+ }
+
+ // Set _renderTransforms to last transform property to correctly render the transforms list
+ if (!isNaN(lastTransformGroupIndex)) {
+ let i = 0;
+ forEachChildren(this, (/** @type {Tween} */tween) => {
+ if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) {
+ tween._renderTransforms = 1;
+ if (tween._composition === compositionTypes.blend) {
+ forEachChildren(additive.animation, (/** @type {Tween} */additiveTween) => {
+ if (additiveTween.id === tween.id) {
+ additiveTween._renderTransforms = 1;
+ }
+ });
+ }
+ }
+ i++;
+ });
+ }
+
+ }
+
+ if (!targetsLength) {
+ console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
+ }
+
+ if (iterationDelay) {
+ forEachChildren(this, (/** @type {Tween} */tween) => {
+ // If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too
+ if (!(tween._startTime - tween._delay)) {
+ tween._delay -= iterationDelay;
+ }
+ tween._startTime -= iterationDelay;
+ });
+ iterationDuration -= iterationDelay;
+ } else {
+ iterationDelay = 0;
+ }
+
+ // Prevents iterationDuration to be NaN if no valid animatable props have been provided
+ // Prevents _iterationCount to be NaN if no valid animatable props have been provided
+ if (!iterationDuration) {
+ iterationDuration = minValue;
+ this.iterationCount = 0;
+ }
+ /** @type {TargetsArray} */
+ this.targets = parsedTargets;
+ /** @type {Number} */
+ this.duration = iterationDuration === minValue ? minValue : clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || minValue;
+ /** @type {Callback<this>} */
+ this.onRender = onRender || animDefaults.onRender;
+ /** @type {EasingFunction} */
+ this._ease = animEase;
+ /** @type {Number} */
+ this._delay = iterationDelay;
+ // NOTE: I'm keeping delay values separated from offsets in timelines because delays can override previous tweens and it could be confusing to debug a timeline with overridden tweens and no associated visible delays.
+ // this._delay = parent ? 0 : iterationDelay;
+ // this._offset += parent ? iterationDelay : 0;
+ /** @type {Number} */
+ this.iterationDuration = iterationDuration;
+ /** @type {{}} */
+ this._inlineStyles = animInlineStyles;
+
+ if (!this._autoplay && shouldTriggerRender) this.onRender(this);
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ if (currentDuration === normalizeTime(newDuration)) return this;
+ const timeScale = newDuration / currentDuration;
+ // NOTE: Find a better way to handle the stretch of an animation after stretch = 0
+ forEachChildren(this, (/** @type {Tween} */tween) => {
+ // Rounding is necessary here to minimize floating point errors
+ tween._updateDuration = normalizeTime(tween._updateDuration * timeScale);
+ tween._changeDuration = normalizeTime(tween._changeDuration * timeScale);
+ tween._currentTime *= timeScale;
+ tween._startTime *= timeScale;
+ tween._absoluteStartTime *= timeScale;
+ });
+ return super.stretch(newDuration);
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ forEachChildren(this, (/** @type {Tween} */tween) => {
+ const tweenFunc = tween._func;
+ if (tweenFunc) {
+ const ogValue = getOriginalAnimatableValue(tween.target, tween.property, tween._tweenType);
+ decomposeRawValue(ogValue, decomposedOriginalValue);
+ decomposeRawValue(tweenFunc(), toTargetObject);
+ tween._fromNumbers = cloneArray(decomposedOriginalValue.d);
+ tween._fromNumber = decomposedOriginalValue.n;
+ tween._toNumbers = cloneArray(toTargetObject.d);
+ tween._strings = cloneArray(toTargetObject.s);
+ // Make sure to apply relative operators https://github.com/juliangarnier/anime/issues/1025
+ tween._toNumber = toTargetObject.o ? getRelativeValue(decomposedOriginalValue.n, toTargetObject.n, toTargetObject.o) : toTargetObject.n;
+ }
+ });
+ return this;
+ }
+
+ /**
+ * Cancel the animation and revert all the values affected by this animation to their original state
+ * @return {this}
+ */
+ revert() {
+ super.revert();
+ return cleanInlineStyles(this);
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback) {
+ return super.then(callback);
+ }
+
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @return {JSAnimation}
+ */
+ const animate = (targets, parameters) => new JSAnimation(targets, parameters, null, 0, false).init();
+
+
+
+
+
+ const WAAPIAnimationsLookups = {
+ _head: null,
+ _tail: null,
+ };
+
+ /**
+ * @param {DOMTarget} $el
+ * @param {String} [property]
+ * @param {WAAPIAnimation} [parent]
+ */
+ const removeWAAPIAnimation = ($el, property, parent) => {
+ let nextLookup = WAAPIAnimationsLookups._head;
+ while (nextLookup) {
+ const next = nextLookup._next;
+ const matchTarget = nextLookup.$el === $el;
+ const matchProperty = !property || nextLookup.property === property;
+ const matchParent = !parent || nextLookup.parent === parent;
+ if (matchTarget && matchProperty && matchParent) {
+ const anim = nextLookup.animation;
+ try { anim.commitStyles(); } catch {} anim.cancel();
+ removeChild(WAAPIAnimationsLookups, nextLookup);
+ const lookupParent = nextLookup.parent;
+ if (lookupParent) {
+ lookupParent._completed++;
+ if (lookupParent.animations.length === lookupParent._completed) {
+ lookupParent.completed = true;
+ if (!lookupParent.muteCallbacks) {
+ lookupParent.paused = true;
+ lookupParent.onComplete(lookupParent);
+ lookupParent._resolve(lookupParent);
+ }
+ }
+ }
+ }
+ nextLookup = next;
+ }
+ };
+
+ /**
+ * @param {WAAPIAnimation} parent
+ * @param {DOMTarget} $el
+ * @param {String} property
+ * @param {PropertyIndexedKeyframes} keyframes
+ * @param {KeyframeAnimationOptions} params
+ * @retun {Animation}
+ */
+ const addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
+ const animation = $el.animate(keyframes, params);
+ const animTotalDuration = params.delay + (+params.duration * params.iterations);
+ animation.playbackRate = parent._speed;
+ if (parent.paused) animation.pause();
+ if (parent.duration < animTotalDuration) {
+ parent.duration = animTotalDuration;
+ parent.controlAnimation = animation;
+ }
+ parent.animations.push(animation);
+ removeWAAPIAnimation($el, property);
+ addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null });
+ const handleRemove = () => { removeWAAPIAnimation($el, property, parent); };
+ animation.onremove = handleRemove;
+ animation.onfinish = handleRemove;
+ return animation;
+ };
+
+
+
+
+
+ /**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
+ * @param {String} propName
+ * @return {String}
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
+ * @param {String} propName
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+ function get(targetSelector, propName, unit) {
+ const targets = registerTargets(targetSelector);
+ if (!targets.length) return;
+ const [ target ] = targets;
+ const tweenType = getTweenType(target, propName);
+ const normalizePropName = sanitizePropertyName(propName, target, tweenType);
+ let originalValue = getOriginalAnimatableValue(target, normalizePropName);
+ if (isUnd(unit)) {
+ return originalValue;
+ } else {
+ decomposeRawValue(originalValue, decomposedOriginalValue);
+ if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) {
+ if (unit === false) {
+ return decomposedOriginalValue.n;
+ } else {
+ const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false);
+ return `${round$1(convertedValue.n, globals.precision)}${convertedValue.u}`;
+ }
+ }
+ }
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @return {JSAnimation}
+ */
+ const set = (targets, parameters) => {
+ if (isUnd(parameters)) return;
+ parameters.duration = minValue;
+ // Do not overrides currently active tweens by default
+ parameters.composition = setValue(parameters.composition, compositionTypes.none);
+ // Skip init() and force rendering by playing the animation
+ return new JSAnimation(targets, parameters, null, 0, true).resume();
+ };
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {Renderable|WAAPIAnimation} [renderable]
+ * @param {String} [propertyName]
+ * @return {TargetsArray}
+ */
+ const remove = (targets, renderable, propertyName) => {
+ const targetsArray = parseTargets(targets);
+ for (let i = 0, l = targetsArray.length; i < l; i++) {
+ removeWAAPIAnimation(
+ /** @type {DOMTarget} */(targetsArray[i]),
+ propertyName,
+ renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable),
+ );
+ }
+ removeTargetsFromRenderable(
+ targetsArray,
+ /** @type {Renderable} */(renderable),
+ propertyName
+ );
+ return targetsArray;
+ };
+
+
+
+
+
+ /**
+ * Timeline's children offsets positions parser
+ * @param {Timeline} timeline
+ * @param {String} timePosition
+ * @return {Number}
+ */
+ const getPrevChildOffset = (timeline, timePosition) => {
+ if (stringStartsWith(timePosition, '<')) {
+ const goToPrevAnimationOffset = timePosition[1] === '<';
+ const prevAnimation = /** @type {Tickable} */(timeline._tail);
+ const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
+ return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
+ }
+ };
+
+ /**
+ * @param {Timeline} timeline
+ * @param {TimelinePosition} [timePosition]
+ * @return {Number}
+ */
+ const parseTimelinePosition = (timeline, timePosition) => {
+ let tlDuration = timeline.iterationDuration;
+ if (tlDuration === minValue) tlDuration = 0;
+ if (isUnd(timePosition)) return tlDuration;
+ if (isNum(+timePosition)) return +timePosition;
+ const timePosStr = /** @type {String} */(timePosition);
+ const tlLabels = timeline ? timeline.labels : null;
+ const hasLabels = !isNil(tlLabels);
+ const prevOffset = getPrevChildOffset(timeline, timePosStr);
+ const hasSibling = !isUnd(prevOffset);
+ const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
+ if (matchedRelativeOperator) {
+ const fullOperator = matchedRelativeOperator[0];
+ const split = timePosStr.split(fullOperator);
+ const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
+ const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
+ const parsedNumericalOffset = +split[1];
+ return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
+ } else {
+ return hasSibling ? prevOffset :
+ hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
+ tlDuration : tlDuration;
+ }
+ };
+
+
+
+
+
+ /**
+ * @param {Timeline} tl
+ * @return {Number}
+ */
+ function getTimelineTotalDuration(tl) {
+ return clampInfinity(((tl.iterationDuration + tl._loopDelay) * tl.iterationCount) - tl._loopDelay) || minValue;
+ }
+
+ /**
+ * @overload
+ * @param {TimerParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @return {Timeline}
+ *
+ * @overload
+ * @param {AnimationParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @param {TargetsParam} targets
+ * @param {Number} [index]
+ * @param {Number} [length]
+ * @return {Timeline}
+ *
+ * @param {TimerParams|AnimationParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @param {TargetsParam} [targets]
+ * @param {Number} [index]
+ * @param {Number} [length]
+ */
+ function addTlChild(childParams, tl, timePosition, targets, index, length) {
+ const isSetter = isNum(childParams.duration) && /** @type {Number} */(childParams.duration) <= minValue;
+ // Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position
+ const adjustedPosition = isSetter ? timePosition - minValue : timePosition;
+ tick(tl, adjustedPosition, 1, 1, tickModes.AUTO);
+ const tlChild = targets ?
+ new JSAnimation(targets,/** @type {AnimationParams} */(childParams), tl, adjustedPosition, false, index, length) :
+ new Timer(/** @type {TimerParams} */(childParams), tl, adjustedPosition);
+ tlChild.init(1);
+ // TODO: Might be better to insert at a position relative to startTime?
+ addChild(tl, tlChild);
+ forEachChildren(tl, (/** @type {Renderable} */child) => {
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > tl.iterationDuration) tl.iterationDuration = childDur;
+ });
+ tl.duration = getTimelineTotalDuration(tl);
+ return tl;
+ }
+
+ class Timeline extends Timer {
+
+ /**
+ * @param {TimelineParams} [parameters]
+ */
+ constructor(parameters = {}) {
+ super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0);
+ /** @type {Number} */
+ this.duration = 0; // TL duration starts at 0 and grows when adding children
+ /** @type {Record<String, Number>} */
+ this.labels = {};
+ const defaultsParams = parameters.defaults;
+ const globalDefaults = globals.defaults;
+ /** @type {DefaultsParams} */
+ this.defaults = defaultsParams ? mergeObjects(defaultsParams, globalDefaults) : globalDefaults;
+ /** @type {Callback<this>} */
+ this.onRender = parameters.onRender || globalDefaults.onRender;
+ const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase);
+ this._ease = tlPlaybackEase ? parseEase(tlPlaybackEase) : null;
+ /** @type {Number} */
+ this.iterationDuration = 0;
+ }
+
+ /**
+ * @overload
+ * @param {TargetsParam} a1
+ * @param {AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ * @return {this}
+ *
+ * @overload
+ * @param {TimerParams} a1
+ * @param {TimelinePosition} [a2]
+ * @return {this}
+ *
+ * @param {TargetsParam|TimerParams} a1
+ * @param {TimelinePosition|AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ */
+ add(a1, a2, a3) {
+ const isAnim = isObj(a2);
+ const isTimer = isObj(a1);
+ if (isAnim || isTimer) {
+ this._hasChildren = true;
+ if (isAnim) {
+ const childParams = /** @type {AnimationParams} */(a2);
+ // Check for function for children stagger positions
+ if (isFnc(a3)) {
+ const staggeredPosition = a3;
+ const parsedTargetsArray = parseTargets(/** @type {TargetsParam} */(a1));
+ // Store initial duration before adding new children that will change the duration
+ const tlDuration = this.duration;
+ // Store initial _iterationDuration before adding new children that will change the duration
+ const tlIterationDuration = this.iterationDuration;
+ // Store the original id in order to add specific indexes to the new animations ids
+ const id = childParams.id;
+ let i = 0;
+ /** @type {Number} */
+ const parsedLength = (parsedTargetsArray.length);
+ parsedTargetsArray.forEach((/** @type {Target} */target) => {
+ // Create a new parameter object for each staggered children
+ const staggeredChildParams = { ...childParams };
+ // Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation
+ this.duration = tlDuration;
+ this.iterationDuration = tlIterationDuration;
+ if (!isUnd(id)) staggeredChildParams.id = id + '-' + i;
+ addTlChild(
+ staggeredChildParams,
+ this,
+ parseTimelinePosition(this, staggeredPosition(target, i, parsedLength, this)),
+ target,
+ i,
+ parsedLength
+ );
+ i++;
+ });
+ } else {
+ addTlChild(
+ childParams,
+ this,
+ parseTimelinePosition(this, a3),
+ /** @type {TargetsParam} */(a1),
+ );
+ }
+ } else {
+ // It's a Timer
+ addTlChild(
+ /** @type TimerParams */(a1),
+ this,
+ parseTimelinePosition(this,a2),
+ );
+ }
+ return this.init(1); // 1 = internalRender
+ }
+ }
+
+ /**
+ * @overload
+ * @param {Tickable} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {WAAPIAnimation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ */
+ sync(synced, position) {
+ if (isUnd(synced) || synced && isUnd(synced.pause)) return this;
+ synced.pause();
+ const duration = +(/** @type {globalThis.Animation} */(synced).effect ? /** @type {globalThis.Animation} */(synced).effect.getTiming().duration : /** @type {Tickable} */(synced).duration);
+ return this.add(synced, { currentTime: [0, duration], duration, ease: 'linear' }, position);
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ set(targets, parameters, position) {
+ if (isUnd(parameters)) return this;
+ parameters.duration = minValue;
+ parameters.composition = compositionTypes.replace;
+ return this.add(targets, parameters, position);
+ }
+
+ /**
+ * @param {Callback<Timer>} callback
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ call(callback, position) {
+ if (isUnd(callback) || callback && !isFnc(callback)) return this;
+ return this.add({ duration: 0, onComplete: () => callback(this) }, position);
+ }
+
+ /**
+ * @param {String} labelName
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ */
+ label(labelName, position) {
+ if (isUnd(labelName) || labelName && !isStr(labelName)) return this;
+ this.labels[labelName] = parseTimelinePosition(this, position);
+ return this;
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {String} [propertyName]
+ * @return {this}
+ */
+ remove(targets, propertyName) {
+ removeTargetsFromRenderable(parseTargets(targets), this, propertyName);
+ return this;
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ if (currentDuration === normalizeTime(newDuration)) return this;
+ const timeScale = newDuration / currentDuration;
+ const labels = this.labels;
+ forEachChildren(this, (/** @type {JSAnimation} */child) => child.stretch(child.duration * timeScale));
+ for (let labelName in labels) labels[labelName] *= timeScale;
+ return super.stretch(newDuration);
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ forEachChildren(this, (/** @type {JSAnimation} */child) => {
+ if (child.refresh) child.refresh();
+ });
+ return this;
+ }
+
+ /**
+ * @return {this}
+ */
+ revert() {
+ super.revert();
+ forEachChildren(this, (/** @type {JSAnimation} */child) => child.revert, true);
+ return cleanInlineStyles(this);
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback) {
+ return super.then(callback);
+ }
+ }
+
+ /**
+ * @param {TimelineParams} [parameters]
+ * @return {Timeline}
+ */
+ const createTimeline = parameters => new Timeline(parameters).init();
+
+
+
+ class Animatable {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ */
+ constructor(targets, parameters) {
+ if (scope.current) scope.current.register(this);
+ const beginHandler = () => {
+ if (this.callbacks.completed) this.callbacks.reset();
+ this.callbacks.play();
+ };
+ const pauseHandler = () => {
+ if (this.callbacks.completed) return;
+ let paused = true;
+ for (let name in this.animations) {
+ const anim = this.animations[name];
+ if (!anim.paused && paused) {
+ paused = false;
+ break;
+ }
+ }
+ if (paused) {
+ this.callbacks.complete();
+ }
+ };
+ /** @type {AnimationParams} */
+ const globalParams = {
+ onBegin: beginHandler,
+ onComplete: pauseHandler,
+ onPause: pauseHandler,
+ };
+ /** @type {AnimationParams} */
+ const callbacksAnimationParams = { v: 1, autoplay: false };
+ const properties = {};
+ this.targets = [];
+ this.animations = {};
+ /** @type {JSAnimation|null} */
+ this.callbacks = null;
+ if (isUnd(targets) || isUnd(parameters)) return;
+ for (let propName in parameters) {
+ const paramValue = parameters[propName];
+ if (isKey(propName)) {
+ properties[propName] = paramValue;
+ } else if (stringStartsWith(propName, 'on')) {
+ callbacksAnimationParams[propName] = paramValue;
+ } else {
+ globalParams[propName] = paramValue;
+ }
+ }
+ this.callbacks = new JSAnimation({ v: 0 }, callbacksAnimationParams);
+ for (let propName in properties) {
+ const propValue = properties[propName];
+ const isObjValue = isObj(propValue);
+ /** @type {TweenParamsOptions} */
+ let propParams = {};
+ let to = '+=0';
+ if (isObjValue) {
+ const unit = propValue.unit;
+ if (isStr(unit)) to += unit;
+ } else {
+ propParams.duration = propValue;
+ }
+ propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to;
+ const animParams = mergeObjects(globalParams, propParams);
+ animParams.composition = compositionTypes.replace;
+ animParams.autoplay = false;
+ const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init();
+ if (!this.targets.length) this.targets.push(...animation.targets);
+ /** @type {AnimatableProperty} */
+ this[propName] = (to, duration, ease) => {
+ const tween = /** @type {Tween} */(animation._head);
+ if (isUnd(to) && tween) {
+ const numbers = tween._numbers;
+ if (numbers && numbers.length) {
+ return numbers;
+ } else {
+ return tween._modifier(tween._number);
+ }
+ } else {
+ forEachChildren(animation, (/** @type {Tween} */tween) => {
+ if (isArr(to)) {
+ for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) {
+ if (!isUnd(tween._numbers[i])) {
+ tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i]));
+ tween._toNumbers[i] = to[i];
+ }
+ }
+ } else {
+ tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number));
+ tween._toNumber = /** @type {Number} */(to);
+ }
+ if (!isUnd(ease)) tween._ease = parseEase(ease);
+ tween._currentTime = 0;
+ });
+ if (!isUnd(duration)) animation.stretch(duration);
+ animation.reset(1).resume();
+ return this;
+ }
+ };
+ }
+ }
+
+ revert() {
+ for (let propName in this.animations) {
+ this[propName] = noop;
+ this.animations[propName].revert();
+ }
+ this.animations = {};
+ this.targets.length = 0;
+ if (this.callbacks) this.callbacks.revert();
+ return this;
+ }
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ * @return {AnimatableObject}
+ */
+ const createAnimatable = (targets, parameters) => /** @type {AnimatableObject} */ (new Animatable(targets, parameters));
+
+ /**
+ * Rounds a number to fixed decimal places
+ * @param {Number|String} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {String}
+ */
+ const roundPad$1 = (v, decimalLength) => (+v).toFixed(decimalLength);
+
+ /**
+ * Pads the start of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {String}
+ */
+ const padStart$1 = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString);
+
+ /**
+ * Pads the end of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {String}
+ */
+ const padEnd$1 = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString);
+
+ /**
+ * Wraps a value within a range
+ * @param {Number} v - Value to wrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {Number}
+ */
+ const wrap$1 = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min;
+
+ /**
+ * Maps a value from one range to another
+ * @param {Number} value - Input value
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {Number}
+ */
+ const mapRange$1 = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow);
+
+ /**
+ * Converts degrees to radians
+ * @param {Number} degrees - Angle in degrees
+ * @return {Number}
+ */
+ const degToRad$1 = degrees => degrees * Math.PI / 180;
+
+ /**
+ * Converts radians to degrees
+ * @param {Number} radians - Angle in radians
+ * @return {Number}
+ */
+ const radToDeg$1 = radians => radians * 180 / Math.PI;
+
+ /**
+ * Frame rate independent damped lerp
+ * Based on: https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
+ */
+ const damp$1 = (start, end, deltaTime, factor) => {
+ return !factor ? start : factor === 1 ? end : lerp$1(start, end, 1 - Math.exp(-factor * deltaTime * .1));
+ };
+
+ var numberImports = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ clamp: clamp$1,
+ damp: damp$1,
+ degToRad: degToRad$1,
+ lerp: lerp$1,
+ mapRange: mapRange$1,
+ padEnd: padEnd$1,
+ padStart: padStart$1,
+ radToDeg: radToDeg$1,
+ round: round$1,
+ roundPad: roundPad$1,
+ snap: snap$1,
+ wrap: wrap$1
+ });
+
+
+
+ /*
+ * Spring ease solver adapted from https://webkit.org/demos/spring/spring.js
+ * (c) 2016 Webkit - Apple Inc
+ */
+
+ const maxSpringParamValue = K * 10;
+
+ class Spring {
+ /**
+ * @param {SpringParams} [parameters]
+ */
+ constructor(parameters = {}) {
+ this.timeStep = .02; // Interval fed to the solver to calculate duration
+ this.restThreshold = .0005; // Values below this threshold are considered resting position
+ this.restDuration = 200; // Duration in ms used to check if the spring is resting after reaching restThreshold
+ this.maxDuration = 60000; // The maximum allowed spring duration in ms (default 1 min)
+ this.maxRestSteps = this.restDuration / this.timeStep / K; // How many steps allowed after reaching restThreshold before stopping the duration calculation
+ this.maxIterations = this.maxDuration / this.timeStep / K; // Calculate the maximum iterations allowed based on maxDuration
+ this.m = clamp$1(setValue(parameters.mass, 1), 0, maxSpringParamValue);
+ this.s = clamp$1(setValue(parameters.stiffness, 100), 1, maxSpringParamValue);
+ this.d = clamp$1(setValue(parameters.damping, 10), .1, maxSpringParamValue);
+ this.v = clamp$1(setValue(parameters.velocity, 0), -maxSpringParamValue, maxSpringParamValue);
+ this.w0 = 0;
+ this.zeta = 0;
+ this.wd = 0;
+ this.b = 0;
+ this.solverDuration = 0;
+ this.duration = 0;
+ this.compute();
+ /** @type {EasingFunction} */
+ this.ease = t => t === 0 || t === 1 ? t : this.solve(t * this.solverDuration);
+ }
+
+ /** @type {EasingFunction} */
+ solve(time) {
+ const { zeta, w0, wd, b } = this;
+ let t = time;
+ if (zeta < 1) {
+ t = exp(-t * zeta * w0) * (1 * cos(wd * t) + b * sin(wd * t));
+ } else {
+ t = (1 + b * t) * exp(-t * w0);
+ }
+ return 1 - t;
+ }
+
+ compute() {
+ const { maxRestSteps, maxIterations, restThreshold, timeStep, m, d, s, v } = this;
+ const w0 = this.w0 = clamp$1(sqrt(s / m), minValue, K);
+ const zeta = this.zeta = d / (2 * sqrt(s * m));
+ const wd = this.wd = zeta < 1 ? w0 * sqrt(1 - zeta * zeta) : 0;
+ this.b = zeta < 1 ? (zeta * w0 + -v) / wd : -v + w0;
+ let solverTime = 0;
+ let restSteps = 0;
+ let iterations = 0;
+ while (restSteps < maxRestSteps && iterations < maxIterations) {
+ if (abs(1 - this.solve(solverTime)) < restThreshold) {
+ restSteps++;
+ } else {
+ restSteps = 0;
+ }
+ this.solverDuration = solverTime;
+ solverTime += timeStep;
+ iterations++;
+ }
+ this.duration = round$1(this.solverDuration * K, 0) * globals.timeScale;
+ }
+
+ get mass() {
+ return this.m;
+ }
+
+ set mass(v) {
+ this.m = clamp$1(setValue(v, 1), 0, maxSpringParamValue);
+ this.compute();
+ }
+
+ get stiffness() {
+ return this.s;
+ }
+
+ set stiffness(v) {
+ this.s = clamp$1(setValue(v, 100), 1, maxSpringParamValue);
+ this.compute();
+ }
+
+ get damping() {
+ return this.d;
+ }
+
+ set damping(v) {
+ this.d = clamp$1(setValue(v, 10), .1, maxSpringParamValue);
+ this.compute();
+ }
+
+ get velocity() {
+ return this.v;
+ }
+
+ set velocity(v) {
+ this.v = clamp$1(setValue(v, 0), -maxSpringParamValue, maxSpringParamValue);
+ this.compute();
+ }
+ }
+
+ /**
+ * @param {SpringParams} [parameters]
+ * @returns {Spring}
+ */
+ const createSpring = (parameters) => new Spring(parameters);
+
+
+
+
+
+ /**
+ * @param {Event} e
+ */
+ const preventDefault = e => {
+ if (e.cancelable) e.preventDefault();
+ };
+
+ class DOMProxy {
+ /** @param {Object} el */
+ constructor(el) {
+ this.el = el;
+ this.zIndex = 0;
+ this.parentElement = null;
+ this.classList = {
+ add: noop,
+ remove: noop,
+ };
+ }
+
+ get x() { return this.el.x || 0 };
+ set x(v) { this.el.x = v; };
+
+ get y() { return this.el.y || 0 };
+ set y(v) { this.el.y = v; };
+
+ get width() { return this.el.width || 0 };
+ set width(v) { this.el.width = v; };
+
+ get height() { return this.el.height || 0 };
+ set height(v) { this.el.height = v; };
+
+ getBoundingClientRect() {
+ return {
+ top: this.y,
+ right: this.x,
+ bottom: this.y + this.height,
+ left: this.x + this.width,
+ }
+ }
+ }
+
+ class Transforms {
+ /**
+ * @param {DOMTarget|DOMProxy} $el
+ */
+ constructor($el) {
+ this.$el = $el;
+ this.inlineTransforms = [];
+ this.point = new DOMPoint();
+ this.inversedMatrix = this.getMatrix().inverse();
+ }
+
+ /**
+ * @param {Number} x
+ * @param {Number} y
+ * @return {DOMPoint}
+ */
+ normalizePoint(x, y) {
+ this.point.x = x;
+ this.point.y = y;
+ return this.point.matrixTransform(this.inversedMatrix);
+ }
+
+ /**
+ * @callback TraverseParentsCallback
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ */
+
+ /**
+ * @param {TraverseParentsCallback} cb
+ */
+ traverseUp(cb) {
+ let $el = /** @type {DOMTarget|Document} */(this.$el.parentElement), i = 0;
+ while ($el && $el !== doc) {
+ cb(/** @type {DOMTarget} */($el), i);
+ $el = /** @type {DOMTarget} */($el.parentElement);
+ i++;
+ }
+ }
+
+ getMatrix() {
+ const matrix = new DOMMatrix();
+ this.traverseUp($el => {
+ const transformValue = getComputedStyle($el).transform;
+ if (transformValue) {
+ const elMatrix = new DOMMatrix(transformValue);
+ matrix.preMultiplySelf(elMatrix);
+ }
+ });
+ return matrix;
+ }
+
+ remove() {
+ this.traverseUp(($el, i) => {
+ this.inlineTransforms[i] = $el.style.transform;
+ $el.style.transform = 'none';
+ });
+ }
+
+ revert() {
+ this.traverseUp(($el, i) => {
+ const ct = this.inlineTransforms[i];
+ if (ct === '') {
+ $el.style.removeProperty('transform');
+ } else {
+ $el.style.transform = ct;
+ }
+ });
+ }
+ }
+
+ /**
+ * @template {Array<Number>|DOMTargetSelector|String|Number|Boolean|Function|DraggableCursorParams} T
+ * @param {T | ((draggable: Draggable) => T)} value
+ * @param {Draggable} draggable
+ * @return {T}
+ */
+ const parseDraggableFunctionParameter = (value, draggable) => value && isFnc(value) ? /** @type {Function} */(value)(draggable) : /** @type {T} */(value);
+
+ let zIndex = 0;
+
+ class Draggable {
+ /**
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
+ */
+ constructor(target, parameters = {}) {
+ if (!target) return;
+ if (scope.current) scope.current.register(this);
+ const paramX = parameters.x;
+ const paramY = parameters.y;
+ const trigger = parameters.trigger;
+ const modifier = parameters.modifier;
+ const ease = parameters.releaseEase;
+ const customEase = ease && parseEase(ease);
+ const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
+ const xProp = /** @type {String} */(isObj(paramX) && !isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX');
+ const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY');
+ const container = parseDraggableFunctionParameter(parameters.container, this);
+ this.containerArray = isArr(container) ? container : null;
+ this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body);
+ this.useWin = this.$container === doc.body;
+ /** @type {Window | HTMLElement} */
+ this.$scrollContainer = this.useWin ? win : this.$container;
+ this.$target = /** @type {HTMLElement} */(isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]);
+ this.$trigger = /** @type {HTMLElement} */(parseTargets(trigger ? trigger : target)[0]);
+ this.fixed = get(this.$target, 'position') === 'fixed';
+ // Refreshable parameters
+ this.isFinePointer = true;
+ /** @type {[Number, Number, Number, Number]} */
+ this.containerPadding = [0, 0, 0, 0];
+ /** @type {Number} */
+ this.containerFriction = 0;
+ /** @type {Number} */
+ this.releaseContainerFriction = 0;
+ /** @type {Number|Array<Number>} */
+ this.snapX = 0;
+ /** @type {Number|Array<Number>} */
+ this.snapY = 0;
+ /** @type {Number} */
+ this.scrollSpeed = 0;
+ /** @type {Number} */
+ this.scrollThreshold = 0;
+ /** @type {Number} */
+ this.dragSpeed = 0;
+ /** @type {Number} */
+ this.maxVelocity = 0;
+ /** @type {Number} */
+ this.minVelocity = 0;
+ /** @type {Number} */
+ this.velocityMultiplier = 0;
+ /** @type {Boolean|DraggableCursorParams} */
+ this.cursor = false;
+ /** @type {Spring} */
+ this.releaseXSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({
+ mass: setValue(parameters.releaseMass, 1),
+ stiffness: setValue(parameters.releaseStiffness, 80),
+ damping: setValue(parameters.releaseDamping, 20),
+ });
+ /** @type {Spring} */
+ this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({
+ mass: setValue(parameters.releaseMass, 1),
+ stiffness: setValue(parameters.releaseStiffness, 80),
+ damping: setValue(parameters.releaseDamping, 20),
+ });
+ /** @type {EasingFunction} */
+ this.releaseEase = customEase || eases.outQuint;
+ /** @type {Boolean} */
+ this.hasReleaseSpring = hasSpring;
+ /** @type {Callback<this>} */
+ this.onGrab = parameters.onGrab || noop;
+ /** @type {Callback<this>} */
+ this.onDrag = parameters.onDrag || noop;
+ /** @type {Callback<this>} */
+ this.onRelease = parameters.onRelease || noop;
+ /** @type {Callback<this>} */
+ this.onUpdate = parameters.onUpdate || noop;
+ /** @type {Callback<this>} */
+ this.onSettle = parameters.onSettle || noop;
+ /** @type {Callback<this>} */
+ this.onSnap = parameters.onSnap || noop;
+ /** @type {Callback<this>} */
+ this.onResize = parameters.onResize || noop;
+ /** @type {Callback<this>} */
+ this.onAfterResize = parameters.onAfterResize || noop;
+ /** @type {[Number, Number]} */
+ this.disabled = [0, 0];
+ /** @type {AnimatableParams} */
+ const animatableParams = {};
+ if (modifier) animatableParams.modifier = modifier;
+ if (isUnd(paramX) || paramX === true) {
+ animatableParams[xProp] = 0;
+ } else if (isObj(paramX)) {
+ const paramXObject = /** @type {DraggableAxisParam} */(paramX);
+ const animatableXParams = {};
+ if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier;
+ if (paramXObject.composition) animatableXParams.composition = paramXObject.composition;
+ animatableParams[xProp] = animatableXParams;
+ } else if (paramX === false) {
+ animatableParams[xProp] = 0;
+ this.disabled[0] = 1;
+ }
+ if (isUnd(paramY) || paramY === true) {
+ animatableParams[yProp] = 0;
+ } else if (isObj(paramY)) {
+ const paramYObject = /** @type {DraggableAxisParam} */(paramY);
+ const animatableYParams = {};
+ if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier;
+ if (paramYObject.composition) animatableYParams.composition = paramYObject.composition;
+ animatableParams[yProp] = animatableYParams;
+ } else if (paramY === false) {
+ animatableParams[yProp] = 0;
+ this.disabled[1] = 1;
+ }
+ /** @type {AnimatableObject} */
+ this.animate = /** @type {AnimatableObject} */(new Animatable(this.$target, animatableParams));
+ // Internal props
+ this.xProp = xProp;
+ this.yProp = yProp;
+ this.destX = 0;
+ this.destY = 0;
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.scroll = {x: 0, y: 0};
+ /** @type {[Number, Number, Number, Number]} */
+ this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y
+ /** @type {[Number, Number]} */
+ this.snapped = [0, 0]; // x, y
+ /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */
+ this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2
+ /** @type {[Number, Number]} */
+ this.scrollView = [0, 0]; // w, h
+ /** @type {[Number, Number, Number, Number]} */
+ this.dragArea = [0, 0, 0, 0]; // x, y, w, h
+ /** @type {[Number, Number, Number, Number]} */
+ this.containerBounds = [-maxValue, maxValue, maxValue, -maxValue]; // t, r, b, l
+ /** @type {[Number, Number, Number, Number]} */
+ this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l
+ /** @type {[Number, Number, Number, Number]} */
+ this.targetBounds = [0, 0, 0, 0]; // t, r, b, l
+ /** @type {[Number, Number]} */
+ this.window = [0, 0]; // w, h
+ /** @type {[Number, Number, Number]} */
+ this.velocityStack = [0, 0, 0];
+ /** @type {Number} */
+ this.velocityStackIndex = 0;
+ /** @type {Number} */
+ this.velocityTime = now();
+ /** @type {Number} */
+ this.velocity = 0;
+ /** @type {Number} */
+ this.angle = 0;
+ /** @type {JSAnimation} */
+ this.cursorStyles = null;
+ /** @type {JSAnimation} */
+ this.triggerStyles = null;
+ /** @type {JSAnimation} */
+ this.bodyStyles = null;
+ /** @type {JSAnimation} */
+ this.targetStyles = null;
+ /** @type {JSAnimation} */
+ this.touchActionStyles = null;
+ this.transforms = new Transforms(this.$target);
+ this.overshootCoords = { x: 0, y: 0 };
+ this.overshootTicker = new Timer({
+ autoplay: false,
+ onUpdate: () => {
+ this.updated = true;
+ this.manual = true;
+ // Use a duration of 1 to prevent the animatable from completing immediately to prevent issues with onSettle()
+ // https://github.com/juliangarnier/anime/issues/1045
+ if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 1);
+ if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 1);
+ },
+ onComplete: () => {
+ this.manual = false;
+ if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0);
+ if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0);
+ },
+ }, null, 0).init();
+ this.updateTicker = new Timer({ autoplay: false, onUpdate: () => this.update() }, null,0,).init();
+ this.contained = !isUnd(container);
+ this.manual = false;
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.enabled = false;
+ this.initialized = false;
+ this.activeProp = this.disabled[1] ? xProp : yProp;
+ this.animate.callbacks.onRender = () => {
+ const hasUpdated = this.updated;
+ const hasMoved = this.grabbed && hasUpdated;
+ const hasReleased = !hasMoved && this.released;
+ const x = this.x;
+ const y = this.y;
+ const dx = x - this.coords[2];
+ const dy = y - this.coords[3];
+ this.deltaX = dx;
+ this.deltaY = dy;
+ this.coords[2] = x;
+ this.coords[3] = y;
+ // Check if dx or dy are not 0 to check if the draggable has actually moved
+ // https://github.com/juliangarnier/anime/issues/1032
+ if (hasUpdated && (dx || dy)) {
+ this.onUpdate(this);
+ }
+ if (!hasReleased) {
+ this.updated = false;
+ } else {
+ this.computeVelocity(dx, dy);
+ this.angle = atan2(dy, dx);
+ }
+ };
+ this.animate.callbacks.onComplete = () => {
+ if ((!this.grabbed && this.released)) {
+ // Set released to false before calling onSettle to avoid recursion
+ this.released = false;
+ }
+ if (!this.manual) {
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.onSettle(this);
+ }
+ };
+ this.resizeTicker = new Timer({
+ autoplay: false,
+ duration: 150 * globals.timeScale,
+ onComplete: () => {
+ this.onResize(this);
+ this.refresh();
+ this.onAfterResize(this);
+ },
+ }).init();
+ this.parameters = parameters;
+ this.resizeObserver = new ResizeObserver(() => {
+ if (this.initialized) {
+ this.resizeTicker.restart();
+ } else {
+ this.initialized = true;
+ }
+ });
+ this.enable();
+ this.refresh();
+ this.resizeObserver.observe(this.$container);
+ if (!isObj(target)) this.resizeObserver.observe(this.$target);
+ }
+
+ /**
+ * @param {Number} dx
+ * @param {Number} dy
+ * @return {Number}
+ */
+ computeVelocity(dx, dy) {
+ const prevTime = this.velocityTime;
+ const curTime = now();
+ const elapsed = curTime - prevTime;
+ if (elapsed < 17) return this.velocity;
+ this.velocityTime = curTime;
+ const velocityStack = this.velocityStack;
+ const vMul = this.velocityMultiplier;
+ const minV = this.minVelocity;
+ const maxV = this.maxVelocity;
+ const vi = this.velocityStackIndex;
+ velocityStack[vi] = round$1(clamp$1((sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5);
+ const velocity = max(velocityStack[0], velocityStack[1], velocityStack[2]);
+ this.velocity = velocity;
+ this.velocityStackIndex = (vi + 1) % 3;
+ return velocity;
+ }
+
+ /**
+ * @param {Number} x
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setX(x, muteUpdateCallback = false) {
+ if (this.disabled[0]) return;
+ const v = round$1(x, 5);
+ this.overshootTicker.pause();
+ this.manual = true;
+ this.updated = !muteUpdateCallback;
+ this.destX = v;
+ this.snapped[0] = snap$1(v, this.snapX);
+ this.animate[this.xProp](v, 0);
+ this.manual = false;
+ return this;
+ }
+
+ /**
+ * @param {Number} y
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setY(y, muteUpdateCallback = false) {
+ if (this.disabled[1]) return;
+ const v = round$1(y, 5);
+ this.overshootTicker.pause();
+ this.manual = true;
+ this.updated = !muteUpdateCallback;
+ this.destY = v;
+ this.snapped[1] = snap$1(v, this.snapY);
+ this.animate[this.yProp](v, 0);
+ this.manual = false;
+ return this;
+ }
+
+ get x() {
+ return round$1(/** @type {Number} */(this.animate[this.xProp]()), globals.precision);
+ }
+
+ set x(x) {
+ this.setX(x, false);
+ }
+
+ get y() {
+ return round$1(/** @type {Number} */(this.animate[this.yProp]()), globals.precision);
+ }
+
+ set y(y) {
+ this.setY(y, false);
+ }
+
+ get progressX() {
+ return mapRange$1(this.x, this.containerBounds[3], this.containerBounds[1], 0, 1);
+ }
+
+ set progressX(x) {
+ this.setX(mapRange$1(x, 0, 1, this.containerBounds[3], this.containerBounds[1]), false);
+ }
+
+ get progressY() {
+ return mapRange$1(this.y, this.containerBounds[0], this.containerBounds[2], 0, 1);
+ }
+
+ set progressY(y) {
+ this.setY(mapRange$1(y, 0, 1, this.containerBounds[0], this.containerBounds[2]), false);
+ }
+
+ updateScrollCoords() {
+ const sx = round$1(this.useWin ? win.scrollX : this.$container.scrollLeft, 0);
+ const sy = round$1(this.useWin ? win.scrollY : this.$container.scrollTop, 0);
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const threshold = this.scrollThreshold;
+ this.scroll.x = sx;
+ this.scroll.y = sy;
+ this.scrollBounds[0] = sy - this.targetBounds[0] + cpt - threshold;
+ this.scrollBounds[1] = sx - this.targetBounds[1] - cpr + threshold;
+ this.scrollBounds[2] = sy - this.targetBounds[2] - cpb + threshold;
+ this.scrollBounds[3] = sx - this.targetBounds[3] + cpl - threshold;
+ }
+
+ updateBoundingValues() {
+ const $container = this.$container;
+ // Return early if no $container defined to prevents error when reading scrollWidth / scrollHeight
+ // https://github.com/juliangarnier/anime/issues/1064
+ if (!$container) return;
+ const cx = this.x;
+ const cy = this.y;
+ const cx2 = this.coords[2];
+ const cy2 = this.coords[3];
+ // Prevents interfering with the scroll area in cases the target is outside of the container
+ // Make sure the temp coords are also adjuset to prevents wrong delta calculation on updates
+ this.coords[2] = 0;
+ this.coords[3] = 0;
+ this.setX(0, true);
+ this.setY(0, true);
+ this.transforms.remove();
+ const iw = this.window[0] = win.innerWidth;
+ const ih = this.window[1] = win.innerHeight;
+ const uw = this.useWin;
+ const sw = $container.scrollWidth;
+ const sh = $container.scrollHeight;
+ const fx = this.fixed;
+ const transformContainerRect = $container.getBoundingClientRect();
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ this.dragArea[0] = uw ? 0 : transformContainerRect.left;
+ this.dragArea[1] = uw ? 0 : transformContainerRect.top;
+ this.scrollView[0] = uw ? clamp$1(sw, iw, sw) : sw;
+ this.scrollView[1] = uw ? clamp$1(sh, ih, sh) : sh;
+ this.updateScrollCoords();
+ const { width, height, left, top, right, bottom } = $container.getBoundingClientRect();
+ this.dragArea[2] = round$1(uw ? clamp$1(width, iw, iw) : width, 0);
+ this.dragArea[3] = round$1(uw ? clamp$1(height, ih, ih) : height, 0);
+ const containerOverflow = get($container, 'overflow');
+ const visibleOverflow = containerOverflow === 'visible';
+ const hiddenOverflow = containerOverflow === 'hidden';
+ this.canScroll = fx ? false :
+ this.contained &&
+ (($container === doc.body && visibleOverflow) || (!hiddenOverflow && !visibleOverflow)) &&
+ (sw > this.dragArea[2] + cpl - cpr || sh > this.dragArea[3] + cpt - cpb) &&
+ (!this.containerArray || (this.containerArray && !isArr(this.containerArray)));
+ if (this.contained) {
+ const sx = this.scroll.x;
+ const sy = this.scroll.y;
+ const canScroll = this.canScroll;
+ const targetRect = this.$target.getBoundingClientRect();
+ const hiddenLeft = canScroll ? uw ? 0 : $container.scrollLeft : 0;
+ const hiddenTop = canScroll ? uw ? 0 : $container.scrollTop : 0;
+ const hiddenRight = canScroll ? this.scrollView[0] - hiddenLeft - width : 0;
+ const hiddenBottom = canScroll ? this.scrollView[1] - hiddenTop - height : 0;
+ this.targetBounds[0] = round$1((targetRect.top + sy) - (uw ? 0 : top), 0);
+ this.targetBounds[1] = round$1((targetRect.right + sx) - (uw ? iw : right), 0);
+ this.targetBounds[2] = round$1((targetRect.bottom + sy) - (uw ? ih : bottom), 0);
+ this.targetBounds[3] = round$1((targetRect.left + sx) - (uw ? 0 : left), 0);
+ if (this.containerArray) {
+ this.containerBounds[0] = this.containerArray[0] + cpt;
+ this.containerBounds[1] = this.containerArray[1] - cpr;
+ this.containerBounds[2] = this.containerArray[2] - cpb;
+ this.containerBounds[3] = this.containerArray[3] + cpl;
+ } else {
+ this.containerBounds[0] = -round$1(targetRect.top - (fx ? clamp$1(top, 0, ih) : top) + hiddenTop - cpt, 0);
+ this.containerBounds[1] = -round$1(targetRect.right - (fx ? clamp$1(right, 0, iw) : right) - hiddenRight + cpr, 0);
+ this.containerBounds[2] = -round$1(targetRect.bottom - (fx ? clamp$1(bottom, 0, ih) : bottom) - hiddenBottom + cpb, 0);
+ this.containerBounds[3] = -round$1(targetRect.left - (fx ? clamp$1(left, 0, iw) : left) + hiddenLeft - cpl, 0);
+ }
+ }
+ this.transforms.revert();
+ // Restore coordinates
+ this.coords[2] = cx2;
+ this.coords[3] = cy2;
+ this.setX(cx, true);
+ this.setY(cy, true);
+ }
+
+ /**
+ * @param {Array} bounds
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number}
+ */
+ isOutOfBounds(bounds, x, y) {
+ // Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB
+ if (!this.contained) return 0;
+ const [ bt, br, bb, bl ] = bounds;
+ const [ dx, dy ] = this.disabled;
+ const obx = !dx && x < bl || !dx && x > br;
+ const oby = !dy && y < bt || !dy && y > bb;
+ return obx && !oby ? 1 : !obx && oby ? 2 : obx && oby ? 3 : 0;
+ }
+
+ refresh() {
+ const params = this.parameters;
+ const paramX = params.x;
+ const paramY = params.y;
+ const container = parseDraggableFunctionParameter(params.container, this);
+ const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0;
+ const containerPadding = /** @type {[Number, Number, Number, Number]} */(isArr(cp) ? cp : [cp, cp, cp, cp]);
+ const cx = this.x;
+ const cy = this.y;
+ const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this);
+ const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' };
+ if (parsedCursorStyles) {
+ const { onHover, onGrab } = /** @type {DraggableCursorParams} */(parsedCursorStyles);
+ if (onHover) cursorStyles.onHover = onHover;
+ if (onGrab) cursorStyles.onGrab = onGrab;
+ }
+ this.containerArray = isArr(container) ? container : null;
+ this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body);
+ this.useWin = this.$container === doc.body;
+ /** @type {Window | HTMLElement} */
+ this.$scrollContainer = this.useWin ? win : this.$container;
+ this.isFinePointer = matchMedia('(pointer:fine)').matches;
+ this.containerPadding = setValue(containerPadding, [0, 0, 0, 0]);
+ this.containerFriction = clamp$1(setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1);
+ this.releaseContainerFriction = clamp$1(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1);
+ this.snapX = parseDraggableFunctionParameter(isObj(paramX) && !isUnd(paramX.snap) ? paramX.snap : params.snap, this);
+ this.snapY = parseDraggableFunctionParameter(isObj(paramY) && !isUnd(paramY.snap) ? paramY.snap : params.snap, this);
+ this.scrollSpeed = setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5);
+ this.scrollThreshold = setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20);
+ this.dragSpeed = setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1);
+ this.minVelocity = setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0);
+ this.maxVelocity = setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50);
+ this.velocityMultiplier = setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1);
+ this.cursor = parsedCursorStyles === false ? false : cursorStyles;
+ this.updateBoundingValues();
+
+ // const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y);
+ // if (ob === 1 || ob === 3) this.progressX = px;
+ // if (ob === 2 || ob === 3) this.progressY = py;
+
+ // if (this.initialized && this.contained) {
+ // if (this.progressX !== px) this.progressX = px;
+ // if (this.progressY !== py) this.progressY = py;
+ // }
+
+ const [ bt, br, bb, bl ] = this.containerBounds;
+ this.setX(clamp$1(cx, bl, br), true);
+ this.setY(clamp$1(cy, bt, bb), true);
+ }
+
+ update() {
+ this.updateScrollCoords();
+ if (this.canScroll) {
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const [ sw, sh ] = this.scrollView;
+ const daw = this.dragArea[2];
+ const dah = this.dragArea[3];
+ const csx = this.scroll.x;
+ const csy = this.scroll.y;
+ const nsw = this.$container.scrollWidth;
+ const nsh = this.$container.scrollHeight;
+ const csw = this.useWin ? clamp$1(nsw, this.window[0], nsw) : nsw;
+ const csh = this.useWin ? clamp$1(nsh, this.window[1], nsh) : nsh;
+ const swd = sw - csw;
+ const shd = sh - csh;
+ // Handle cases where the scrollarea dimensions changes during drag
+ if (this.dragged && swd > 0) {
+ this.coords[0] -= swd;
+ this.scrollView[0] = csw;
+ }
+ if (this.dragged && shd > 0) {
+ this.coords[1] -= shd;
+ this.scrollView[1] = csh;
+ }
+ // Handle autoscroll when target is at the edges of the scroll bounds
+ const s = this.scrollSpeed * 10;
+ const threshold = this.scrollThreshold;
+ const [ x, y ] = this.coords;
+ const [ st, sr, sb, sl ] = this.scrollBounds;
+ const t = round$1(clamp$1((y - st + cpt) / threshold, -1, 0) * s, 0);
+ const r = round$1(clamp$1((x - sr - cpr) / threshold, 0, 1) * s, 0);
+ const b = round$1(clamp$1((y - sb - cpb) / threshold, 0, 1) * s, 0);
+ const l = round$1(clamp$1((x - sl + cpl) / threshold, -1, 0) * s, 0);
+ if (t || b || l || r) {
+ const [nx, ny] = this.disabled;
+ let scrollX = csx;
+ let scrollY = csy;
+ if (!nx) {
+ scrollX = round$1(clamp$1(csx + (l || r), 0, sw - daw), 0);
+ this.coords[0] -= csx - scrollX;
+ }
+ if (!ny) {
+ scrollY = round$1(clamp$1(csy + (t || b), 0, sh - dah), 0);
+ this.coords[1] -= csy - scrollY;
+ }
+ // Note: Safari mobile requires to use different scroll methods depending if using the window or not
+ if (this.useWin) {
+ this.$scrollContainer.scrollBy(-(csx - scrollX), -(csy - scrollY));
+ } else {
+ this.$scrollContainer.scrollTo(scrollX, scrollY);
+ }
+ }
+ }
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
+ this.coords[0] += (px1 - px3) * this.dragSpeed;
+ this.coords[1] += (py1 - py3) * this.dragSpeed;
+ this.pointer[4] = px1;
+ this.pointer[5] = py1;
+ const [ cx, cy ] = this.coords;
+ const [ sx, sy ] = this.snapped;
+ const cf = (1 - this.containerFriction) * this.dragSpeed;
+ this.setX(cx > cr ? cr + (cx - cr) * cf : cx < cl ? cl + (cx - cl) * cf : cx, false);
+ this.setY(cy > cb ? cb + (cy - cb) * cf : cy < ct ? ct + (cy - ct) * cf : cy, false);
+ this.computeVelocity(px1 - px3, py1 - py3);
+ this.angle = atan2(py1 - py2, px1 - px2);
+ const [ nsx, nsy ] = this.snapped;
+ if (nsx !== sx && this.snapX || nsy !== sy && this.snapY) {
+ this.onSnap(this);
+ }
+ }
+
+ stop() {
+ this.updateTicker.pause();
+ this.overshootTicker.pause();
+ // Pauses the in bounds onRelease animations
+ for (let prop in this.animate.animations) this.animate.animations[prop].pause();
+ removeTargetsFromRenderable([this], null, 'x');
+ removeTargetsFromRenderable([this], null, 'y');
+ removeTargetsFromRenderable([this], null, 'progressX');
+ removeTargetsFromRenderable([this], null, 'progressY');
+ removeTargetsFromRenderable([this.scroll]); // Removes any active animations on the container scroll
+ removeTargetsFromRenderable([this.overshootCoords]); // Removes active overshoot animations
+ return this;
+ }
+
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ scrollInView(duration, gap = 0, ease = eases.inOutQuad) {
+ this.updateScrollCoords();
+ const x = this.destX;
+ const y = this.destY;
+ const scroll = this.scroll;
+ const scrollBounds = this.scrollBounds;
+ const canScroll = this.canScroll;
+ if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) {
+ const [ st, sr, sb, sl ] = scrollBounds;
+ const t = round$1(clamp$1(y - st, -maxValue, 0), 0);
+ const r = round$1(clamp$1(x - sr, 0, maxValue), 0);
+ const b = round$1(clamp$1(y - sb, 0, maxValue), 0);
+ const l = round$1(clamp$1(x - sl, -maxValue, 0), 0);
+ new JSAnimation(scroll, {
+ x: round$1(scroll.x + (l ? l - gap : r ? r + gap : 0), 0),
+ y: round$1(scroll.y + (t ? t - gap : b ? b + gap : 0), 0),
+ duration: isUnd(duration) ? 350 * globals.timeScale : duration,
+ ease,
+ onUpdate: () => {
+ this.canScroll = false;
+ this.$scrollContainer.scrollTo(scroll.x, scroll.y);
+ }
+ }).init().then(() => {
+ this.canScroll = canScroll;
+ });
+ }
+ return this;
+ }
+
+ handleHover() {
+ if (this.isFinePointer && this.cursor && !this.cursorStyles) {
+ this.cursorStyles = set(this.$trigger, {
+ cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover
+ });
+ }
+ }
+
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ animateInView(duration, gap = 0, ease = eases.inOutQuad) {
+ this.stop();
+ this.updateBoundingValues();
+ const x = this.x;
+ const y = this.y;
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const bt = this.scroll.y - this.targetBounds[0] + cpt + gap;
+ const br = this.scroll.x - this.targetBounds[1] - cpr - gap;
+ const bb = this.scroll.y - this.targetBounds[2] - cpb - gap;
+ const bl = this.scroll.x - this.targetBounds[3] + cpl + gap;
+ const ob = this.isOutOfBounds([bt, br, bb, bl], x, y);
+ if (ob) {
+ const [ disabledX, disabledY ] = this.disabled;
+ const destX = clamp$1(snap$1(x, this.snapX), bl, br);
+ const destY = clamp$1(snap$1(y, this.snapY), bt, bb);
+ const dur = isUnd(duration) ? 350 * globals.timeScale : duration;
+ if (!disabledX && (ob === 1 || ob === 3)) this.animate[this.xProp](destX, dur, ease);
+ if (!disabledY && (ob === 2 || ob === 3)) this.animate[this.yProp](destY, dur, ease);
+ }
+ return this;
+ }
+
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleDown(e) {
+ const $eTarget = /** @type {HTMLElement} */(e.target);
+ if (this.grabbed || /** @type {HTMLInputElement} */($eTarget).type === 'range') return;
+
+ e.stopPropagation();
+
+ this.grabbed = true;
+ this.released = false;
+ this.stop();
+ this.updateBoundingValues();
+ const touches = /** @type {TouchEvent} */(e).changedTouches;
+ const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
+ const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
+ const { x, y } = this.transforms.normalizePoint(eventX, eventY);
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const cf = (1 - this.containerFriction) * this.dragSpeed;
+ const cx = this.x;
+ const cy = this.y;
+ this.coords[0] = this.coords[2] = !cf ? cx : cx > cr ? cr + (cx - cr) / cf : cx < cl ? cl + (cx - cl) / cf : cx;
+ this.coords[1] = this.coords[3] = !cf ? cy : cy > cb ? cb + (cy - cb) / cf : cy < ct ? ct + (cy - ct) / cf : cy;
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.pointer[2] = x;
+ this.pointer[3] = y;
+ this.pointer[4] = x;
+ this.pointer[5] = y;
+ this.pointer[6] = x;
+ this.pointer[7] = y;
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.angle = 0;
+ if (this.targetStyles) {
+ this.targetStyles.revert();
+ this.targetStyles = null;
+ }
+ const z = /** @type {Number} */(get(this.$target, 'zIndex', false));
+ zIndex = (z > zIndex ? z : zIndex) + 1;
+ this.targetStyles = set(this.$target, { zIndex });
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+ if (this.cursorStyles) {
+ this.cursorStyles.revert();
+ this.cursorStyles = null;
+ }
+ if (this.isFinePointer && this.cursor) {
+ this.bodyStyles = set(doc.body, {
+ cursor: /** @type {DraggableCursorParams} */(this.cursor).onGrab
+ });
+ }
+ this.scrollInView(100, 0, eases.out(3));
+ this.onGrab(this);
+
+ doc.addEventListener('touchmove', this);
+ doc.addEventListener('touchend', this);
+ doc.addEventListener('touchcancel', this);
+ doc.addEventListener('mousemove', this);
+ doc.addEventListener('mouseup', this);
+ doc.addEventListener('selectstart', this);
+ }
+
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleMove(e) {
+ if (!this.grabbed) return;
+ const touches = /** @type {TouchEvent} */(e).changedTouches;
+ const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
+ const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
+ const { x, y } = this.transforms.normalizePoint(eventX, eventY);
+ const movedX = x - this.pointer[6];
+ const movedY = y - this.pointer[7];
+
+ let $parent = /** @type {HTMLElement} */(e.target);
+ let isAtTop = false;
+ let isAtBottom = false;
+ let canTouchScroll = false;
+
+ while (touches && $parent && $parent !== this.$trigger) {
+ const overflowY = get($parent, 'overflow-y');
+ if (overflowY !== 'hidden' && overflowY !== 'visible') {
+ const { scrollTop, scrollHeight, clientHeight } = $parent;
+ if (scrollHeight > clientHeight) {
+ canTouchScroll = true;
+ isAtTop = scrollTop <= 3;
+ isAtBottom = scrollTop >= (scrollHeight - clientHeight) - 3;
+ break;
+ }
+ }
+ $parent = $parent.parentElement;
+ }
+
+ if (canTouchScroll && ((!isAtTop && !isAtBottom) || (isAtTop && movedY < 0) || (isAtBottom && movedY > 0))) {
+
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.pointer[2] = x;
+ this.pointer[3] = y;
+ this.pointer[4] = x;
+ this.pointer[5] = y;
+ this.pointer[6] = x;
+ this.pointer[7] = y;
+
+ } else {
+
+ preventDefault(e);
+
+ // Needed to prevents click on handleUp
+ if (!this.triggerStyles) this.triggerStyles = set(this.$trigger, { pointerEvents: 'none' });
+ // Needed to prevent page scroll while dragging on touch devvice
+ this.$trigger.addEventListener('touchstart', preventDefault, { passive: false });
+ this.$trigger.addEventListener('touchmove', preventDefault, { passive: false });
+ this.$trigger.addEventListener('touchend', preventDefault);
+
+
+ if ((!this.disabled[0] && abs(movedX) > 3) || (!this.disabled[1] && abs(movedY) > 3)) {
+
+ this.updateTicker.resume();
+ this.pointer[2] = this.pointer[0];
+ this.pointer[3] = this.pointer[1];
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.dragged = true;
+ this.released = false;
+ this.onDrag(this);
+ }
+ }
+ }
+
+ handleUp() {
+
+ if (!this.grabbed) return;
+
+ this.updateTicker.pause();
+
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+
+ if (this.bodyStyles) {
+ this.bodyStyles.revert();
+ this.bodyStyles = null;
+ }
+
+ const [ disabledX, disabledY ] = this.disabled;
+ const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const [ sx, sy ] = this.snapped;
+ const springX = this.releaseXSpring;
+ const springY = this.releaseYSpring;
+ const releaseEase = this.releaseEase;
+ const hasReleaseSpring = this.hasReleaseSpring;
+ const overshootCoords = this.overshootCoords;
+ const cx = this.x;
+ const cy = this.y;
+ const pv = this.computeVelocity(px1 - px3, py1 - py3);
+ const pa = this.angle = atan2(py1 - py2, px1 - px2);
+ const ds = pv * 150;
+ const cf = (1 - this.releaseContainerFriction) * this.dragSpeed;
+ const nx = cx + (cos(pa) * ds);
+ const ny = cy + (sin(pa) * ds);
+ const bx = nx > cr ? cr + (nx - cr) * cf : nx < cl ? cl + (nx - cl) * cf : nx;
+ const by = ny > cb ? cb + (ny - cb) * cf : ny < ct ? ct + (ny - ct) * cf : ny;
+ const dx = this.destX = clamp$1(round$1(snap$1(bx, this.snapX), 5), cl, cr);
+ const dy = this.destY = clamp$1(round$1(snap$1(by, this.snapY), 5), ct, cb);
+ const ob = this.isOutOfBounds(this.containerBounds, nx, ny);
+
+ let durationX = 0;
+ let durationY = 0;
+ let easeX = releaseEase;
+ let easeY = releaseEase;
+ let longestReleaseDuration = 0;
+
+ overshootCoords.x = cx;
+ overshootCoords.y = cy;
+
+ if (!disabledX) {
+ const directionX = dx === cr ? cx > cr ? -1 : 1 : cx < cl ? -1 : 1;
+ const distanceX = round$1(cx - dx, 0);
+ springX.velocity = disabledY && hasReleaseSpring ? distanceX ? (ds * directionX) / abs(distanceX) : 0 : pv;
+ const { ease, duration, restDuration } = springX;
+ durationX = cx === dx ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.timeScale);
+ if (hasReleaseSpring) easeX = ease;
+ if (durationX > longestReleaseDuration) longestReleaseDuration = durationX;
+ }
+
+ if (!disabledY) {
+ const directionY = dy === cb ? cy > cb ? -1 : 1 : cy < ct ? -1 : 1;
+ const distanceY = round$1(cy - dy, 0);
+ springY.velocity = disabledX && hasReleaseSpring ? distanceY ? (ds * directionY) / abs(distanceY) : 0 : pv;
+ const { ease, duration, restDuration } = springY;
+ durationY = cy === dy ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.timeScale);
+ if (hasReleaseSpring) easeY = ease;
+ if (durationY > longestReleaseDuration) longestReleaseDuration = durationY;
+ }
+
+ if (!hasReleaseSpring && ob && cf && (durationX || durationY)) {
+
+ const composition = compositionTypes.blend;
+
+ new JSAnimation(overshootCoords, {
+ x: { to: bx, duration: durationX * .65 },
+ y: { to: by, duration: durationY * .65 },
+ ease: releaseEase,
+ composition,
+ }).init();
+
+ new JSAnimation(overshootCoords, {
+ x: { to: dx, duration: durationX },
+ y: { to: dy, duration: durationY },
+ ease: releaseEase,
+ composition,
+ }).init();
+
+ this.overshootTicker.stretch(max(durationX, durationY)).restart();
+
+ } else {
+
+ if (!disabledX) this.animate[this.xProp](dx, durationX, easeX);
+ if (!disabledY) this.animate[this.yProp](dy, durationY, easeY);
+
+ }
+
+ this.scrollInView(longestReleaseDuration, this.scrollThreshold, releaseEase);
+
+ let hasSnapped = false;
+
+ if (dx !== sx) {
+ this.snapped[0] = dx;
+ if (this.snapX) hasSnapped = true;
+ }
+
+ if (dy !== sy && this.snapY) {
+ this.snapped[1] = dy;
+ if (this.snapY) hasSnapped = true;
+ }
+
+ if (hasSnapped) this.onSnap(this);
+
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = true;
+ this.released = true;
+
+ // It's important to trigger the callback after the release animations to be able to cancel them
+ this.onRelease(this);
+
+ this.$trigger.removeEventListener('touchstart', preventDefault);
+ this.$trigger.removeEventListener('touchmove', preventDefault);
+ this.$trigger.removeEventListener('touchend', preventDefault);
+
+ doc.removeEventListener('touchmove', this);
+ doc.removeEventListener('touchend', this);
+ doc.removeEventListener('touchcancel', this);
+ doc.removeEventListener('mousemove', this);
+ doc.removeEventListener('mouseup', this);
+ doc.removeEventListener('selectstart', this);
+ }
+
+ reset() {
+ this.stop();
+ this.resizeTicker.pause();
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.setX(0, true);
+ this.setY(0, true);
+ this.coords[0] = 0;
+ this.coords[1] = 0;
+ this.pointer[0] = 0;
+ this.pointer[1] = 0;
+ this.pointer[2] = 0;
+ this.pointer[3] = 0;
+ this.pointer[4] = 0;
+ this.pointer[5] = 0;
+ this.pointer[6] = 0;
+ this.pointer[7] = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.angle = 0;
+ return this;
+ }
+
+ enable() {
+ if (!this.enabled) {
+ this.enabled = true;
+ this.$target.classList.remove('is-disabled');
+ this.touchActionStyles = set(this.$trigger, {
+ touchAction: this.disabled[0] ? 'pan-x' : this.disabled[1] ? 'pan-y' : 'none'
+ });
+ this.$trigger.addEventListener('touchstart', this, { passive: true });
+ this.$trigger.addEventListener('mousedown', this, { passive: true });
+ this.$trigger.addEventListener('mouseenter', this);
+ }
+ return this;
+ }
+
+ disable() {
+ this.enabled = false;
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.touchActionStyles.revert();
+ if (this.cursorStyles) {
+ this.cursorStyles.revert();
+ this.cursorStyles = null;
+ }
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+ if (this.bodyStyles) {
+ this.bodyStyles.revert();
+ this.bodyStyles = null;
+ }
+ if (this.targetStyles) {
+ this.targetStyles.revert();
+ this.targetStyles = null;
+ }
+ this.$target.classList.add('is-disabled');
+ this.$trigger.removeEventListener('touchstart', this);
+ this.$trigger.removeEventListener('mousedown', this);
+ this.$trigger.removeEventListener('mouseenter', this);
+ doc.removeEventListener('touchmove', this);
+ doc.removeEventListener('touchend', this);
+ doc.removeEventListener('touchcancel', this);
+ doc.removeEventListener('mousemove', this);
+ doc.removeEventListener('mouseup', this);
+ doc.removeEventListener('selectstart', this);
+ return this;
+ }
+
+ revert() {
+ this.reset();
+ this.disable();
+ this.$target.classList.remove('is-disabled');
+ this.updateTicker.revert();
+ this.overshootTicker.revert();
+ this.resizeTicker.revert();
+ this.animate.revert();
+ this.resizeObserver.disconnect();
+ return this;
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'mousedown':
+ this.handleDown(/** @type {MouseEvent} */(e));
+ break;
+ case 'touchstart':
+ this.handleDown(/** @type {TouchEvent} */(e));
+ break;
+ case 'mousemove':
+ this.handleMove(/** @type {MouseEvent} */(e));
+ break;
+ case 'touchmove':
+ this.handleMove(/** @type {TouchEvent} */(e));
+ break;
+ case 'mouseup':
+ this.handleUp();
+ break;
+ case 'touchend':
+ this.handleUp();
+ break;
+ case 'touchcancel':
+ this.handleUp();
+ break;
+ case 'mouseenter':
+ this.handleHover();
+ break;
+ case 'selectstart':
+ preventDefault(e);
+ break;
+ }
+ }
+ }
+
+ /**
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
+ * @return {Draggable}
+ */
+ const createDraggable = (target, parameters) => new Draggable(target, parameters);
+
+
+
+ /**
+ * @param {Callback<Timer>} [callback]
+ * @return {Timer}
+ */
+ const sync = (callback = noop) => {
+ return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
+ };
+
+ /**
+ * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor
+ * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)}
+ */
+ const keepTime = constructor => {
+ /** @type {Tickable} */
+ let tracked;
+ return (...args) => {
+ let currentIteration, currentIterationProgress, reversed, alternate;
+ if (tracked) {
+ currentIteration = tracked.currentIteration;
+ currentIterationProgress = tracked.iterationProgress;
+ reversed = tracked.reversed;
+ alternate = tracked._alternate;
+ tracked.revert();
+ }
+ const cleanup = constructor(...args);
+ if (cleanup && !isFnc(cleanup) && cleanup.revert) tracked = cleanup;
+ if (!isUnd(currentIterationProgress)) {
+ /** @type {Tickable} */(tracked).currentIteration = currentIteration;
+ /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress;
+ }
+ return cleanup || noop;
+ }
+ };
+
+
+
+ class Scope {
+ /** @param {ScopeParams} [parameters] */
+ constructor(parameters = {}) {
+ if (scope.current) scope.current.register(this);
+ const rootParam = parameters.root;
+ /** @type {Document|DOMTarget} */
+ let root = doc;
+ if (rootParam) {
+ root = /** @type {ReactRef} */(rootParam).current ||
+ /** @type {AngularRef} */(rootParam).nativeElement ||
+ parseTargets(/** @type {DOMTargetSelector} */(rootParam))[0] ||
+ doc;
+ }
+ const scopeDefaults = parameters.defaults;
+ const globalDefault = globals.defaults;
+ const mediaQueries = parameters.mediaQueries;
+ /** @type {DefaultsParams} */
+ this.defaults = scopeDefaults ? mergeObjects(scopeDefaults, globalDefault) : globalDefault;
+ /** @type {Document|DOMTarget} */
+ this.root = root;
+ /** @type {Array<ScopeConstructorCallback>} */
+ this.constructors = [];
+ /** @type {Array<ScopeCleanupCallback>} */
+ this.revertConstructors = [];
+ /** @type {Array<Revertible>} */
+ this.revertibles = [];
+ /** @type {Array<ScopeConstructorCallback | ((scope: this) => Tickable)>} */
+ this.constructorsOnce = [];
+ /** @type {Array<ScopeCleanupCallback>} */
+ this.revertConstructorsOnce = [];
+ /** @type {Array<Revertible>} */
+ this.revertiblesOnce = [];
+ /** @type {Boolean} */
+ this.once = false;
+ /** @type {Number} */
+ this.onceIndex = 0;
+ /** @type {Record<String, ScopeMethod>} */
+ this.methods = {};
+ /** @type {Record<String, Boolean>} */
+ this.matches = {};
+ /** @type {Record<String, MediaQueryList>} */
+ this.mediaQueryLists = {};
+ /** @type {Record<String, any>} */
+ this.data = {};
+ if (mediaQueries) {
+ for (let mq in mediaQueries) {
+ const _mq = win.matchMedia(mediaQueries[mq]);
+ this.mediaQueryLists[mq] = _mq;
+ _mq.addEventListener('change', this);
+ }
+ }
+ }
+
+ /**
+ * @param {Revertible} revertible
+ */
+ register(revertible) {
+ const store = this.once ? this.revertiblesOnce : this.revertibles;
+ store.push(revertible);
+ }
+
+ /**
+ * @template T
+ * @param {ScopedCallback<T>} cb
+ * @return {T}
+ */
+ execute(cb) {
+ let activeScope = scope.current;
+ let activeRoot = scope.root;
+ let activeDefaults = globals.defaults;
+ scope.current = this;
+ scope.root = this.root;
+ globals.defaults = this.defaults;
+ const mqs = this.mediaQueryLists;
+ for (let mq in mqs) this.matches[mq] = mqs[mq].matches;
+ const returned = cb(this);
+ scope.current = activeScope;
+ scope.root = activeRoot;
+ globals.defaults = activeDefaults;
+ return returned;
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ this.onceIndex = 0;
+ this.execute(() => {
+ let i = this.revertibles.length;
+ let y = this.revertConstructors.length;
+ while (i--) this.revertibles[i].revert();
+ while (y--) this.revertConstructors[y](this);
+ this.revertibles.length = 0;
+ this.revertConstructors.length = 0;
+ this.constructors.forEach((/** @type {ScopeConstructorCallback} */constructor) => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructors.push(revertConstructor);
+ }
+ });
+ });
+ return this;
+ }
+
+ /**
+ * @overload
+ * @param {String} a1
+ * @param {ScopeMethod} a2
+ * @return {this}
+ *
+ * @overload
+ * @param {ScopeConstructorCallback} a1
+ * @return {this}
+ *
+ * @param {String|ScopeConstructorCallback} a1
+ * @param {ScopeMethod} [a2]
+ */
+ add(a1, a2) {
+ this.once = false;
+ if (isFnc(a1)) {
+ const constructor = /** @type {ScopeConstructorCallback} */(a1);
+ this.constructors.push(constructor);
+ this.execute(() => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructors.push(revertConstructor);
+ }
+ });
+ } else {
+ this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args));
+ }
+ return this;
+ }
+
+ /**
+ * @param {ScopeConstructorCallback} scopeConstructorCallback
+ * @return {this}
+ */
+ addOnce(scopeConstructorCallback) {
+ this.once = true;
+ if (isFnc(scopeConstructorCallback)) {
+ const currentIndex = this.onceIndex++;
+ const tracked = this.constructorsOnce[currentIndex];
+ if (tracked) return this;
+ const constructor = /** @type {ScopeConstructorCallback} */(scopeConstructorCallback);
+ this.constructorsOnce[currentIndex] = constructor;
+ this.execute(() => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructorsOnce.push(revertConstructor);
+ }
+ });
+ }
+ return this;
+ }
+
+ /**
+ * @param {(scope: this) => Tickable} cb
+ * @return {Tickable}
+ */
+ keepTime(cb) {
+ this.once = true;
+ const currentIndex = this.onceIndex++;
+ const tracked = /** @type {(scope: this) => Tickable} */(this.constructorsOnce[currentIndex]);
+ if (isFnc(tracked)) return tracked(this);
+ const constructor = /** @type {(scope: this) => Tickable} */(keepTime(cb));
+ this.constructorsOnce[currentIndex] = constructor;
+ let trackedTickable;
+ this.execute(() => {
+ trackedTickable = constructor(this);
+ });
+ return trackedTickable;
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'change':
+ this.refresh();
+ break;
+ }
+ }
+
+ revert() {
+ const revertibles = this.revertibles;
+ const revertConstructors = this.revertConstructors;
+ const revertiblesOnce = this.revertiblesOnce;
+ const revertConstructorsOnce = this.revertConstructorsOnce;
+ const mqs = this.mediaQueryLists;
+ let i = revertibles.length;
+ let j = revertConstructors.length;
+ let k = revertiblesOnce.length;
+ let l = revertConstructorsOnce.length;
+ while (i--) revertibles[i].revert();
+ while (j--) revertConstructors[j](this);
+ while (k--) revertiblesOnce[k].revert();
+ while (l--) revertConstructorsOnce[l](this);
+ for (let mq in mqs) mqs[mq].removeEventListener('change', this);
+ revertibles.length = 0;
+ revertConstructors.length = 0;
+ this.constructors.length = 0;
+ revertiblesOnce.length = 0;
+ revertConstructorsOnce.length = 0;
+ this.constructorsOnce.length = 0;
+ this.onceIndex = 0;
+ this.matches = {};
+ this.methods = {};
+ this.mediaQueryLists = {};
+ this.data = {};
+ }
+ }
+
+ /**
+ * @param {ScopeParams} [params]
+ * @return {Scope}
+ */
+ const createScope = params => new Scope(params);
+
+
+
+
+
+
+
+
+
+ /**
+ * @return {Number}
+ */
+ const getMaxViewHeight = () => {
+ const $el = doc.createElement('div');
+ doc.body.appendChild($el);
+ $el.style.height = '100lvh';
+ const height = $el.offsetHeight;
+ doc.body.removeChild($el);
+ return height;
+ };
+
+ /**
+ * @template {ScrollThresholdValue|String|Number|Boolean|Function|Object} T
+ * @param {T | ((observer: ScrollObserver) => T)} value
+ * @param {ScrollObserver} scroller
+ * @return {T}
+ */
+ const parseScrollObserverFunctionParameter = (value, scroller) => value && isFnc(value) ? /** @type {Function} */(value)(scroller) : /** @type {T} */(value);
+
+ const scrollContainers = new Map();
+
+ class ScrollContainer {
+ /**
+ * @param {HTMLElement} $el
+ */
+ constructor($el) {
+ /** @type {HTMLElement} */
+ this.element = $el;
+ /** @type {Boolean} */
+ this.useWin = this.element === doc.body;
+ /** @type {Number} */
+ this.winWidth = 0;
+ /** @type {Number} */
+ this.winHeight = 0;
+ /** @type {Number} */
+ this.width = 0;
+ /** @type {Number} */
+ this.height = 0;
+ /** @type {Number} */
+ this.left = 0;
+ /** @type {Number} */
+ this.top = 0;
+ /** @type {Number} */
+ this.zIndex = 0;
+ /** @type {Number} */
+ this.scrollX = 0;
+ /** @type {Number} */
+ this.scrollY = 0;
+ /** @type {Number} */
+ this.prevScrollX = 0;
+ /** @type {Number} */
+ this.prevScrollY = 0;
+ /** @type {Number} */
+ this.scrollWidth = 0;
+ /** @type {Number} */
+ this.scrollHeight = 0;
+ /** @type {Number} */
+ this.velocity = 0;
+ /** @type {Boolean} */
+ this.backwardX = false;
+ /** @type {Boolean} */
+ this.backwardY = false;
+ /** @type {Timer} */
+ this.scrollTicker = new Timer({
+ autoplay: false,
+ onBegin: () => this.dataTimer.resume(),
+ onUpdate: () => {
+ const backwards = this.backwardX || this.backwardY;
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => child.handleScroll(), backwards);
+ },
+ onComplete: () => this.dataTimer.pause()
+ }).init();
+ /** @type {Timer} */
+ this.dataTimer = new Timer({
+ autoplay: false,
+ frameRate: 30,
+ onUpdate: (/** @type {Timer} */self) => {
+ const dt = self.deltaTime;
+ const px = this.prevScrollX;
+ const py = this.prevScrollY;
+ const nx = this.scrollX;
+ const ny = this.scrollY;
+ const dx = px - nx;
+ const dy = py - ny;
+ this.prevScrollX = nx;
+ this.prevScrollY = ny;
+ if (dx) this.backwardX = px > nx;
+ if (dy) this.backwardY = py > ny;
+ this.velocity = round$1(dt > 0 ? Math.sqrt(dx * dx + dy * dy) / dt : 0, 5);
+ }
+ }).init();
+ /** @type {Timer} */
+ this.resizeTicker = new Timer({
+ autoplay: false,
+ duration: 250 * globals.timeScale,
+ onComplete: () => {
+ this.updateWindowBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ }
+ }).init();
+ /** @type {Timer} */
+ this.wakeTicker = new Timer({
+ autoplay: false,
+ duration: 500 * globals.timeScale,
+ onBegin: () => {
+ this.scrollTicker.resume();
+ },
+ onComplete: () => {
+ this.scrollTicker.pause();
+ }
+ }).init();
+ /** @type {ScrollObserver} */
+ this._head = null;
+ /** @type {ScrollObserver} */
+ this._tail = null;
+ this.updateScrollCoords();
+ this.updateWindowBounds();
+ this.updateBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ this.resizeObserver = new ResizeObserver(() => this.resizeTicker.restart());
+ this.resizeObserver.observe(this.element);
+ (this.useWin ? win : this.element).addEventListener('scroll', this, false);
+ }
+
+ updateScrollCoords() {
+ const useWin = this.useWin;
+ const $el = this.element;
+ this.scrollX = round$1(useWin ? win.scrollX : $el.scrollLeft, 0);
+ this.scrollY = round$1(useWin ? win.scrollY : $el.scrollTop, 0);
+ }
+
+ updateWindowBounds() {
+ this.winWidth = win.innerWidth;
+ this.winHeight = getMaxViewHeight();
+ }
+
+ updateBounds() {
+ const style = getComputedStyle(this.element);
+ const $el = this.element;
+ this.scrollWidth = $el.scrollWidth + parseFloat(style.marginLeft) + parseFloat(style.marginRight);
+ this.scrollHeight = $el.scrollHeight + parseFloat(style.marginTop) + parseFloat(style.marginBottom);
+ this.updateWindowBounds();
+ let width, height;
+ if (this.useWin) {
+ width = this.winWidth;
+ height = this.winHeight;
+ } else {
+ const elRect = $el.getBoundingClientRect();
+ width = $el.clientWidth;
+ height = $el.clientHeight;
+ this.top = elRect.top;
+ this.left = elRect.left;
+ }
+ this.width = width;
+ this.height = height;
+ }
+
+ refreshScrollObservers() {
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => {
+ if (child._debug) {
+ child.removeDebug();
+ }
+ });
+ this.updateBounds();
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => {
+ child.refresh();
+ if (child._debug) {
+ child.debug();
+ }
+ });
+ }
+
+ refresh() {
+ this.updateWindowBounds();
+ this.updateBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ }
+
+ handleScroll() {
+ this.updateScrollCoords();
+ this.wakeTicker.restart();
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'scroll':
+ this.handleScroll();
+ break;
+ }
+ }
+
+ revert() {
+ this.scrollTicker.cancel();
+ this.dataTimer.cancel();
+ this.resizeTicker.cancel();
+ this.wakeTicker.cancel();
+ this.resizeObserver.disconnect();
+ (this.useWin ? win : this.element).removeEventListener('scroll', this);
+ scrollContainers.delete(this.element);
+ }
+ }
+
+ /**
+ * @param {TargetsParam} target
+ * @return {ScrollContainer}
+ */
+ const registerAndGetScrollContainer = target => {
+ const $el = /** @type {HTMLElement} */(target ? parseTargets(target)[0] || doc.body : doc.body);
+ let scrollContainer = scrollContainers.get($el);
+ if (!scrollContainer) {
+ scrollContainer = new ScrollContainer($el);
+ scrollContainers.set($el, scrollContainer);
+ }
+ return scrollContainer;
+ };
+
+ /**
+ * @param {HTMLElement} $el
+ * @param {Number|string} v
+ * @param {Number} size
+ * @param {Number} [under]
+ * @param {Number} [over]
+ * @return {Number}
+ */
+ const convertValueToPx = ($el, v, size, under, over) => {
+ const clampMin = v === 'min';
+ const clampMax = v === 'max';
+ const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 :
+ v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' :
+ v === 'center' ? '50%' :
+ v;
+ const { n, u } = decomposeRawValue(value, decomposedOriginalValue);
+ let px = n;
+ if (u === '%') {
+ px = (n / 100) * size;
+ } else if (u) {
+ px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n;
+ }
+ if (clampMax && under < 0) px += under;
+ if (clampMin && over > 0) px += over;
+ return px;
+ };
+
+ /**
+ * @param {HTMLElement} $el
+ * @param {ScrollThresholdValue} v
+ * @param {Number} size
+ * @param {Number} [under]
+ * @param {Number} [over]
+ * @return {Number}
+ */
+ const parseBoundValue = ($el, v, size, under, over) => {
+ /** @type {Number} */
+ let value;
+ if (isStr(v)) {
+ const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v));
+ if (matchedOperator) {
+ const splitter = matchedOperator[0];
+ const operator = splitter[0];
+ const splitted = /** @type {String} */(v).split(splitter);
+ const clampMin = splitted[0] === 'min';
+ const clampMax = splitted[0] === 'max';
+ const valueAPx = convertValueToPx($el, splitted[0], size, under, over);
+ const valueBPx = convertValueToPx($el, splitted[1], size, under, over);
+ if (clampMin) {
+ const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator);
+ value = min < valueAPx ? valueAPx : min;
+ } else if (clampMax) {
+ const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator);
+ value = max > valueAPx ? valueAPx : max;
+ } else {
+ value = getRelativeValue(valueAPx, valueBPx, operator);
+ }
+ } else {
+ value = convertValueToPx($el, v, size, under, over);
+ }
+ } else {
+ value = /** @type {Number} */(v);
+ }
+ return round$1(value, 0);
+ };
+
+ /**
+ * @param {JSAnimation} linked
+ * @return {HTMLElement}
+ */
+ const getAnimationDomTarget = linked => {
+ let $linkedTarget;
+ const linkedTargets = linked.targets;
+ for (let i = 0, l = linkedTargets.length; i < l; i++) {
+ const target = linkedTargets[i];
+ if (target[isDomSymbol]) {
+ $linkedTarget = /** @type {HTMLElement} */(target);
+ break;
+ }
+ }
+ return $linkedTarget;
+ };
+
+ let scrollerIndex = 0;
+
+ const debugColors$1 = ['#FF4B4B','#FF971B','#FFC730','#F9F640','#7AFF5A','#18FF74','#17E09B','#3CFFEC','#05DBE9','#33B3F1','#638CF9','#C563FE','#FF4FCF','#F93F8A'];
+
+ class ScrollObserver {
+ /**
+ * @param {ScrollObserverParams} parameters
+ */
+ constructor(parameters = {}) {
+ if (scope.current) scope.current.register(this);
+ const syncMode = setValue(parameters.sync, 'play pause');
+ const ease = syncMode ? parseEase(/** @type {EasingParam} */(syncMode)) : null;
+ const isLinear = syncMode && (syncMode === 'linear' || syncMode === none);
+ const isEase = syncMode && !(ease === none && !isLinear);
+ const isSmooth = syncMode && (isNum(syncMode) || syncMode === true || isLinear);
+ const isMethods = syncMode && (isStr(syncMode) && !isEase && !isSmooth);
+ const syncMethods = isMethods ? /** @type {String} */(syncMode).split(' ').map(
+ (/** @type {String} */m) => () => {
+ const linked = this.linked;
+ return linked && linked[m] ? linked[m]() : null;
+ }
+ ) : null;
+ const biDirSync = isMethods && syncMethods.length > 2;
+ /** @type {Number} */
+ this.index = scrollerIndex++;
+ /** @type {String|Number} */
+ this.id = !isUnd(parameters.id) ? parameters.id : this.index;
+ /** @type {ScrollContainer} */
+ this.container = registerAndGetScrollContainer(parameters.container);
+ /** @type {HTMLElement} */
+ this.target = null;
+ /** @type {Tickable|WAAPIAnimation} */
+ this.linked = null;
+ /** @type {Boolean} */
+ this.repeat = null;
+ /** @type {Boolean} */
+ this.horizontal = null;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ this.enter = null;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ this.leave = null;
+ /** @type {Boolean} */
+ this.sync = isEase || isSmooth || !!syncMethods;
+ /** @type {EasingFunction} */
+ this.syncEase = isEase ? ease : null;
+ /** @type {Number} */
+ this.syncSmooth = isSmooth ? syncMode === true || isLinear ? 1 : /** @type {Number} */(syncMode) : null;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnter = syncMethods && !biDirSync && syncMethods[0] ? syncMethods[0] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeave = syncMethods && !biDirSync && syncMethods[1] ? syncMethods[1] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnterForward = syncMethods && biDirSync && syncMethods[0] ? syncMethods[0] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeaveForward = syncMethods && biDirSync && syncMethods[1] ? syncMethods[1] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnterBackward = syncMethods && biDirSync && syncMethods[2] ? syncMethods[2] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeaveBackward = syncMethods && biDirSync && syncMethods[3] ? syncMethods[3] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnter = parameters.onEnter || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeave = parameters.onLeave || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnterForward = parameters.onEnterForward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeaveForward = parameters.onLeaveForward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnterBackward = parameters.onEnterBackward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeaveBackward = parameters.onLeaveBackward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onUpdate = parameters.onUpdate || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncComplete = parameters.onSyncComplete || noop;
+ /** @type {Boolean} */
+ this.reverted = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Boolean} */
+ this.began = false;
+ /** @type {Boolean} */
+ this.isInView = false;
+ /** @type {Boolean} */
+ this.forceEnter = false;
+ /** @type {Boolean} */
+ this.hasEntered = false;
+ // /** @type {Array.<Number>} */
+ // this.offsets = [];
+ /** @type {Number} */
+ this.offset = 0;
+ /** @type {Number} */
+ this.offsetStart = 0;
+ /** @type {Number} */
+ this.offsetEnd = 0;
+ /** @type {Number} */
+ this.distance = 0;
+ /** @type {Number} */
+ this.prevProgress = 0;
+ /** @type {Array} */
+ this.thresholds = ['start', 'end', 'end', 'start'];
+ /** @type {[Number, Number, Number, Number]} */
+ this.coords = [0, 0, 0, 0];
+ /** @type {JSAnimation} */
+ this.debugStyles = null;
+ /** @type {HTMLElement} */
+ this.$debug = null;
+ /** @type {ScrollObserverParams} */
+ this._params = parameters;
+ /** @type {Boolean} */
+ this._debug = setValue(parameters.debug, false);
+ /** @type {ScrollObserver} */
+ this._next = null;
+ /** @type {ScrollObserver} */
+ this._prev = null;
+ addChild(this.container, this);
+ // Wait for the next frame to add to the container in order to handle calls to link()
+ sync(() => {
+ if (this.reverted) return;
+ if (!this.target) {
+ const target = /** @type {HTMLElement} */(parseTargets(parameters.target)[0]);
+ this.target = target || doc.body;
+ this.refresh();
+ }
+ if (this._debug) this.debug();
+ });
+ }
+
+ /**
+ * @param {Tickable|WAAPIAnimation} linked
+ */
+ link(linked) {
+ if (linked) {
+ // Make sure to pause the linked object in case it's added later
+ linked.pause();
+ this.linked = linked;
+ // Try to use a target of the linked object if no target parameters specified
+ if (!this._params.target) {
+ /** @type {HTMLElement} */
+ let $linkedTarget;
+ if (!isUnd(/** @type {JSAnimation} */(linked).targets)) {
+ $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(linked));
+ } else {
+ forEachChildren(/** @type {Timeline} */(linked), (/** @type {JSAnimation} */child) => {
+ if (child.targets && !$linkedTarget) {
+ $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(child));
+ }
+ });
+ }
+ // Fallback to body if no target found
+ this.target = $linkedTarget || doc.body;
+ this.refresh();
+ }
+ }
+ return this;
+ }
+
+ get velocity() {
+ return this.container.velocity;
+ }
+
+ get backward() {
+ return this.horizontal ? this.container.backwardX : this.container.backwardY;
+ }
+
+ get scroll() {
+ return this.horizontal ? this.container.scrollX : this.container.scrollY;
+ }
+
+ get progress() {
+ const p = (this.scroll - this.offsetStart) / this.distance;
+ return p === Infinity || isNaN(p) ? 0 : round$1(clamp$1(p, 0, 1), 6);
+ }
+
+ refresh() {
+ this.reverted = false;
+ const params = this._params;
+ this.repeat = setValue(parseScrollObserverFunctionParameter(params.repeat, this), true);
+ this.horizontal = setValue(parseScrollObserverFunctionParameter(params.axis, this), 'y') === 'x';
+ this.enter = setValue(parseScrollObserverFunctionParameter(params.enter, this), 'end start');
+ this.leave = setValue(parseScrollObserverFunctionParameter(params.leave, this), 'start end');
+ this.updateBounds();
+ this.handleScroll();
+ return this;
+ }
+
+ removeDebug() {
+ if (this.$debug) {
+ this.$debug.parentNode.removeChild(this.$debug);
+ this.$debug = null;
+ }
+ if (this.debugStyles) {
+ this.debugStyles.revert();
+ this.$debug = null;
+ }
+ return this;
+ }
+
+ debug() {
+ this.removeDebug();
+ const container = this.container;
+ const isHori = this.horizontal;
+ const $existingDebug = container.element.querySelector(':scope > .animejs-onscroll-debug');
+ const $debug = doc.createElement('div');
+ const $thresholds = doc.createElement('div');
+ const $triggers = doc.createElement('div');
+ const color = debugColors$1[this.index % debugColors$1.length];
+ const useWin = container.useWin;
+ const containerWidth = useWin ? container.winWidth : container.width;
+ const containerHeight = useWin ? container.winHeight : container.height;
+ const scrollWidth = container.scrollWidth;
+ const scrollHeight = container.scrollHeight;
+ const size = this.container.width > 360 ? 320 : 260;
+ const offLeft = isHori ? 0 : 10;
+ const offTop = isHori ? 10 : 0;
+ const half = isHori ? 24 : size / 2;
+ const labelHeight = isHori ? half : 15;
+ const labelWidth = isHori ? 60 : half;
+ const labelSize = isHori ? labelWidth : labelHeight;
+ const repeat = isHori ? 'repeat-x' : 'repeat-y';
+ /**
+ * @param {Number} v
+ * @return {String}
+ */
+ const gradientOffset = v => isHori ? '0px '+(v)+'px' : (v)+'px'+' 2px';
+ /**
+ * @param {String} c
+ * @return {String}
+ */
+ const lineCSS = (c) => `linear-gradient(${isHori ? 90 : 0}deg, ${c} 2px, transparent 1px)`;
+ /**
+ * @param {String} p
+ * @param {Number} l
+ * @param {Number} t
+ * @param {Number} w
+ * @param {Number} h
+ * @return {String}
+ */
+ const baseCSS = (p, l, t, w, h) => `position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`;
+ $debug.style.cssText = `${baseCSS('absolute', offLeft, offTop, isHori ? scrollWidth : size, isHori ? size : scrollHeight)}
+ pointer-events: none;
+ z-index: ${this.container.zIndex++};
+ display: flex;
+ flex-direction: ${isHori ? 'column' : 'row'};
+ filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));
+ `;
+ $thresholds.style.cssText = `${baseCSS('sticky', 0, 0, isHori ? containerWidth : half, isHori ? half : containerHeight)}`;
+ if (!$existingDebug) {
+ $thresholds.style.cssText += `background:
+ ${lineCSS('#FFFF')}${gradientOffset(half-10)} / ${isHori ? '100px 100px' : '100px 100px'} ${repeat},
+ ${lineCSS('#FFF8')}${gradientOffset(half-10)} / ${isHori ? '10px 10px' : '10px 10px'} ${repeat};
+ `;
+ }
+ $triggers.style.cssText = `${baseCSS('relative', 0, 0, isHori ? scrollWidth : half, isHori ? half : scrollHeight)}`;
+ if (!$existingDebug) {
+ $triggers.style.cssText += `background:
+ ${lineCSS('#FFFF')}${gradientOffset(0)} / ${isHori ? '100px 10px' : '10px 100px'} ${repeat},
+ ${lineCSS('#FFF8')}${gradientOffset(0)} / ${isHori ? '10px 0px' : '0px 10px'} ${repeat};
+ `;
+ }
+ const labels = [' enter: ', ' leave: '];
+ this.coords.forEach((v, i) => {
+ const isView = i > 1;
+ const value = (isView ? 0 : this.offset) + v;
+ const isTail = i % 2;
+ const isFirst = value < labelSize;
+ const isOver = value > (isView ? isHori ? containerWidth : containerHeight : isHori ? scrollWidth : scrollHeight) - labelSize;
+ const isFlip = (isView ? isTail && !isFirst : !isTail && !isFirst) || isOver;
+ const $label = doc.createElement('div');
+ const $text = doc.createElement('div');
+ const dirProp = isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top';
+ const flipOffset = isFlip ? (isHori ? labelWidth : labelHeight) + (!isView ? isHori ? -1 : -2 : isHori ? -1 : isOver ? 0 : -2) : !isView ? isHori ? 1 : 0 : isHori ? 1 : 0;
+ // $text.innerHTML = `${!isView ? '' : labels[isTail] + ' '}${this.id}: ${this.thresholds[i]} ${isView ? '' : labels[isTail]}`;
+ $text.innerHTML = `${this.id}${labels[isTail]}${this.thresholds[i]}`;
+ $label.style.cssText = `${baseCSS('absolute', 0, 0, labelWidth, labelHeight)}
+ display: flex;
+ flex-direction: ${isHori ? 'column' : 'row'};
+ justify-content: flex-${isView ? 'start' : 'end'};
+ align-items: flex-${isFlip ? 'end' : 'start'};
+ border-${dirProp}: 2px ${isTail ? 'solid' : 'solid'} ${color};
+ `;
+ $text.style.cssText = `
+ overflow: hidden;
+ max-width: ${(size / 2) - 10}px;
+ height: ${labelHeight};
+ margin-${isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'}: -2px;
+ padding: 1px;
+ font-family: ui-monospace, monospace;
+ font-size: 10px;
+ letter-spacing: -.025em;
+ line-height: 9px;
+ font-weight: 600;
+ text-align: ${isHori && isFlip || !isHori && !isView ? 'right' : 'left'};
+ white-space: pre;
+ text-overflow: ellipsis;
+ color: ${isTail ? color : 'rgba(0,0,0,.75)'};
+ background-color: ${isTail ? 'rgba(0,0,0,.65)' : color};
+ border: 2px solid ${isTail ? color : 'transparent'};
+ border-${isHori ? isFlip ? 'top-left' : 'top-right' : isFlip ? 'top-left' : 'bottom-left'}-radius: 5px;
+ border-${isHori ? isFlip ? 'bottom-left' : 'bottom-right' : isFlip ? 'top-right' : 'bottom-right'}-radius: 5px;
+ `;
+ $label.appendChild($text);
+ let position = value - flipOffset + (isHori ? 1 : 0);
+ $label.style[isHori ? 'left' : 'top'] = `${position}px`;
+ // $label.style[isHori ? 'left' : 'top'] = value - flipOffset + (!isFlip && isFirst && !isView ? 1 : isFlip ? 0 : -2) + 'px';
+ (isView ? $thresholds : $triggers).appendChild($label);
+ });
+
+ $debug.appendChild($thresholds);
+ $debug.appendChild($triggers);
+ container.element.appendChild($debug);
+
+ if (!$existingDebug) $debug.classList.add('animejs-onscroll-debug');
+ this.$debug = $debug;
+ const containerPosition = get(container.element, 'position');
+ if (containerPosition === 'static') {
+ this.debugStyles = set(container.element, { position: 'relative '});
+ }
+
+ }
+
+ updateBounds() {
+ if (this._debug) {
+ this.removeDebug();
+ }
+ let stickys;
+ const $target = this.target;
+ const container = this.container;
+ const isHori = this.horizontal;
+ const linked = this.linked;
+ let linkedTime;
+ let $el = $target;
+ // let offsetX = 0;
+ // let offsetY = 0;
+ // let $offsetParent = $el;
+ /** @type {Element} */
+ if (linked) {
+ linkedTime = linked.currentTime;
+ linked.seek(0, true);
+ }
+ /* Old implementation to get offset and targetSize before fixing https://github.com/juliangarnier/anime/issues/1021
+ // const isContainerStatic = get(container.element, 'position') === 'static' ? set(container.element, { position: 'relative '}) : false;
+ // while ($el && $el !== container.element && $el !== doc.body) {
+ // const isSticky = get($el, 'position') === 'sticky' ?
+ // set($el, { position: 'static' }) :
+ // false;
+ // if ($el === $offsetParent) {
+ // offsetX += $el.offsetLeft || 0;
+ // offsetY += $el.offsetTop || 0;
+ // $offsetParent = $el.offsetParent;
+ // }
+ // $el = /** @type {HTMLElement} */($el.parentElement);
+ // if (isSticky) {
+ // if (!stickys) stickys = [];
+ // stickys.push(isSticky);
+ // }
+ // }
+ // if (isContainerStatic) isContainerStatic.revert();
+ // const offset = isHori ? offsetX : offsetY;
+ // const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight;
+
+ while ($el && $el !== container.element && $el !== doc.body) {
+ const isSticky = get($el, 'position') === 'sticky' ? set($el, { position: 'static' }) : false;
+ $el = $el.parentElement;
+ if (isSticky) {
+ if (!stickys) stickys = [];
+ stickys.push(isSticky);
+ }
+ }
+ const rect = $target.getBoundingClientRect();
+ const offset = isHori ? rect.left + container.scrollX - container.left : rect.top + container.scrollY - container.top;
+ const targetSize = isHori ? rect.width : rect.height;
+ const containerSize = isHori ? container.width : container.height;
+ const scrollSize = isHori ? container.scrollWidth : container.scrollHeight;
+ const maxScroll = scrollSize - containerSize;
+ const enter = this.enter;
+ const leave = this.leave;
+
+ /** @type {ScrollThresholdValue} */
+ let enterTarget = 'start';
+ /** @type {ScrollThresholdValue} */
+ let leaveTarget = 'end';
+ /** @type {ScrollThresholdValue} */
+ let enterContainer = 'end';
+ /** @type {ScrollThresholdValue} */
+ let leaveContainer = 'start';
+
+ if (isStr(enter)) {
+ const splitted = /** @type {String} */(enter).split(' ');
+ enterContainer = splitted[0];
+ enterTarget = splitted.length > 1 ? splitted[1] : enterTarget;
+ } else if (isObj(enter)) {
+ const e = /** @type {ScrollThresholdParam} */(enter);
+ if (!isUnd(e.container)) enterContainer = e.container;
+ if (!isUnd(e.target)) enterTarget = e.target;
+ } else if (isNum(enter)) {
+ enterContainer = /** @type {Number} */(enter);
+ }
+
+ if (isStr(leave)) {
+ const splitted = /** @type {String} */(leave).split(' ');
+ leaveContainer = splitted[0];
+ leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget;
+ } else if (isObj(leave)) {
+ const t = /** @type {ScrollThresholdParam} */(leave);
+ if (!isUnd(t.container)) leaveContainer = t.container;
+ if (!isUnd(t.target)) leaveTarget = t.target;
+ } else if (isNum(leave)) {
+ leaveContainer = /** @type {Number} */(leave);
+ }
+
+ const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize);
+ const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize);
+ const under = (parsedEnterTarget + offset) - containerSize;
+ const over = (parsedLeaveTarget + offset) - maxScroll;
+ const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over);
+ const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over);
+ const offsetStart = parsedEnterTarget + offset - parsedEnterContainer;
+ const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer;
+ const scrollDelta = offsetEnd - offsetStart;
+ // this.offsets[0] = offsetX;
+ // this.offsets[1] = offsetY;
+ this.offset = offset;
+ this.offsetStart = offsetStart;
+ this.offsetEnd = offsetEnd;
+ this.distance = scrollDelta <= 0 ? 0 : scrollDelta;
+ this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer];
+ this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer];
+ if (stickys) {
+ stickys.forEach(sticky => sticky.revert());
+ }
+ if (linked) {
+ linked.seek(linkedTime, true);
+ }
+ if (this._debug) {
+ this.debug();
+ }
+ }
+
+ handleScroll() {
+ const linked = this.linked;
+ const sync = this.sync;
+ const syncEase = this.syncEase;
+ const syncSmooth = this.syncSmooth;
+ const shouldSeek = linked && (syncEase || syncSmooth);
+ const isHori = this.horizontal;
+ const container = this.container;
+ const scroll = this.scroll;
+ const isBefore = scroll <= this.offsetStart;
+ const isAfter = scroll >= this.offsetEnd;
+ const isInView = !isBefore && !isAfter;
+ const isOnTheEdge = scroll === this.offsetStart || scroll === this.offsetEnd;
+ const forceEnter = !this.hasEntered && isOnTheEdge;
+ const $debug = this._debug && this.$debug;
+ let hasUpdated = false;
+ let syncCompleted = false;
+ let p = this.progress;
+
+ if (isBefore && this.began) {
+ this.began = false;
+ }
+
+ if (p > 0 && !this.began) {
+ this.began = true;
+ }
+
+ if (shouldSeek) {
+ const lp = linked.progress;
+ if (syncSmooth && isNum(syncSmooth)) {
+ if (/** @type {Number} */(syncSmooth) < 1) {
+ const step = 0.0001;
+ const snap = lp < p && p === 1 ? step : lp > p && !p ? -step : 0;
+ p = round$1(lerp$1(lp, p, lerp$1(.01, .2, /** @type {Number} */(syncSmooth))) + snap, 6);
+ }
+ } else if (syncEase) {
+ p = syncEase(p);
+ }
+ hasUpdated = p !== this.prevProgress;
+ syncCompleted = lp === 1;
+ if (hasUpdated && !syncCompleted && (syncSmooth && lp)) {
+ container.wakeTicker.restart();
+ }
+ }
+
+ if ($debug) {
+ const sticky = isHori ? container.scrollY : container.scrollX;
+ $debug.style[isHori ? 'top' : 'left'] = sticky + 10 + 'px';
+ }
+
+ // Trigger enter callbacks if already in view or when entering the view
+ if ((isInView && !this.isInView) || (forceEnter && !this.forceEnter && !this.hasEntered)) {
+ if (isInView) this.isInView = true;
+ if (!this.forceEnter || !this.hasEntered) {
+ if ($debug && isInView) $debug.style.zIndex = `${this.container.zIndex++}`;
+ this.onSyncEnter(this);
+ this.onEnter(this);
+ if (this.backward) {
+ this.onSyncEnterBackward(this);
+ this.onEnterBackward(this);
+ } else {
+ this.onSyncEnterForward(this);
+ this.onEnterForward(this);
+ }
+ this.hasEntered = true;
+ if (forceEnter) this.forceEnter = true;
+ } else if (isInView) {
+ this.forceEnter = false;
+ }
+ }
+
+ if (isInView || !isInView && this.isInView) {
+ hasUpdated = true;
+ }
+
+ if (hasUpdated) {
+ if (shouldSeek) linked.seek(linked.duration * p);
+ this.onUpdate(this);
+ }
+
+ if (!isInView && this.isInView) {
+ this.isInView = false;
+ this.onSyncLeave(this);
+ this.onLeave(this);
+ if (this.backward) {
+ this.onSyncLeaveBackward(this);
+ this.onLeaveBackward(this);
+ } else {
+ this.onSyncLeaveForward(this);
+ this.onLeaveForward(this);
+ }
+ if (sync && !syncSmooth) {
+ syncCompleted = true;
+ }
+ }
+
+ if (p >= 1 && this.began && !this.completed && (sync && syncCompleted || !sync)) {
+ if (sync) {
+ this.onSyncComplete(this);
+ }
+ this.completed = true;
+ if ((!this.repeat && !linked) || (!this.repeat && linked && linked.completed)) {
+ this.revert();
+ }
+ }
+
+ if (p < 1 && this.completed) {
+ this.completed = false;
+ }
+
+ this.prevProgress = p;
+ }
+
+ revert() {
+ if (this.reverted) return;
+ const container = this.container;
+ removeChild(container, this);
+ if (!container._head) {
+ container.revert();
+ }
+ if (this._debug) {
+ this.removeDebug();
+ }
+ this.reverted = true;
+ return this;
+ }
+
+ }
+
+ /**
+ * @param {ScrollObserverParams} [parameters={}]
+ * @return {ScrollObserver}
+ */
+ const onScroll = (parameters = {}) => new ScrollObserver(parameters);
+
+ var index$3 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ cubicBezier: cubicBezier,
+ eases: eases,
+ irregular: irregular,
+ linear: linear,
+ none: none,
+ steps: steps
+ });
+
+ // Chain-able utilities
+
+ const numberUtils = numberImports; // Needed to keep the import when bundling
+
+ const chainables = {};
+
+ /**
+ * @callback UtilityFunction
+ * @param {...*} args
+ * @return {Number|String}
+ *
+ * @param {UtilityFunction} fn
+ * @param {Number} [last=0]
+ * @return {function(...(Number|String)): function(Number|String): (Number|String)}
+ */
+ const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args);
+
+ /**
+ * @param {Function} fn
+ * @return {function(...(Number|String))}
+ */
+ const chain = fn => {
+ return (...args) => {
+ const result = fn(...args);
+ return new Proxy(noop, {
+ apply: (_, __, [v]) => result(v),
+ get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => {
+ const nextResult = chainables[prop](...nextArgs);
+ return (/**@type {Number|String} */v) => nextResult(result(v));
+ })
+ });
+ }
+ };
+
+ /**
+ * @param {UtilityFunction} fn
+ * @param {String} name
+ * @param {Number} [right]
+ * @return {function(...(Number|String)): UtilityFunction}
+ */
+ const makeChainable = (name, fn, right = 0) => {
+ const chained = (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args);
+ if (!chainables[name]) chainables[name] = chained;
+ return chained;
+ };
+
+ /**
+ * @typedef {Object} ChainablesMap
+ * @property {ChainedClamp} clamp
+ * @property {ChainedRound} round
+ * @property {ChainedSnap} snap
+ * @property {ChainedWrap} wrap
+ * @property {ChainedLerp} lerp
+ * @property {ChainedDamp} damp
+ * @property {ChainedMapRange} mapRange
+ * @property {ChainedRoundPad} roundPad
+ * @property {ChainedPadStart} padStart
+ * @property {ChainedPadEnd} padEnd
+ * @property {ChainedDegToRad} degToRad
+ * @property {ChainedRadToDeg} radToDeg
+ */
+
+ /**
+ * @callback ChainedUtilsResult
+ * @param {Number} value - The value to process through the chained operations
+ * @return {Number} The processed result
+ */
+
+ /**
+ * @typedef {ChainablesMap & ChainedUtilsResult} ChainableUtil
+ */
+
+ // Chainable
+
+ /**
+ * @callback ChainedRoundPad
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+ const roundPad = /** @type {typeof numberUtils.roundPad & ChainedRoundPad} */(makeChainable('roundPad', numberUtils.roundPad));
+
+ /**
+ * @callback ChainedPadStart
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+ const padStart = /** @type {typeof numberUtils.padStart & ChainedPadStart} */(makeChainable('padStart', numberUtils.padStart));
+
+ /**
+ * @callback ChainedPadEnd
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+ const padEnd = /** @type {typeof numberUtils.padEnd & ChainedPadEnd} */(makeChainable('padEnd', numberUtils.padEnd));
+
+ /**
+ * @callback ChainedWrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+ const wrap = /** @type {typeof numberUtils.wrap & ChainedWrap} */(makeChainable('wrap', numberUtils.wrap));
+
+ /**
+ * @callback ChainedMapRange
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {ChainableUtil}
+ */
+ const mapRange = /** @type {typeof numberUtils.mapRange & ChainedMapRange} */(makeChainable('mapRange', numberUtils.mapRange));
+
+ /**
+ * @callback ChainedDegToRad
+ * @return {ChainableUtil}
+ */
+ const degToRad = /** @type {typeof numberUtils.degToRad & ChainedDegToRad} */(makeChainable('degToRad', numberUtils.degToRad));
+
+ /**
+ * @callback ChainedRadToDeg
+ * @return {ChainableUtil}
+ */
+ const radToDeg = /** @type {typeof numberUtils.radToDeg & ChainedRadToDeg} */(makeChainable('radToDeg', numberUtils.radToDeg));
+
+ /**
+ * @callback ChainedSnap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {ChainableUtil}
+ */
+ const snap = /** @type {typeof numberUtils.snap & ChainedSnap} */(makeChainable('snap', numberUtils.snap));
+
+ /**
+ * @callback ChainedClamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+ const clamp = /** @type {typeof numberUtils.clamp & ChainedClamp} */(makeChainable('clamp', numberUtils.clamp));
+
+ /**
+ * @callback ChainedRound
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+ const round = /** @type {typeof numberUtils.round & ChainedRound} */(makeChainable('round', numberUtils.round));
+
+ /**
+ * @callback ChainedLerp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @return {ChainableUtil}
+ */
+ const lerp = /** @type {typeof numberUtils.lerp & ChainedLerp} */(makeChainable('lerp', numberUtils.lerp, 1));
+
+ /**
+ * @callback ChainedDamp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @return {ChainableUtil}
+ */
+ const damp = /** @type {typeof numberUtils.damp & ChainedDamp} */(makeChainable('damp', numberUtils.damp, 1));
+
+ /**
+ * Generate a random number between optional min and max (inclusive) and decimal precision
+ *
+ * @callback RandomNumberGenerator
+ * @param {Number} [min=0] - The minimum value (inclusive)
+ * @param {Number} [max=1] - The maximum value (inclusive)
+ * @param {Number} [decimalLength=0] - Number of decimal places to round to
+ * @return {Number} A random number between min and max
+ */
+
+ /**
+ * Generates a random number between min and max (inclusive) with optional decimal precision
+ *
+ * @type {RandomNumberGenerator}
+ */
+ const random = (min = 0, max = 1, decimalLength = 0) => {
+ const m = 10 ** decimalLength;
+ return Math.floor((Math.random() * (max - min + (1 / m)) + min) * m) / m;
+ };
+
+ let _seed = 0;
+
+ /**
+ * Creates a seeded pseudorandom number generator function
+ *
+ * @param {Number} [seed] - The seed value for the random number generator
+ * @param {Number} [seededMin=0] - The minimum default value (inclusive) of the returned function
+ * @param {Number} [seededMax=1] - The maximum default value (inclusive) of the returned function
+ * @param {Number} [seededDecimalLength=0] - Default number of decimal places to round to of the returned function
+ * @return {RandomNumberGenerator} A function to generate a random number between optional min and max (inclusive) and decimal precision
+ */
+ const createSeededRandom = (seed, seededMin = 0, seededMax = 1, seededDecimalLength = 0) => {
+ let t = seed === undefined ? _seed++ : seed;
+ return (min = seededMin, max = seededMax, decimalLength = seededDecimalLength) => {
+ t += 0x6D2B79F5;
+ t = Math.imul(t ^ t >>> 15, t | 1);
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
+ const m = 10 ** decimalLength;
+ return Math.floor(((((t ^ t >>> 14) >>> 0) / 4294967296) * (max - min + (1 / m)) + min) * m) / m;
+ }
+ };
+
+ /**
+ * Picks a random element from an array or a string
+ *
+ * @template T
+ * @param {String|Array<T>} items - The array or string to pick from
+ * @return {String|T} A random element from the array or character from the string
+ */
+ const randomPick = items => items[random(0, items.length - 1)];
+
+ /**
+ * Shuffles an array in-place using the Fisher-Yates algorithm
+ * Adapted from https://bost.ocks.org/mike/shuffle/
+ *
+ * @param {Array} items - The array to shuffle (will be modified in-place)
+ * @return {Array} The same array reference, now shuffled
+ */
+ const shuffle = items => {
+ let m = items.length, t, i;
+ while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; }
+ return items;
+ };
+
+
+
+
+
+ /**
+ * @overload
+ * @param {Number} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+ /**
+ * @overload
+ * @param {String} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+ /**
+ * @overload
+ * @param {[Number, Number]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+ /**
+ * @overload
+ * @param {[String, String]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+ /**
+ * @param {Number|String|[Number, Number]|[String, String]} val The staggered value or range
+ * @param {StaggerParams} [params] The stagger parameters
+ * @return {StaggerFunction<Number|String>}
+ */
+ const stagger = (val, params = {}) => {
+ let values = [];
+ let maxValue = 0;
+ const from = params.from;
+ const reversed = params.reversed;
+ const ease = params.ease;
+ const hasEasing = !isUnd(ease);
+ const hasSpring = hasEasing && !isUnd(/** @type {Spring} */(ease).ease);
+ const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEase(ease) : null;
+ const grid = params.grid;
+ const axis = params.axis;
+ const customTotal = params.total;
+ const fromFirst = isUnd(from) || from === 0 || from === 'first';
+ const fromCenter = from === 'center';
+ const fromLast = from === 'last';
+ const fromRandom = from === 'random';
+ const isRange = isArr(val);
+ const useProp = params.use;
+ const val1 = isRange ? parseNumber(val[0]) : parseNumber(val);
+ const val2 = isRange ? parseNumber(val[1]) : 0;
+ const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString);
+ const start = params.start || 0 + (isRange ? val1 : 0);
+ let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0;
+ return (target, i, t, tl) => {
+ const [ registeredTarget ] = registerTargets(target);
+ const total = isUnd(customTotal) ? t : customTotal;
+ const customIndex = !isUnd(useProp) ? isFnc(useProp) ? useProp(registeredTarget, i, total) : getOriginalAnimatableValue(registeredTarget, useProp) : false;
+ const staggerIndex = isNum(customIndex) || isStr(customIndex) && isNum(+customIndex) ? +customIndex : i;
+ if (fromCenter) fromIndex = (total - 1) / 2;
+ if (fromLast) fromIndex = total - 1;
+ if (!values.length) {
+ for (let index = 0; index < total; index++) {
+ if (!grid) {
+ values.push(abs(fromIndex - index));
+ } else {
+ const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2;
+ const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2;
+ const toX = index % grid[0];
+ const toY = floor(index / grid[0]);
+ const distanceX = fromX - toX;
+ const distanceY = fromY - toY;
+ let value = sqrt(distanceX * distanceX + distanceY * distanceY);
+ if (axis === 'x') value = -distanceX;
+ if (axis === 'y') value = -distanceY;
+ values.push(value);
+ }
+ maxValue = max(...values);
+ }
+ if (staggerEase) values = values.map(val => staggerEase(val / maxValue) * maxValue);
+ if (reversed) values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val));
+ if (fromRandom) values = shuffle(values);
+ }
+ const spacing = isRange ? (val2 - val1) / maxValue : val1;
+ const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl.iterationDuration : start) : /** @type {Number} */(start);
+ /** @type {String|Number} */
+ let output = offset + ((spacing * round$1(values[staggerIndex], 2)) || 0);
+ if (params.modifier) output = params.modifier(output);
+ if (unitMatch) output = `${output}${unitMatch[2]}`;
+ return output;
+ }
+ };
+
+ var index$2 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ $: registerTargets,
+ clamp: clamp,
+ cleanInlineStyles: cleanInlineStyles,
+ createSeededRandom: createSeededRandom,
+ damp: damp,
+ degToRad: degToRad,
+ get: get,
+ keepTime: keepTime,
+ lerp: lerp,
+ mapRange: mapRange,
+ padEnd: padEnd,
+ padStart: padStart,
+ radToDeg: radToDeg,
+ random: random,
+ randomPick: randomPick,
+ remove: remove,
+ round: round,
+ roundPad: roundPad,
+ set: set,
+ shuffle: shuffle,
+ snap: snap,
+ stagger: stagger,
+ sync: sync,
+ wrap: wrap
+ });
+
+
+
+ /**
+ * @param {TargetsParam} path
+ * @return {SVGGeometryElement|void}
+ */
+ const getPath = path => {
+ const parsedTargets = parseTargets(path);
+ const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
+ if (!$parsedSvg || !isSvg($parsedSvg)) return console.warn(`${path} is not a valid SVGGeometryElement`);
+ return $parsedSvg;
+ };
+
+
+
+ // Motion path animation
+
+ /**
+ * @param {SVGGeometryElement} $path
+ * @param {Number} progress
+ * @param {Number}lookup
+ * @return {DOMPoint}
+ */
+ const getPathPoint = ($path, progress, lookup = 0) => {
+ return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0);
+ };
+
+ /**
+ * @param {SVGGeometryElement} $path
+ * @param {String} pathProperty
+ * @return {FunctionValue}
+ */
+ const getPathProgess = ($path, pathProperty) => {
+ return $el => {
+ const totalLength = +($path.getTotalLength());
+ const inSvg = $el[isSvgSymbol];
+ const ctm = $path.getCTM();
+ /** @type {TweenObjectValue} */
+ return {
+ from: 0,
+ to: totalLength,
+ /** @type {TweenModifier} */
+ modifier: progress => {
+ if (pathProperty === 'a') {
+ const p0 = getPathPoint($path, progress, -1);
+ const p1 = getPathPoint($path, progress, 1);
+ return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI;
+ } else {
+ const p = getPathPoint($path, progress, 0);
+ return pathProperty === 'x' ?
+ inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
+ inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
+ }
+ }
+ }
+ }
+ };
+
+ /**
+ * @param {TargetsParam} path
+ */
+ const createMotionPath = path => {
+ const $path = getPath(path);
+ if (!$path) return;
+ return {
+ translateX: getPathProgess($path, 'x'),
+ translateY: getPathProgess($path, 'y'),
+ rotate: getPathProgess($path, 'a'),
+ }
+ };
+
+
+
+ /**
+ * @param {SVGGeometryElement} [$el]
+ * @return {Number}
+ */
+ const getScaleFactor = $el => {
+ let scaleFactor = 1;
+ if ($el && $el.getCTM) {
+ const ctm = $el.getCTM();
+ if (ctm) {
+ const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
+ const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
+ scaleFactor = (scaleX + scaleY) / 2;
+ }
+ }
+ return scaleFactor;
+ };
+
+ /**
+ * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
+ * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
+ * @param {number} start - Starting position (0-1)
+ * @param {number} end - Ending position (0-1)
+ * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
+ */
+ const createDrawableProxy = ($el, start, end) => {
+ const pathLength = K;
+ const computedStyles = getComputedStyle($el);
+ const strokeLineCap = computedStyles.strokeLinecap;
+ // @ts-ignore
+ const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
+ let currentCap = strokeLineCap;
+
+ const proxy = new Proxy($el, {
+ get(target, property) {
+ const value = target[property];
+ if (property === proxyTargetSymbol) return target;
+ if (property === 'setAttribute') {
+ return (...args) => {
+ if (args[0] === 'draw') {
+ const value = args[1];
+ const values = value.split(' ');
+ const v1 = +values[0];
+ const v2 = +values[1];
+ // TOTO: Benchmark if performing two slices is more performant than one split
+ // const spaceIndex = value.indexOf(' ');
+ // const v1 = round(+value.slice(0, spaceIndex), precision);
+ // const v2 = round(+value.slice(spaceIndex + 1), precision);
+ const scaleFactor = getScaleFactor($scalled);
+ const os = v1 * -pathLength * scaleFactor;
+ const d1 = (v2 * pathLength * scaleFactor) + os;
+ const d2 = (pathLength * scaleFactor +
+ ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
+ if (strokeLineCap !== 'butt') {
+ const newCap = v1 === v2 ? 'butt' : strokeLineCap;
+ if (currentCap !== newCap) {
+ target.style.strokeLinecap = `${newCap}`;
+ currentCap = newCap;
+ }
+ }
+ target.setAttribute('stroke-dashoffset', `${os}`);
+ target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
+ }
+ return Reflect.apply(value, target, args);
+ };
+ }
+
+ if (isFnc(value)) {
+ return (...args) => Reflect.apply(value, target, args);
+ } else {
+ return value;
+ }
+ }
+ });
+
+ if ($el.getAttribute('pathLength') !== `${pathLength}`) {
+ $el.setAttribute('pathLength', `${pathLength}`);
+ proxy.setAttribute('draw', `${start} ${end}`);
+ }
+
+ return /** @type {DrawableSVGGeometry} */(proxy);
+ };
+
+ /**
+ * Creates drawable proxies for multiple SVG elements.
+ * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
+ * @param {number} [start=0] - Starting position (0-1)
+ * @param {number} [end=0] - Ending position (0-1)
+ * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
+ */
+ const createDrawable = (selector, start = 0, end = 0) => {
+ const els = parseTargets(selector);
+ return els.map($el => createDrawableProxy(
+ /** @type {SVGGeometryElement} */($el),
+ start,
+ end
+ ));
+ };
+
+
+
+ /**
+ * @param {TargetsParam} path2
+ * @param {Number} [precision]
+ * @return {FunctionValue}
+ */
+ const morphTo = (path2, precision = .33) => ($path1) => {
+ const $path2 = /** @type {SVGGeometryElement} */(getPath(path2));
+ if (!$path2) return;
+ const isPath = $path1.tagName === 'path';
+ const separator = isPath ? ' ' : ',';
+ const previousPoints = $path1[morphPointsSymbol];
+ if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
+
+ let v1 = '', v2 = '';
+
+ if (!precision) {
+ v1 = $path1.getAttribute(isPath ? 'd' : 'points');
+ v2 = $path2.getAttribute(isPath ? 'd' : 'points');
+ } else {
+ const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
+ const length2 = $path2.getTotalLength();
+ const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
+ for (let i = 0; i < maxPoints; i++) {
+ const t = i / (maxPoints - 1);
+ const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
+ const pointOnPath2 = $path2.getPointAtLength(length2 * t);
+ const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
+ v1 += prefix + round$1(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
+ v2 += prefix + round$1(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
+ }
+ }
+
+ $path1[morphPointsSymbol] = v2;
+
+ return [v1, v2];
+ };
+
+ var index$1 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ createDrawable: createDrawable,
+ createMotionPath: createMotionPath,
+ morphTo: morphTo
+ });
+
+
+
+ const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter;
+ const valueRgx = /\{value\}/g;
+ const indexRgx = /\{i\}/g;
+ const whiteSpaceGroupRgx = /(\s+)/;
+ const whiteSpaceRgx = /^\s+$/;
+ const lineType = 'line';
+ const wordType = 'word';
+ const charType = 'char';
+ const dataLine = `data-line`;
+
+ /**
+ * @typedef {Object} Segment
+ * @property {String} segment
+ * @property {Boolean} [isWordLike]
+ */
+
+ /**
+ * @typedef {Object} Segmenter
+ * @property {function(String): Iterable<Segment>} segment
+ */
+
+ /** @type {Segmenter} */
+ let wordSegmenter = null;
+ /** @type {Segmenter} */
+ let graphemeSegmenter = null;
+ let $splitTemplate = null;
+
+ /**
+ * @param {Segment} seg
+ * @return {Boolean}
+ */
+ const isSegmentWordLike = seg => {
+ return seg.isWordLike ||
+ seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later
+ isNum(+seg.segment); // Safari doesn't considers numbers as words
+ };
+
+ /**
+ * @param {HTMLElement} $el
+ */
+ const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true');
+
+ /**
+ * @param {DOMTarget} $el
+ * @param {String} type
+ * @return {Array<HTMLElement>}
+ */
+ const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))];
+
+ const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' };
+
+ /**
+ * @param {HTMLElement} $el
+ */
+ const filterEmptyElements = $el => {
+ if (!$el.childElementCount && !$el.textContent.trim()) {
+ const $parent = $el.parentElement;
+ $el.remove();
+ if ($parent) filterEmptyElements($parent);
+ }
+ };
+
+ /**
+ * @param {HTMLElement} $el
+ * @param {Number} lineIndex
+ * @param {Set<HTMLElement>} bin
+ * @returns {Set<HTMLElement>}
+ */
+ const filterLineElements = ($el, lineIndex, bin) => {
+ const dataLineAttr = $el.getAttribute(dataLine);
+ if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') bin.add($el);
+ let i = $el.childElementCount;
+ while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin);
+ return bin;
+ };
+
+ /**
+ * @param {'line'|'word'|'char'} type
+ * @param {SplitTemplateParams} params
+ * @return {String}
+ */
+ const generateTemplate = (type, params = {}) => {
+ let template = ``;
+ const classString = isStr(params.class) ? ` class="${params.class}"` : '';
+ const cloneType = setValue(params.clone, false);
+ const wrapType = setValue(params.wrap, false);
+ const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false;
+ if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`;
+ template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`;
+ if (cloneType) {
+ const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0';
+ const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0';
+ template += `<span>{value}</span>`;
+ template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`;
+ } else {
+ template += `{value}`;
+ }
+ template += `</span>`;
+ if (wrapType) template += `</span>`;
+ return template;
+ };
+
+ /**
+ * @param {String|SplitFunctionValue} htmlTemplate
+ * @param {Array<HTMLElement>} store
+ * @param {Node|HTMLElement} node
+ * @param {DocumentFragment} $parentFragment
+ * @param {'line'|'word'|'char'} type
+ * @param {Boolean} debug
+ * @param {Number} lineIndex
+ * @param {Number} [wordIndex]
+ * @param {Number} [charIndex]
+ * @return {HTMLElement}
+ */
+ const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => {
+ const isLine = type === lineType;
+ const isChar = type === charType;
+ const className = `_${type}_`;
+ const template = isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate;
+ const displayStyle = isLine ? 'block' : 'inline-block';
+ $splitTemplate.innerHTML = template
+ .replace(valueRgx, `<i class="${className}"></i>`)
+ .replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`);
+ const $content = $splitTemplate.content;
+ const $highestParent = /** @type {HTMLElement} */($content.firstElementChild);
+ const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent;
+ const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`));
+ const replacablesLength = $replacables.length;
+ if (replacablesLength) {
+ $highestParent.style.display = displayStyle;
+ $split.style.display = displayStyle;
+ $split.setAttribute(dataLine, `${lineIndex}`);
+ if (!isLine) {
+ $split.setAttribute('data-word', `${wordIndex}`);
+ if (isChar) $split.setAttribute('data-char', `${charIndex}`);
+ }
+ let i = replacablesLength;
+ while (i--) {
+ const $replace = $replacables[i];
+ const $closestParent = $replace.parentElement;
+ $closestParent.style.display = displayStyle;
+ if (isLine) {
+ $closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML;
+ } else {
+ $closestParent.replaceChild(node.cloneNode(true), $replace);
+ }
+ }
+ store.push($split);
+ $parentFragment.appendChild($content);
+ } else {
+ console.warn(`The expression "{value}" is missing from the provided template.`);
+ }
+ if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`;
+ return $highestParent;
+ };
+
+ /**
+ * A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
+ * @class
+ */
+ class TextSplitter {
+ /**
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ */
+ constructor(target, parameters = {}) {
+ // Only init segmenters when needed
+ if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : {
+ segment: (text) => {
+ const segments = [];
+ const words = text.split(whiteSpaceGroupRgx);
+ for (let i = 0, l = words.length; i < l; i++) {
+ const segment = words[i];
+ segments.push({
+ segment,
+ isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like
+ });
+ }
+ return segments;
+ }
+ };
+ if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : {
+ segment: text => [...text].map(char => ({ segment: char }))
+ };
+ if (!$splitTemplate && isBrowser) $splitTemplate = doc.createElement('template');
+ if (scope.current) scope.current.register(this);
+ const { words, chars, lines, accessible, includeSpaces, debug } = parameters;
+ const $target = /** @type {HTMLElement} */((target = isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (getNodeList(target) || [])[0]);
+ const lineParams = lines === true ? {} : lines;
+ const wordParams = words === true || isUnd(words) ? {} : words;
+ const charParams = chars === true ? {} : chars;
+ this.debug = setValue(debug, false);
+ this.includeSpaces = setValue(includeSpaces, false);
+ this.accessible = setValue(accessible, true);
+ this.linesOnly = lineParams && (!wordParams && !charParams);
+ /** @type {String|false|SplitFunctionValue} */
+ this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams;
+ /** @type {String|false|SplitFunctionValue} */
+ this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams;
+ /** @type {String|false|SplitFunctionValue} */
+ this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams;
+ this.$target = $target;
+ this.html = $target && $target.innerHTML;
+ this.lines = [];
+ this.words = [];
+ this.chars = [];
+ this.effects = [];
+ this.effectsCleanups = [];
+ this.cache = null;
+ this.ready = false;
+ this.width = 0;
+ this.resizeTimeout = null;
+ const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split();
+ // Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback
+ this.resizeObserver = new ResizeObserver(() => {
+ // Use a setTimeout instead of a Timer for better tree shaking
+ clearTimeout(this.resizeTimeout);
+ this.resizeTimeout = setTimeout(() => {
+ const currentWidth = /** @type {HTMLElement} */($target).offsetWidth;
+ if (currentWidth === this.width) return;
+ this.width = currentWidth;
+ handleSplit();
+ }, 150);
+ });
+ // Only declare the font ready promise when splitting by lines and not alreay split
+ if (this.lineTemplate && !this.ready) {
+ doc.fonts.ready.then(handleSplit);
+ } else {
+ handleSplit();
+ }
+ $target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.');
+ }
+
+ /**
+ * @param {(...args: any[]) => Tickable | (() => void)} effect
+ * @return this
+ */
+ addEffect(effect) {
+ if (!isFnc(effect)) return console.warn('Effect must return a function.');
+ const refreshableEffect = keepTime(effect);
+ this.effects.push(refreshableEffect);
+ if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this);
+ return this;
+ }
+
+ revert() {
+ clearTimeout(this.resizeTimeout);
+ this.lines.length = this.words.length = this.chars.length = 0;
+ this.resizeObserver.disconnect();
+ // Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process
+ this.effectsCleanups.forEach(cleanup => isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert());
+ this.$target.innerHTML = this.html;
+ return this;
+ }
+
+ /**
+ * Recursively processes a node and its children
+ * @param {Node} node
+ */
+ splitNode(node) {
+ const wordTemplate = this.wordTemplate;
+ const charTemplate = this.charTemplate;
+ const includeSpaces = this.includeSpaces;
+ const debug = this.debug;
+ const nodeType = node.nodeType;
+ if (nodeType === 3) {
+ const nodeText = node.nodeValue;
+ // If the nodeText is only whitespace, leave it as is
+ if (nodeText.trim()) {
+ const tempWords = [];
+ const words = this.words;
+ const chars = this.chars;
+ const wordSegments = wordSegmenter.segment(nodeText);
+ const $wordsFragment = doc.createDocumentFragment();
+ let prevSeg = null;
+ for (const wordSegment of wordSegments) {
+ const segment = wordSegment.segment;
+ const isWordLike = isSegmentWordLike(wordSegment);
+ // Determine if this segment should be a new word, first segment always becomes a new word
+ if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) {
+ tempWords.push(segment);
+ } else {
+ // Only concatenate if both current and previous are non-word-like and don't contain spaces
+ const lastWordIndex = tempWords.length - 1;
+ const lastWord = tempWords[lastWordIndex];
+ if (!lastWord.includes(' ') && !segment.includes(' ')) {
+ tempWords[lastWordIndex] += segment;
+ } else {
+ tempWords.push(segment);
+ }
+ }
+ prevSeg = wordSegment;
+ }
+
+ for (let i = 0, l = tempWords.length; i < l; i++) {
+ const word = tempWords[i];
+ if (!word.trim()) {
+ // Preserve whitespace only if includeSpaces is false and if the current space is not the first node
+ if (i && includeSpaces) continue;
+ $wordsFragment.appendChild(doc.createTextNode(word));
+ } else {
+ const nextWord = tempWords[i + 1];
+ const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim();
+ const wordToProcess = word;
+ const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null;
+ const $charsFragment = charTemplate ? doc.createDocumentFragment() : doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word);
+ if (charTemplate) {
+ const charSegmentsArray = [...charSegments];
+ for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) {
+ const charSegment = charSegmentsArray[j];
+ const isLastChar = j === jl - 1;
+ // If this is the last character and includeSpaces is true with a following space, append the space
+ const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment;
+ const $charNode = doc.createTextNode(charText);
+ processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length);
+ }
+ }
+ if (wordTemplate) {
+ processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length);
+ // Chars elements must be re-parsed in the split() method if both words and chars are parsed
+ } else if (charTemplate) {
+ $wordsFragment.appendChild($charsFragment);
+ } else {
+ $wordsFragment.appendChild(doc.createTextNode(word));
+ }
+ // Skip the next iteration if we included a space
+ if (hasWordFollowingSpace) i++;
+ }
+ }
+ node.parentNode.replaceChild($wordsFragment, node);
+ }
+ } else if (nodeType === 1) {
+ // Converting to an array is necessary to work around childNodes pottential mutation
+ const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]);
+ for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]);
+ }
+ }
+
+ /**
+ * @param {Boolean} clearCache
+ * @return {this}
+ */
+ split(clearCache = false) {
+ const $el = this.$target;
+ const isCached = !!this.cache && !clearCache;
+ const lineTemplate = this.lineTemplate;
+ const wordTemplate = this.wordTemplate;
+ const charTemplate = this.charTemplate;
+ const fontsReady = doc.fonts.status !== 'loading';
+ const canSplitLines = lineTemplate && fontsReady;
+ this.ready = !lineTemplate || fontsReady;
+ if (canSplitLines || clearCache) {
+ // No need to revert effects animations here since it's already taken care by the refreshable
+ this.effectsCleanups.forEach(cleanup => isFnc(cleanup) && cleanup(this));
+ }
+ if (!isCached) {
+ if (clearCache) {
+ $el.innerHTML = this.html;
+ this.words.length = this.chars.length = 0;
+ }
+ this.splitNode($el);
+ this.cache = $el.innerHTML;
+ }
+ if (canSplitLines) {
+ if (isCached) $el.innerHTML = this.cache;
+ this.lines.length = 0;
+ if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
+ }
+ // Always reparse characters after a line reset or if both words and chars are activated
+ if (charTemplate && (canSplitLines || wordTemplate)) {
+ this.chars = getAllTopLevelElements($el, charType);
+ }
+ // Words are used when lines only and prioritized over chars
+ const elementsArray = this.words.length ? this.words : this.chars;
+ let y, linesCount = 0;
+ for (let i = 0, l = elementsArray.length; i < l; i++) {
+ const $el = elementsArray[i];
+ const { top, height } = $el.getBoundingClientRect();
+ if (y && top - y > height * .5) linesCount++;
+ $el.setAttribute(dataLine, `${linesCount}`);
+ const nested = $el.querySelectorAll(`[${dataLine}]`);
+ let c = nested.length;
+ while (c--) nested[c].setAttribute(dataLine, `${linesCount}`);
+ y = top;
+ }
+ if (canSplitLines) {
+ const linesFragment = doc.createDocumentFragment();
+ const parents = new Set();
+ const clones = [];
+ for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) {
+ const $clone = /** @type {HTMLElement} */($el.cloneNode(true));
+ filterLineElements($clone, lineIndex, new Set()).forEach($el => {
+ const $parent = $el.parentElement;
+ if ($parent) parents.add($parent);
+ $el.remove();
+ });
+ clones.push($clone);
+ }
+ parents.forEach(filterEmptyElements);
+ for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) {
+ processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex);
+ }
+ $el.innerHTML = '';
+ $el.appendChild(linesFragment);
+ if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
+ if (charTemplate) this.chars = getAllTopLevelElements($el, charType);
+ }
+ // Remove the word wrappers and clear the words array if lines split only
+ if (this.linesOnly) {
+ const words = this.words;
+ let w = words.length;
+ while (w--) {
+ const $word = words[w];
+ $word.replaceWith($word.textContent);
+ }
+ words.length = 0;
+ }
+ if (this.accessible && (canSplitLines || !isCached)) {
+ const $accessible = doc.createElement('span');
+ // Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html)
+ $accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;
+ // $accessible.setAttribute('tabindex', '-1');
+ $accessible.innerHTML = this.html;
+ $el.insertBefore($accessible, $el.firstChild);
+ this.lines.forEach(setAriaHidden);
+ this.words.forEach(setAriaHidden);
+ this.chars.forEach(setAriaHidden);
+ }
+ this.width = /** @type {HTMLElement} */($el).offsetWidth;
+ if (canSplitLines || clearCache) {
+ this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this));
+ }
+ return this;
+ }
+
+ refresh() {
+ this.split(true);
+ }
+ }
+
+ /**
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
+ */
+ const splitText = (target, parameters) => new TextSplitter(target, parameters);
+
+ /**
+ * @deprecated text.split() is deprecated, import splitText() directly, or text.splitText()
+ *
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
+ */
+ const split = (target, parameters) => {
+ console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()');
+ return new TextSplitter(target, parameters);
+ };
+
+ var index = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ TextSplitter: TextSplitter,
+ split: split,
+ splitText: splitText
+ });
+
+
+
+
+
+
+
+ /**
+ * Converts an easing function into a valid CSS linear() timing function string
+ * @param {EasingFunction} fn
+ * @param {number} [samples=100]
+ * @returns {string} CSS linear() timing function
+ */
+ const easingToLinear = (fn, samples = 100) => {
+ const points = [];
+ for (let i = 0; i <= samples; i++) points.push(fn(i / samples));
+ return `linear(${points.join(', ')})`;
+ };
+
+ const WAAPIEasesLookups = {
+ in: 'ease-in',
+ out: 'ease-out',
+ inOut: 'ease-in-out',
+ };
+
+ const WAAPIeases = /*#__PURE__*/(() => {
+ const list = {};
+ for (let type in easeTypes) list[type] = (/** @type {String|Number} */p) => easeTypes[type](easeInPower(p));
+ return /** @type {Record<String, EasingFunction>} */(list);
+ })();
+
+ /**
+ * @param {EasingParam} ease
+ * @return {String}
+ */
+ const parseWAAPIEasing = (ease) => {
+ let parsedEase = WAAPIEasesLookups[ease];
+ if (parsedEase) return parsedEase;
+ parsedEase = 'linear';
+ if (isStr(ease)) {
+ if (
+ stringStartsWith(ease, 'linear') ||
+ stringStartsWith(ease, 'cubic-') ||
+ stringStartsWith(ease, 'steps') ||
+ stringStartsWith(ease, 'ease')
+ ) {
+ parsedEase = ease;
+ } else if (stringStartsWith(ease, 'cubicB')) {
+ parsedEase = toLowerCase(ease);
+ } else {
+ const parsed = parseEaseString(ease, WAAPIeases, WAAPIEasesLookups);
+ if (isFnc(parsed)) parsedEase = parsed === none ? 'linear' : easingToLinear(parsed);
+ }
+ WAAPIEasesLookups[ease] = parsedEase;
+ } else if (isFnc(ease)) {
+ const easing = easingToLinear(ease);
+ if (easing) parsedEase = easing;
+ } else if (/** @type {Spring} */(ease).ease) {
+ parsedEase = easingToLinear(/** @type {Spring} */(ease).ease);
+ }
+ return parsedEase;
+ };
+
+ const transformsShorthands = ['x', 'y', 'z'];
+ const commonDefaultPXProperties = [
+ 'perspective',
+ 'width',
+ 'height',
+ 'margin',
+ 'padding',
+ 'top',
+ 'right',
+ 'bottom',
+ 'left',
+ 'borderWidth',
+ 'fontSize',
+ 'borderRadius',
+ ...transformsShorthands
+ ];
+
+ const validIndividualTransforms = /*#__PURE__*/ (() => [...transformsShorthands, ...validTransforms.filter(t => ['X', 'Y', 'Z'].some(axis => t.endsWith(axis)))])();
+
+ let transformsPropertiesRegistered = null;
+
+ /**
+ * @param {String} propName
+ * @param {WAAPIKeyframeValue} value
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ * @param {Number} targetsLength
+ * @return {String}
+ */
+ const normalizeTweenValue = (propName, value, $el, i, targetsLength) => {
+ let v = getFunctionValue(/** @type {any} */(value), $el, i, targetsLength);
+ if (!isNum(v)) return v;
+ if (commonDefaultPXProperties.includes(propName) || stringStartsWith(propName, 'translate')) return `${v}px`;
+ if (stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew')) return `${v}deg`;
+ return `${v}`;
+ };
+
+ /**
+ * @param {DOMTarget} $el
+ * @param {String} propName
+ * @param {WAAPIKeyframeValue} from
+ * @param {WAAPIKeyframeValue} to
+ * @param {Number} i
+ * @param {Number} targetsLength
+ * @return {WAAPITweenValue}
+ */
+ const parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => {
+ /** @type {WAAPITweenValue} */
+ let tweenValue = '0';
+ const computedTo = !isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName];
+ if (!isUnd(from)) {
+ const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength);
+ tweenValue = [computedFrom, computedTo];
+ } else {
+ tweenValue = isArr(to) ? to.map((/** @type {any} */v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo;
+ }
+ return tweenValue;
+ };
+
+ class WAAPIAnimation {
+ /**
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
+ */
+ constructor(targets, params) {
+
+ if (scope.current) scope.current.register(this);
+
+ // Skip the registration and fallback to no animation in case CSS.registerProperty is not supported
+ if (isNil(transformsPropertiesRegistered)) {
+ if (isBrowser && (isUnd(CSS) || !Object.hasOwnProperty.call(CSS, 'registerProperty'))) {
+ transformsPropertiesRegistered = false;
+ } else {
+ validTransforms.forEach(t => {
+ const isSkew = stringStartsWith(t, 'skew');
+ const isScale = stringStartsWith(t, 'scale');
+ const isRotate = stringStartsWith(t, 'rotate');
+ const isTranslate = stringStartsWith(t, 'translate');
+ const isAngle = isRotate || isSkew;
+ const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*";
+ try {
+ CSS.registerProperty({
+ name: '--' + t,
+ syntax,
+ inherits: false,
+ initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0',
+ });
+ } catch {} });
+ transformsPropertiesRegistered = true;
+ }
+ }
+
+ const parsedTargets = registerTargets(targets);
+ const targetsLength = parsedTargets.length;
+
+ if (!targetsLength) {
+ console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
+ }
+
+ const ease = setValue(params.ease, parseWAAPIEasing(globals.defaults.ease));
+ const spring = /** @type {Spring} */(ease).ease && ease;
+ const autoplay = setValue(params.autoplay, globals.defaults.autoplay);
+ const scroll = autoplay && /** @type {ScrollObserver} */(autoplay).link ? autoplay : false;
+ const alternate = params.alternate && /** @type {Boolean} */(params.alternate) === true;
+ const reversed = params.reversed && /** @type {Boolean} */(params.reversed) === true;
+ const loop = setValue(params.loop, globals.defaults.loop);
+ const iterations = /** @type {Number} */((loop === true || loop === Infinity) ? Infinity : isNum(loop) ? loop + 1 : 1);
+ /** @type {PlaybackDirection} */
+ const direction = alternate ? reversed ? 'alternate-reverse' : 'alternate' : reversed ? 'reverse' : 'normal';
+ /** @type {FillMode} */
+ const fill = 'forwards';
+ /** @type {String} */
+ const easing = parseWAAPIEasing(ease);
+ const timeScale = (globals.timeScale === 1 ? 1 : K);
+
+ /** @type {DOMTargetsArray}] */
+ this.targets = parsedTargets;
+ /** @type {Array<globalThis.Animation>}] */
+ this.animations = [];
+ /** @type {globalThis.Animation}] */
+ this.controlAnimation = null;
+ /** @type {Callback<this>} */
+ this.onComplete = params.onComplete || noop;
+ /** @type {Number} */
+ this.duration = 0;
+ /** @type {Boolean} */
+ this.muteCallbacks = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Boolean} */
+ this.paused = !autoplay || scroll !== false;
+ /** @type {Boolean} */
+ this.reversed = reversed;
+ /** @type {Boolean|ScrollObserver} */
+ this.autoplay = autoplay;
+ /** @type {Number} */
+ this._speed = setValue(params.playbackRate, globals.defaults.playbackRate);
+ /** @type {Function} */
+ this._resolve = noop; // Used by .then()
+ /** @type {Number} */
+ this._completed = 0;
+ /** @type {Array<Object>}] */
+ this._inlineStyles = parsedTargets.map($el => $el.getAttribute('style'));
+
+ parsedTargets.forEach(($el, i) => {
+
+ const cachedTransforms = $el[transformsSymbol];
+
+ const hasIndividualTransforms = validIndividualTransforms.some(t => params.hasOwnProperty(t));
+
+ /** @type {Number} */
+ const duration = (spring ? /** @type {Spring} */(spring).duration : getFunctionValue(setValue(params.duration, globals.defaults.duration), $el, i, targetsLength)) * timeScale;
+ /** @type {Number} */
+ const delay = getFunctionValue(setValue(params.delay, globals.defaults.delay), $el, i, targetsLength) * timeScale;
+ /** @type {CompositeOperation} */
+ const composite = /** @type {CompositeOperation} */(setValue(params.composition, 'replace'));
+
+ for (let name in params) {
+ if (!isKey(name)) continue;
+ /** @type {PropertyIndexedKeyframes} */
+ const keyframes = {};
+ /** @type {KeyframeAnimationOptions} */
+ const tweenParams = { iterations, direction, fill, easing, duration, delay, composite };
+ const propertyValue = params[name];
+ const individualTransformProperty = hasIndividualTransforms ? validTransforms.includes(name) ? name : shortTransforms.get(name) : false;
+ let parsedPropertyValue;
+ if (isObj(propertyValue)) {
+ const tweenOptions = /** @type {WAAPITweenOptions} */(propertyValue);
+ const tweenOptionsEase = setValue(tweenOptions.ease, ease);
+ const tweenOptionsSpring = /** @type {Spring} */(tweenOptionsEase).ease && tweenOptionsEase;
+ const to = /** @type {WAAPITweenOptions} */(tweenOptions).to;
+ const from = /** @type {WAAPITweenOptions} */(tweenOptions).from;
+ /** @type {Number} */
+ tweenParams.duration = (tweenOptionsSpring ? /** @type {Spring} */(tweenOptionsSpring).duration : getFunctionValue(setValue(tweenOptions.duration, duration), $el, i, targetsLength)) * timeScale;
+ /** @type {Number} */
+ tweenParams.delay = getFunctionValue(setValue(tweenOptions.delay, delay), $el, i, targetsLength) * timeScale;
+ /** @type {CompositeOperation} */
+ tweenParams.composite = /** @type {CompositeOperation} */(setValue(tweenOptions.composition, composite));
+ /** @type {String} */
+ tweenParams.easing = parseWAAPIEasing(tweenOptionsEase);
+ parsedPropertyValue = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
+ if (individualTransformProperty) {
+ keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
+ cachedTransforms[individualTransformProperty] = parsedPropertyValue;
+ } else {
+ keyframes[name] = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
+ }
+ addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
+ if (!isUnd(from)) {
+ if (!individualTransformProperty) {
+ $el.style[name] = keyframes[name][0];
+ } else {
+ const key = `--${individualTransformProperty}`;
+ $el.style.setProperty(key, keyframes[key][0]);
+ }
+ }
+ } else {
+ parsedPropertyValue = isArr(propertyValue) ?
+ propertyValue.map((/** @type {any} */v) => normalizeTweenValue(name, v, $el, i, targetsLength)) :
+ normalizeTweenValue(name, /** @type {any} */(propertyValue), $el, i, targetsLength);
+ if (individualTransformProperty) {
+ keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
+ cachedTransforms[individualTransformProperty] = parsedPropertyValue;
+ } else {
+ keyframes[name] = parsedPropertyValue;
+ }
+ addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
+ }
+ }
+ if (hasIndividualTransforms) {
+ let transforms = emptyString;
+ for (let t in cachedTransforms) {
+ transforms += `${transformsFragmentStrings[t]}var(--${t})) `;
+ }
+ $el.style.transform = transforms;
+ }
+ });
+
+ if (scroll) {
+ /** @type {ScrollObserver} */(this.autoplay).link(this);
+ }
+ }
+
+ /**
+ * @callback forEachCallback
+ * @param {globalThis.Animation} animation
+ */
+
+ /**
+ * @param {forEachCallback|String} callback
+ * @return {this}
+ */
+ forEach(callback) {
+ const cb = isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback;
+ this.animations.forEach(cb);
+ return this;
+ }
+
+ get speed() {
+ return this._speed;
+ }
+
+ set speed(speed) {
+ this._speed = +speed;
+ this.forEach(anim => anim.playbackRate = speed);
+ }
+
+ get currentTime() {
+ const controlAnimation = this.controlAnimation;
+ const timeScale = globals.timeScale;
+ return this.completed ? this.duration : controlAnimation ? +controlAnimation.currentTime * (timeScale === 1 ? 1 : timeScale) : 0;
+ }
+
+ set currentTime(time) {
+ const t = time * (globals.timeScale === 1 ? 1 : K);
+ this.forEach(anim => {
+ // Make sure the animation playState is not 'paused' in order to properly trigger an onfinish callback.
+ // The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported.
+ // https://developer.mozilla.org/en-US/docs/Web/API/Animation/finish_event
+ if (t >= this.duration) anim.play();
+ anim.currentTime = t;
+ });
+ }
+
+ get progress() {
+ return this.currentTime / this.duration;
+ }
+
+ set progress(progress) {
+ this.forEach(anim => anim.currentTime = progress * this.duration || 0);
+ }
+
+ resume() {
+ if (!this.paused) return this;
+ this.paused = false;
+ // TODO: Store the current time, and seek back to the last position
+ return this.forEach('play');
+ }
+
+ pause() {
+ if (this.paused) return this;
+ this.paused = true;
+ return this.forEach('pause');
+ }
+
+ alternate() {
+ this.reversed = !this.reversed;
+ this.forEach('reverse');
+ if (this.paused) this.forEach('pause');
+ return this;
+ }
+
+ play() {
+ if (this.reversed) this.alternate();
+ return this.resume();
+ }
+
+ reverse() {
+ if (!this.reversed) this.alternate();
+ return this.resume();
+ }
+
+ /**
+ * @param {Number} time
+ * @param {Boolean} muteCallbacks
+ */
+ seek(time, muteCallbacks = false) {
+ if (muteCallbacks) this.muteCallbacks = true;
+ if (time < this.duration) this.completed = false;
+ this.currentTime = time;
+ this.muteCallbacks = false;
+ if (this.paused) this.pause();
+ return this;
+ }
+
+ restart() {
+ this.completed = false;
+ return this.seek(0, true).resume();
+ }
+
+ commitStyles() {
+ return this.forEach('commitStyles');
+ }
+
+ complete() {
+ return this.seek(this.duration);
+ }
+
+ cancel() {
+ this.forEach('cancel');
+ return this.pause();
+ }
+
+ revert() {
+ this.cancel();
+ this.targets.forEach(($el, i) => $el.setAttribute('style', this._inlineStyles[i]) );
+ return this;
+ }
+
+ /**
+ * @param {WAAPICallback} [callback]
+ * @return {Promise}
+ */
+ then(callback = noop) {
+ const then = this.then;
+ const onResolve = () => {
+ this.then = null;
+ callback(this);
+ this.then = then;
+ this._resolve = noop;
+ };
+ return new Promise(r => {
+ this._resolve = () => r(onResolve());
+ if (this.completed) this._resolve();
+ return this;
+ });
+ }
+ }
+
+ const waapi = {
+ /**
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
+ * @return {WAAPIAnimation}
+ */
+ animate: (targets, params) => new WAAPIAnimation(targets, params),
+ convertEase: easingToLinear
+ };
+
+ exports.$ = registerTargets;
+ exports.Animatable = Animatable;
+ exports.Draggable = Draggable;
+ exports.JSAnimation = JSAnimation;
+ exports.Scope = Scope;
+ exports.ScrollObserver = ScrollObserver;
+ exports.Spring = Spring;
+ exports.TextSplitter = TextSplitter;
+ exports.Timeline = Timeline;
+ exports.Timer = Timer;
+ exports.WAAPIAnimation = WAAPIAnimation;
+ exports.animate = animate;
+ exports.clamp = clamp;
+ exports.cleanInlineStyles = cleanInlineStyles;
+ exports.createAnimatable = createAnimatable;
+ exports.createDraggable = createDraggable;
+ exports.createDrawable = createDrawable;
+ exports.createMotionPath = createMotionPath;
+ exports.createScope = createScope;
+ exports.createSeededRandom = createSeededRandom;
+ exports.createSpring = createSpring;
+ exports.createTimeline = createTimeline;
+ exports.createTimer = createTimer;
+ exports.cubicBezier = cubicBezier;
+ exports.damp = damp;
+ exports.degToRad = degToRad;
+ exports.eases = eases;
+ exports.easings = index$3;
+ exports.engine = engine;
+ exports.get = get;
+ exports.irregular = irregular;
+ exports.keepTime = keepTime;
+ exports.lerp = lerp;
+ exports.linear = linear;
+ exports.mapRange = mapRange;
+ exports.morphTo = morphTo;
+ exports.none = none;
+ exports.onScroll = onScroll;
+ exports.padEnd = padEnd;
+ exports.padStart = padStart;
+ exports.radToDeg = radToDeg;
+ exports.random = random;
+ exports.randomPick = randomPick;
+ exports.remove = remove;
+ exports.round = round;
+ exports.roundPad = roundPad;
+ exports.scrollContainers = scrollContainers;
+ exports.set = set;
+ exports.shuffle = shuffle;
+ exports.snap = snap;
+ exports.split = split;
+ exports.splitText = splitText;
+ exports.stagger = stagger;
+ exports.steps = steps;
+ exports.svg = index$1;
+ exports.sync = sync;
+ exports.text = index;
+ exports.utils = index$2;
+ exports.waapi = waapi;
+ exports.wrap = wrap;
+
+}));
diff --git a/dist/bundles/anime.umd.min.js b/dist/bundles/anime.umd.min.js
new file mode 100644
index 00000000..654bea5b
--- /dev/null
+++ b/dist/bundles/anime.umd.min.js
@@ -0,0 +1,7 @@
+/**
+ * Anime.js - UMD minified bundle
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).anime={})}(this,function(t){"use strict";const e="undefined"!=typeof window,s=e?window:null,i=e?document:null,r={replace:0,none:1,blend:2},n=Symbol(),o=Symbol(),a=Symbol(),h=Symbol(),l=Symbol(),c=Symbol(),d=1e-11,u=1e12,p=1e3,m="",f=(()=>{const t=new Map;return t.set("x","translateX"),t.set("y","translateY"),t.set("z","translateZ"),t})(),g=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],_=g.reduce((t,e)=>({...t,[e]:e+"("}),{}),y=()=>{},v=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i,b=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i,T=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,S=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i,w=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,x=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi,k=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i,$=/([a-z])([A-Z])/g,E=/(\w+)(\([^)]+\)+)/g,C=/(\*=|\+=|-=)/,B={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:120,loop:0,reversed:!1,alternate:!1,autoplay:!0,duration:p,delay:0,loopDelay:0,ease:"out(2)",composition:r.replace,modifier:t=>t,onBegin:y,onBeforeUpdate:y,onUpdate:y,onLoop:y,onPause:y,onComplete:y,onRender:y},D={current:null,root:i},L={defaults:B,precision:4,timeScale:1,tickThreshold:200},A={version:"4.2.0",engine:null};e&&(s.AnimeJS||(s.AnimeJS=[]),s.AnimeJS.push(A));const N=t=>t.replace($,"$1-$2").toLowerCase(),O=(t,e)=>0===t.indexOf(e),F=Date.now,P=Array.isArray,R=t=>t&&t.constructor===Object,M=t=>"number"==typeof t&&!isNaN(t),z=t=>"string"==typeof t,I=t=>"function"==typeof t,Y=t=>void 0===t,X=t=>Y(t)||null===t,W=t=>e&&t instanceof SVGElement,V=t=>v.test(t),H=t=>O(t,"rgb"),U=t=>O(t,"hsl"),q=t=>!L.defaults.hasOwnProperty(t),j=["opacity","rotate","overflow","color"],Q=t=>z(t)?parseFloat(t):t,G=Math.pow,Z=Math.sqrt,J=Math.sin,K=Math.cos,tt=Math.abs,et=Math.exp,st=Math.ceil,it=Math.floor,rt=Math.asin,nt=Math.max,ot=Math.atan2,at=Math.PI,ht=Math.round,lt=(t,e,s)=>t<e?e:t>s?s:t,ct={},dt=(t,e)=>{if(e<0)return t;if(!e)return ht(t);let s=ct[e];return s||(s=ct[e]=10**e),ht(t*s)/s},ut=(t,e)=>P(e)?e.reduce((e,s)=>tt(s-t)<tt(e-t)?s:e):e?ht(t/e)*e:t,pt=(t,e,s)=>t+(e-t)*s,mt=t=>t===1/0?u:t===-1/0?-u:t,ft=t=>t<=d?d:mt(dt(t,11)),gt=t=>P(t)?[...t]:t,_t=(t,e)=>{const s={...t};for(let i in e){const r=t[i];s[i]=Y(r)?e[i]:r}return s},yt=(t,e,s,i="_prev",r="_next")=>{let n=t._head,o=r;for(s&&(n=t._tail,o=i);n;){const t=n[o];e(n),n=t}},vt=(t,e,s="_prev",i="_next")=>{const r=e[s],n=e[i];r?r[i]=n:t._head=n,n?n[s]=r:t._tail=r,e[s]=null,e[i]=null},bt=(t,e,s,i="_prev",r="_next")=>{let n=t._tail;for(;n&&s&&s(n,e);)n=n[i];const o=n?n[r]:t._head;n?n[r]=e:t._head=e,o?o[i]=e:t._tail=e,e[i]=n,e[r]=o},Tt=(t,e,s)=>(s<0&&(s+=1),s>1&&(s-=1),s<1/6?t+6*(e-t)*s:s<.5?e:s<2/3?t+(e-t)*(2/3-s)*6:t),St=(t,e)=>Y(t)?e:t,wt=(t,e,s,i,r)=>{if(I(t)){const n=()=>{const r=t(e,s,i);return isNaN(+r)?r||0:+r};return r&&(r.func=n),n()}return t},xt=(t,e)=>t[o]?t[a]&&((t,e)=>{if(j.includes(e))return!1;if(t.getAttribute(e)||e in t){if("scale"===e){const e=t.parentNode;return e&&"filter"===e.tagName}return!0}})(t,e)?1:g.includes(e)||f.get(e)?3:O(e,"--")?4:e in t.style?2:e in t?0:1:0,kt=(t,e,s)=>{const i=t.style[e];i&&s&&(s[e]=i);const r=i||getComputedStyle(t[c]||t).getPropertyValue(e);return"auto"===r?"0":r},$t=(t,e,s,i)=>{const r=Y(s)?xt(t,e):s;return 0===r?t[e]||0:1===r?t.getAttribute(e):3===r?((t,e,s)=>{const i=t.style.transform;let r;if(i){const n=t[h];let o;for(;o=E.exec(i);){const t=o[1],i=o[2].slice(1,-1);n[t]=i,t===e&&(r=i,s&&(s[e]=i))}}return i&&!Y(r)?r:O(e,"scale")?"1":O(e,"rotate")||O(e,"skew")?"0deg":"0px"})(t,e,i):4===r?kt(t,e,i).trimStart():kt(t,e,i)},Et=(t,e,s)=>"-"===s?t-e:"+"===s?t+e:t*e,Ct=(t,e)=>{if(e.t=0,e.n=0,e.u=null,e.o=null,e.d=null,e.s=null,!t)return e;const s=+t;if(isNaN(s)){let s=t;"="===s[1]&&(e.o=s[0],s=s.slice(2));const n=!s.includes(" ")&&k.exec(s);if(n)return e.t=1,e.n=+n[1],e.u=n[2],e;if(e.o)return e.n=+s,e;if(V(r=s)||H(r)||U(r))return e.t=2,e.d=H(i=s)?(t=>{const e=b.exec(t)||T.exec(t),s=Y(e[4])?1:+e[4];return[+e[1],+e[2],+e[3],s]})(i):V(i)?(t=>{const e=t.length,s=4===e||5===e;return[+("0x"+t[1]+t[s?1:2]),+("0x"+t[s?2:3]+t[s?2:4]),+("0x"+t[s?3:5]+t[s?3:6]),5===e||9===e?+(+("0x"+t[s?4:7]+t[s?4:8])/255).toFixed(3):1]})(i):U(i)?(t=>{const e=S.exec(t)||w.exec(t),s=+e[1]/360,i=+e[2]/100,r=+e[3]/100,n=Y(e[4])?1:+e[4];let o,a,h;if(0===i)o=a=h=r;else{const t=r<.5?r*(1+i):r+i-r*i,e=2*r-t;o=dt(255*Tt(e,t,s+1/3),0),a=dt(255*Tt(e,t,s),0),h=dt(255*Tt(e,t,s-1/3),0)}return[o,a,h,n]})(i):[0,0,0,1],e;{const t=s.match(x);return e.t=3,e.d=t?t.map(Number):[],e.s=s.split(x)||[],e}}var i,r;return e.n=s,e},Bt=(t,e)=>(e.t=t._valueType,e.n=t._toNumber,e.u=t._unit,e.o=null,e.d=gt(t._toNumbers),e.s=gt(t._strings),e),Dt={t:0,n:0,u:null,o:null,d:null,s:null},Lt=(t,e,s,i,n)=>{const o=t.parent,a=t.duration,l=t.completed,c=t.iterationDuration,u=t.iterationCount,p=t._currentIteration,f=t._loopDelay,g=t._reversed,y=t._alternate,v=t._hasChildren,b=t._delay,T=t._currentTime,S=b+c,w=e-b,x=lt(T,-b,a),k=lt(w,-b,a),$=w-T,E=k>0,C=k>=a,B=a<=d,D=2===n;let A=0,N=w,O=0;if(u>1){const e=~~(k/(c+(C?0:f)));t._currentIteration=lt(e,0,u),C&&t._currentIteration--,A=t._currentIteration%2,N=k%(c+f)||0}const F=g^(y&&A),P=t._ease;let R=C?F?0:a:F?c-N:N;P&&(R=c*P(R/c)||0);const M=(o?o.backwards:w<T)?!F:!!F;if(t._currentTime=w,t._iterationTime=R,t.backwards=M,E&&!t.began?(t.began=!0,s||o&&(M||!o.began)||t.onBegin(t)):w<=0&&(t.began=!1),s||v||!E||t._currentIteration===p||t.onLoop(t),D||1===n&&(e>=b&&e<=S||e<=b&&x>b||e>=S&&x!==a)||R>=S&&x!==a||R<=b&&x>0||e<=x&&x===a&&l||C&&!l&&B){if(E&&(t.computeDeltaTime(x),s||t.onBeforeUpdate(t)),!v){const e=D||(M?-1*$:$)>=L.tickThreshold,n=t._offset+(o?o._offset:0)+b+R;let a,l,c,d,u=t._head,p=0;for(;u;){const t=u._composition,s=u._currentTime,o=u._changeDuration,f=u._absoluteStartTime+u._changeDuration,g=u._nextRep,y=u._prevRep,v=t!==r.none;if((e||(s!==o||n<=f+(g?g._delay:0))&&(0!==s||n>=u._absoluteStartTime))&&(!v||!u._isOverridden&&(!u._isOverlapped||n<=f)&&(!g||g._isOverridden||n<=g._absoluteStartTime)&&(!y||y._isOverridden||n>=y._absoluteStartTime+y._changeDuration+u._delay))){const e=u._currentTime=lt(R-u._startTime,0,o),s=u._ease(e/u._updateDuration),n=u._modifier,m=u._valueType,f=u._tweenType,g=0===f,_=0===m,y=_&&g||0===s||1===s?-1:L.precision;let b,T;if(_)b=T=n(dt(pt(u._fromNumber,u._toNumber,s),y));else if(1===m)T=n(dt(pt(u._fromNumber,u._toNumber,s),y)),b=`${T}${u._unit}`;else if(2===m){const t=u._fromNumbers,e=u._toNumbers,i=dt(lt(n(pt(t[0],e[0],s)),0,255),0),r=dt(lt(n(pt(t[1],e[1],s)),0,255),0),o=dt(lt(n(pt(t[2],e[2],s)),0,255),0),a=lt(n(dt(pt(t[3],e[3],s),y)),0,1);if(b=`rgba(${i},${r},${o},${a})`,v){const t=u._numbers;t[0]=i,t[1]=r,t[2]=o,t[3]=a}}else if(3===m){b=u._strings[0];for(let t=0,e=u._toNumbers.length;t<e;t++){const e=n(dt(pt(u._fromNumbers[t],u._toNumbers[t],s),y)),i=u._strings[t+1];b+=`${i?e+i:e}`,v&&(u._numbers[t]=e)}}if(v&&(u._number=T),i||t===r.blend)u._value=b;else{const t=u.property;a=u.target,g?a[t]=b:1===f?a.setAttribute(t,b):(l=a.style,3===f?(a!==c&&(c=a,d=a[h]),d[t]=b,p=1):2===f?l[t]=b:4===f&&l.setProperty(t,b)),E&&(O=1)}}if(p&&u._renderTransforms){let t=m;for(let e in d)t+=`${_[e]}${d[e]}) `;l.transform=t,p=0}u=u._next}!s&&O&&t.onRender(t)}!s&&E&&t.onUpdate(t)}return o&&B?!s&&(o.began&&!M&&w>=a&&!l||M&&w<=d&&l)&&(t.onComplete(t),t.completed=!M):E&&C?u===1/0?t._startTime+=t.duration:t._currentIteration>=u-1&&(t.paused=!0,l||v||(t.completed=!0,s||o&&(M||!o.began)||(t.onComplete(t),t._resolve(t)))):t.completed=!1,O},At=(t,e,s,i,r)=>{const n=t._currentIteration;if(Lt(t,e,s,i,r),t._hasChildren){const o=t,a=o.backwards,h=i?e:o._iterationTime,l=F();let c=0,u=!0;if(!i&&o._currentIteration!==n){const t=o.iterationDuration;yt(o,e=>{if(a){const i=e.duration,r=e._offset+e._delay;s||!(i<=d)||r&&r+i!==t||e.onComplete(e)}else!e.completed&&!e.backwards&&e._currentTime<e.iterationDuration&&Lt(e,t,s,1,2),e.began=!1,e.completed=!1}),s||o.onLoop(o)}yt(o,t=>{const e=dt((h-t._offset)*t._speed,12),n=t._fps<o._fps?t.requestTick(l):r;c+=Lt(t,e,s,i,n),!t.completed&&u&&(u=!1)},a),!s&&c&&o.onRender(o),(u||a)&&o._currentTime>=o.duration&&(o.paused=!0,o.completed||(o.completed=!0,s||(o.onComplete(o),o._resolve(o))))}},Nt={},Ot=(t,e,s)=>{if(3===s)return f.get(t)||t;if(2===s||1===s&&W(e)&&t in e.style){const e=Nt[t];if(e)return e;{const e=t?N(t):t;return Nt[t]=e,e}}return t},Ft=t=>{if(t._hasChildren)yt(t,Ft,!0);else{const e=t;e.pause(),yt(e,t=>{const s=t.property,i=t.target;if(i[o]){const r=i.style,n=e._inlineStyles[s];if(3===t._tweenType){const e=i[h];if(Y(n)||n===m?delete e[s]:e[s]=n,t._renderTransforms)if(Object.keys(e).length){let t=m;for(let s in e)t+=_[s]+e[s]+") ";r.transform=t}else r.removeProperty("transform")}else Y(n)||n===m?r.removeProperty(s):r[s]=n;e._tail===t&&e.targets.forEach(t=>{t.getAttribute&&t.getAttribute("style")===m&&t.removeAttribute("style")})}})}return t};class Pt{constructor(t=0){this.deltaTime=0,this._currentTime=t,this._elapsedTime=t,this._startTime=t,this._lastTime=t,this._scheduledTime=0,this._frameDuration=dt(p/120,0),this._fps=120,this._speed=1,this._hasChildren=!1,this._head=null,this._tail=null}get fps(){return this._fps}set fps(t){const e=this._frameDuration,s=+t,i=s<d?d:s,r=dt(p/i,0);this._fps=i,this._frameDuration=r,this._scheduledTime+=r-e}get speed(){return this._speed}set speed(t){const e=+t;this._speed=e<d?d:e}requestTick(t){const e=this._scheduledTime,s=this._elapsedTime;if(this._elapsedTime+=t-s,s<e)return 0;const i=this._frameDuration,r=s-e;return this._scheduledTime+=r<i?i:r,1}computeDeltaTime(t){const e=t-this._lastTime;return this.deltaTime=e,this._lastTime=t,e}}const Rt={animation:null,update:y},Mt=(()=>e?requestAnimationFrame:setImmediate)(),zt=(()=>e?cancelAnimationFrame:clearImmediate)();class It extends Pt{constructor(t){super(t),this.useDefaultMainLoop=!0,this.pauseOnDocumentHidden=!0,this.defaults=B,this.paused=!0,this.reqId=0}update(){const t=this._currentTime=F();if(this.requestTick(t)){this.computeDeltaTime(t);const e=this._speed,s=this._fps;let i=this._head;for(;i;){const r=i._next;i.paused?(vt(this,i),this._hasChildren=!!this._tail,i._running=!1,i.completed&&!i._cancelled&&i.cancel()):At(i,(t-i._startTime)*i._speed*e,0,0,i._fps<s?i.requestTick(t):1),i=r}Rt.update()}}wake(){return this.useDefaultMainLoop&&!this.reqId&&(this.requestTick(F()),this.reqId=Mt(Xt)),this}pause(){if(this.reqId)return this.paused=!0,Wt()}resume(){if(this.paused)return this.paused=!1,yt(this,t=>t.resetTime()),this.wake()}get speed(){return this._speed*(1===L.timeScale?1:p)}set speed(t){this._speed=t*L.timeScale,yt(this,t=>t.speed=t._speed)}get timeUnit(){return 1===L.timeScale?"ms":"s"}set timeUnit(t){const e="s"===t,s=e?.001:1;if(L.timeScale!==s){L.timeScale=s,L.tickThreshold=200*s;const t=e?.001:p;this.defaults.duration*=t,this._speed*=t}}get precision(){return L.precision}set precision(t){L.precision=t}}const Yt=(()=>{const t=new It(F());return e&&(A.engine=t,i.addEventListener("visibilitychange",()=>{t.pauseOnDocumentHidden&&(i.hidden?t.pause():t.resume())})),t})(),Xt=()=>{Yt._head?(Yt.reqId=Mt(Xt),Yt.update()):Yt.reqId=0},Wt=()=>(zt(Yt.reqId),Yt.reqId=0,Yt),Vt={_rep:new WeakMap,_add:new Map},Ht=(t,e,s="_rep")=>{const i=Vt[s];let r=i.get(t);return r||(r={},i.set(t,r)),r[e]?r[e]:r[e]={_head:null,_tail:null}},Ut=(t,e)=>t._isOverridden||t._absoluteStartTime>e._absoluteStartTime,qt=t=>{t._isOverlapped=1,t._isOverridden=1,t._changeDuration=d,t._currentTime=d},jt=(t,e)=>{const s=t._composition;if(s===r.replace){const s=t._absoluteStartTime;bt(e,t,Ut,"_prevRep","_nextRep");const i=t._prevRep;if(i){const e=i.parent,r=i._absoluteStartTime+i._changeDuration;if(t.parent.id!==e.id&&e.iterationCount>1&&r+(e.duration-e.iterationDuration)>s){qt(i);let t=i._prevRep;for(;t&&t.parent.id===e.id;)qt(t),t=t._prevRep}const n=s-t._delay;if(r>n){const t=i._startTime,e=r-(t+i._updateDuration),s=dt(n-e-t,12);i._changeDuration=s,i._currentTime=s,i._isOverlapped=1,s<d&&qt(i)}let o=!0;if(yt(e,t=>{t._isOverlapped||(o=!1)}),o){const t=e.parent;if(t){let s=!0;yt(t,t=>{t!==e&&yt(t,t=>{t._isOverlapped||(s=!1)})}),s&&t.cancel()}else e.cancel()}}}else if(s===r.blend){const e=Ht(t.target,t.property,"_add"),s=(t=>{let e=Rt.animation;return e||(e={duration:d,computeDeltaTime:y,_offset:0,_delay:0,_head:null,_tail:null},Rt.animation=e,Rt.update=()=>{t.forEach(t=>{for(let e in t){const s=t[e],i=s._head;if(i){const t=i._valueType,e=3===t||2===t?gt(i._fromNumbers):null;let r=i._fromNumber,n=s._tail;for(;n&&n!==i;){if(e)for(let t=0,s=n._numbers.length;t<s;t++)e[t]+=n._numbers[t];else r+=n._number;n=n._prevAdd}i._toNumber=r,i._toNumbers=e}}}),Lt(e,1,1,0,2)}),e})(Vt._add);let i=e._head;i||(i={...t},i._composition=r.replace,i._updateDuration=d,i._startTime=0,i._numbers=gt(t._fromNumbers),i._number=0,i._next=null,i._prev=null,bt(e,i),bt(s,i));const n=t._toNumber;if(t._fromNumber=i._fromNumber-n,t._toNumber=0,t._numbers=gt(t._fromNumbers),t._number=0,i._fromNumber=n,t._toNumbers){const e=gt(t._toNumbers);e&&e.forEach((e,s)=>{t._fromNumbers[s]=i._fromNumbers[s]-e,t._toNumbers[s]=0}),i._fromNumbers=e}bt(e,t,null,"_prevAdd","_nextAdd")}return t},Qt=t=>{const e=t._composition;if(e!==r.none){const s=t.target,i=t.property,n=Vt._rep.get(s)[i];if(vt(n,t,"_prevRep","_nextRep"),e===r.blend){const e=Vt._add,r=e.get(s);if(!r)return;const n=r[i],o=Rt.animation;vt(n,t,"_prevAdd","_nextAdd");const a=n._head;if(a&&a===n._tail){vt(n,a,"_prevAdd","_nextAdd"),vt(o,a);let t=!0;for(let e in r)if(r[e]._head){t=!1;break}t&&e.delete(s)}}}return t},Gt=(t,e,s)=>{let i=!1;return yt(e,r=>{const n=r.target;if(t.includes(n)){const t=r.property,o=r._tweenType,a=Ot(s,n,o);(!a||a&&a===t)&&(r.parent._tail===r&&3===r._tweenType&&r._prev&&3===r._prev._tweenType&&(r._prev._renderTransforms=1),vt(e,r),Qt(r),i=!0)}},!0),i},Zt=(t,e,s)=>{const i=e||Yt;let r;if(i._hasChildren){let e=0;yt(i,n=>{if(!n._hasChildren)if(r=Gt(t,n,s),r&&!n._head)n.cancel(),vt(i,n);else{const t=n._offset+n._delay+n.duration;t>e&&(e=t)}n._head?Zt(t,n,s):n._hasChildren=!1},!0),Y(i.iterationDuration)||(i.iterationDuration=e)}else r=Gt(t,i,s);r&&!i._head&&(i._hasChildren=!1,i.cancel&&i.cancel())},Jt=t=>(t.paused=!0,t.began=!1,t.completed=!1,t),Kt=t=>t._cancelled?(t._hasChildren?yt(t,Kt):yt(t,t=>{t._composition!==r.none&&jt(t,Ht(t.target,t.property))}),t._cancelled=0,t):t;let te=0;class ee extends Pt{constructor(t={},e=null,s=0){super(0);const{id:i,delay:r,duration:n,reversed:o,alternate:a,loop:h,loopDelay:l,autoplay:c,frameRate:u,playbackRate:p,onComplete:m,onLoop:f,onPause:g,onBegin:_,onBeforeUpdate:v,onUpdate:b}=t;D.current&&D.current.register(this);const T=e?0:Yt._elapsedTime,S=e?e.defaults:L.defaults,w=I(r)||Y(r)?S.delay:+r,x=I(n)||Y(n)?1/0:+n,k=St(h,S.loop),$=St(l,S.loopDelay),E=!0===k||k===1/0||k<0?1/0:k+1;let C=0;e?C=s:(Yt.reqId||Yt.requestTick(F()),C=(Yt._elapsedTime-Yt._startTime)*L.timeScale),this.id=Y(i)?++te:i,this.parent=e,this.duration=mt((x+$)*E-$)||d,this.backwards=!1,this.paused=!0,this.began=!1,this.completed=!1,this.onBegin=_||S.onBegin,this.onBeforeUpdate=v||S.onBeforeUpdate,this.onUpdate=b||S.onUpdate,this.onLoop=f||S.onLoop,this.onPause=g||S.onPause,this.onComplete=m||S.onComplete,this.iterationDuration=x,this.iterationCount=E,this._autoplay=!e&&St(c,S.autoplay),this._offset=C,this._delay=w,this._loopDelay=$,this._iterationTime=0,this._currentIteration=0,this._resolve=y,this._running=!1,this._reversed=+St(o,S.reversed),this._reverse=this._reversed,this._cancelled=0,this._alternate=St(a,S.alternate),this._prev=null,this._next=null,this._elapsedTime=T,this._startTime=T,this._lastTime=T,this._fps=St(u,S.frameRate),this._speed=St(p,S.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(t){t?this.cancel():this.reset(1).play()}get currentTime(){return lt(dt(this._currentTime,L.precision),-this._delay,this.duration)}set currentTime(t){const e=this.paused;this.pause().seek(+t),e||this.resume()}get iterationCurrentTime(){return dt(this._iterationTime,L.precision)}set iterationCurrentTime(t){this.currentTime=this.iterationDuration*this._currentIteration+t}get progress(){return lt(dt(this._currentTime/this.duration,10),0,1)}set progress(t){this.currentTime=this.duration*t}get iterationProgress(){return lt(dt(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(t){const e=this.iterationDuration;this.currentTime=e*this._currentIteration+e*t}get currentIteration(){return this._currentIteration}set currentIteration(t){this.currentTime=this.iterationDuration*lt(+t,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(t){t?this.reverse():this.play()}get speed(){return super.speed}set speed(t){super.speed=t,this.resetTime()}reset(t=0){return Kt(this),this._reversed&&!this._reverse&&(this.reversed=!1),this._iterationTime=this.iterationDuration,At(this,0,1,t,2),Jt(this),this._hasChildren&&yt(this,Jt),this}init(t=0){this.fps=this._fps,this.speed=this._speed,!t&&this._hasChildren&&At(this,this.duration,1,t,2),this.reset(t);const e=this._autoplay;return!0===e?this.resume():e&&!Y(e.linked)&&e.link(this),this}resetTime(){const t=1/(this._speed*Yt._speed);return this._startTime=F()-(this._currentTime+this._delay)*t,this}pause(){return this.paused||(this.paused=!0,this.onPause(this)),this}resume(){return this.paused?(this.paused=!1,this.duration<=d&&!this._hasChildren?At(this,d,0,0,2):(this._running||(bt(Yt,this),Yt._hasChildren=!0,this._running=!0),this.resetTime(),this._startTime-=12,Yt.wake()),this):this}restart(){return this.reset(0).resume()}seek(t,e=0,s=0){Kt(this),this.completed=!1;const i=this.paused;return this.paused=!0,At(this,t+this._delay,~~e,~~s,1),i?this:this.resume()}alternate(){const t=this._reversed,e=this.iterationCount,s=this.iterationDuration,i=e===1/0?it(u/s):e;return this._reversed=+(!this._alternate||i%2?!t:t),e===1/0?this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress:this.seek(s*i-this._currentTime),this.resetTime(),this}play(){return this._reversed&&this.alternate(),this.resume()}reverse(){return this._reversed||this.alternate(),this.resume()}cancel(){return this._hasChildren?yt(this,t=>t.cancel(),!0):yt(this,Qt),this._cancelled=1,this.pause()}stretch(t){const e=this.duration,s=ft(t);if(e===s)return this;const i=t/e,r=t<=d;return this.duration=r?d:s,this.iterationDuration=r?d:ft(this.iterationDuration*i),this._offset*=i,this._delay*=i,this._loopDelay*=i,this}revert(){At(this,0,1,0,1);const t=this._autoplay;return t&&t.linked&&t.linked===this&&t.revert(),this.cancel()}complete(){return this.seek(this.duration).cancel()}then(t=y){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=y};return new Promise(t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this))}}function se(t){const e=z(t)?D.root.querySelectorAll(t):t;if(e instanceof NodeList||e instanceof HTMLCollection)return e}function ie(t){if(X(t))return[];if(!e)return P(t)&&t.flat(1/0)||[t];if(P(t)){const e=t.flat(1/0),s=[];for(let t=0,i=e.length;t<i;t++){const i=e[t];if(!X(i)){const t=se(i);if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!X(i)){let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}else{let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}}return s}const s=se(t);return s?Array.from(s):[t]}function re(t){const e=ie(t),s=e.length;if(s)for(let t=0;t<s;t++){const s=e[t];if(!s[n]){s[n]=!0;const t=W(s);(s.nodeType||t)&&(s[o]=!0,s[a]=t,s[h]={})}}return e}const ne={deg:1,rad:180/at,turn:360},oe={},ae=(t,e,s,r=!1)=>{const n=e.u,o=e.n;if(1===e.t&&n===s)return e;const a=o+n+s,h=oe[a];if(Y(h)||r){let r;if(n in ne)r=o*ne[n]/ne[s];else{const e=100,a=t.cloneNode(),h=t.parentNode,l=h&&h!==i?h:i.body;l.appendChild(a);const c=a.style;c.width=e+n;const d=a.offsetWidth||e;c.width=e+s;const u=d/(a.offsetWidth||e);l.removeChild(a),r=u*o}e.n=r,oe[a]=r}else e.n=h;return e.t,e.u=s,e},he=t=>t,le=(t=1.68)=>e=>G(e,+t),ce={in:t=>e=>t(e),out:t=>e=>1-t(1-e),inOut:t=>e=>e<.5?t(2*e)/2:1-t(-2*e+2)/2,outIn:t=>e=>e<.5?(1-t(1-2*e))/2:(t(2*e-1)+1)/2},de=(t,e,s)=>{if(s[t])return s[t];if(t.indexOf("(")<=-1){const i=ce[t]||t.includes("Back")||t.includes("Elastic")?e[t]():e[t];return i?s[t]=i:he}{const i=t.slice(0,-1).split("("),r=e[i[0]];return r?s[t]=r(...i[1].split(",")):he}},ue=(t,e,s)=>(((1-3*s+3*e)*t+(3*s-6*e))*t+3*e)*t,pe=(t=.5,e=0,s=.5,i=1)=>t===e&&s===i?he:r=>0===r||1===r?r:ue(((t,e,s)=>{let i,r,n=0,o=1,a=0;do{r=n+(o-n)/2,i=ue(r,e,s)-t,i>0?o=r:n=r}while(tt(i)>1e-7&&++a<100);return r})(r,t,s),e,i),me=(t=10,e)=>{const s=e?st:it;return e=>s(lt(e,0,1)*t)*(1/t)},fe=(...t)=>{const e=t.length;if(!e)return he;const s=e-1,i=t[0],r=t[s],n=[0],o=[Q(i)];for(let e=1;e<s;e++){const i=t[e],r=z(i)?i.trim().split(" "):[i],a=r[0],h=r[1];n.push(Y(h)?e/s:Q(h)/100),o.push(Q(a))}return o.push(Q(r)),n.push(1),function(t){for(let e=1,s=n.length;e<s;e++){const s=n[e];if(t<=s){const i=n[e-1],r=o[e-1];return r+(o[e]-r)*(t-i)/(s-i)}}return o[o.length-1]}},ge=(t=10,e=1)=>{const s=[0],i=t-1;for(let t=1;t<i;t++){const r=s[t-1],n=t/i,o=n*(1-e)+(n+((t+1)/i-n)*Math.random())*e;s.push(lt(o,r,1))}return s.push(1),fe(...s)},_e=at/2,ye=2*at,ve={[m]:le,Quad:le(2),Cubic:le(3),Quart:le(4),Quint:le(5),Sine:t=>1-K(t*_e),Circ:t=>1-Z(1-t*t),Expo:t=>t?G(2,10*t-10):0,Bounce:t=>{let e,s=4;for(;t<((e=G(2,--s))-1)/11;);return 1/G(4,3-s)-7.5625*G((3*e-2)/22-t,2)},Back:(t=1.70158)=>e=>(+t+1)*e*e*e-+t*e*e,Elastic:(t=1,e=.3)=>{const s=lt(+t,1,10),i=lt(+e,d,2),r=i/ye*rt(1/s),n=ye/i;return t=>0===t||1===t?t:-s*G(2,-10*(1-t))*J((1-t-r)*n)}},be=(()=>{const t={linear:fe,irregular:ge,steps:me,cubicBezier:pe};for(let e in ce)for(let s in ve){const i=ve[s],r=ce[e];t[e+s]=s===m||"Back"===s||"Elastic"===s?(t,e)=>r(i(t,e)):r(i)}return t})(),Te={linear:he},Se=t=>I(t)?t:z(t)?de(t,be,Te):he,we={t:0,n:0,u:null,o:null,d:null,s:null},xe={t:0,n:0,u:null,o:null,d:null,s:null},ke={func:null},$e=[null],Ee=[null,null],Ce={to:null};let Be,De,Le=0;class Ae extends ee{constructor(t,e,s,i,n=!1,o=0,a=0){super(e,s,i);const h=re(t),l=h.length,c=e.keyframes,u=c?_t(((t,e)=>{const s={};if(P(t)){const e=[].concat(...t.map(t=>Object.keys(t))).filter(q);for(let i=0,r=e.length;i<r;i++){const r=e[i],n=t.map(t=>{const e={};for(let s in t){const i=t[s];q(s)?s===r&&(e.to=i):e[s]=i}return e});s[r]=n}}else{const i=St(e.duration,L.defaults.duration),r=Object.keys(t).map(e=>({o:parseFloat(e)/100,p:t[e]})).sort((t,e)=>t.o-e.o);r.forEach(t=>{const e=t.o,r=t.p;for(let t in r)if(q(t)){let n=s[t];n||(n=s[t]=[]);const o=e*i;let a=n.length,h=n[a-1];const l={to:r[t]};let c=0;for(let t=0;t<a;t++)c+=n[t].duration;1===a&&(l.from=h.to),r.ease&&(l.ease=r.ease),l.duration=o-(a?c:0),n.push(l)}return t});for(let t in s){const e=s[t];let i;for(let t=0,s=e.length;t<s;t++){const s=e[t],r=s.ease;s.ease=i||void 0,i=r}e[0].duration||e.shift()}}return s})(c,e),e):e,{delay:m,duration:f,ease:g,playbackEase:_,modifier:y,composition:v,onRender:b}=u,T=s?s.defaults:L.defaults,S=St(_,T.playbackEase),w=S?Se(S):null,x=!Y(g)&&!Y(g.ease),k=x?g.ease:St(g,w?"linear":T.ease),$=x?g.duration:St(f,T.duration),E=St(m,T.delay),C=y||T.modifier,B=Y(v)&&l>=p?r.none:Y(v)?T.composition:v,D={},A=this._offset+(s?s._offset:0);let N=NaN,O=NaN,F=0,z=0;for(let t=0;t<l;t++){const e=h[t],i=o||t,c=a||l;let p=NaN,m=NaN;for(let t in u)if(q(t)){const o=xt(e,t),a=Ot(t,e,o);let h=u[t];const l=P(h);if(n&&!l&&(Ee[0]=h,Ee[1]=h,h=Ee),l){const t=h.length,e=!R(h[0]);2===t&&e?(Ce.to=h,$e[0]=Ce,Be=$e):t>2&&e?(Be=[],h.forEach((t,e)=>{e?1===e?(Ee[1]=t,Be.push(Ee)):Be.push(t):Ee[0]=t})):Be=h}else $e[0]=h,Be=$e;let f=null,g=null,_=NaN,y=0,v=0;for(let t=Be.length;v<t;v++){const n=Be[v];R(n)?De=n:(Ce.to=n,De=Ce),ke.func=null;const h=wt(De.to,e,i,c,ke);let l;R(h)&&!Y(h.to)?(De=h,l=h.to):l=h;const u=wt(De.from,e,i,c),p=De.ease,m=!Y(p)&&!Y(p.ease),b=m?p.ease:p||k,T=m?p.duration:wt(St(De.duration,t>1?wt($,e,i,c)/t:$),e,i,c),S=wt(St(De.delay,v?0:E),e,i,c),w=wt(St(De.composition,B),e,i,c),x=M(w)?w:r[w],L=De.modifier||C,N=!Y(u),O=!Y(l),I=P(l),X=I||N&&O,W=g?y+S:S,V=dt(A+W,12);z||!N&&!I||(z=1);let H=g;if(x!==r.none){f||(f=Ht(e,a));let t=f._head;for(;t&&!t._isOverridden&&t._absoluteStartTime<=V;)if(H=t,t=t._nextRep,t&&t._absoluteStartTime>=V)for(;t;)qt(t),t=t._nextRep}if(X?(Ct(I?wt(l[0],e,i,c):u,we),Ct(I?wt(l[1],e,i,c,ke):l,xe),0===we.t&&(H?1===H._valueType&&(we.t=1,we.u=H._unit):(Ct($t(e,a,o,D),Dt),1===Dt.t&&(we.t=1,we.u=Dt.u)))):(O?Ct(l,xe):g?Bt(g,xe):Ct(s&&H&&H.parent.parent===s?H._value:$t(e,a,o,D),xe),N?Ct(u,we):g?Bt(g,we):Ct(s&&H&&H.parent.parent===s?H._value:$t(e,a,o,D),we)),we.o&&(we.n=Et(H?H._toNumber:Ct($t(e,a,o,D),Dt).n,we.n,we.o)),xe.o&&(xe.n=Et(we.n,xe.n,xe.o)),we.t!==xe.t)if(3===we.t||3===xe.t){const t=3===we.t?we:xe,e=3===we.t?xe:we;e.t=3,e.s=gt(t.s),e.d=t.d.map(()=>e.n)}else if(1===we.t||1===xe.t){const t=1===we.t?we:xe,e=1===we.t?xe:we;e.t=1,e.u=t.u}else if(2===we.t||2===xe.t){const t=2===we.t?we:xe,e=2===we.t?xe:we;e.t=2,e.s=t.s,e.d=[0,0,0,1]}if(we.u!==xe.u){let t=xe.u?we:xe;t=ae(e,t,xe.u?xe.u:we.u,!1)}if(xe.d&&we.d&&xe.d.length!==we.d.length){const t=we.d.length>xe.d.length?we:xe,e=t===we?xe:we;e.d=t.d.map((t,s)=>Y(e.d[s])?0:e.d[s]),e.s=gt(t.s)}const U=dt(+T||d,12),q={parent:this,id:Le++,property:a,target:e,_value:null,_func:ke.func,_ease:Se(b),_fromNumbers:gt(we.d),_toNumbers:gt(xe.d),_strings:gt(xe.s),_fromNumber:we.n,_toNumber:xe.n,_numbers:gt(we.d),_number:we.n,_unit:xe.u,_modifier:L,_currentTime:0,_startTime:W,_delay:+S,_updateDuration:U,_changeDuration:U,_absoluteStartTime:V,_tweenType:o,_valueType:xe.t,_composition:x,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};x!==r.none&&jt(q,f),isNaN(_)&&(_=q._startTime),y=dt(W+U,12),g=q,F++,bt(this,q)}(isNaN(O)||_<O)&&(O=_),(isNaN(N)||y>N)&&(N=y),3===o&&(p=F-v,m=F)}if(!isNaN(p)){let t=0;yt(this,e=>{t>=p&&t<m&&(e._renderTransforms=1,e._composition===r.blend&&yt(Rt.animation,t=>{t.id===e.id&&(t._renderTransforms=1)})),t++})}}l||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation."),O?(yt(this,t=>{t._startTime-t._delay||(t._delay-=O),t._startTime-=O}),N-=O):O=0,N||(N=d,this.iterationCount=0),this.targets=h,this.duration=N===d?d:mt((N+this._loopDelay)*this.iterationCount-this._loopDelay)||d,this.onRender=b||T.onRender,this._ease=w,this._delay=O,this.iterationDuration=N,this._inlineStyles=D,!this._autoplay&&z&&this.onRender(this)}stretch(t){const e=this.duration;if(e===ft(t))return this;const s=t/e;return yt(this,t=>{t._updateDuration=ft(t._updateDuration*s),t._changeDuration=ft(t._changeDuration*s),t._currentTime*=s,t._startTime*=s,t._absoluteStartTime*=s}),super.stretch(t)}refresh(){return yt(this,t=>{const e=t._func;if(e){const s=$t(t.target,t.property,t._tweenType);Ct(s,Dt),Ct(e(),xe),t._fromNumbers=gt(Dt.d),t._fromNumber=Dt.n,t._toNumbers=gt(xe.d),t._strings=gt(xe.s),t._toNumber=xe.o?Et(Dt.n,xe.n,xe.o):xe.n}}),this}revert(){return super.revert(),Ft(this)}then(t){return super.then(t)}}const Ne={_head:null,_tail:null},Oe=(t,e,s)=>{let i=Ne._head;for(;i;){const r=i._next,n=i.$el===t,o=!e||i.property===e,a=!s||i.parent===s;if(n&&o&&a){const t=i.animation;try{t.commitStyles()}catch{}t.cancel(),vt(Ne,i);const e=i.parent;e&&(e._completed++,e.animations.length===e._completed&&(e.completed=!0,e.muteCallbacks||(e.paused=!0,e.onComplete(e),e._resolve(e))))}i=r}},Fe=(t,e,s,i,r)=>{const n=e.animate(i,r),o=r.delay+ +r.duration*r.iterations;n.playbackRate=t._speed,t.paused&&n.pause(),t.duration<o&&(t.duration=o,t.controlAnimation=n),t.animations.push(n),Oe(e,s),bt(Ne,{parent:t,animation:n,$el:e,property:s,_next:null,_prev:null});const a=()=>{Oe(e,s,t)};return n.onremove=a,n.onfinish=a,n};function Pe(t,e,s){const i=re(t);if(!i.length)return;const[r]=i,n=xt(r,e),o=Ot(e,r,n);let a=$t(r,o);if(Y(s))return a;if(Ct(a,Dt),0===Dt.t||1===Dt.t){if(!1===s)return Dt.n;{const t=ae(r,Dt,s,!1);return`${dt(t.n,L.precision)}${t.u}`}}}const Re=(t,e)=>{if(!Y(e))return e.duration=d,e.composition=St(e.composition,r.none),new Ae(t,e,null,0,!0).resume()},Me=(t,e,s)=>{const i=ie(t);for(let t=0,r=i.length;t<r;t++)Oe(i[t],s,e&&e.controlAnimation&&e);return Zt(i,e,s),i},ze=(t,e)=>{let s=t.iterationDuration;if(s===d&&(s=0),Y(e))return s;if(M(+e))return+e;const i=e,r=t?t.labels:null,n=!X(r),o=((t,e)=>{if(O(e,"<")){const s="<"===e[1],i=t._tail,r=i?i._offset+i._delay:0;return s?r:r+i.duration}})(t,i),a=!Y(o),h=C.exec(i);if(h){const t=h[0],e=i.split(t),l=n&&e[0]?r[e[0]]:s,c=a?o:n?l:s,d=+e[1];return Et(c,d,t[0])}return a?o:n?Y(r[i])?s:r[i]:s};function Ie(t,e,s,i,r,n){const o=M(t.duration)&&t.duration<=d?s-d:s;At(e,o,1,1,1);const a=i?new Ae(i,t,e,o,!1,r,n):new ee(t,e,o);return a.init(1),bt(e,a),yt(e,t=>{const s=t._offset+t._delay+t.duration;s>e.iterationDuration&&(e.iterationDuration=s)}),e.duration=function(t){return mt((t.iterationDuration+t._loopDelay)*t.iterationCount-t._loopDelay)||d}(e),e}class Ye extends ee{constructor(t={}){super(t,null,0),this.duration=0,this.labels={};const e=t.defaults,s=L.defaults;this.defaults=e?_t(e,s):s,this.onRender=t.onRender||s.onRender;const i=St(t.playbackEase,s.playbackEase);this._ease=i?Se(i):null,this.iterationDuration=0}add(t,e,s){const i=R(e),r=R(t);if(i||r){if(this._hasChildren=!0,i){const i=e;if(I(s)){const e=s,r=ie(t),n=this.duration,o=this.iterationDuration,a=i.id;let h=0;const l=r.length;r.forEach(t=>{const s={...i};this.duration=n,this.iterationDuration=o,Y(a)||(s.id=a+"-"+h),Ie(s,this,ze(this,e(t,h,l,this)),t,h,l),h++})}else Ie(i,this,ze(this,s),t)}else Ie(t,this,ze(this,e));return this.init(1)}}sync(t,e){if(Y(t)||t&&Y(t.pause))return this;t.pause();const s=+(t.effect?t.effect.getTiming().duration:t.duration);return this.add(t,{currentTime:[0,s],duration:s,ease:"linear"},e)}set(t,e,s){return Y(e)?this:(e.duration=d,e.composition=r.replace,this.add(t,e,s))}call(t,e){return Y(t)||t&&!I(t)?this:this.add({duration:0,onComplete:()=>t(this)},e)}label(t,e){return Y(t)||t&&!z(t)||(this.labels[t]=ze(this,e)),this}remove(t,e){return Zt(ie(t),this,e),this}stretch(t){const e=this.duration;if(e===ft(t))return this;const s=t/e,i=this.labels;yt(this,t=>t.stretch(t.duration*s));for(let t in i)i[t]*=s;return super.stretch(t)}refresh(){return yt(this,t=>{t.refresh&&t.refresh()}),this}revert(){return super.revert(),yt(this,t=>t.revert,!0),Ft(this)}then(t){return super.then(t)}}class Xe{constructor(t,e){D.current&&D.current.register(this);const s=()=>{if(this.callbacks.completed)return;let t=!0;for(let e in this.animations)if(!this.animations[e].paused&&t){t=!1;break}t&&this.callbacks.complete()},i={onBegin:()=>{this.callbacks.completed&&this.callbacks.reset(),this.callbacks.play()},onComplete:s,onPause:s},n={v:1,autoplay:!1},o={};if(this.targets=[],this.animations={},this.callbacks=null,!Y(t)&&!Y(e)){for(let t in e){const s=e[t];q(t)?o[t]=s:O(t,"on")?n[t]=s:i[t]=s}this.callbacks=new Ae({v:0},n);for(let e in o){const s=o[e],n=R(s);let a={},h="+=0";if(n){const t=s.unit;z(t)&&(h+=t)}else a.duration=s;a[e]=n?_t({to:h},s):h;const l=_t(i,a);l.composition=r.replace,l.autoplay=!1;const c=this.animations[e]=new Ae(t,l,null,0,!1).init();this.targets.length||this.targets.push(...c.targets),this[e]=(t,e,s)=>{const i=c._head;if(Y(t)&&i){const t=i._numbers;return t&&t.length?t:i._modifier(i._number)}return yt(c,e=>{if(P(t))for(let s=0,i=t.length;s<i;s++)Y(e._numbers[s])||(e._fromNumbers[s]=e._modifier(e._numbers[s]),e._toNumbers[s]=t[s]);else e._fromNumber=e._modifier(e._number),e._toNumber=t;Y(s)||(e._ease=Se(s)),e._currentTime=0}),Y(e)||c.stretch(e),c.reset(1).resume(),this}}}}revert(){for(let t in this.animations)this[t]=y,this.animations[t].revert();return this.animations={},this.targets.length=0,this.callbacks&&this.callbacks.revert(),this}}const We=(t,e,s,i,r)=>i+(t-e)/(s-e)*(r-i);var Ve=Object.freeze({__proto__:null,clamp:lt,damp:(t,e,s,i)=>i?1===i?e:pt(t,e,1-Math.exp(-i*s*.1)):t,degToRad:t=>t*Math.PI/180,lerp:pt,mapRange:We,padEnd:(t,e,s)=>`${t}`.padEnd(e,s),padStart:(t,e,s)=>`${t}`.padStart(e,s),radToDeg:t=>180*t/Math.PI,round:dt,roundPad:(t,e)=>(+t).toFixed(e),snap:ut,wrap:(t,e,s)=>((t-e)%(s-e)+(s-e))%(s-e)+e});const He=10*p;class Ue{constructor(t={}){this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/p,this.maxIterations=this.maxDuration/this.timeStep/p,this.m=lt(St(t.mass,1),0,He),this.s=lt(St(t.stiffness,100),1,He),this.d=lt(St(t.damping,10),.1,He),this.v=lt(St(t.velocity,0),-1e4,He),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.solverDuration=0,this.duration=0,this.compute(),this.ease=t=>0===t||1===t?t:this.solve(t*this.solverDuration)}solve(t){const{zeta:e,w0:s,wd:i,b:r}=this;let n=t;return n=e<1?et(-n*e*s)*(1*K(i*n)+r*J(i*n)):(1+r*n)*et(-n*s),1-n}compute(){const{maxRestSteps:t,maxIterations:e,restThreshold:s,timeStep:i,m:r,d:n,s:o,v:a}=this,h=this.w0=lt(Z(o/r),d,p),l=this.zeta=n/(2*Z(o*r)),c=this.wd=l<1?h*Z(1-l*l):0;this.b=l<1?(l*h-a)/c:-a+h;let u=0,m=0,f=0;for(;m<t&&f<e;)tt(1-this.solve(u))<s?m++:m=0,this.solverDuration=u,u+=i,f++;this.duration=dt(this.solverDuration*p,0)*L.timeScale}get mass(){return this.m}set mass(t){this.m=lt(St(t,1),0,He),this.compute()}get stiffness(){return this.s}set stiffness(t){this.s=lt(St(t,100),1,He),this.compute()}get damping(){return this.d}set damping(t){this.d=lt(St(t,10),.1,He),this.compute()}get velocity(){return this.v}set velocity(t){this.v=lt(St(t,0),-1e4,He),this.compute()}}const qe=t=>new Ue(t),je=t=>{t.cancelable&&t.preventDefault()};class Qe{constructor(t){this.el=t,this.zIndex=0,this.parentElement=null,this.classList={add:y,remove:y}}get x(){return this.el.x||0}set x(t){this.el.x=t}get y(){return this.el.y||0}set y(t){this.el.y=t}get width(){return this.el.width||0}set width(t){this.el.width=t}get height(){return this.el.height||0}set height(t){this.el.height=t}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class Ge{constructor(t){this.$el=t,this.inlineTransforms=[],this.point=new DOMPoint,this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(t,e){return this.point.x=t,this.point.y=e,this.point.matrixTransform(this.inversedMatrix)}traverseUp(t){let e=this.$el.parentElement,s=0;for(;e&&e!==i;)t(e,s),e=e.parentElement,s++}getMatrix(){const t=new DOMMatrix;return this.traverseUp(e=>{const s=getComputedStyle(e).transform;if(s){const e=new DOMMatrix(s);t.preMultiplySelf(e)}}),t}remove(){this.traverseUp((t,e)=>{this.inlineTransforms[e]=t.style.transform,t.style.transform="none"})}revert(){this.traverseUp((t,e)=>{const s=this.inlineTransforms[e];""===s?t.style.removeProperty("transform"):t.style.transform=s})}}const Ze=(t,e)=>t&&I(t)?t(e):t;let Je=0;class Ke{constructor(t,e={}){if(!t)return;D.current&&D.current.register(this);const r=e.x,n=e.y,o=e.trigger,a=e.modifier,h=e.releaseEase,l=h&&Se(h),c=!Y(h)&&!Y(h.ease),d=R(r)&&!Y(r.mapTo)?r.mapTo:"translateX",p=R(n)&&!Y(n.mapTo)?n.mapTo:"translateY",m=Ze(e.container,this);this.containerArray=P(m)?m:null,this.$container=m&&!this.containerArray?ie(m)[0]:i.body,this.useWin=this.$container===i.body,this.$scrollContainer=this.useWin?s:this.$container,this.$target=R(t)?new Qe(t):ie(t)[0],this.$trigger=ie(o||t)[0],this.fixed="fixed"===Pe(this.$target,"position"),this.isFinePointer=!0,this.containerPadding=[0,0,0,0],this.containerFriction=0,this.releaseContainerFriction=0,this.snapX=0,this.snapY=0,this.scrollSpeed=0,this.scrollThreshold=0,this.dragSpeed=0,this.maxVelocity=0,this.minVelocity=0,this.velocityMultiplier=0,this.cursor=!1,this.releaseXSpring=c?h:qe({mass:St(e.releaseMass,1),stiffness:St(e.releaseStiffness,80),damping:St(e.releaseDamping,20)}),this.releaseYSpring=c?h:qe({mass:St(e.releaseMass,1),stiffness:St(e.releaseStiffness,80),damping:St(e.releaseDamping,20)}),this.releaseEase=l||be.outQuint,this.hasReleaseSpring=c,this.onGrab=e.onGrab||y,this.onDrag=e.onDrag||y,this.onRelease=e.onRelease||y,this.onUpdate=e.onUpdate||y,this.onSettle=e.onSettle||y,this.onSnap=e.onSnap||y,this.onResize=e.onResize||y,this.onAfterResize=e.onAfterResize||y,this.disabled=[0,0];const f={};if(a&&(f.modifier=a),Y(r)||!0===r)f[d]=0;else if(R(r)){const t=r,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[d]=e}else!1===r&&(f[d]=0,this.disabled[0]=1);if(Y(n)||!0===n)f[p]=0;else if(R(n)){const t=n,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[p]=e}else!1===n&&(f[p]=0,this.disabled[1]=1);this.animate=new Xe(this.$target,f),this.xProp=d,this.yProp=p,this.destX=0,this.destY=0,this.deltaX=0,this.deltaY=0,this.scroll={x:0,y:0},this.coords=[this.x,this.y,0,0],this.snapped=[0,0],this.pointer=[0,0,0,0,0,0,0,0],this.scrollView=[0,0],this.dragArea=[0,0,0,0],this.containerBounds=[-u,u,u,-u],this.scrollBounds=[0,0,0,0],this.targetBounds=[0,0,0,0],this.window=[0,0],this.velocityStack=[0,0,0],this.velocityStackIndex=0,this.velocityTime=F(),this.velocity=0,this.angle=0,this.cursorStyles=null,this.triggerStyles=null,this.bodyStyles=null,this.targetStyles=null,this.touchActionStyles=null,this.transforms=new Ge(this.$target),this.overshootCoords={x:0,y:0},this.overshootTicker=new ee({autoplay:!1,onUpdate:()=>{this.updated=!0,this.manual=!0,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,1),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=!1,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,0),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init(),this.updateTicker=new ee({autoplay:!1,onUpdate:()=>this.update()},null,0).init(),this.contained=!Y(m),this.manual=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.enabled=!1,this.initialized=!1,this.activeProp=this.disabled[1]?d:p,this.animate.callbacks.onRender=()=>{const t=this.updated,e=!(this.grabbed&&t)&&this.released,s=this.x,i=this.y,r=s-this.coords[2],n=i-this.coords[3];this.deltaX=r,this.deltaY=n,this.coords[2]=s,this.coords[3]=i,t&&(r||n)&&this.onUpdate(this),e?(this.computeVelocity(r,n),this.angle=ot(n,r)):this.updated=!1},this.animate.callbacks.onComplete=()=>{!this.grabbed&&this.released&&(this.released=!1),this.manual||(this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.onSettle(this))},this.resizeTicker=new ee({autoplay:!1,duration:150*L.timeScale,onComplete:()=>{this.onResize(this),this.refresh(),this.onAfterResize(this)}}).init(),this.parameters=e,this.resizeObserver=new ResizeObserver(()=>{this.initialized?this.resizeTicker.restart():this.initialized=!0}),this.enable(),this.refresh(),this.resizeObserver.observe(this.$container),R(t)||this.resizeObserver.observe(this.$target)}computeVelocity(t,e){const s=this.velocityTime,i=F(),r=i-s;if(r<17)return this.velocity;this.velocityTime=i;const n=this.velocityStack,o=this.velocityMultiplier,a=this.minVelocity,h=this.maxVelocity,l=this.velocityStackIndex;n[l]=dt(lt(Z(t*t+e*e)/r*o,a,h),5);const c=nt(n[0],n[1],n[2]);return this.velocity=c,this.velocityStackIndex=(l+1)%3,c}setX(t,e=!1){if(this.disabled[0])return;const s=dt(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destX=s,this.snapped[0]=ut(s,this.snapX),this.animate[this.xProp](s,0),this.manual=!1,this}setY(t,e=!1){if(this.disabled[1])return;const s=dt(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destY=s,this.snapped[1]=ut(s,this.snapY),this.animate[this.yProp](s,0),this.manual=!1,this}get x(){return dt(this.animate[this.xProp](),L.precision)}set x(t){this.setX(t,!1)}get y(){return dt(this.animate[this.yProp](),L.precision)}set y(t){this.setY(t,!1)}get progressX(){return We(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(t){this.setX(We(t,0,1,this.containerBounds[3],this.containerBounds[1]),!1)}get progressY(){return We(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(t){this.setY(We(t,0,1,this.containerBounds[0],this.containerBounds[2]),!1)}updateScrollCoords(){const t=dt(this.useWin?s.scrollX:this.$container.scrollLeft,0),e=dt(this.useWin?s.scrollY:this.$container.scrollTop,0),[i,r,n,o]=this.containerPadding,a=this.scrollThreshold;this.scroll.x=t,this.scroll.y=e,this.scrollBounds[0]=e-this.targetBounds[0]+i-a,this.scrollBounds[1]=t-this.targetBounds[1]-r+a,this.scrollBounds[2]=e-this.targetBounds[2]-n+a,this.scrollBounds[3]=t-this.targetBounds[3]+o-a}updateBoundingValues(){const t=this.$container;if(!t)return;const e=this.x,r=this.y,n=this.coords[2],o=this.coords[3];this.coords[2]=0,this.coords[3]=0,this.setX(0,!0),this.setY(0,!0),this.transforms.remove();const a=this.window[0]=s.innerWidth,h=this.window[1]=s.innerHeight,l=this.useWin,c=t.scrollWidth,d=t.scrollHeight,u=this.fixed,p=t.getBoundingClientRect(),[m,f,g,_]=this.containerPadding;this.dragArea[0]=l?0:p.left,this.dragArea[1]=l?0:p.top,this.scrollView[0]=l?lt(c,a,c):c,this.scrollView[1]=l?lt(d,h,d):d,this.updateScrollCoords();const{width:y,height:v,left:b,top:T,right:S,bottom:w}=t.getBoundingClientRect();this.dragArea[2]=dt(l?lt(y,a,a):y,0),this.dragArea[3]=dt(l?lt(v,h,h):v,0);const x=Pe(t,"overflow"),k="visible"===x,$="hidden"===x;if(this.canScroll=!u&&this.contained&&(t===i.body&&k||!$&&!k)&&(c>this.dragArea[2]+_-f||d>this.dragArea[3]+m-g)&&(!this.containerArray||this.containerArray&&!P(this.containerArray)),this.contained){const e=this.scroll.x,s=this.scroll.y,i=this.canScroll,r=this.$target.getBoundingClientRect(),n=i?l?0:t.scrollLeft:0,o=i?l?0:t.scrollTop:0,c=i?this.scrollView[0]-n-y:0,d=i?this.scrollView[1]-o-v:0;this.targetBounds[0]=dt(r.top+s-(l?0:T),0),this.targetBounds[1]=dt(r.right+e-(l?a:S),0),this.targetBounds[2]=dt(r.bottom+s-(l?h:w),0),this.targetBounds[3]=dt(r.left+e-(l?0:b),0),this.containerArray?(this.containerBounds[0]=this.containerArray[0]+m,this.containerBounds[1]=this.containerArray[1]-f,this.containerBounds[2]=this.containerArray[2]-g,this.containerBounds[3]=this.containerArray[3]+_):(this.containerBounds[0]=-dt(r.top-(u?lt(T,0,h):T)+o-m,0),this.containerBounds[1]=-dt(r.right-(u?lt(S,0,a):S)-c+f,0),this.containerBounds[2]=-dt(r.bottom-(u?lt(w,0,h):w)-d+g,0),this.containerBounds[3]=-dt(r.left-(u?lt(b,0,a):b)+n-_,0))}this.transforms.revert(),this.coords[2]=n,this.coords[3]=o,this.setX(e,!0),this.setY(r,!0)}isOutOfBounds(t,e,s){if(!this.contained)return 0;const[i,r,n,o]=t,[a,h]=this.disabled,l=!a&&e<o||!a&&e>r,c=!h&&s<i||!h&&s>n;return l&&!c?1:!l&&c?2:l&&c?3:0}refresh(){const t=this.parameters,e=t.x,r=t.y,n=Ze(t.container,this),o=Ze(t.containerPadding,this)||0,a=P(o)?o:[o,o,o,o],h=this.x,l=this.y,c=Ze(t.cursor,this),d={onHover:"grab",onGrab:"grabbing"};if(c){const{onHover:t,onGrab:e}=c;t&&(d.onHover=t),e&&(d.onGrab=e)}this.containerArray=P(n)?n:null,this.$container=n&&!this.containerArray?ie(n)[0]:i.body,this.useWin=this.$container===i.body,this.$scrollContainer=this.useWin?s:this.$container,this.isFinePointer=matchMedia("(pointer:fine)").matches,this.containerPadding=St(a,[0,0,0,0]),this.containerFriction=lt(St(Ze(t.containerFriction,this),.8),0,1),this.releaseContainerFriction=lt(St(Ze(t.releaseContainerFriction,this),this.containerFriction),0,1),this.snapX=Ze(R(e)&&!Y(e.snap)?e.snap:t.snap,this),this.snapY=Ze(R(r)&&!Y(r.snap)?r.snap:t.snap,this),this.scrollSpeed=St(Ze(t.scrollSpeed,this),1.5),this.scrollThreshold=St(Ze(t.scrollThreshold,this),20),this.dragSpeed=St(Ze(t.dragSpeed,this),1),this.minVelocity=St(Ze(t.minVelocity,this),0),this.maxVelocity=St(Ze(t.maxVelocity,this),50),this.velocityMultiplier=St(Ze(t.velocityMultiplier,this),1),this.cursor=!1!==c&&d,this.updateBoundingValues();const[u,p,m,f]=this.containerBounds;this.setX(lt(h,f,p),!0),this.setY(lt(l,u,m),!0)}update(){if(this.updateScrollCoords(),this.canScroll){const[t,e,s,i]=this.containerPadding,[r,n]=this.scrollView,o=this.dragArea[2],a=this.dragArea[3],h=this.scroll.x,l=this.scroll.y,c=this.$container.scrollWidth,d=this.$container.scrollHeight,u=this.useWin?lt(c,this.window[0],c):c,p=this.useWin?lt(d,this.window[1],d):d,m=r-u,f=n-p;this.dragged&&m>0&&(this.coords[0]-=m,this.scrollView[0]=u),this.dragged&&f>0&&(this.coords[1]-=f,this.scrollView[1]=p);const g=10*this.scrollSpeed,_=this.scrollThreshold,[y,v]=this.coords,[b,T,S,w]=this.scrollBounds,x=dt(lt((v-b+t)/_,-1,0)*g,0),k=dt(lt((y-T-e)/_,0,1)*g,0),$=dt(lt((v-S-s)/_,0,1)*g,0),E=dt(lt((y-w+i)/_,-1,0)*g,0);if(x||$||E||k){const[t,e]=this.disabled;let s=h,i=l;t||(s=dt(lt(h+(E||k),0,r-o),0),this.coords[0]-=h-s),e||(i=dt(lt(l+(x||$),0,n-a),0),this.coords[1]-=l-i),this.useWin?this.$scrollContainer.scrollBy(-(h-s),-(l-i)):this.$scrollContainer.scrollTo(s,i)}}const[t,e,s,i]=this.containerBounds,[r,n,o,a,h,l]=this.pointer;this.coords[0]+=(r-h)*this.dragSpeed,this.coords[1]+=(n-l)*this.dragSpeed,this.pointer[4]=r,this.pointer[5]=n;const[c,d]=this.coords,[u,p]=this.snapped,m=(1-this.containerFriction)*this.dragSpeed;this.setX(c>e?e+(c-e)*m:c<i?i+(c-i)*m:c,!1),this.setY(d>s?s+(d-s)*m:d<t?t+(d-t)*m:d,!1),this.computeVelocity(r-h,n-l),this.angle=ot(n-a,r-o);const[f,g]=this.snapped;(f!==u&&this.snapX||g!==p&&this.snapY)&&this.onSnap(this)}stop(){this.updateTicker.pause(),this.overshootTicker.pause();for(let t in this.animate.animations)this.animate.animations[t].pause();return Zt([this],null,"x"),Zt([this],null,"y"),Zt([this],null,"progressX"),Zt([this],null,"progressY"),Zt([this.scroll]),Zt([this.overshootCoords]),this}scrollInView(t,e=0,s=be.inOutQuad){this.updateScrollCoords();const i=this.destX,r=this.destY,n=this.scroll,o=this.scrollBounds,a=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(o,i,r)){const[h,l,c,d]=o,p=dt(lt(r-h,-u,0),0),m=dt(lt(i-l,0,u),0),f=dt(lt(r-c,0,u),0),g=dt(lt(i-d,-u,0),0);new Ae(n,{x:dt(n.x+(g?g-e:m?m+e:0),0),y:dt(n.y+(p?p-e:f?f+e:0),0),duration:Y(t)?350*L.timeScale:t,ease:s,onUpdate:()=>{this.canScroll=!1,this.$scrollContainer.scrollTo(n.x,n.y)}}).init().then(()=>{this.canScroll=a})}return this}handleHover(){this.isFinePointer&&this.cursor&&!this.cursorStyles&&(this.cursorStyles=Re(this.$trigger,{cursor:this.cursor.onHover}))}animateInView(t,e=0,s=be.inOutQuad){this.stop(),this.updateBoundingValues();const i=this.x,r=this.y,[n,o,a,h]=this.containerPadding,l=this.scroll.y-this.targetBounds[0]+n+e,c=this.scroll.x-this.targetBounds[1]-o-e,d=this.scroll.y-this.targetBounds[2]-a-e,u=this.scroll.x-this.targetBounds[3]+h+e,p=this.isOutOfBounds([l,c,d,u],i,r);if(p){const[e,n]=this.disabled,o=lt(ut(i,this.snapX),u,c),a=lt(ut(r,this.snapY),l,d),h=Y(t)?350*L.timeScale:t;e||1!==p&&3!==p||this.animate[this.xProp](o,h,s),n||2!==p&&3!==p||this.animate[this.yProp](a,h,s)}return this}handleDown(t){const e=t.target;if(this.grabbed||"range"===e.type)return;t.stopPropagation(),this.grabbed=!0,this.released=!1,this.stop(),this.updateBoundingValues();const s=t.changedTouches,r=s?s[0].clientX:t.clientX,n=s?s[0].clientY:t.clientY,{x:o,y:a}=this.transforms.normalizePoint(r,n),[h,l,c,d]=this.containerBounds,u=(1-this.containerFriction)*this.dragSpeed,p=this.x,m=this.y;this.coords[0]=this.coords[2]=u?p>l?l+(p-l)/u:p<d?d+(p-d)/u:p:p,this.coords[1]=this.coords[3]=u?m>c?c+(m-c)/u:m<h?h+(m-h)/u:m:m,this.pointer[0]=o,this.pointer[1]=a,this.pointer[2]=o,this.pointer[3]=a,this.pointer[4]=o,this.pointer[5]=a,this.pointer[6]=o,this.pointer[7]=a,this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null);const f=Pe(this.$target,"zIndex",!1);Je=(f>Je?f:Je)+1,this.targetStyles=Re(this.$target,{zIndex:Je}),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.isFinePointer&&this.cursor&&(this.bodyStyles=Re(i.body,{cursor:this.cursor.onGrab})),this.scrollInView(100,0,be.out(3)),this.onGrab(this),i.addEventListener("touchmove",this),i.addEventListener("touchend",this),i.addEventListener("touchcancel",this),i.addEventListener("mousemove",this),i.addEventListener("mouseup",this),i.addEventListener("selectstart",this)}handleMove(t){if(!this.grabbed)return;const e=t.changedTouches,s=e?e[0].clientX:t.clientX,i=e?e[0].clientY:t.clientY,{x:r,y:n}=this.transforms.normalizePoint(s,i),o=r-this.pointer[6],a=n-this.pointer[7];let h=t.target,l=!1,c=!1,d=!1;for(;e&&h&&h!==this.$trigger;){const t=Pe(h,"overflow-y");if("hidden"!==t&&"visible"!==t){const{scrollTop:t,scrollHeight:e,clientHeight:s}=h;if(e>s){d=!0,l=t<=3,c=t>=e-s-3;break}}h=h.parentElement}d&&(!l&&!c||l&&a<0||c&&a>0)?(this.pointer[0]=r,this.pointer[1]=n,this.pointer[2]=r,this.pointer[3]=n,this.pointer[4]=r,this.pointer[5]=n,this.pointer[6]=r,this.pointer[7]=n):(je(t),this.triggerStyles||(this.triggerStyles=Re(this.$trigger,{pointerEvents:"none"})),this.$trigger.addEventListener("touchstart",je,{passive:!1}),this.$trigger.addEventListener("touchmove",je,{passive:!1}),this.$trigger.addEventListener("touchend",je),(!this.disabled[0]&&tt(o)>3||!this.disabled[1]&&tt(a)>3)&&(this.updateTicker.resume(),this.pointer[2]=this.pointer[0],this.pointer[3]=this.pointer[1],this.pointer[0]=r,this.pointer[1]=n,this.dragged=!0,this.released=!1,this.onDrag(this)))}handleUp(){if(!this.grabbed)return;this.updateTicker.pause(),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null);const[t,e]=this.disabled,[s,n,o,a,h,l]=this.pointer,[c,d,u,p]=this.containerBounds,[m,f]=this.snapped,g=this.releaseXSpring,_=this.releaseYSpring,y=this.releaseEase,v=this.hasReleaseSpring,b=this.overshootCoords,T=this.x,S=this.y,w=this.computeVelocity(s-h,n-l),x=this.angle=ot(n-a,s-o),k=150*w,$=(1-this.releaseContainerFriction)*this.dragSpeed,E=T+K(x)*k,C=S+J(x)*k,B=E>d?d+(E-d)*$:E<p?p+(E-p)*$:E,D=C>u?u+(C-u)*$:C<c?c+(C-c)*$:C,A=this.destX=lt(dt(ut(B,this.snapX),5),p,d),N=this.destY=lt(dt(ut(D,this.snapY),5),c,u),O=this.isOutOfBounds(this.containerBounds,E,C);let F=0,P=0,R=y,M=y,z=0;if(b.x=T,b.y=S,!t){const t=A===d?T>d?-1:1:T<p?-1:1,s=dt(T-A,0);g.velocity=e&&v?s?k*t/tt(s):0:w;const{ease:i,duration:r,restDuration:n}=g;F=T===A?0:v?r:r-n*L.timeScale,v&&(R=i),F>z&&(z=F)}if(!e){const e=N===u?S>u?-1:1:S<c?-1:1,s=dt(S-N,0);_.velocity=t&&v?s?k*e/tt(s):0:w;const{ease:i,duration:r,restDuration:n}=_;P=S===N?0:v?r:r-n*L.timeScale,v&&(M=i),P>z&&(z=P)}if(!v&&O&&$&&(F||P)){const t=r.blend;new Ae(b,{x:{to:B,duration:.65*F},y:{to:D,duration:.65*P},ease:y,composition:t}).init(),new Ae(b,{x:{to:A,duration:F},y:{to:N,duration:P},ease:y,composition:t}).init(),this.overshootTicker.stretch(nt(F,P)).restart()}else t||this.animate[this.xProp](A,F,R),e||this.animate[this.yProp](N,P,M);this.scrollInView(z,this.scrollThreshold,y);let I=!1;A!==m&&(this.snapped[0]=A,this.snapX&&(I=!0)),N!==f&&this.snapY&&(this.snapped[1]=N,this.snapY&&(I=!0)),I&&this.onSnap(this),this.grabbed=!1,this.dragged=!1,this.updated=!0,this.released=!0,this.onRelease(this),this.$trigger.removeEventListener("touchstart",je),this.$trigger.removeEventListener("touchmove",je),this.$trigger.removeEventListener("touchend",je),i.removeEventListener("touchmove",this),i.removeEventListener("touchend",this),i.removeEventListener("touchcancel",this),i.removeEventListener("mousemove",this),i.removeEventListener("mouseup",this),i.removeEventListener("selectstart",this)}reset(){return this.stop(),this.resizeTicker.pause(),this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.setX(0,!0),this.setY(0,!0),this.coords[0]=0,this.coords[1]=0,this.pointer[0]=0,this.pointer[1]=0,this.pointer[2]=0,this.pointer[3]=0,this.pointer[4]=0,this.pointer[5]=0,this.pointer[6]=0,this.pointer[7]=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this}enable(){return this.enabled||(this.enabled=!0,this.$target.classList.remove("is-disabled"),this.touchActionStyles=Re(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"}),this.$trigger.addEventListener("touchstart",this,{passive:!0}),this.$trigger.addEventListener("mousedown",this,{passive:!0}),this.$trigger.addEventListener("mouseenter",this)),this}disable(){return this.enabled=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.touchActionStyles.revert(),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null),this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null),this.$target.classList.add("is-disabled"),this.$trigger.removeEventListener("touchstart",this),this.$trigger.removeEventListener("mousedown",this),this.$trigger.removeEventListener("mouseenter",this),i.removeEventListener("touchmove",this),i.removeEventListener("touchend",this),i.removeEventListener("touchcancel",this),i.removeEventListener("mousemove",this),i.removeEventListener("mouseup",this),i.removeEventListener("selectstart",this),this}revert(){return this.reset(),this.disable(),this.$target.classList.remove("is-disabled"),this.updateTicker.revert(),this.overshootTicker.revert(),this.resizeTicker.revert(),this.animate.revert(),this.resizeObserver.disconnect(),this}handleEvent(t){switch(t.type){case"mousedown":case"touchstart":this.handleDown(t);break;case"mousemove":case"touchmove":this.handleMove(t);break;case"mouseup":case"touchend":case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":je(t)}}}const ts=(t=y)=>new ee({duration:1*L.timeScale,onComplete:t},null,0).resume(),es=t=>{let e;return(...s)=>{let i,r,n,o;e&&(i=e.currentIteration,r=e.iterationProgress,n=e.reversed,o=e._alternate,e.revert());const a=t(...s);return a&&!I(a)&&a.revert&&(e=a),Y(r)||(e.currentIteration=i,e.iterationProgress=(o&&i%2?!n:n)?1-r:r),a||y}};class ss{constructor(t={}){D.current&&D.current.register(this);const e=t.root;let r=i;e&&(r=e.current||e.nativeElement||ie(e)[0]||i);const n=t.defaults,o=L.defaults,a=t.mediaQueries;if(this.defaults=n?_t(n,o):o,this.root=r,this.constructors=[],this.revertConstructors=[],this.revertibles=[],this.constructorsOnce=[],this.revertConstructorsOnce=[],this.revertiblesOnce=[],this.once=!1,this.onceIndex=0,this.methods={},this.matches={},this.mediaQueryLists={},this.data={},a)for(let t in a){const e=s.matchMedia(a[t]);this.mediaQueryLists[t]=e,e.addEventListener("change",this)}}register(t){(this.once?this.revertiblesOnce:this.revertibles).push(t)}execute(t){let e=D.current,s=D.root,i=L.defaults;D.current=this,D.root=this.root,L.defaults=this.defaults;const r=this.mediaQueryLists;for(let t in r)this.matches[t]=r[t].matches;const n=t(this);return D.current=e,D.root=s,L.defaults=i,n}refresh(){return this.onceIndex=0,this.execute(()=>{let t=this.revertibles.length,e=this.revertConstructors.length;for(;t--;)this.revertibles[t].revert();for(;e--;)this.revertConstructors[e](this);this.revertibles.length=0,this.revertConstructors.length=0,this.constructors.forEach(t=>{const e=t(this);I(e)&&this.revertConstructors.push(e)})}),this}add(t,e){if(this.once=!1,I(t)){const e=t;this.constructors.push(e),this.execute(()=>{const t=e(this);I(t)&&this.revertConstructors.push(t)})}else this.methods[t]=(...t)=>this.execute(()=>e(...t));return this}addOnce(t){if(this.once=!0,I(t)){const e=this.onceIndex++;if(this.constructorsOnce[e])return this;const s=t;this.constructorsOnce[e]=s,this.execute(()=>{const t=s(this);I(t)&&this.revertConstructorsOnce.push(t)})}return this}keepTime(t){this.once=!0;const e=this.onceIndex++,s=this.constructorsOnce[e];if(I(s))return s(this);const i=es(t);let r;return this.constructorsOnce[e]=i,this.execute(()=>{r=i(this)}),r}handleEvent(t){"change"===t.type&&this.refresh()}revert(){const t=this.revertibles,e=this.revertConstructors,s=this.revertiblesOnce,i=this.revertConstructorsOnce,r=this.mediaQueryLists;let n=t.length,o=e.length,a=s.length,h=i.length;for(;n--;)t[n].revert();for(;o--;)e[o](this);for(;a--;)s[a].revert();for(;h--;)i[h](this);for(let t in r)r[t].removeEventListener("change",this);t.length=0,e.length=0,this.constructors.length=0,s.length=0,i.length=0,this.constructorsOnce.length=0,this.onceIndex=0,this.matches={},this.methods={},this.mediaQueryLists={},this.data={}}}const is=(t,e)=>t&&I(t)?t(e):t,rs=new Map;class ns{constructor(t){this.element=t,this.useWin=this.element===i.body,this.winWidth=0,this.winHeight=0,this.width=0,this.height=0,this.left=0,this.top=0,this.zIndex=0,this.scrollX=0,this.scrollY=0,this.prevScrollX=0,this.prevScrollY=0,this.scrollWidth=0,this.scrollHeight=0,this.velocity=0,this.backwardX=!1,this.backwardY=!1,this.scrollTicker=new ee({autoplay:!1,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const t=this.backwardX||this.backwardY;yt(this,t=>t.handleScroll(),t)},onComplete:()=>this.dataTimer.pause()}).init(),this.dataTimer=new ee({autoplay:!1,frameRate:30,onUpdate:t=>{const e=t.deltaTime,s=this.prevScrollX,i=this.prevScrollY,r=this.scrollX,n=this.scrollY,o=s-r,a=i-n;this.prevScrollX=r,this.prevScrollY=n,o&&(this.backwardX=s>r),a&&(this.backwardY=i>n),this.velocity=dt(e>0?Math.sqrt(o*o+a*a)/e:0,5)}}).init(),this.resizeTicker=new ee({autoplay:!1,duration:250*L.timeScale,onComplete:()=>{this.updateWindowBounds(),this.refreshScrollObservers(),this.handleScroll()}}).init(),this.wakeTicker=new ee({autoplay:!1,duration:500*L.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init(),this._head=null,this._tail=null,this.updateScrollCoords(),this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll(),this.resizeObserver=new ResizeObserver(()=>this.resizeTicker.restart()),this.resizeObserver.observe(this.element),(this.useWin?s:this.element).addEventListener("scroll",this,!1)}updateScrollCoords(){const t=this.useWin,e=this.element;this.scrollX=dt(t?s.scrollX:e.scrollLeft,0),this.scrollY=dt(t?s.scrollY:e.scrollTop,0)}updateWindowBounds(){this.winWidth=s.innerWidth,this.winHeight=(()=>{const t=i.createElement("div");i.body.appendChild(t),t.style.height="100lvh";const e=t.offsetHeight;return i.body.removeChild(t),e})()}updateBounds(){const t=getComputedStyle(this.element),e=this.element;let s,i;if(this.scrollWidth=e.scrollWidth+parseFloat(t.marginLeft)+parseFloat(t.marginRight),this.scrollHeight=e.scrollHeight+parseFloat(t.marginTop)+parseFloat(t.marginBottom),this.updateWindowBounds(),this.useWin)s=this.winWidth,i=this.winHeight;else{const t=e.getBoundingClientRect();s=e.clientWidth,i=e.clientHeight,this.top=t.top,this.left=t.left}this.width=s,this.height=i}refreshScrollObservers(){yt(this,t=>{t._debug&&t.removeDebug()}),this.updateBounds(),yt(this,t=>{t.refresh(),t._debug&&t.debug()})}refresh(){this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll()}handleScroll(){this.updateScrollCoords(),this.wakeTicker.restart()}handleEvent(t){"scroll"===t.type&&this.handleScroll()}revert(){this.scrollTicker.cancel(),this.dataTimer.cancel(),this.resizeTicker.cancel(),this.wakeTicker.cancel(),this.resizeObserver.disconnect(),(this.useWin?s:this.element).removeEventListener("scroll",this),rs.delete(this.element)}}const os=(t,e,s,i,r)=>{const n="min"===e,o="max"===e,a="top"===e||"left"===e||"start"===e||n?0:"bottom"===e||"right"===e||"end"===e||o?"100%":"center"===e?"50%":e,{n:h,u:l}=Ct(a,Dt);let c=h;return"%"===l?c=h/100*s:l&&(c=ae(t,Dt,"px",!0).n),o&&i<0&&(c+=i),n&&r>0&&(c+=r),c},as=(t,e,s,i,r)=>{let n;if(z(e)){const o=C.exec(e);if(o){const a=o[0],h=a[0],l=e.split(a),c="min"===l[0],d="max"===l[0],u=os(t,l[0],s,i,r),p=os(t,l[1],s,i,r);if(c){const e=Et(os(t,"min",s),p,h);n=e<u?u:e}else if(d){const e=Et(os(t,"max",s),p,h);n=e>u?u:e}else n=Et(u,p,h)}else n=os(t,e,s,i,r)}else n=e;return dt(n,0)},hs=t=>{let e;const s=t.targets;for(let t=0,i=s.length;t<i;t++){const i=s[t];if(i[o]){e=i;break}}return e};let ls=0;const cs=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class ds{constructor(t={}){D.current&&D.current.register(this);const e=St(t.sync,"play pause"),s=e?Se(e):null,r=e&&("linear"===e||e===he),n=e&&!(s===he&&!r),o=e&&(M(e)||!0===e||r),a=e&&z(e)&&!n&&!o,h=a?e.split(" ").map(t=>()=>{const e=this.linked;return e&&e[t]?e[t]():null}):null,l=a&&h.length>2;this.index=ls++,this.id=Y(t.id)?this.index:t.id,this.container=(t=>{const e=t&&ie(t)[0]||i.body;let s=rs.get(e);return s||(s=new ns(e),rs.set(e,s)),s})(t.container),this.target=null,this.linked=null,this.repeat=null,this.horizontal=null,this.enter=null,this.leave=null,this.sync=n||o||!!h,this.syncEase=n?s:null,this.syncSmooth=o?!0===e||r?1:e:null,this.onSyncEnter=h&&!l&&h[0]?h[0]:y,this.onSyncLeave=h&&!l&&h[1]?h[1]:y,this.onSyncEnterForward=h&&l&&h[0]?h[0]:y,this.onSyncLeaveForward=h&&l&&h[1]?h[1]:y,this.onSyncEnterBackward=h&&l&&h[2]?h[2]:y,this.onSyncLeaveBackward=h&&l&&h[3]?h[3]:y,this.onEnter=t.onEnter||y,this.onLeave=t.onLeave||y,this.onEnterForward=t.onEnterForward||y,this.onLeaveForward=t.onLeaveForward||y,this.onEnterBackward=t.onEnterBackward||y,this.onLeaveBackward=t.onLeaveBackward||y,this.onUpdate=t.onUpdate||y,this.onSyncComplete=t.onSyncComplete||y,this.reverted=!1,this.completed=!1,this.began=!1,this.isInView=!1,this.forceEnter=!1,this.hasEntered=!1,this.offset=0,this.offsetStart=0,this.offsetEnd=0,this.distance=0,this.prevProgress=0,this.thresholds=["start","end","end","start"],this.coords=[0,0,0,0],this.debugStyles=null,this.$debug=null,this._params=t,this._debug=St(t.debug,!1),this._next=null,this._prev=null,bt(this.container,this),ts(()=>{if(!this.reverted){if(!this.target){const e=ie(t.target)[0];this.target=e||i.body,this.refresh()}this._debug&&this.debug()}})}link(t){if(t&&(t.pause(),this.linked=t,!this._params.target)){let e;Y(t.targets)?yt(t,t=>{t.targets&&!e&&(e=hs(t))}):e=hs(t),this.target=e||i.body,this.refresh()}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const t=(this.scroll-this.offsetStart)/this.distance;return t===1/0||isNaN(t)?0:dt(lt(t,0,1),6)}refresh(){this.reverted=!1;const t=this._params;return this.repeat=St(is(t.repeat,this),!0),this.horizontal="x"===St(is(t.axis,this),"y"),this.enter=St(is(t.enter,this),"end start"),this.leave=St(is(t.leave,this),"start end"),this.updateBounds(),this.handleScroll(),this}removeDebug(){return this.$debug&&(this.$debug.parentNode.removeChild(this.$debug),this.$debug=null),this.debugStyles&&(this.debugStyles.revert(),this.$debug=null),this}debug(){this.removeDebug();const t=this.container,e=this.horizontal,s=t.element.querySelector(":scope > .animejs-onscroll-debug"),r=i.createElement("div"),n=i.createElement("div"),o=i.createElement("div"),a=cs[this.index%cs.length],h=t.useWin,l=h?t.winWidth:t.width,c=h?t.winHeight:t.height,d=t.scrollWidth,u=t.scrollHeight,p=this.container.width>360?320:260,m=e?0:10,f=e?10:0,g=e?24:p/2,_=e?g:15,y=e?60:g,v=e?y:_,b=e?"repeat-x":"repeat-y",T=t=>e?"0px "+t+"px":t+"px 2px",S=t=>`linear-gradient(${e?90:0}deg, ${t} 2px, transparent 1px)`,w=(t,e,s,i,r)=>`position:${t};left:${e}px;top:${s}px;width:${i}px;height:${r}px;`;r.style.cssText=`${w("absolute",m,f,e?d:p,e?p:u)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${e?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `,n.style.cssText=`${w("sticky",0,0,e?l:g,e?g:c)}`,s||(n.style.cssText+=`background:\n ${S("#FFFF")}${T(g-10)} / 100px 100px ${b},\n ${S("#FFF8")}${T(g-10)} / 10px 10px ${b};\n `),o.style.cssText=`${w("relative",0,0,e?d:g,e?g:u)}`,s||(o.style.cssText+=`background:\n ${S("#FFFF")}${T(0)} / ${e?"100px 10px":"10px 100px"} ${b},\n ${S("#FFF8")}${T(0)} / ${e?"10px 0px":"0px 10px"} ${b};\n `);const x=[" enter: "," leave: "];this.coords.forEach((t,s)=>{const r=s>1,h=(r?0:this.offset)+t,m=s%2,f=h<v,g=h>(r?e?l:c:e?d:u)-v,b=(r?m&&!f:!m&&!f)||g,T=i.createElement("div"),S=i.createElement("div"),k=e?b?"right":"left":b?"bottom":"top",$=b?(e?y:_)+(r?e?-1:g?0:-2:e?-1:-2):e?1:0;S.innerHTML=`${this.id}${x[m]}${this.thresholds[s]}`,T.style.cssText=`${w("absolute",0,0,y,_)}\n display: flex;\n flex-direction: ${e?"column":"row"};\n justify-content: flex-${r?"start":"end"};\n align-items: flex-${b?"end":"start"};\n border-${k}: 2px solid ${a};\n `,S.style.cssText=`\n overflow: hidden;\n max-width: ${p/2-10}px;\n height: ${_};\n margin-${e?b?"right":"left":b?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${e&&b||!e&&!r?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${m?a:"rgba(0,0,0,.75)"};\n background-color: ${m?"rgba(0,0,0,.65)":a};\n border: 2px solid ${m?a:"transparent"};\n border-${e?b?"top-left":"top-right":b?"top-left":"bottom-left"}-radius: 5px;\n border-${e?b?"bottom-left":"bottom-right":b?"top-right":"bottom-right"}-radius: 5px;\n `,T.appendChild(S);let E=h-$+(e?1:0);T.style[e?"left":"top"]=`${E}px`,(r?n:o).appendChild(T)}),r.appendChild(n),r.appendChild(o),t.element.appendChild(r),s||r.classList.add("animejs-onscroll-debug"),this.$debug=r,"static"===Pe(t.element,"position")&&(this.debugStyles=Re(t.element,{position:"relative "}))}updateBounds(){let t;this._debug&&this.removeDebug();const e=this.target,s=this.container,r=this.horizontal,n=this.linked;let o,a=e;for(n&&(o=n.currentTime,n.seek(0,!0)),a.parentElement;a&&a!==s.element&&a!==i.body;){const e="sticky"===Pe(a,"position")&&Re(a,{position:"static"});a=a.parentElement,e&&(t||(t=[]),t.push(e))}const h=e.getBoundingClientRect(),l=r?h.left+s.scrollX-s.left:h.top+s.scrollY-s.top,c=r?h.width:h.height,d=r?s.width:s.height,u=(r?s.scrollWidth:s.scrollHeight)-d,p=this.enter,m=this.leave;let f="start",g="end",_="end",y="start";if(z(p)){const t=p.split(" ");_=t[0],f=t.length>1?t[1]:f}else if(R(p)){const t=p;Y(t.container)||(_=t.container),Y(t.target)||(f=t.target)}else M(p)&&(_=p);if(z(m)){const t=m.split(" ");y=t[0],g=t.length>1?t[1]:g}else if(R(m)){const t=m;Y(t.container)||(y=t.container),Y(t.target)||(g=t.target)}else M(m)&&(y=m);const v=as(e,f,c),b=as(e,g,c),T=v+l-d,S=b+l-u,w=as(e,_,d,T,S),x=as(e,y,d,T,S),k=v+l-w,$=b+l-x,E=$-k;this.offset=l,this.offsetStart=k,this.offsetEnd=$,this.distance=E<=0?0:E,this.thresholds=[f,g,_,y],this.coords=[v,b,w,x],t&&t.forEach(t=>t.revert()),n&&n.seek(o,!0),this._debug&&this.debug()}handleScroll(){const t=this.linked,e=this.sync,s=this.syncEase,i=this.syncSmooth,r=t&&(s||i),n=this.horizontal,o=this.container,a=this.scroll,h=a<=this.offsetStart,l=a>=this.offsetEnd,c=!h&&!l,d=a===this.offsetStart||a===this.offsetEnd,u=!this.hasEntered&&d,p=this._debug&&this.$debug;let m=!1,f=!1,g=this.progress;if(h&&this.began&&(this.began=!1),g>0&&!this.began&&(this.began=!0),r){const e=t.progress;if(i&&M(i)){if(i<1){const t=1e-4,s=e<g&&1===g?t:e>g&&!g?-t:0;g=dt(pt(e,g,pt(.01,.2,i))+s,6)}}else s&&(g=s(g));m=g!==this.prevProgress,f=1===e,m&&!f&&i&&e&&o.wakeTicker.restart()}if(p){const t=n?o.scrollY:o.scrollX;p.style[n?"top":"left"]=t+10+"px"}(c&&!this.isInView||u&&!this.forceEnter&&!this.hasEntered)&&(c&&(this.isInView=!0),this.forceEnter&&this.hasEntered?c&&(this.forceEnter=!1):(p&&c&&(p.style.zIndex=""+this.container.zIndex++),this.onSyncEnter(this),this.onEnter(this),this.backward?(this.onSyncEnterBackward(this),this.onEnterBackward(this)):(this.onSyncEnterForward(this),this.onEnterForward(this)),this.hasEntered=!0,u&&(this.forceEnter=!0))),(c||!c&&this.isInView)&&(m=!0),m&&(r&&t.seek(t.duration*g),this.onUpdate(this)),!c&&this.isInView&&(this.isInView=!1,this.onSyncLeave(this),this.onLeave(this),this.backward?(this.onSyncLeaveBackward(this),this.onLeaveBackward(this)):(this.onSyncLeaveForward(this),this.onLeaveForward(this)),e&&!i&&(f=!0)),g>=1&&this.began&&!this.completed&&(e&&f||!e)&&(e&&this.onSyncComplete(this),this.completed=!0,(!this.repeat&&!t||!this.repeat&&t&&t.completed)&&this.revert()),g<1&&this.completed&&(this.completed=!1),this.prevProgress=g}revert(){if(this.reverted)return;const t=this.container;return vt(t,this),t._head||t.revert(),this._debug&&this.removeDebug(),this.reverted=!0,this}}var us=Object.freeze({__proto__:null,cubicBezier:pe,eases:be,irregular:ge,linear:fe,none:he,steps:me});const ps=Ve,ms={},fs=t=>(...e)=>{const s=t(...e);return new Proxy(y,{apply:(t,e,[i])=>s(i),get:(t,e)=>fs((...t)=>{const i=ms[e](...t);return t=>i(s(t))})})},gs=(t,e,s=0)=>{const i=(...t)=>(t.length<e.length?fs(((t,e=0)=>(...s)=>e?e=>t(...s,e):e=>t(e,...s))(e,s)):e)(...t);return ms[t]||(ms[t]=i),i},_s=gs("roundPad",ps.roundPad),ys=gs("padStart",ps.padStart),vs=gs("padEnd",ps.padEnd),bs=gs("wrap",ps.wrap),Ts=gs("mapRange",ps.mapRange),Ss=gs("degToRad",ps.degToRad),ws=gs("radToDeg",ps.radToDeg),xs=gs("snap",ps.snap),ks=gs("clamp",ps.clamp),$s=gs("round",ps.round),Es=gs("lerp",ps.lerp,1),Cs=gs("damp",ps.damp,1),Bs=(t=0,e=1,s=0)=>{const i=10**s;return Math.floor((Math.random()*(e-t+1/i)+t)*i)/i};let Ds=0;const Ls=(t,e=0,s=1,i=0)=>{let r=void 0===t?Ds++:t;return(t=e,n=s,o=i)=>{r+=1831565813,r=Math.imul(r^r>>>15,1|r),r^=r+Math.imul(r^r>>>7,61|r);const a=10**o;return Math.floor((((r^r>>>14)>>>0)/4294967296*(n-t+1/a)+t)*a)/a}},As=t=>t[Bs(0,t.length-1)],Ns=t=>{let e,s,i=t.length;for(;i;)s=Bs(0,--i),e=t[i],t[i]=t[s],t[s]=e;return t},Os=(t,e={})=>{let s=[],i=0;const r=e.from,n=e.reversed,o=e.ease,a=!Y(o),h=a&&!Y(o.ease)?o.ease:a?Se(o):null,l=e.grid,c=e.axis,d=e.total,u=Y(r)||0===r||"first"===r,p="center"===r,f="last"===r,g="random"===r,_=P(t),y=e.use,v=Q(_?t[0]:t),b=_?Q(t[1]):0,T=k.exec((_?t[1]:t)+m),S=e.start||0+(_?v:0);let w=u?0:M(r)?r:0;return(t,r,o,a)=>{const[u]=re(t),m=Y(d)?o:d,x=!Y(y)&&(I(y)?y(u,r,m):$t(u,y)),k=M(x)||z(x)&&M(+x)?+x:r;if(p&&(w=(m-1)/2),f&&(w=m-1),!s.length){for(let t=0;t<m;t++){if(l){const e=p?(l[0]-1)/2:w%l[0],i=p?(l[1]-1)/2:it(w/l[0]),r=e-t%l[0],n=i-it(t/l[0]);let o=Z(r*r+n*n);"x"===c&&(o=-r),"y"===c&&(o=-n),s.push(o)}else s.push(tt(w-t));i=nt(...s)}h&&(s=s.map(t=>h(t/i)*i)),n&&(s=s.map(t=>c?t<0?-1*t:-t:tt(i-t))),g&&(s=Ns(s))}const $=_?(b-v)/i:v;let E=(a?ze(a,Y(e.start)?a.iterationDuration:S):S)+($*dt(s[k],2)||0);return e.modifier&&(E=e.modifier(E)),T&&(E=`${E}${T[2]}`),E}};var Fs=Object.freeze({__proto__:null,$:re,clamp:ks,cleanInlineStyles:Ft,createSeededRandom:Ls,damp:Cs,degToRad:Ss,get:Pe,keepTime:es,lerp:Es,mapRange:Ts,padEnd:vs,padStart:ys,radToDeg:ws,random:Bs,randomPick:As,remove:Me,round:$s,roundPad:_s,set:Re,shuffle:Ns,snap:xs,stagger:Os,sync:ts,wrap:bs});const Ps=t=>{const e=ie(t)[0];return e&&W(e)?e:console.warn(`${t} is not a valid SVGGeometryElement`)},Rs=(t,e,s=0)=>t.getPointAtLength(e+s>=1?e+s:0),Ms=(t,e)=>s=>{const i=+t.getTotalLength(),r=s[a],n=t.getCTM();return{from:0,to:i,modifier:s=>{if("a"===e){const e=Rs(t,s,-1),i=Rs(t,s,1);return 180*ot(i.y-e.y,i.x-e.x)/at}{const i=Rs(t,s,0);return"x"===e?r||!n?i.x:i.x*n.a+i.y*n.c+n.e:r||!n?i.y:i.x*n.b+i.y*n.d+n.f}}}},zs=t=>{const e=Ps(t);if(e)return{translateX:Ms(e,"x"),translateY:Ms(e,"y"),rotate:Ms(e,"a")}},Is=(t,e=0,s=0)=>ie(t).map(t=>((t,e,s)=>{const i=p,r=getComputedStyle(t),n=r.strokeLinecap,o="non-scaling-stroke"===r.vectorEffect?t:null;let a=n;const h=new Proxy(t,{get(t,e){const s=t[e];return e===c?t:"setAttribute"===e?(...e)=>{if("draw"===e[0]){const s=e[1].split(" "),r=+s[0],h=+s[1],l=(t=>{let e=1;if(t&&t.getCTM){const s=t.getCTM();s&&(e=(Z(s.a*s.a+s.b*s.b)+Z(s.c*s.c+s.d*s.d))/2)}return e})(o),c=-1e3*r*l,d=h*i*l+c,u=i*l+(0===r&&1===h||1===r&&0===h?0:10*l)-d;if("butt"!==n){const e=r===h?"butt":n;a!==e&&(t.style.strokeLinecap=`${e}`,a=e)}t.setAttribute("stroke-dashoffset",`${c}`),t.setAttribute("stroke-dasharray",`${d} ${u}`)}return Reflect.apply(s,t,e)}:I(s)?(...e)=>Reflect.apply(s,t,e):s}});return"1000"!==t.getAttribute("pathLength")&&(t.setAttribute("pathLength","1000"),h.setAttribute("draw",`${e} ${s}`)),h})(t,e,s)),Ys=(t,e=.33)=>s=>{const i=Ps(t);if(!i)return;const r="path"===s.tagName,n=r?" ":",",o=s[l];o&&s.setAttribute(r?"d":"points",o);let a="",h="";if(e){const t=s.getTotalLength(),o=i.getTotalLength(),l=Math.max(Math.ceil(t*e),Math.ceil(o*e));for(let e=0;e<l;e++){const c=e/(l-1),d=s.getPointAtLength(t*c),u=i.getPointAtLength(o*c),p=r?0===e?"M":"L":"";a+=p+dt(d.x,3)+n+d.y+" ",h+=p+dt(u.x,3)+n+u.y+" "}}else a=s.getAttribute(r?"d":"points"),h=i.getAttribute(r?"d":"points");return s[l]=h,[a,h]};var Xs=Object.freeze({__proto__:null,createDrawable:Is,createMotionPath:zs,morphTo:Ys});const Ws="undefined"!=typeof Intl&&Intl.Segmenter,Vs=/\{value\}/g,Hs=/\{i\}/g,Us=/(\s+)/,qs=/^\s+$/,js="line",Qs="word",Gs="char",Zs="data-line";let Js=null,Ks=null,ti=null;const ei=t=>t.isWordLike||" "===t.segment||M(+t.segment),si=t=>t.setAttribute("aria-hidden","true"),ii=(t,e)=>[...t.querySelectorAll(`[data-${e}]:not([data-${e}] [data-${e}])`)],ri={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"},ni=t=>{if(!t.childElementCount&&!t.textContent.trim()){const e=t.parentElement;t.remove(),e&&ni(e)}},oi=(t,e,s)=>{const i=t.getAttribute(Zs);(null!==i&&+i!==e||"BR"===t.tagName)&&s.add(t);let r=t.childElementCount;for(;r--;)oi(t.children[r],e,s);return s},ai=(t,e={})=>{let s="";const i=z(e.class)?` class="${e.class}"`:"",r=St(e.clone,!1),n=St(e.wrap,!1),o=n?!0===n?"clip":n:!!r&&"clip";return n&&(s+=`<span${o?` style="overflow:${o};"`:""}>`),s+=`<span${i}${r?' style="position:relative;"':""} data-${t}="{i}">`,r?(s+="<span>{value}</span>",s+=`<span inert style="position:absolute;top:${"top"===r?"-100%":"bottom"===r?"100%":"0"};left:${"left"===r?"-100%":"right"===r?"100%":"0"};white-space:nowrap;">{value}</span>`):s+="{value}",s+="</span>",n&&(s+="</span>"),s},hi=(t,e,s,i,r,n,o,a,h)=>{const l=r===js,c=r===Gs,d=`_${r}_`,u=I(t)?t(s):t,p=l?"block":"inline-block";ti.innerHTML=u.replace(Vs,`<i class="${d}"></i>`).replace(Hs,`${c?h:l?o:a}`);const m=ti.content,f=m.firstElementChild,g=m.querySelector(`[data-${r}]`)||f,_=m.querySelectorAll(`i.${d}`),y=_.length;if(y){f.style.display=p,g.style.display=p,g.setAttribute(Zs,`${o}`),l||(g.setAttribute("data-word",`${a}`),c&&g.setAttribute("data-char",`${h}`));let t=y;for(;t--;){const e=_[t],i=e.parentElement;i.style.display=p,l?i.innerHTML=s.innerHTML:i.replaceChild(s.cloneNode(!0),e)}e.push(g),i.appendChild(m)}else console.warn('The expression "{value}" is missing from the provided template.');return n&&(f.style.outline=`1px dotted ${ri[r]}`),f};class li{constructor(t,s={}){Js||(Js=Ws?new Ws([],{granularity:Qs}):{segment:t=>{const e=[],s=t.split(Us);for(let t=0,i=s.length;t<i;t++){const i=s[t];e.push({segment:i,isWordLike:!qs.test(i)})}return e}}),Ks||(Ks=Ws?new Ws([],{granularity:"grapheme"}):{segment:t=>[...t].map(t=>({segment:t}))}),!ti&&e&&(ti=i.createElement("template")),D.current&&D.current.register(this);const{words:r,chars:n,lines:o,accessible:a,includeSpaces:h,debug:l}=s,c=(t=P(t)?t[0]:t)&&t.nodeType?t:(se(t)||[])[0],d=!0===o?{}:o,u=!0===r||Y(r)?{}:r,p=!0===n?{}:n;this.debug=St(l,!1),this.includeSpaces=St(h,!1),this.accessible=St(a,!0),this.linesOnly=d&&!u&&!p,this.lineTemplate=R(d)?ai(js,d):d,this.wordTemplate=R(u)||this.linesOnly?ai(Qs,u):u,this.charTemplate=R(p)?ai(Gs,p):p,this.$target=c,this.html=c&&c.innerHTML,this.lines=[],this.words=[],this.chars=[],this.effects=[],this.effectsCleanups=[],this.cache=null,this.ready=!1,this.width=0,this.resizeTimeout=null;const m=()=>this.html&&(d||u||p)&&this.split();this.resizeObserver=new ResizeObserver(()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{const t=c.offsetWidth;t!==this.width&&(this.width=t,m())},150)}),this.lineTemplate&&!this.ready?i.fonts.ready.then(m):m(),c?this.resizeObserver.observe(c):console.warn("No Text Splitter target found.")}addEffect(t){if(!I(t))return console.warn("Effect must return a function.");const e=es(t);return this.effects.push(e),this.ready&&(this.effectsCleanups[this.effects.length-1]=e(this)),this}revert(){return clearTimeout(this.resizeTimeout),this.lines.length=this.words.length=this.chars.length=0,this.resizeObserver.disconnect(),this.effectsCleanups.forEach(t=>I(t)?t(this):t.revert&&t.revert()),this.$target.innerHTML=this.html,this}splitNode(t){const e=this.wordTemplate,s=this.charTemplate,r=this.includeSpaces,n=this.debug,o=t.nodeType;if(3===o){const o=t.nodeValue;if(o.trim()){const a=[],h=this.words,l=this.chars,c=Js.segment(o),d=i.createDocumentFragment();let u=null;for(const t of c){const e=t.segment,s=ei(t);if(!u||s&&u&&ei(u))a.push(e);else{const t=a.length-1;a[t].includes(" ")||e.includes(" ")?a.push(e):a[t]+=e}u=t}for(let t=0,o=a.length;t<o;t++){const o=a[t];if(o.trim()){const c=a[t+1],u=r&&c&&!c.trim(),p=o,m=s?Ks.segment(p):null,f=s?i.createDocumentFragment():i.createTextNode(u?o+" ":o);if(s){const t=[...m];for(let e=0,r=t.length;e<r;e++){const o=t[e],a=e===r-1&&u?o.segment+" ":o.segment,c=i.createTextNode(a);hi(s,l,c,f,Gs,n,-1,h.length,l.length)}}e?hi(e,h,f,d,Qs,n,-1,h.length,l.length):s?d.appendChild(f):d.appendChild(i.createTextNode(o)),u&&t++}else{if(t&&r)continue;d.appendChild(i.createTextNode(o))}}t.parentNode.replaceChild(d,t)}}else if(1===o){const e=[...t.childNodes];for(let t=0,s=e.length;t<s;t++)this.splitNode(e[t])}}split(t=!1){const e=this.$target,s=!!this.cache&&!t,r=this.lineTemplate,n=this.wordTemplate,o=this.charTemplate,a="loading"!==i.fonts.status,h=r&&a;this.ready=!r||a,(h||t)&&this.effectsCleanups.forEach(t=>I(t)&&t(this)),s||(t&&(e.innerHTML=this.html,this.words.length=this.chars.length=0),this.splitNode(e),this.cache=e.innerHTML),h&&(s&&(e.innerHTML=this.cache),this.lines.length=0,n&&(this.words=ii(e,Qs))),o&&(h||n)&&(this.chars=ii(e,Gs));const l=this.words.length?this.words:this.chars;let c,d=0;for(let t=0,e=l.length;t<e;t++){const e=l[t],{top:s,height:i}=e.getBoundingClientRect();c&&s-c>.5*i&&d++,e.setAttribute(Zs,`${d}`);const r=e.querySelectorAll(`[${Zs}]`);let n=r.length;for(;n--;)r[n].setAttribute(Zs,`${d}`);c=s}if(h){const t=i.createDocumentFragment(),s=new Set,a=[];for(let t=0;t<d+1;t++){const i=e.cloneNode(!0);oi(i,t,new Set).forEach(t=>{const e=t.parentElement;e&&s.add(e),t.remove()}),a.push(i)}s.forEach(ni);for(let e=0,s=a.length;e<s;e++)hi(r,this.lines,a[e],t,js,this.debug,e);e.innerHTML="",e.appendChild(t),n&&(this.words=ii(e,Qs)),o&&(this.chars=ii(e,Gs))}if(this.linesOnly){const t=this.words;let e=t.length;for(;e--;){const s=t[e];s.replaceWith(s.textContent)}t.length=0}if(this.accessible&&(h||!s)){const t=i.createElement("span");t.style.cssText="position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;",t.innerHTML=this.html,e.insertBefore(t,e.firstChild),this.lines.forEach(si),this.words.forEach(si),this.chars.forEach(si)}return this.width=e.offsetWidth,(h||t)&&this.effects.forEach((t,e)=>this.effectsCleanups[e]=t(this)),this}refresh(){this.split(!0)}}const ci=(t,e)=>new li(t,e),di=(t,e)=>(console.warn("text.split() is deprecated, import splitText() directly, or text.splitText()"),new li(t,e));var ui=Object.freeze({__proto__:null,TextSplitter:li,split:di,splitText:ci});const pi=(t,e=100)=>{const s=[];for(let i=0;i<=e;i++)s.push(t(i/e));return`linear(${s.join(", ")})`},mi={in:"ease-in",out:"ease-out",inOut:"ease-in-out"},fi=(()=>{const t={};for(let e in ce)t[e]=t=>ce[e](le(t));return t})(),gi=t=>{let e=mi[t];if(e)return e;if(e="linear",z(t)){if(O(t,"linear")||O(t,"cubic-")||O(t,"steps")||O(t,"ease"))e=t;else if(O(t,"cubicB"))e=N(t);else{const s=de(t,fi,mi);I(s)&&(e=s===he?"linear":pi(s))}mi[t]=e}else if(I(t)){const s=pi(t);s&&(e=s)}else t.ease&&(e=pi(t.ease));return e},_i=["x","y","z"],yi=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",..._i],vi=(()=>[..._i,...g.filter(t=>["X","Y","Z"].some(e=>t.endsWith(e)))])();let bi=null;const Ti=(t,e,s,i,r)=>{let n=wt(e,s,i,r);return M(n)?yi.includes(t)||O(t,"translate")?`${n}px`:O(t,"rotate")||O(t,"skew")?`${n}deg`:`${n}`:n},Si=(t,e,s,i,r,n)=>{let o="0";const a=Y(i)?getComputedStyle(t)[e]:Ti(e,i,t,r,n);return o=Y(s)?P(i)?i.map(s=>Ti(e,s,t,r,n)):a:[Ti(e,s,t,r,n),a],o};class wi{constructor(t,s){D.current&&D.current.register(this),X(bi)&&(!e||!Y(CSS)&&Object.hasOwnProperty.call(CSS,"registerProperty")?(g.forEach(t=>{const e=O(t,"skew"),s=O(t,"scale"),i=O(t,"rotate"),r=O(t,"translate"),n=i||e,o=n?"<angle>":s?"<number>":r?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:o,inherits:!1,initialValue:r?"0px":n?"0deg":s?"1":"0"})}catch{}}),bi=!0):bi=!1);const i=re(t),r=i.length;r||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation.");const n=St(s.ease,gi(L.defaults.ease)),o=n.ease&&n,a=St(s.autoplay,L.defaults.autoplay),l=!(!a||!a.link)&&a,c=s.alternate&&!0===s.alternate,d=s.reversed&&!0===s.reversed,u=St(s.loop,L.defaults.loop),v=!0===u||u===1/0?1/0:M(u)?u+1:1,b=c?d?"alternate-reverse":"alternate":d?"reverse":"normal",T=gi(n),S=1===L.timeScale?1:p;this.targets=i,this.animations=[],this.controlAnimation=null,this.onComplete=s.onComplete||y,this.duration=0,this.muteCallbacks=!1,this.completed=!1,this.paused=!a||!1!==l,this.reversed=d,this.autoplay=a,this._speed=St(s.playbackRate,L.defaults.playbackRate),this._resolve=y,this._completed=0,this._inlineStyles=i.map(t=>t.getAttribute("style")),i.forEach((t,e)=>{const i=t[h],a=vi.some(t=>s.hasOwnProperty(t)),l=(o?o.duration:wt(St(s.duration,L.defaults.duration),t,e,r))*S,c=wt(St(s.delay,L.defaults.delay),t,e,r)*S,d=St(s.composition,"replace");for(let o in s){if(!q(o))continue;const h={},u={iterations:v,direction:b,fill:"forwards",easing:T,duration:l,delay:c,composite:d},p=s[o],m=!!a&&(g.includes(o)?o:f.get(o));let _;if(R(p)){const s=p,a=St(s.ease,n),f=a.ease&&a,g=s.to,y=s.from;if(u.duration=(f?f.duration:wt(St(s.duration,l),t,e,r))*S,u.delay=wt(St(s.delay,c),t,e,r)*S,u.composite=St(s.composition,d),u.easing=gi(a),_=Si(t,o,y,g,e,r),m?(h[`--${m}`]=_,i[m]=_):h[o]=Si(t,o,y,g,e,r),Fe(this,t,o,h,u),!Y(y))if(m){const e=`--${m}`;t.style.setProperty(e,h[e][0])}else t.style[o]=h[o][0]}else _=P(p)?p.map(s=>Ti(o,s,t,e,r)):Ti(o,p,t,e,r),m?(h[`--${m}`]=_,i[m]=_):h[o]=_,Fe(this,t,o,h,u)}if(a){let e=m;for(let t in i)e+=`${_[t]}var(--${t})) `;t.style.transform=e}}),l&&this.autoplay.link(this)}forEach(t){const e=z(t)?e=>e[t]():t;return this.animations.forEach(e),this}get speed(){return this._speed}set speed(t){this._speed=+t,this.forEach(e=>e.playbackRate=t)}get currentTime(){const t=this.controlAnimation,e=L.timeScale;return this.completed?this.duration:t?+t.currentTime*(1===e?1:e):0}set currentTime(t){const e=t*(1===L.timeScale?1:p);this.forEach(t=>{e>=this.duration&&t.play(),t.currentTime=e})}get progress(){return this.currentTime/this.duration}set progress(t){this.forEach(e=>e.currentTime=t*this.duration||0)}resume(){return this.paused?(this.paused=!1,this.forEach("play")):this}pause(){return this.paused?this:(this.paused=!0,this.forEach("pause"))}alternate(){return this.reversed=!this.reversed,this.forEach("reverse"),this.paused&&this.forEach("pause"),this}play(){return this.reversed&&this.alternate(),this.resume()}reverse(){return this.reversed||this.alternate(),this.resume()}seek(t,e=!1){return e&&(this.muteCallbacks=!0),t<this.duration&&(this.completed=!1),this.currentTime=t,this.muteCallbacks=!1,this.paused&&this.pause(),this}restart(){return this.completed=!1,this.seek(0,!0).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){return this.forEach("cancel"),this.pause()}revert(){return this.cancel(),this.targets.forEach((t,e)=>t.setAttribute("style",this._inlineStyles[e])),this}then(t=y){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=y};return new Promise(t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this))}}const xi={animate:(t,e)=>new wi(t,e),convertEase:pi};t.$=re,t.Animatable=Xe,t.Draggable=Ke,t.JSAnimation=Ae,t.Scope=ss,t.ScrollObserver=ds,t.Spring=Ue,t.TextSplitter=li,t.Timeline=Ye,t.Timer=ee,t.WAAPIAnimation=wi,t.animate=(t,e)=>new Ae(t,e,null,0,!1).init(),t.clamp=ks,t.cleanInlineStyles=Ft,t.createAnimatable=(t,e)=>new Xe(t,e),t.createDraggable=(t,e)=>new Ke(t,e),t.createDrawable=Is,t.createMotionPath=zs,t.createScope=t=>new ss(t),t.createSeededRandom=Ls,t.createSpring=qe,t.createTimeline=t=>new Ye(t).init(),t.createTimer=t=>new ee(t,null,0).init(),t.cubicBezier=pe,t.damp=Cs,t.degToRad=Ss,t.eases=be,t.easings=us,t.engine=Yt,t.get=Pe,t.irregular=ge,t.keepTime=es,t.lerp=Es,t.linear=fe,t.mapRange=Ts,t.morphTo=Ys,t.none=he,t.onScroll=(t={})=>new ds(t),t.padEnd=vs,t.padStart=ys,t.radToDeg=ws,t.random=Bs,t.randomPick=As,t.remove=Me,t.round=$s,t.roundPad=_s,t.scrollContainers=rs,t.set=Re,t.shuffle=Ns,t.snap=xs,t.split=di,t.splitText=ci,t.stagger=Os,t.steps=me,t.svg=Xs,t.sync=ts,t.text=ui,t.utils=Fs,t.waapi=xi,t.wrap=bs});
diff --git a/dist/modules/animatable/animatable.cjs b/dist/modules/animatable/animatable.cjs
new file mode 100644
index 00000000..83eee4fa
--- /dev/null
+++ b/dist/modules/animatable/animatable.cjs
@@ -0,0 +1,150 @@
+/**
+ * Anime.js - animatable - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var globals = require('../core/globals.cjs');
+var helpers = require('../core/helpers.cjs');
+var animation = require('../animation/animation.cjs');
+var eases = require('../easings/eases.cjs');
+
+/**
+ * @import {
+ * TargetsParam,
+ * AnimatableParams,
+ * AnimationParams,
+ * TweenParamsOptions,
+ * Tween,
+ * AnimatableProperty,
+ * AnimatableObject,
+ * } from '../types/index.js';
+ */
+
+class Animatable {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ */
+ constructor(targets, parameters) {
+ if (globals.scope.current) globals.scope.current.register(this);
+ const beginHandler = () => {
+ if (this.callbacks.completed) this.callbacks.reset();
+ this.callbacks.play();
+ };
+ const pauseHandler = () => {
+ if (this.callbacks.completed) return;
+ let paused = true;
+ for (let name in this.animations) {
+ const anim = this.animations[name];
+ if (!anim.paused && paused) {
+ paused = false;
+ break;
+ }
+ }
+ if (paused) {
+ this.callbacks.complete();
+ }
+ };
+ /** @type {AnimationParams} */
+ const globalParams = {
+ onBegin: beginHandler,
+ onComplete: pauseHandler,
+ onPause: pauseHandler,
+ };
+ /** @type {AnimationParams} */
+ const callbacksAnimationParams = { v: 1, autoplay: false };
+ const properties = {};
+ this.targets = [];
+ this.animations = {};
+ /** @type {JSAnimation|null} */
+ this.callbacks = null;
+ if (helpers.isUnd(targets) || helpers.isUnd(parameters)) return;
+ for (let propName in parameters) {
+ const paramValue = parameters[propName];
+ if (helpers.isKey(propName)) {
+ properties[propName] = paramValue;
+ } else if (helpers.stringStartsWith(propName, 'on')) {
+ callbacksAnimationParams[propName] = paramValue;
+ } else {
+ globalParams[propName] = paramValue;
+ }
+ }
+ this.callbacks = new animation.JSAnimation({ v: 0 }, callbacksAnimationParams);
+ for (let propName in properties) {
+ const propValue = properties[propName];
+ const isObjValue = helpers.isObj(propValue);
+ /** @type {TweenParamsOptions} */
+ let propParams = {};
+ let to = '+=0';
+ if (isObjValue) {
+ const unit = propValue.unit;
+ if (helpers.isStr(unit)) to += unit;
+ } else {
+ propParams.duration = propValue;
+ }
+ propParams[propName] = isObjValue ? helpers.mergeObjects({ to }, propValue) : to;
+ const animParams = helpers.mergeObjects(globalParams, propParams);
+ animParams.composition = consts.compositionTypes.replace;
+ animParams.autoplay = false;
+ const animation$1 = this.animations[propName] = new animation.JSAnimation(targets, animParams, null, 0, false).init();
+ if (!this.targets.length) this.targets.push(...animation$1.targets);
+ /** @type {AnimatableProperty} */
+ this[propName] = (to, duration, ease) => {
+ const tween = /** @type {Tween} */(animation$1._head);
+ if (helpers.isUnd(to) && tween) {
+ const numbers = tween._numbers;
+ if (numbers && numbers.length) {
+ return numbers;
+ } else {
+ return tween._modifier(tween._number);
+ }
+ } else {
+ helpers.forEachChildren(animation$1, (/** @type {Tween} */tween) => {
+ if (helpers.isArr(to)) {
+ for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) {
+ if (!helpers.isUnd(tween._numbers[i])) {
+ tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i]));
+ tween._toNumbers[i] = to[i];
+ }
+ }
+ } else {
+ tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number));
+ tween._toNumber = /** @type {Number} */(to);
+ }
+ if (!helpers.isUnd(ease)) tween._ease = eases.parseEase(ease);
+ tween._currentTime = 0;
+ });
+ if (!helpers.isUnd(duration)) animation$1.stretch(duration);
+ animation$1.reset(1).resume();
+ return this;
+ }
+ };
+ }
+ }
+
+ revert() {
+ for (let propName in this.animations) {
+ this[propName] = consts.noop;
+ this.animations[propName].revert();
+ }
+ this.animations = {};
+ this.targets.length = 0;
+ if (this.callbacks) this.callbacks.revert();
+ return this;
+ }
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ * @return {AnimatableObject}
+ */
+const createAnimatable = (targets, parameters) => /** @type {AnimatableObject} */ (new Animatable(targets, parameters));
+
+exports.Animatable = Animatable;
+exports.createAnimatable = createAnimatable;
diff --git a/dist/modules/animatable/animatable.d.ts b/dist/modules/animatable/animatable.d.ts
new file mode 100644
index 00000000..7a18f83c
--- /dev/null
+++ b/dist/modules/animatable/animatable.d.ts
@@ -0,0 +1,28 @@
+/**
+ * @import {
+ * TargetsParam,
+ * AnimatableParams,
+ * AnimationParams,
+ * TweenParamsOptions,
+ * Tween,
+ * AnimatableProperty,
+ * AnimatableObject,
+ * } from '../types/index.js';
+ */
+export class Animatable {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ */
+ constructor(targets: TargetsParam, parameters: AnimatableParams);
+ targets: (HTMLElement | SVGElement | import("../types/index.js").JSTarget)[];
+ animations: {};
+ /** @type {JSAnimation|null} */
+ callbacks: JSAnimation | null;
+ revert(): this;
+}
+export function createAnimatable(targets: TargetsParam, parameters: AnimatableParams): AnimatableObject;
+import { JSAnimation } from '../animation/animation.js';
+import type { TargetsParam } from '../types/index.js';
+import type { AnimatableParams } from '../types/index.js';
+import type { AnimatableObject } from '../types/index.js';
diff --git a/dist/modules/animatable/animatable.js b/dist/modules/animatable/animatable.js
new file mode 100644
index 00000000..44385b0f
--- /dev/null
+++ b/dist/modules/animatable/animatable.js
@@ -0,0 +1,147 @@
+/**
+ * Anime.js - animatable - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { compositionTypes, noop } from '../core/consts.js';
+import { scope } from '../core/globals.js';
+import { isUnd, isKey, stringStartsWith, isObj, mergeObjects, forEachChildren, isStr, isArr } from '../core/helpers.js';
+import { JSAnimation } from '../animation/animation.js';
+import { parseEase } from '../easings/eases.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * AnimatableParams,
+ * AnimationParams,
+ * TweenParamsOptions,
+ * Tween,
+ * AnimatableProperty,
+ * AnimatableObject,
+ * } from '../types/index.js';
+ */
+
+class Animatable {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ */
+ constructor(targets, parameters) {
+ if (scope.current) scope.current.register(this);
+ const beginHandler = () => {
+ if (this.callbacks.completed) this.callbacks.reset();
+ this.callbacks.play();
+ };
+ const pauseHandler = () => {
+ if (this.callbacks.completed) return;
+ let paused = true;
+ for (let name in this.animations) {
+ const anim = this.animations[name];
+ if (!anim.paused && paused) {
+ paused = false;
+ break;
+ }
+ }
+ if (paused) {
+ this.callbacks.complete();
+ }
+ };
+ /** @type {AnimationParams} */
+ const globalParams = {
+ onBegin: beginHandler,
+ onComplete: pauseHandler,
+ onPause: pauseHandler,
+ };
+ /** @type {AnimationParams} */
+ const callbacksAnimationParams = { v: 1, autoplay: false };
+ const properties = {};
+ this.targets = [];
+ this.animations = {};
+ /** @type {JSAnimation|null} */
+ this.callbacks = null;
+ if (isUnd(targets) || isUnd(parameters)) return;
+ for (let propName in parameters) {
+ const paramValue = parameters[propName];
+ if (isKey(propName)) {
+ properties[propName] = paramValue;
+ } else if (stringStartsWith(propName, 'on')) {
+ callbacksAnimationParams[propName] = paramValue;
+ } else {
+ globalParams[propName] = paramValue;
+ }
+ }
+ this.callbacks = new JSAnimation({ v: 0 }, callbacksAnimationParams);
+ for (let propName in properties) {
+ const propValue = properties[propName];
+ const isObjValue = isObj(propValue);
+ /** @type {TweenParamsOptions} */
+ let propParams = {};
+ let to = '+=0';
+ if (isObjValue) {
+ const unit = propValue.unit;
+ if (isStr(unit)) to += unit;
+ } else {
+ propParams.duration = propValue;
+ }
+ propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to;
+ const animParams = mergeObjects(globalParams, propParams);
+ animParams.composition = compositionTypes.replace;
+ animParams.autoplay = false;
+ const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init();
+ if (!this.targets.length) this.targets.push(...animation.targets);
+ /** @type {AnimatableProperty} */
+ this[propName] = (to, duration, ease) => {
+ const tween = /** @type {Tween} */(animation._head);
+ if (isUnd(to) && tween) {
+ const numbers = tween._numbers;
+ if (numbers && numbers.length) {
+ return numbers;
+ } else {
+ return tween._modifier(tween._number);
+ }
+ } else {
+ forEachChildren(animation, (/** @type {Tween} */tween) => {
+ if (isArr(to)) {
+ for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) {
+ if (!isUnd(tween._numbers[i])) {
+ tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i]));
+ tween._toNumbers[i] = to[i];
+ }
+ }
+ } else {
+ tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number));
+ tween._toNumber = /** @type {Number} */(to);
+ }
+ if (!isUnd(ease)) tween._ease = parseEase(ease);
+ tween._currentTime = 0;
+ });
+ if (!isUnd(duration)) animation.stretch(duration);
+ animation.reset(1).resume();
+ return this;
+ }
+ };
+ }
+ }
+
+ revert() {
+ for (let propName in this.animations) {
+ this[propName] = noop;
+ this.animations[propName].revert();
+ }
+ this.animations = {};
+ this.targets.length = 0;
+ if (this.callbacks) this.callbacks.revert();
+ return this;
+ }
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {AnimatableParams} parameters
+ * @return {AnimatableObject}
+ */
+const createAnimatable = (targets, parameters) => /** @type {AnimatableObject} */ (new Animatable(targets, parameters));
+
+export { Animatable, createAnimatable };
diff --git a/dist/modules/animatable/index.cjs b/dist/modules/animatable/index.cjs
new file mode 100644
index 00000000..50967488
--- /dev/null
+++ b/dist/modules/animatable/index.cjs
@@ -0,0 +1,15 @@
+/**
+ * Anime.js - animatable - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var animatable = require('./animatable.cjs');
+
+
+
+exports.Animatable = animatable.Animatable;
+exports.createAnimatable = animatable.createAnimatable;
diff --git a/dist/modules/animatable/index.d.ts b/dist/modules/animatable/index.d.ts
new file mode 100644
index 00000000..f79ab63d
--- /dev/null
+++ b/dist/modules/animatable/index.d.ts
@@ -0,0 +1 @@
+export * from "./animatable.js";
diff --git a/dist/modules/animatable/index.js b/dist/modules/animatable/index.js
new file mode 100644
index 00000000..aea24004
--- /dev/null
+++ b/dist/modules/animatable/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - animatable - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { Animatable, createAnimatable } from './animatable.js';
diff --git a/dist/modules/animation/additive.cjs b/dist/modules/animation/additive.cjs
new file mode 100644
index 00000000..3a90c9eb
--- /dev/null
+++ b/dist/modules/animation/additive.cjs
@@ -0,0 +1,82 @@
+/**
+ * Anime.js - animation - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var render = require('../core/render.cjs');
+
+const additive = {
+ animation: null,
+ update: consts.noop,
+};
+
+/**
+ * @import {
+ * Tween,
+ * TweenAdditiveLookups,
+ * } from '../types/index.js'
+ */
+
+/**
+ * @typedef AdditiveAnimation
+ * @property {Number} duration
+ * @property {Number} _offset
+ * @property {Number} _delay
+ * @property {Tween} _head
+ * @property {Tween} _tail
+ */
+
+/**
+ * @param {TweenAdditiveLookups} lookups
+ * @return {AdditiveAnimation}
+ */
+const addAdditiveAnimation = lookups => {
+ let animation = additive.animation;
+ if (!animation) {
+ animation = {
+ duration: consts.minValue,
+ computeDeltaTime: consts.noop,
+ _offset: 0,
+ _delay: 0,
+ _head: null,
+ _tail: null,
+ };
+ additive.animation = animation;
+ additive.update = () => {
+ lookups.forEach(propertyAnimation => {
+ for (let propertyName in propertyAnimation) {
+ const tweens = propertyAnimation[propertyName];
+ const lookupTween = tweens._head;
+ if (lookupTween) {
+ const valueType = lookupTween._valueType;
+ const additiveValues = valueType === consts.valueTypes.COMPLEX || valueType === consts.valueTypes.COLOR ? helpers.cloneArray(lookupTween._fromNumbers) : null;
+ let additiveValue = lookupTween._fromNumber;
+ let tween = tweens._tail;
+ while (tween && tween !== lookupTween) {
+ if (additiveValues) {
+ for (let i = 0, l = tween._numbers.length; i < l; i++) additiveValues[i] += tween._numbers[i];
+ } else {
+ additiveValue += tween._number;
+ }
+ tween = tween._prevAdd;
+ }
+ lookupTween._toNumber = additiveValue;
+ lookupTween._toNumbers = additiveValues;
+ }
+ }
+ });
+ // TODO: Avoid polymorphism here, idealy the additive animation should be a regular animation with a higher priority in the render loop
+ render.render(animation, 1, 1, 0, consts.tickModes.FORCE);
+ };
+ }
+ return animation;
+};
+
+exports.addAdditiveAnimation = addAdditiveAnimation;
+exports.additive = additive;
diff --git a/dist/modules/animation/additive.d.ts b/dist/modules/animation/additive.d.ts
new file mode 100644
index 00000000..a44e8e2a
--- /dev/null
+++ b/dist/modules/animation/additive.d.ts
@@ -0,0 +1,15 @@
+export namespace additive {
+ export let animation: any;
+ export { noop as update };
+}
+export function addAdditiveAnimation(lookups: TweenAdditiveLookups): AdditiveAnimation;
+export type AdditiveAnimation = {
+ duration: number;
+ _offset: number;
+ _delay: number;
+ _head: Tween;
+ _tail: Tween;
+};
+import { noop } from '../core/consts.js';
+import type { TweenAdditiveLookups } from '../types/index.js';
+import type { Tween } from '../types/index.js';
diff --git a/dist/modules/animation/additive.js b/dist/modules/animation/additive.js
new file mode 100644
index 00000000..96934a9d
--- /dev/null
+++ b/dist/modules/animation/additive.js
@@ -0,0 +1,79 @@
+/**
+ * Anime.js - animation - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { noop, minValue, valueTypes, tickModes } from '../core/consts.js';
+import { cloneArray } from '../core/helpers.js';
+import { render } from '../core/render.js';
+
+const additive = {
+ animation: null,
+ update: noop,
+};
+
+/**
+ * @import {
+ * Tween,
+ * TweenAdditiveLookups,
+ * } from '../types/index.js'
+ */
+
+/**
+ * @typedef AdditiveAnimation
+ * @property {Number} duration
+ * @property {Number} _offset
+ * @property {Number} _delay
+ * @property {Tween} _head
+ * @property {Tween} _tail
+ */
+
+/**
+ * @param {TweenAdditiveLookups} lookups
+ * @return {AdditiveAnimation}
+ */
+const addAdditiveAnimation = lookups => {
+ let animation = additive.animation;
+ if (!animation) {
+ animation = {
+ duration: minValue,
+ computeDeltaTime: noop,
+ _offset: 0,
+ _delay: 0,
+ _head: null,
+ _tail: null,
+ };
+ additive.animation = animation;
+ additive.update = () => {
+ lookups.forEach(propertyAnimation => {
+ for (let propertyName in propertyAnimation) {
+ const tweens = propertyAnimation[propertyName];
+ const lookupTween = tweens._head;
+ if (lookupTween) {
+ const valueType = lookupTween._valueType;
+ const additiveValues = valueType === valueTypes.COMPLEX || valueType === valueTypes.COLOR ? cloneArray(lookupTween._fromNumbers) : null;
+ let additiveValue = lookupTween._fromNumber;
+ let tween = tweens._tail;
+ while (tween && tween !== lookupTween) {
+ if (additiveValues) {
+ for (let i = 0, l = tween._numbers.length; i < l; i++) additiveValues[i] += tween._numbers[i];
+ } else {
+ additiveValue += tween._number;
+ }
+ tween = tween._prevAdd;
+ }
+ lookupTween._toNumber = additiveValue;
+ lookupTween._toNumbers = additiveValues;
+ }
+ }
+ });
+ // TODO: Avoid polymorphism here, idealy the additive animation should be a regular animation with a higher priority in the render loop
+ render(animation, 1, 1, 0, tickModes.FORCE);
+ };
+ }
+ return animation;
+};
+
+export { addAdditiveAnimation, additive };
diff --git a/dist/modules/animation/animation.cjs b/dist/modules/animation/animation.cjs
new file mode 100644
index 00000000..dfb8be21
--- /dev/null
+++ b/dist/modules/animation/animation.cjs
@@ -0,0 +1,660 @@
+/**
+ * Anime.js - animation - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var globals = require('../core/globals.cjs');
+var targets = require('../core/targets.cjs');
+var values = require('../core/values.cjs');
+var styles = require('../core/styles.cjs');
+var units = require('../core/units.cjs');
+var eases = require('../easings/eases.cjs');
+var timer = require('../timer/timer.cjs');
+var composition = require('./composition.cjs');
+var additive = require('./additive.cjs');
+
+/**
+ * @import {
+ * Tween,
+ * TweenKeyValue,
+ * TweenParamsOptions,
+ * TweenValues,
+ * DurationKeyframes,
+ * PercentageKeyframes,
+ * AnimationParams,
+ * TweenPropValue,
+ * ArraySyntaxValue,
+ * TargetsParam,
+ * TimerParams,
+ * TweenParamValue,
+ * DOMTarget,
+ * TargetsArray,
+ * Callback,
+ * EasingFunction,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+ *
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+ */
+
+// Defines decomposed values target objects only once and mutate their properties later to avoid GC
+// TODO: Maybe move the objects creation to values.js and use the decompose function to create the base object
+const fromTargetObject = values.createDecomposedValueTargetObject();
+const toTargetObject = values.createDecomposedValueTargetObject();
+const toFunctionStore = { func: null };
+const keyframesTargetArray = [null];
+const fastSetValuesArray = [null, null];
+/** @type {TweenKeyValue} */
+const keyObjectTarget = { to: null };
+
+let tweenId = 0;
+let keyframes;
+/** @type {TweenParamsOptions & TweenValues} */
+let key;
+
+/**
+ * @param {DurationKeyframes | PercentageKeyframes} keyframes
+ * @param {AnimationParams} parameters
+ * @return {AnimationParams}
+ */
+const generateKeyframes = (keyframes, parameters) => {
+ /** @type {AnimationParams} */
+ const properties = {};
+ if (helpers.isArr(keyframes)) {
+ const propertyNames = [].concat(.../** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(helpers.isKey);
+ for (let i = 0, l = propertyNames.length; i < l; i++) {
+ const propName = propertyNames[i];
+ const propArray = /** @type {DurationKeyframes} */(keyframes).map(key => {
+ /** @type {TweenKeyValue} */
+ const newKey = {};
+ for (let p in key) {
+ const keyValue = /** @type {TweenPropValue} */(key[p]);
+ if (helpers.isKey(p)) {
+ if (p === propName) {
+ newKey.to = keyValue;
+ }
+ } else {
+ newKey[p] = keyValue;
+ }
+ }
+ return newKey;
+ });
+ properties[propName] = /** @type {ArraySyntaxValue} */(propArray);
+ }
+
+ } else {
+ const totalDuration = /** @type {Number} */(values.setValue(parameters.duration, globals.globals.defaults.duration));
+ const keys = Object.keys(keyframes)
+ .map(key => { return {o: parseFloat(key) / 100, p: keyframes[key]} })
+ .sort((a, b) => a.o - b.o);
+ keys.forEach(key => {
+ const offset = key.o;
+ const prop = key.p;
+ for (let name in prop) {
+ if (helpers.isKey(name)) {
+ let propArray = /** @type {Array} */(properties[name]);
+ if (!propArray) propArray = properties[name] = [];
+ const duration = offset * totalDuration;
+ let length = propArray.length;
+ let prevKey = propArray[length - 1];
+ const keyObj = { to: prop[name] };
+ let durProgress = 0;
+ for (let i = 0; i < length; i++) {
+ durProgress += propArray[i].duration;
+ }
+ if (length === 1) {
+ keyObj.from = prevKey.to;
+ }
+ if (prop.ease) {
+ keyObj.ease = prop.ease;
+ }
+ keyObj.duration = duration - (length ? durProgress : 0);
+ propArray.push(keyObj);
+ }
+ }
+ return key;
+ });
+
+ for (let name in properties) {
+ const propArray = /** @type {Array} */(properties[name]);
+ let prevEase;
+ // let durProgress = 0
+ for (let i = 0, l = propArray.length; i < l; i++) {
+ const prop = propArray[i];
+ // Emulate WAPPI easing parameter position
+ const currentEase = prop.ease;
+ prop.ease = prevEase ? prevEase : undefined;
+ prevEase = currentEase;
+ // durProgress += prop.duration;
+ // if (i === l - 1 && durProgress !== totalDuration) {
+ // propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress })
+ // }
+ }
+ if (!propArray[0].duration) {
+ propArray.shift();
+ }
+ }
+
+ }
+
+ return properties;
+};
+
+class JSAnimation extends timer.Timer {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {Timeline} [parent]
+ * @param {Number} [parentPosition]
+ * @param {Boolean} [fastSet=false]
+ * @param {Number} [index=0]
+ * @param {Number} [length=0]
+ */
+ constructor(
+ targets$1,
+ parameters,
+ parent,
+ parentPosition,
+ fastSet = false,
+ index = 0,
+ length = 0
+ ) {
+
+ super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
+
+ const parsedTargets = targets.registerTargets(targets$1);
+ const targetsLength = parsedTargets.length;
+
+ // If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties
+
+ const kfParams = /** @type {AnimationParams} */(parameters).keyframes;
+ const params = /** @type {AnimationParams} */(kfParams ? helpers.mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters);
+
+ const {
+ delay,
+ duration,
+ ease,
+ playbackEase,
+ modifier,
+ composition: composition$1,
+ onRender,
+ } = params;
+
+ const animDefaults = parent ? parent.defaults : globals.globals.defaults;
+ const animaPlaybackEase = values.setValue(playbackEase, animDefaults.playbackEase);
+ const animEase = animaPlaybackEase ? eases.parseEase(animaPlaybackEase) : null;
+ const hasSpring = !helpers.isUnd(ease) && !helpers.isUnd(/** @type {Spring} */(ease).ease);
+ const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : values.setValue(ease, animEase ? 'linear' : animDefaults.ease);
+ const tDuration = hasSpring ? /** @type {Spring} */(ease).duration : values.setValue(duration, animDefaults.duration);
+ const tDelay = values.setValue(delay, animDefaults.delay);
+ const tModifier = modifier || animDefaults.modifier;
+ // If no composition is defined and the targets length is high (>= 1000) set the composition to 'none' (0) for faster tween creation
+ const tComposition = helpers.isUnd(composition$1) && targetsLength >= consts.K ? consts.compositionTypes.none : !helpers.isUnd(composition$1) ? composition$1 : animDefaults.composition;
+ // TODO: Do not create an empty object until we know the animation will generate inline styles
+ const animInlineStyles = {};
+ // const absoluteOffsetTime = this._offset;
+ const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0);
+
+ let iterationDuration = NaN;
+ let iterationDelay = NaN;
+ let animationAnimationLength = 0;
+ let shouldTriggerRender = 0;
+
+ for (let targetIndex = 0; targetIndex < targetsLength; targetIndex++) {
+
+ const target = parsedTargets[targetIndex];
+ const ti = index || targetIndex;
+ const tl = length || targetsLength;
+
+ let lastTransformGroupIndex = NaN;
+ let lastTransformGroupLength = NaN;
+
+ for (let p in params) {
+
+ if (helpers.isKey(p)) {
+
+ const tweenType = values.getTweenType(target, p);
+
+ const propName = styles.sanitizePropertyName(p, target, tweenType);
+
+ let propValue = params[p];
+
+ const isPropValueArray = helpers.isArr(propValue);
+
+ if (fastSet && !isPropValueArray) {
+ fastSetValuesArray[0] = propValue;
+ fastSetValuesArray[1] = propValue;
+ propValue = fastSetValuesArray;
+ }
+
+ // TODO: Allow nested keyframes inside ObjectValue value (prop: { to: [.5, 1, .75, 2, 3] })
+ // Normalize property values to valid keyframe syntax:
+ // [x, y] to [{to: [x, y]}] or {to: x} to [{to: x}] or keep keys syntax [{}, {}, {}...]
+ // const keyframes = isArr(propValue) ? propValue.length === 2 && !isObj(propValue[0]) ? [{ to: propValue }] : propValue : [propValue];
+ if (isPropValueArray) {
+ const arrayLength = /** @type {Array} */(propValue).length;
+ const isNotObjectValue = !helpers.isObj(propValue[0]);
+ // Convert [x, y] to [{to: [x, y]}]
+ if (arrayLength === 2 && isNotObjectValue) {
+ keyObjectTarget.to = /** @type {TweenParamValue} */(/** @type {unknown} */(propValue));
+ keyframesTargetArray[0] = keyObjectTarget;
+ keyframes = keyframesTargetArray;
+ // Convert [x, y, z] to [[x, y], z]
+ } else if (arrayLength > 2 && isNotObjectValue) {
+ keyframes = [];
+ /** @type {Array.<Number>} */(propValue).forEach((v, i) => {
+ if (!i) {
+ fastSetValuesArray[0] = v;
+ } else if (i === 1) {
+ fastSetValuesArray[1] = v;
+ keyframes.push(fastSetValuesArray);
+ } else {
+ keyframes.push(v);
+ }
+ });
+ } else {
+ keyframes = /** @type {Array.<TweenKeyValue>} */(propValue);
+ }
+ } else {
+ keyframesTargetArray[0] = propValue;
+ keyframes = keyframesTargetArray;
+ }
+
+ let siblings = null;
+ let prevTween = null;
+ let firstTweenChangeStartTime = NaN;
+ let lastTweenChangeEndTime = 0;
+ let tweenIndex = 0;
+
+ for (let l = keyframes.length; tweenIndex < l; tweenIndex++) {
+
+ const keyframe = keyframes[tweenIndex];
+
+ if (helpers.isObj(keyframe)) {
+ key = keyframe;
+ } else {
+ keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe);
+ key = keyObjectTarget;
+ }
+
+ toFunctionStore.func = null;
+
+ const computedToValue = values.getFunctionValue(key.to, target, ti, tl, toFunctionStore);
+
+ let tweenToValue;
+ // Allows function based values to return an object syntax value ({to: v})
+ if (helpers.isObj(computedToValue) && !helpers.isUnd(computedToValue.to)) {
+ key = computedToValue;
+ tweenToValue = computedToValue.to;
+ } else {
+ tweenToValue = computedToValue;
+ }
+ const tweenFromValue = values.getFunctionValue(key.from, target, ti, tl);
+ const keyEasing = key.ease;
+ const hasSpring = !helpers.isUnd(keyEasing) && !helpers.isUnd(/** @type {Spring} */(keyEasing).ease);
+ // Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time
+ const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing || tEasing;
+ // Calculate default individual keyframe duration by dividing the tl of keyframes
+ const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).duration : values.getFunctionValue(values.setValue(key.duration, (l > 1 ? values.getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl);
+ // Default delay value should only be applied to the first tween
+ const tweenDelay = values.getFunctionValue(values.setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl);
+ const computedComposition = values.getFunctionValue(values.setValue(key.composition, tComposition), target, ti, tl);
+ const tweenComposition = helpers.isNum(computedComposition) ? computedComposition : consts.compositionTypes[computedComposition];
+ // Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper
+ const tweenModifier = key.modifier || tModifier;
+ const hasFromvalue = !helpers.isUnd(tweenFromValue);
+ const hasToValue = !helpers.isUnd(tweenToValue);
+ const isFromToArray = helpers.isArr(tweenToValue);
+ const isFromToValue = isFromToArray || (hasFromvalue && hasToValue);
+ const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay;
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const absoluteStartTime = helpers.round(absoluteOffsetTime + tweenStartTime, 12);
+
+ // Force a onRender callback if the animation contains at least one from value and autoplay is set to false
+ if (!shouldTriggerRender && (hasFromvalue || isFromToArray)) shouldTriggerRender = 1;
+
+ let prevSibling = prevTween;
+
+ if (tweenComposition !== consts.compositionTypes.none) {
+ if (!siblings) siblings = composition.getTweenSiblings(target, propName);
+ let nextSibling = siblings._head;
+ // Iterate trough all the next siblings until we find a sibling with an equal or inferior start time
+ while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) {
+ prevSibling = nextSibling;
+ nextSibling = nextSibling._nextRep;
+ // Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time
+ if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) {
+ while (nextSibling) {
+ composition.overrideTween(nextSibling);
+ // This will ends both the current while loop and the upper one once all the next sibllings have been overriden
+ nextSibling = nextSibling._nextRep;
+ }
+ }
+ }
+ }
+
+ // Decompose values
+ if (isFromToValue) {
+ values.decomposeRawValue(isFromToArray ? values.getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject);
+ values.decomposeRawValue(isFromToArray ? values.getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject);
+ if (fromTargetObject.t === consts.valueTypes.NUMBER) {
+ if (prevSibling) {
+ if (prevSibling._valueType === consts.valueTypes.UNIT) {
+ fromTargetObject.t = consts.valueTypes.UNIT;
+ fromTargetObject.u = prevSibling._unit;
+ }
+ } else {
+ values.decomposeRawValue(
+ values.getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles),
+ values.decomposedOriginalValue
+ );
+ if (values.decomposedOriginalValue.t === consts.valueTypes.UNIT) {
+ fromTargetObject.t = consts.valueTypes.UNIT;
+ fromTargetObject.u = values.decomposedOriginalValue.u;
+ }
+ }
+ }
+ } else {
+ if (hasToValue) {
+ values.decomposeRawValue(tweenToValue, toTargetObject);
+ } else {
+ if (prevTween) {
+ values.decomposeTweenValue(prevTween, toTargetObject);
+ } else {
+ // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
+ values.decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
+ values.getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), toTargetObject);
+ }
+ }
+ if (hasFromvalue) {
+ values.decomposeRawValue(tweenFromValue, fromTargetObject);
+ } else {
+ if (prevTween) {
+ values.decomposeTweenValue(prevTween, fromTargetObject);
+ } else {
+ values.decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
+ // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
+ values.getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), fromTargetObject);
+ }
+ }
+ }
+
+ // Apply operators
+ if (fromTargetObject.o) {
+ fromTargetObject.n = values.getRelativeValue(
+ !prevSibling ? values.decomposeRawValue(
+ values.getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles),
+ values.decomposedOriginalValue
+ ).n : prevSibling._toNumber,
+ fromTargetObject.n,
+ fromTargetObject.o
+ );
+ }
+
+ if (toTargetObject.o) {
+ toTargetObject.n = values.getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o);
+ }
+
+ // Values omogenisation in cases of type difference between "from" and "to"
+ if (fromTargetObject.t !== toTargetObject.t) {
+ if (fromTargetObject.t === consts.valueTypes.COMPLEX || toTargetObject.t === consts.valueTypes.COMPLEX) {
+ const complexValue = fromTargetObject.t === consts.valueTypes.COMPLEX ? fromTargetObject : toTargetObject;
+ const notComplexValue = fromTargetObject.t === consts.valueTypes.COMPLEX ? toTargetObject : fromTargetObject;
+ notComplexValue.t = consts.valueTypes.COMPLEX;
+ notComplexValue.s = helpers.cloneArray(complexValue.s);
+ notComplexValue.d = complexValue.d.map(() => notComplexValue.n);
+ } else if (fromTargetObject.t === consts.valueTypes.UNIT || toTargetObject.t === consts.valueTypes.UNIT) {
+ const unitValue = fromTargetObject.t === consts.valueTypes.UNIT ? fromTargetObject : toTargetObject;
+ const notUnitValue = fromTargetObject.t === consts.valueTypes.UNIT ? toTargetObject : fromTargetObject;
+ notUnitValue.t = consts.valueTypes.UNIT;
+ notUnitValue.u = unitValue.u;
+ } else if (fromTargetObject.t === consts.valueTypes.COLOR || toTargetObject.t === consts.valueTypes.COLOR) {
+ const colorValue = fromTargetObject.t === consts.valueTypes.COLOR ? fromTargetObject : toTargetObject;
+ const notColorValue = fromTargetObject.t === consts.valueTypes.COLOR ? toTargetObject : fromTargetObject;
+ notColorValue.t = consts.valueTypes.COLOR;
+ notColorValue.s = colorValue.s;
+ notColorValue.d = [0, 0, 0, 1];
+ }
+ }
+
+ // Unit conversion
+ if (fromTargetObject.u !== toTargetObject.u) {
+ let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject;
+ valueToConvert = units.convertValueUnit(/** @type {DOMTarget} */(target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false);
+ // TODO:
+ // convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u);
+ }
+
+ // Fill in non existing complex values
+ if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) {
+ const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject;
+ const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject;
+ // TODO: Check if n should be used instead of 0 for default complex values
+ shortestValue.d = longestValue.d.map((/** @type {Number} */_, /** @type {Number} */i) => helpers.isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
+ shortestValue.s = helpers.cloneArray(longestValue.s);
+ }
+
+ // Tween factory
+
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const tweenUpdateDuration = helpers.round(+tweenDuration || consts.minValue, 12);
+
+ /** @type {Tween} */
+ const tween = {
+ parent: this,
+ id: tweenId++,
+ property: propName,
+ target: target,
+ _value: null,
+ _func: toFunctionStore.func,
+ _ease: eases.parseEase(tweenEasing),
+ _fromNumbers: helpers.cloneArray(fromTargetObject.d),
+ _toNumbers: helpers.cloneArray(toTargetObject.d),
+ _strings: helpers.cloneArray(toTargetObject.s),
+ _fromNumber: fromTargetObject.n,
+ _toNumber: toTargetObject.n,
+ _numbers: helpers.cloneArray(fromTargetObject.d), // For additive tween and animatables
+ _number: fromTargetObject.n, // For additive tween and animatables
+ _unit: toTargetObject.u,
+ _modifier: tweenModifier,
+ _currentTime: 0,
+ _startTime: tweenStartTime,
+ _delay: +tweenDelay,
+ _updateDuration: tweenUpdateDuration,
+ _changeDuration: tweenUpdateDuration,
+ _absoluteStartTime: absoluteStartTime,
+ // NOTE: Investigate bit packing to stores ENUM / BOOL
+ _tweenType: tweenType,
+ _valueType: toTargetObject.t,
+ _composition: tweenComposition,
+ _isOverlapped: 0,
+ _isOverridden: 0,
+ _renderTransforms: 0,
+ _prevRep: null, // For replaced tween
+ _nextRep: null, // For replaced tween
+ _prevAdd: null, // For additive tween
+ _nextAdd: null, // For additive tween
+ _prev: null,
+ _next: null,
+ };
+
+ if (tweenComposition !== consts.compositionTypes.none) {
+ composition.composeTween(tween, siblings);
+ }
+
+ if (isNaN(firstTweenChangeStartTime)) {
+ firstTweenChangeStartTime = tween._startTime;
+ }
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ lastTweenChangeEndTime = helpers.round(tweenStartTime + tweenUpdateDuration, 12);
+ prevTween = tween;
+ animationAnimationLength++;
+
+ helpers.addChild(this, tween);
+
+ }
+
+ // Update animation timings with the added tweens properties
+
+ if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) {
+ iterationDelay = firstTweenChangeStartTime;
+ }
+
+ if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) {
+ iterationDuration = lastTweenChangeEndTime;
+ }
+
+ // TODO: Find a way to inline tween._renderTransforms = 1 here
+ if (tweenType === consts.tweenTypes.TRANSFORM) {
+ lastTransformGroupIndex = animationAnimationLength - tweenIndex;
+ lastTransformGroupLength = animationAnimationLength;
+ }
+
+ }
+
+ }
+
+ // Set _renderTransforms to last transform property to correctly render the transforms list
+ if (!isNaN(lastTransformGroupIndex)) {
+ let i = 0;
+ helpers.forEachChildren(this, (/** @type {Tween} */tween) => {
+ if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) {
+ tween._renderTransforms = 1;
+ if (tween._composition === consts.compositionTypes.blend) {
+ helpers.forEachChildren(additive.additive.animation, (/** @type {Tween} */additiveTween) => {
+ if (additiveTween.id === tween.id) {
+ additiveTween._renderTransforms = 1;
+ }
+ });
+ }
+ }
+ i++;
+ });
+ }
+
+ }
+
+ if (!targetsLength) {
+ console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
+ }
+
+ if (iterationDelay) {
+ helpers.forEachChildren(this, (/** @type {Tween} */tween) => {
+ // If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too
+ if (!(tween._startTime - tween._delay)) {
+ tween._delay -= iterationDelay;
+ }
+ tween._startTime -= iterationDelay;
+ });
+ iterationDuration -= iterationDelay;
+ } else {
+ iterationDelay = 0;
+ }
+
+ // Prevents iterationDuration to be NaN if no valid animatable props have been provided
+ // Prevents _iterationCount to be NaN if no valid animatable props have been provided
+ if (!iterationDuration) {
+ iterationDuration = consts.minValue;
+ this.iterationCount = 0;
+ }
+ /** @type {TargetsArray} */
+ this.targets = parsedTargets;
+ /** @type {Number} */
+ this.duration = iterationDuration === consts.minValue ? consts.minValue : helpers.clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || consts.minValue;
+ /** @type {Callback<this>} */
+ this.onRender = onRender || animDefaults.onRender;
+ /** @type {EasingFunction} */
+ this._ease = animEase;
+ /** @type {Number} */
+ this._delay = iterationDelay;
+ // NOTE: I'm keeping delay values separated from offsets in timelines because delays can override previous tweens and it could be confusing to debug a timeline with overridden tweens and no associated visible delays.
+ // this._delay = parent ? 0 : iterationDelay;
+ // this._offset += parent ? iterationDelay : 0;
+ /** @type {Number} */
+ this.iterationDuration = iterationDuration;
+ /** @type {{}} */
+ this._inlineStyles = animInlineStyles;
+
+ if (!this._autoplay && shouldTriggerRender) this.onRender(this);
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ if (currentDuration === helpers.normalizeTime(newDuration)) return this;
+ const timeScale = newDuration / currentDuration;
+ // NOTE: Find a better way to handle the stretch of an animation after stretch = 0
+ helpers.forEachChildren(this, (/** @type {Tween} */tween) => {
+ // Rounding is necessary here to minimize floating point errors
+ tween._updateDuration = helpers.normalizeTime(tween._updateDuration * timeScale);
+ tween._changeDuration = helpers.normalizeTime(tween._changeDuration * timeScale);
+ tween._currentTime *= timeScale;
+ tween._startTime *= timeScale;
+ tween._absoluteStartTime *= timeScale;
+ });
+ return super.stretch(newDuration);
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ helpers.forEachChildren(this, (/** @type {Tween} */tween) => {
+ const tweenFunc = tween._func;
+ if (tweenFunc) {
+ const ogValue = values.getOriginalAnimatableValue(tween.target, tween.property, tween._tweenType);
+ values.decomposeRawValue(ogValue, values.decomposedOriginalValue);
+ values.decomposeRawValue(tweenFunc(), toTargetObject);
+ tween._fromNumbers = helpers.cloneArray(values.decomposedOriginalValue.d);
+ tween._fromNumber = values.decomposedOriginalValue.n;
+ tween._toNumbers = helpers.cloneArray(toTargetObject.d);
+ tween._strings = helpers.cloneArray(toTargetObject.s);
+ // Make sure to apply relative operators https://github.com/juliangarnier/anime/issues/1025
+ tween._toNumber = toTargetObject.o ? values.getRelativeValue(values.decomposedOriginalValue.n, toTargetObject.n, toTargetObject.o) : toTargetObject.n;
+ }
+ });
+ return this;
+ }
+
+ /**
+ * Cancel the animation and revert all the values affected by this animation to their original state
+ * @return {this}
+ */
+ revert() {
+ super.revert();
+ return styles.cleanInlineStyles(this);
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback) {
+ return super.then(callback);
+ }
+
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @return {JSAnimation}
+ */
+const animate = (targets, parameters) => new JSAnimation(targets, parameters, null, 0, false).init();
+
+exports.JSAnimation = JSAnimation;
+exports.animate = animate;
diff --git a/dist/modules/animation/animation.d.ts b/dist/modules/animation/animation.d.ts
new file mode 100644
index 00000000..c5f060d0
--- /dev/null
+++ b/dist/modules/animation/animation.d.ts
@@ -0,0 +1,47 @@
+export class JSAnimation extends Timer {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {Timeline} [parent]
+ * @param {Number} [parentPosition]
+ * @param {Boolean} [fastSet=false]
+ * @param {Number} [index=0]
+ * @param {Number} [length=0]
+ */
+ constructor(targets: TargetsParam, parameters: AnimationParams, parent?: Timeline, parentPosition?: number, fastSet?: boolean, index?: number, length?: number);
+ /** @type {TargetsArray} */
+ targets: TargetsArray;
+ /** @type {Callback<this>} */
+ onRender: Callback<this>;
+ /** @type {EasingFunction} */
+ _ease: EasingFunction;
+ /** @type {{}} */
+ _inlineStyles: {};
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration: number): this;
+ /**
+ * @return {this}
+ */
+ refresh(): this;
+ /**
+ * Cancel the animation and revert all the values affected by this animation to their original state
+ * @return {this}
+ */
+ revert(): this;
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback?: Callback<this>): Promise<any>;
+}
+export function animate(targets: TargetsParam, parameters: AnimationParams): JSAnimation;
+import { Timer } from '../timer/timer.js';
+import type { TargetsArray } from '../types/index.js';
+import type { Callback } from '../types/index.js';
+import type { EasingFunction } from '../types/index.js';
+import type { TargetsParam } from '../types/index.js';
+import type { AnimationParams } from '../types/index.js';
+import type { Timeline } from '../timeline/timeline.js';
diff --git a/dist/modules/animation/animation.js b/dist/modules/animation/animation.js
new file mode 100644
index 00000000..327a5167
--- /dev/null
+++ b/dist/modules/animation/animation.js
@@ -0,0 +1,657 @@
+/**
+ * Anime.js - animation - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { K, compositionTypes, valueTypes, minValue, tweenTypes } from '../core/consts.js';
+import { mergeObjects, isUnd, isKey, isObj, round, cloneArray, addChild, forEachChildren, clampInfinity, normalizeTime, isArr, isNum } from '../core/helpers.js';
+import { globals } from '../core/globals.js';
+import { registerTargets } from '../core/targets.js';
+import { setValue, getTweenType, getFunctionValue, decomposeRawValue, createDecomposedValueTargetObject, getOriginalAnimatableValue, decomposedOriginalValue, getRelativeValue, decomposeTweenValue } from '../core/values.js';
+import { sanitizePropertyName, cleanInlineStyles } from '../core/styles.js';
+import { convertValueUnit } from '../core/units.js';
+import { parseEase } from '../easings/eases.js';
+import { Timer } from '../timer/timer.js';
+import { getTweenSiblings, overrideTween, composeTween } from './composition.js';
+import { additive } from './additive.js';
+
+/**
+ * @import {
+ * Tween,
+ * TweenKeyValue,
+ * TweenParamsOptions,
+ * TweenValues,
+ * DurationKeyframes,
+ * PercentageKeyframes,
+ * AnimationParams,
+ * TweenPropValue,
+ * ArraySyntaxValue,
+ * TargetsParam,
+ * TimerParams,
+ * TweenParamValue,
+ * DOMTarget,
+ * TargetsArray,
+ * Callback,
+ * EasingFunction,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+ *
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+ */
+
+// Defines decomposed values target objects only once and mutate their properties later to avoid GC
+// TODO: Maybe move the objects creation to values.js and use the decompose function to create the base object
+const fromTargetObject = createDecomposedValueTargetObject();
+const toTargetObject = createDecomposedValueTargetObject();
+const toFunctionStore = { func: null };
+const keyframesTargetArray = [null];
+const fastSetValuesArray = [null, null];
+/** @type {TweenKeyValue} */
+const keyObjectTarget = { to: null };
+
+let tweenId = 0;
+let keyframes;
+/** @type {TweenParamsOptions & TweenValues} */
+let key;
+
+/**
+ * @param {DurationKeyframes | PercentageKeyframes} keyframes
+ * @param {AnimationParams} parameters
+ * @return {AnimationParams}
+ */
+const generateKeyframes = (keyframes, parameters) => {
+ /** @type {AnimationParams} */
+ const properties = {};
+ if (isArr(keyframes)) {
+ const propertyNames = [].concat(.../** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(isKey);
+ for (let i = 0, l = propertyNames.length; i < l; i++) {
+ const propName = propertyNames[i];
+ const propArray = /** @type {DurationKeyframes} */(keyframes).map(key => {
+ /** @type {TweenKeyValue} */
+ const newKey = {};
+ for (let p in key) {
+ const keyValue = /** @type {TweenPropValue} */(key[p]);
+ if (isKey(p)) {
+ if (p === propName) {
+ newKey.to = keyValue;
+ }
+ } else {
+ newKey[p] = keyValue;
+ }
+ }
+ return newKey;
+ });
+ properties[propName] = /** @type {ArraySyntaxValue} */(propArray);
+ }
+
+ } else {
+ const totalDuration = /** @type {Number} */(setValue(parameters.duration, globals.defaults.duration));
+ const keys = Object.keys(keyframes)
+ .map(key => { return {o: parseFloat(key) / 100, p: keyframes[key]} })
+ .sort((a, b) => a.o - b.o);
+ keys.forEach(key => {
+ const offset = key.o;
+ const prop = key.p;
+ for (let name in prop) {
+ if (isKey(name)) {
+ let propArray = /** @type {Array} */(properties[name]);
+ if (!propArray) propArray = properties[name] = [];
+ const duration = offset * totalDuration;
+ let length = propArray.length;
+ let prevKey = propArray[length - 1];
+ const keyObj = { to: prop[name] };
+ let durProgress = 0;
+ for (let i = 0; i < length; i++) {
+ durProgress += propArray[i].duration;
+ }
+ if (length === 1) {
+ keyObj.from = prevKey.to;
+ }
+ if (prop.ease) {
+ keyObj.ease = prop.ease;
+ }
+ keyObj.duration = duration - (length ? durProgress : 0);
+ propArray.push(keyObj);
+ }
+ }
+ return key;
+ });
+
+ for (let name in properties) {
+ const propArray = /** @type {Array} */(properties[name]);
+ let prevEase;
+ // let durProgress = 0
+ for (let i = 0, l = propArray.length; i < l; i++) {
+ const prop = propArray[i];
+ // Emulate WAPPI easing parameter position
+ const currentEase = prop.ease;
+ prop.ease = prevEase ? prevEase : undefined;
+ prevEase = currentEase;
+ // durProgress += prop.duration;
+ // if (i === l - 1 && durProgress !== totalDuration) {
+ // propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress })
+ // }
+ }
+ if (!propArray[0].duration) {
+ propArray.shift();
+ }
+ }
+
+ }
+
+ return properties;
+};
+
+class JSAnimation extends Timer {
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {Timeline} [parent]
+ * @param {Number} [parentPosition]
+ * @param {Boolean} [fastSet=false]
+ * @param {Number} [index=0]
+ * @param {Number} [length=0]
+ */
+ constructor(
+ targets,
+ parameters,
+ parent,
+ parentPosition,
+ fastSet = false,
+ index = 0,
+ length = 0
+ ) {
+
+ super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
+
+ const parsedTargets = registerTargets(targets);
+ const targetsLength = parsedTargets.length;
+
+ // If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties
+
+ const kfParams = /** @type {AnimationParams} */(parameters).keyframes;
+ const params = /** @type {AnimationParams} */(kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters);
+
+ const {
+ delay,
+ duration,
+ ease,
+ playbackEase,
+ modifier,
+ composition,
+ onRender,
+ } = params;
+
+ const animDefaults = parent ? parent.defaults : globals.defaults;
+ const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
+ const animEase = animaPlaybackEase ? parseEase(animaPlaybackEase) : null;
+ const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
+ const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease);
+ const tDuration = hasSpring ? /** @type {Spring} */(ease).duration : setValue(duration, animDefaults.duration);
+ const tDelay = setValue(delay, animDefaults.delay);
+ const tModifier = modifier || animDefaults.modifier;
+ // If no composition is defined and the targets length is high (>= 1000) set the composition to 'none' (0) for faster tween creation
+ const tComposition = isUnd(composition) && targetsLength >= K ? compositionTypes.none : !isUnd(composition) ? composition : animDefaults.composition;
+ // TODO: Do not create an empty object until we know the animation will generate inline styles
+ const animInlineStyles = {};
+ // const absoluteOffsetTime = this._offset;
+ const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0);
+
+ let iterationDuration = NaN;
+ let iterationDelay = NaN;
+ let animationAnimationLength = 0;
+ let shouldTriggerRender = 0;
+
+ for (let targetIndex = 0; targetIndex < targetsLength; targetIndex++) {
+
+ const target = parsedTargets[targetIndex];
+ const ti = index || targetIndex;
+ const tl = length || targetsLength;
+
+ let lastTransformGroupIndex = NaN;
+ let lastTransformGroupLength = NaN;
+
+ for (let p in params) {
+
+ if (isKey(p)) {
+
+ const tweenType = getTweenType(target, p);
+
+ const propName = sanitizePropertyName(p, target, tweenType);
+
+ let propValue = params[p];
+
+ const isPropValueArray = isArr(propValue);
+
+ if (fastSet && !isPropValueArray) {
+ fastSetValuesArray[0] = propValue;
+ fastSetValuesArray[1] = propValue;
+ propValue = fastSetValuesArray;
+ }
+
+ // TODO: Allow nested keyframes inside ObjectValue value (prop: { to: [.5, 1, .75, 2, 3] })
+ // Normalize property values to valid keyframe syntax:
+ // [x, y] to [{to: [x, y]}] or {to: x} to [{to: x}] or keep keys syntax [{}, {}, {}...]
+ // const keyframes = isArr(propValue) ? propValue.length === 2 && !isObj(propValue[0]) ? [{ to: propValue }] : propValue : [propValue];
+ if (isPropValueArray) {
+ const arrayLength = /** @type {Array} */(propValue).length;
+ const isNotObjectValue = !isObj(propValue[0]);
+ // Convert [x, y] to [{to: [x, y]}]
+ if (arrayLength === 2 && isNotObjectValue) {
+ keyObjectTarget.to = /** @type {TweenParamValue} */(/** @type {unknown} */(propValue));
+ keyframesTargetArray[0] = keyObjectTarget;
+ keyframes = keyframesTargetArray;
+ // Convert [x, y, z] to [[x, y], z]
+ } else if (arrayLength > 2 && isNotObjectValue) {
+ keyframes = [];
+ /** @type {Array.<Number>} */(propValue).forEach((v, i) => {
+ if (!i) {
+ fastSetValuesArray[0] = v;
+ } else if (i === 1) {
+ fastSetValuesArray[1] = v;
+ keyframes.push(fastSetValuesArray);
+ } else {
+ keyframes.push(v);
+ }
+ });
+ } else {
+ keyframes = /** @type {Array.<TweenKeyValue>} */(propValue);
+ }
+ } else {
+ keyframesTargetArray[0] = propValue;
+ keyframes = keyframesTargetArray;
+ }
+
+ let siblings = null;
+ let prevTween = null;
+ let firstTweenChangeStartTime = NaN;
+ let lastTweenChangeEndTime = 0;
+ let tweenIndex = 0;
+
+ for (let l = keyframes.length; tweenIndex < l; tweenIndex++) {
+
+ const keyframe = keyframes[tweenIndex];
+
+ if (isObj(keyframe)) {
+ key = keyframe;
+ } else {
+ keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe);
+ key = keyObjectTarget;
+ }
+
+ toFunctionStore.func = null;
+
+ const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore);
+
+ let tweenToValue;
+ // Allows function based values to return an object syntax value ({to: v})
+ if (isObj(computedToValue) && !isUnd(computedToValue.to)) {
+ key = computedToValue;
+ tweenToValue = computedToValue.to;
+ } else {
+ tweenToValue = computedToValue;
+ }
+ const tweenFromValue = getFunctionValue(key.from, target, ti, tl);
+ const keyEasing = key.ease;
+ const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */(keyEasing).ease);
+ // Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time
+ const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing || tEasing;
+ // Calculate default individual keyframe duration by dividing the tl of keyframes
+ const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).duration : getFunctionValue(setValue(key.duration, (l > 1 ? getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl);
+ // Default delay value should only be applied to the first tween
+ const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl);
+ const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl);
+ const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition];
+ // Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper
+ const tweenModifier = key.modifier || tModifier;
+ const hasFromvalue = !isUnd(tweenFromValue);
+ const hasToValue = !isUnd(tweenToValue);
+ const isFromToArray = isArr(tweenToValue);
+ const isFromToValue = isFromToArray || (hasFromvalue && hasToValue);
+ const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay;
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const absoluteStartTime = round(absoluteOffsetTime + tweenStartTime, 12);
+
+ // Force a onRender callback if the animation contains at least one from value and autoplay is set to false
+ if (!shouldTriggerRender && (hasFromvalue || isFromToArray)) shouldTriggerRender = 1;
+
+ let prevSibling = prevTween;
+
+ if (tweenComposition !== compositionTypes.none) {
+ if (!siblings) siblings = getTweenSiblings(target, propName);
+ let nextSibling = siblings._head;
+ // Iterate trough all the next siblings until we find a sibling with an equal or inferior start time
+ while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) {
+ prevSibling = nextSibling;
+ nextSibling = nextSibling._nextRep;
+ // Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time
+ if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) {
+ while (nextSibling) {
+ overrideTween(nextSibling);
+ // This will ends both the current while loop and the upper one once all the next sibllings have been overriden
+ nextSibling = nextSibling._nextRep;
+ }
+ }
+ }
+ }
+
+ // Decompose values
+ if (isFromToValue) {
+ decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject);
+ decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject);
+ if (fromTargetObject.t === valueTypes.NUMBER) {
+ if (prevSibling) {
+ if (prevSibling._valueType === valueTypes.UNIT) {
+ fromTargetObject.t = valueTypes.UNIT;
+ fromTargetObject.u = prevSibling._unit;
+ }
+ } else {
+ decomposeRawValue(
+ getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles),
+ decomposedOriginalValue
+ );
+ if (decomposedOriginalValue.t === valueTypes.UNIT) {
+ fromTargetObject.t = valueTypes.UNIT;
+ fromTargetObject.u = decomposedOriginalValue.u;
+ }
+ }
+ }
+ } else {
+ if (hasToValue) {
+ decomposeRawValue(tweenToValue, toTargetObject);
+ } else {
+ if (prevTween) {
+ decomposeTweenValue(prevTween, toTargetObject);
+ } else {
+ // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
+ decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
+ getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), toTargetObject);
+ }
+ }
+ if (hasFromvalue) {
+ decomposeRawValue(tweenFromValue, fromTargetObject);
+ } else {
+ if (prevTween) {
+ decomposeTweenValue(prevTween, fromTargetObject);
+ } else {
+ decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
+ // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
+ getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), fromTargetObject);
+ }
+ }
+ }
+
+ // Apply operators
+ if (fromTargetObject.o) {
+ fromTargetObject.n = getRelativeValue(
+ !prevSibling ? decomposeRawValue(
+ getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles),
+ decomposedOriginalValue
+ ).n : prevSibling._toNumber,
+ fromTargetObject.n,
+ fromTargetObject.o
+ );
+ }
+
+ if (toTargetObject.o) {
+ toTargetObject.n = getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o);
+ }
+
+ // Values omogenisation in cases of type difference between "from" and "to"
+ if (fromTargetObject.t !== toTargetObject.t) {
+ if (fromTargetObject.t === valueTypes.COMPLEX || toTargetObject.t === valueTypes.COMPLEX) {
+ const complexValue = fromTargetObject.t === valueTypes.COMPLEX ? fromTargetObject : toTargetObject;
+ const notComplexValue = fromTargetObject.t === valueTypes.COMPLEX ? toTargetObject : fromTargetObject;
+ notComplexValue.t = valueTypes.COMPLEX;
+ notComplexValue.s = cloneArray(complexValue.s);
+ notComplexValue.d = complexValue.d.map(() => notComplexValue.n);
+ } else if (fromTargetObject.t === valueTypes.UNIT || toTargetObject.t === valueTypes.UNIT) {
+ const unitValue = fromTargetObject.t === valueTypes.UNIT ? fromTargetObject : toTargetObject;
+ const notUnitValue = fromTargetObject.t === valueTypes.UNIT ? toTargetObject : fromTargetObject;
+ notUnitValue.t = valueTypes.UNIT;
+ notUnitValue.u = unitValue.u;
+ } else if (fromTargetObject.t === valueTypes.COLOR || toTargetObject.t === valueTypes.COLOR) {
+ const colorValue = fromTargetObject.t === valueTypes.COLOR ? fromTargetObject : toTargetObject;
+ const notColorValue = fromTargetObject.t === valueTypes.COLOR ? toTargetObject : fromTargetObject;
+ notColorValue.t = valueTypes.COLOR;
+ notColorValue.s = colorValue.s;
+ notColorValue.d = [0, 0, 0, 1];
+ }
+ }
+
+ // Unit conversion
+ if (fromTargetObject.u !== toTargetObject.u) {
+ let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject;
+ valueToConvert = convertValueUnit(/** @type {DOMTarget} */(target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false);
+ // TODO:
+ // convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u);
+ }
+
+ // Fill in non existing complex values
+ if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) {
+ const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject;
+ const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject;
+ // TODO: Check if n should be used instead of 0 for default complex values
+ shortestValue.d = longestValue.d.map((/** @type {Number} */_, /** @type {Number} */i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
+ shortestValue.s = cloneArray(longestValue.s);
+ }
+
+ // Tween factory
+
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const tweenUpdateDuration = round(+tweenDuration || minValue, 12);
+
+ /** @type {Tween} */
+ const tween = {
+ parent: this,
+ id: tweenId++,
+ property: propName,
+ target: target,
+ _value: null,
+ _func: toFunctionStore.func,
+ _ease: parseEase(tweenEasing),
+ _fromNumbers: cloneArray(fromTargetObject.d),
+ _toNumbers: cloneArray(toTargetObject.d),
+ _strings: cloneArray(toTargetObject.s),
+ _fromNumber: fromTargetObject.n,
+ _toNumber: toTargetObject.n,
+ _numbers: cloneArray(fromTargetObject.d), // For additive tween and animatables
+ _number: fromTargetObject.n, // For additive tween and animatables
+ _unit: toTargetObject.u,
+ _modifier: tweenModifier,
+ _currentTime: 0,
+ _startTime: tweenStartTime,
+ _delay: +tweenDelay,
+ _updateDuration: tweenUpdateDuration,
+ _changeDuration: tweenUpdateDuration,
+ _absoluteStartTime: absoluteStartTime,
+ // NOTE: Investigate bit packing to stores ENUM / BOOL
+ _tweenType: tweenType,
+ _valueType: toTargetObject.t,
+ _composition: tweenComposition,
+ _isOverlapped: 0,
+ _isOverridden: 0,
+ _renderTransforms: 0,
+ _prevRep: null, // For replaced tween
+ _nextRep: null, // For replaced tween
+ _prevAdd: null, // For additive tween
+ _nextAdd: null, // For additive tween
+ _prev: null,
+ _next: null,
+ };
+
+ if (tweenComposition !== compositionTypes.none) {
+ composeTween(tween, siblings);
+ }
+
+ if (isNaN(firstTweenChangeStartTime)) {
+ firstTweenChangeStartTime = tween._startTime;
+ }
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12);
+ prevTween = tween;
+ animationAnimationLength++;
+
+ addChild(this, tween);
+
+ }
+
+ // Update animation timings with the added tweens properties
+
+ if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) {
+ iterationDelay = firstTweenChangeStartTime;
+ }
+
+ if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) {
+ iterationDuration = lastTweenChangeEndTime;
+ }
+
+ // TODO: Find a way to inline tween._renderTransforms = 1 here
+ if (tweenType === tweenTypes.TRANSFORM) {
+ lastTransformGroupIndex = animationAnimationLength - tweenIndex;
+ lastTransformGroupLength = animationAnimationLength;
+ }
+
+ }
+
+ }
+
+ // Set _renderTransforms to last transform property to correctly render the transforms list
+ if (!isNaN(lastTransformGroupIndex)) {
+ let i = 0;
+ forEachChildren(this, (/** @type {Tween} */tween) => {
+ if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) {
+ tween._renderTransforms = 1;
+ if (tween._composition === compositionTypes.blend) {
+ forEachChildren(additive.animation, (/** @type {Tween} */additiveTween) => {
+ if (additiveTween.id === tween.id) {
+ additiveTween._renderTransforms = 1;
+ }
+ });
+ }
+ }
+ i++;
+ });
+ }
+
+ }
+
+ if (!targetsLength) {
+ console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
+ }
+
+ if (iterationDelay) {
+ forEachChildren(this, (/** @type {Tween} */tween) => {
+ // If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too
+ if (!(tween._startTime - tween._delay)) {
+ tween._delay -= iterationDelay;
+ }
+ tween._startTime -= iterationDelay;
+ });
+ iterationDuration -= iterationDelay;
+ } else {
+ iterationDelay = 0;
+ }
+
+ // Prevents iterationDuration to be NaN if no valid animatable props have been provided
+ // Prevents _iterationCount to be NaN if no valid animatable props have been provided
+ if (!iterationDuration) {
+ iterationDuration = minValue;
+ this.iterationCount = 0;
+ }
+ /** @type {TargetsArray} */
+ this.targets = parsedTargets;
+ /** @type {Number} */
+ this.duration = iterationDuration === minValue ? minValue : clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || minValue;
+ /** @type {Callback<this>} */
+ this.onRender = onRender || animDefaults.onRender;
+ /** @type {EasingFunction} */
+ this._ease = animEase;
+ /** @type {Number} */
+ this._delay = iterationDelay;
+ // NOTE: I'm keeping delay values separated from offsets in timelines because delays can override previous tweens and it could be confusing to debug a timeline with overridden tweens and no associated visible delays.
+ // this._delay = parent ? 0 : iterationDelay;
+ // this._offset += parent ? iterationDelay : 0;
+ /** @type {Number} */
+ this.iterationDuration = iterationDuration;
+ /** @type {{}} */
+ this._inlineStyles = animInlineStyles;
+
+ if (!this._autoplay && shouldTriggerRender) this.onRender(this);
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ if (currentDuration === normalizeTime(newDuration)) return this;
+ const timeScale = newDuration / currentDuration;
+ // NOTE: Find a better way to handle the stretch of an animation after stretch = 0
+ forEachChildren(this, (/** @type {Tween} */tween) => {
+ // Rounding is necessary here to minimize floating point errors
+ tween._updateDuration = normalizeTime(tween._updateDuration * timeScale);
+ tween._changeDuration = normalizeTime(tween._changeDuration * timeScale);
+ tween._currentTime *= timeScale;
+ tween._startTime *= timeScale;
+ tween._absoluteStartTime *= timeScale;
+ });
+ return super.stretch(newDuration);
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ forEachChildren(this, (/** @type {Tween} */tween) => {
+ const tweenFunc = tween._func;
+ if (tweenFunc) {
+ const ogValue = getOriginalAnimatableValue(tween.target, tween.property, tween._tweenType);
+ decomposeRawValue(ogValue, decomposedOriginalValue);
+ decomposeRawValue(tweenFunc(), toTargetObject);
+ tween._fromNumbers = cloneArray(decomposedOriginalValue.d);
+ tween._fromNumber = decomposedOriginalValue.n;
+ tween._toNumbers = cloneArray(toTargetObject.d);
+ tween._strings = cloneArray(toTargetObject.s);
+ // Make sure to apply relative operators https://github.com/juliangarnier/anime/issues/1025
+ tween._toNumber = toTargetObject.o ? getRelativeValue(decomposedOriginalValue.n, toTargetObject.n, toTargetObject.o) : toTargetObject.n;
+ }
+ });
+ return this;
+ }
+
+ /**
+ * Cancel the animation and revert all the values affected by this animation to their original state
+ * @return {this}
+ */
+ revert() {
+ super.revert();
+ return cleanInlineStyles(this);
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback) {
+ return super.then(callback);
+ }
+
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @return {JSAnimation}
+ */
+const animate = (targets, parameters) => new JSAnimation(targets, parameters, null, 0, false).init();
+
+export { JSAnimation, animate };
diff --git a/dist/modules/animation/composition.cjs b/dist/modules/animation/composition.cjs
new file mode 100644
index 00000000..f86d3cb8
--- /dev/null
+++ b/dist/modules/animation/composition.cjs
@@ -0,0 +1,383 @@
+/**
+ * Anime.js - animation - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var styles = require('../core/styles.cjs');
+var engine = require('../engine/engine.cjs');
+var additive = require('./additive.cjs');
+
+/**
+ * @import {
+ * TweenReplaceLookups,
+ * TweenAdditiveLookups,
+ * TweenPropertySiblings,
+ * Tween,
+ * Target,
+ * TargetsArray,
+ * Renderable,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+const lookups = {
+ /** @type {TweenReplaceLookups} */
+ _rep: new WeakMap(),
+ /** @type {TweenAdditiveLookups} */
+ _add: new Map(),
+};
+
+/**
+ * @param {Target} target
+ * @param {String} property
+ * @param {String} lookup
+ * @return {TweenPropertySiblings}
+ */
+const getTweenSiblings = (target, property, lookup = '_rep') => {
+ const lookupMap = lookups[lookup];
+ let targetLookup = lookupMap.get(target);
+ if (!targetLookup) {
+ targetLookup = {};
+ lookupMap.set(target, targetLookup);
+ }
+ return targetLookup[property] ? targetLookup[property] : targetLookup[property] = {
+ _head: null,
+ _tail: null,
+ }
+};
+
+/**
+ * @param {Tween} p
+ * @param {Tween} c
+ * @return {Number|Boolean}
+ */
+const addTweenSortMethod = (p, c) => {
+ return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime;
+};
+
+/**
+ * @param {Tween} tween
+ */
+const overrideTween = tween => {
+ tween._isOverlapped = 1;
+ tween._isOverridden = 1;
+ tween._changeDuration = consts.minValue;
+ tween._currentTime = consts.minValue;
+};
+
+/**
+ * @param {Tween} tween
+ * @param {TweenPropertySiblings} siblings
+ * @return {Tween}
+ */
+const composeTween = (tween, siblings) => {
+
+ const tweenCompositionType = tween._composition;
+
+ // Handle replaced tweens
+
+ if (tweenCompositionType === consts.compositionTypes.replace) {
+
+ const tweenAbsStartTime = tween._absoluteStartTime;
+
+ helpers.addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep');
+
+ const prevSibling = tween._prevRep;
+
+ // Update the previous siblings for composition replace tweens
+
+ if (prevSibling) {
+
+ const prevParent = prevSibling.parent;
+ const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration;
+
+ // Handle looped animations tween
+
+ if (
+ // Check if the previous tween is from a different animation
+ tween.parent.id !== prevParent.id &&
+ // Check if the animation has loops
+ prevParent.iterationCount> 1 &&
+ // Check if _absoluteChangeEndTime of last loop overlaps the current tween
+ prevAbsEndTime + (prevParent.duration - prevParent.iterationDuration) > tweenAbsStartTime
+ ) {
+
+ // TODO: Find a way to only override the iterations overlapping with the tween
+ overrideTween(prevSibling);
+
+ let prevPrevSibling = prevSibling._prevRep;
+
+ // If the tween was part of a set of keyframes, override its siblings
+ while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) {
+ overrideTween(prevPrevSibling);
+ prevPrevSibling = prevPrevSibling._prevRep;
+ }
+
+ }
+
+ const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay;
+
+ if (prevAbsEndTime > absoluteUpdateStartTime) {
+
+ const prevChangeStartTime = prevSibling._startTime;
+ const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration);
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const updatedPrevChangeDuration = helpers.round(absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime, 12);
+
+ prevSibling._changeDuration = updatedPrevChangeDuration;
+ prevSibling._currentTime = updatedPrevChangeDuration;
+ prevSibling._isOverlapped = 1;
+
+ // Override the previous tween if its new _changeDuration is lower than minValue
+ // TODO: See if it's even neceseeary to test against minValue, checking for 0 might be enough
+ if (updatedPrevChangeDuration < consts.minValue) {
+ overrideTween(prevSibling);
+ }
+ }
+
+ // Pause (and cancel) the parent if it only contains overlapped tweens
+
+ let pausePrevParentAnimation = true;
+
+ helpers.forEachChildren(prevParent, (/** @type Tween */t) => {
+ if (!t._isOverlapped) pausePrevParentAnimation = false;
+ });
+
+ if (pausePrevParentAnimation) {
+ const prevParentTL = prevParent.parent;
+ if (prevParentTL) {
+ let pausePrevParentTL = true;
+ helpers.forEachChildren(prevParentTL, (/** @type JSAnimation */a) => {
+ if (a !== prevParent) {
+ helpers.forEachChildren(a, (/** @type Tween */t) => {
+ if (!t._isOverlapped) pausePrevParentTL = false;
+ });
+ }
+ });
+ if (pausePrevParentTL) {
+ prevParentTL.cancel();
+ }
+ } else {
+ prevParent.cancel();
+ // Previously, calling .cancel() on a timeline child would affect the render order of other children
+ // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop
+ // This is no longer needed since timeline tween composition is now handled separately
+ // Keeping this here for reference
+ // prevParent.completed = true;
+ // prevParent.pause();
+ }
+ }
+
+ }
+
+ // let nextSibling = tween._nextRep;
+
+ // // All the next siblings are automatically overridden
+
+ // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) {
+ // while (nextSibling) {
+ // overrideTween(nextSibling);
+ // nextSibling = nextSibling._nextRep;
+ // }
+ // }
+
+ // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) {
+ // while (nextSibling) {
+ // overrideTween(nextSibling);
+ // console.log(tween.id, nextSibling.id);
+ // nextSibling = nextSibling._nextRep;
+ // }
+ // }
+
+ // Handle additive tweens composition
+
+ } else if (tweenCompositionType === consts.compositionTypes.blend) {
+
+ const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add');
+ const additiveAnimation = additive.addAdditiveAnimation(lookups._add);
+
+ let lookupTween = additiveTweenSiblings._head;
+
+ if (!lookupTween) {
+ lookupTween = { ...tween };
+ lookupTween._composition = consts.compositionTypes.replace;
+ lookupTween._updateDuration = consts.minValue;
+ lookupTween._startTime = 0;
+ lookupTween._numbers = helpers.cloneArray(tween._fromNumbers);
+ lookupTween._number = 0;
+ lookupTween._next = null;
+ lookupTween._prev = null;
+ helpers.addChild(additiveTweenSiblings, lookupTween);
+ helpers.addChild(additiveAnimation, lookupTween);
+ }
+
+ // Convert the values of TO to FROM and set TO to 0
+
+ const toNumber = tween._toNumber;
+ tween._fromNumber = lookupTween._fromNumber - toNumber;
+ tween._toNumber = 0;
+ tween._numbers = helpers.cloneArray(tween._fromNumbers);
+ tween._number = 0;
+ lookupTween._fromNumber = toNumber;
+
+ if (tween._toNumbers) {
+ const toNumbers = helpers.cloneArray(tween._toNumbers);
+ if (toNumbers) {
+ toNumbers.forEach((value, i) => {
+ tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value;
+ tween._toNumbers[i] = 0;
+ });
+ }
+ lookupTween._fromNumbers = toNumbers;
+ }
+
+ helpers.addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd');
+
+ }
+
+ return tween;
+
+};
+
+/**
+ * @param {Tween} tween
+ * @return {Tween}
+ */
+const removeTweenSliblings = tween => {
+ const tweenComposition = tween._composition;
+ if (tweenComposition !== consts.compositionTypes.none) {
+ const tweenTarget = tween.target;
+ const tweenProperty = tween.property;
+ const replaceTweensLookup = lookups._rep;
+ const replaceTargetProps = replaceTweensLookup.get(tweenTarget);
+ const tweenReplaceSiblings = replaceTargetProps[tweenProperty];
+ helpers.removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep');
+ if (tweenComposition === consts.compositionTypes.blend) {
+ const addTweensLookup = lookups._add;
+ const addTargetProps = addTweensLookup.get(tweenTarget);
+ if (!addTargetProps) return;
+ const additiveTweenSiblings = addTargetProps[tweenProperty];
+ const additiveAnimation = additive.additive.animation;
+ helpers.removeChild(additiveTweenSiblings, tween, '_prevAdd', '_nextAdd');
+ // If only one tween is left in the additive lookup, it's the tween lookup
+ const lookupTween = additiveTweenSiblings._head;
+ if (lookupTween && lookupTween === additiveTweenSiblings._tail) {
+ helpers.removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd');
+ helpers.removeChild(additiveAnimation, lookupTween);
+ let shouldClean = true;
+ for (let prop in addTargetProps) {
+ if (addTargetProps[prop]._head) {
+ shouldClean = false;
+ break;
+ }
+ }
+ if (shouldClean) {
+ addTweensLookup.delete(tweenTarget);
+ }
+ }
+ }
+ }
+ return tween;
+};
+
+/**
+ * @param {TargetsArray} targetsArray
+ * @param {JSAnimation} animation
+ * @param {String} [propertyName]
+ * @return {Boolean}
+ */
+const removeTargetsFromJSAnimation = (targetsArray, animation, propertyName) => {
+ let tweensMatchesTargets = false;
+ helpers.forEachChildren(animation, (/**@type {Tween} */tween) => {
+ const tweenTarget = tween.target;
+ if (targetsArray.includes(tweenTarget)) {
+ const tweenName = tween.property;
+ const tweenType = tween._tweenType;
+ const normalizePropName = styles.sanitizePropertyName(propertyName, tweenTarget, tweenType);
+ if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
+ // Make sure to flag the previous CSS transform tween to renderTransform
+ if (tween.parent._tail === tween &&
+ tween._tweenType === consts.tweenTypes.TRANSFORM &&
+ tween._prev &&
+ tween._prev._tweenType === consts.tweenTypes.TRANSFORM
+ ) {
+ tween._prev._renderTransforms = 1;
+ }
+ // Removes the tween from the selected animation
+ helpers.removeChild(animation, tween);
+ // Detach the tween from its siblings to make sure blended tweens are correctlly removed
+ removeTweenSliblings(tween);
+ tweensMatchesTargets = true;
+ }
+ }
+ }, true);
+ return tweensMatchesTargets;
+};
+
+/**
+ * @param {TargetsArray} targetsArray
+ * @param {Renderable} [renderable]
+ * @param {String} [propertyName]
+ */
+const removeTargetsFromRenderable = (targetsArray, renderable, propertyName) => {
+ const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine.engine);
+ let removeMatches;
+ if (parent._hasChildren) {
+ let iterationDuration = 0;
+ helpers.forEachChildren(parent, (/** @type {Renderable} */child) => {
+ if (!child._hasChildren) {
+ removeMatches = removeTargetsFromJSAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName);
+ // Remove the child from its parent if no tweens and no children left after the removal
+ if (removeMatches && !child._head) {
+ child.cancel();
+ helpers.removeChild(parent, child);
+ } else {
+ // Calculate the new iterationDuration value to handle onComplete with last child in render()
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > iterationDuration) {
+ iterationDuration = childDur;
+ }
+ }
+ }
+ // Make sure to also remove engine's children targets
+ // NOTE: Avoid recursion?
+ if (child._head) {
+ removeTargetsFromRenderable(targetsArray, child, propertyName);
+ } else {
+ child._hasChildren = false;
+ }
+ }, true);
+ // Update iterationDuration value to handle onComplete with last child in render()
+ if (!helpers.isUnd(/** @type {Renderable} */(parent).iterationDuration)) {
+ /** @type {Renderable} */(parent).iterationDuration = iterationDuration;
+ }
+ } else {
+ removeMatches = removeTargetsFromJSAnimation(
+ targetsArray,
+ /** @type {JSAnimation} */(parent),
+ propertyName
+ );
+ }
+ if (removeMatches && !parent._head) {
+ parent._hasChildren = false;
+ // Cancel the parent if there are no tweens and no children left after the removal
+ // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
+ if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel();
+ }
+};
+
+exports.composeTween = composeTween;
+exports.getTweenSiblings = getTweenSiblings;
+exports.overrideTween = overrideTween;
+exports.removeTargetsFromRenderable = removeTargetsFromRenderable;
+exports.removeTweenSliblings = removeTweenSliblings;
diff --git a/dist/modules/animation/composition.d.ts b/dist/modules/animation/composition.d.ts
new file mode 100644
index 00000000..1cf513f7
--- /dev/null
+++ b/dist/modules/animation/composition.d.ts
@@ -0,0 +1,10 @@
+export function getTweenSiblings(target: Target, property: string, lookup?: string): TweenPropertySiblings;
+export function overrideTween(tween: Tween): void;
+export function composeTween(tween: Tween, siblings: TweenPropertySiblings): Tween;
+export function removeTweenSliblings(tween: Tween): Tween;
+export function removeTargetsFromRenderable(targetsArray: TargetsArray, renderable?: Renderable, propertyName?: string): void;
+import type { Target } from '../types/index.js';
+import type { TweenPropertySiblings } from '../types/index.js';
+import type { Tween } from '../types/index.js';
+import type { TargetsArray } from '../types/index.js';
+import type { Renderable } from '../types/index.js';
diff --git a/dist/modules/animation/composition.js b/dist/modules/animation/composition.js
new file mode 100644
index 00000000..8cdacf56
--- /dev/null
+++ b/dist/modules/animation/composition.js
@@ -0,0 +1,377 @@
+/**
+ * Anime.js - animation - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { minValue, compositionTypes, tweenTypes } from '../core/consts.js';
+import { forEachChildren, removeChild, isUnd, addChild, round, cloneArray } from '../core/helpers.js';
+import { sanitizePropertyName } from '../core/styles.js';
+import { engine } from '../engine/engine.js';
+import { addAdditiveAnimation, additive } from './additive.js';
+
+/**
+ * @import {
+ * TweenReplaceLookups,
+ * TweenAdditiveLookups,
+ * TweenPropertySiblings,
+ * Tween,
+ * Target,
+ * TargetsArray,
+ * Renderable,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+const lookups = {
+ /** @type {TweenReplaceLookups} */
+ _rep: new WeakMap(),
+ /** @type {TweenAdditiveLookups} */
+ _add: new Map(),
+};
+
+/**
+ * @param {Target} target
+ * @param {String} property
+ * @param {String} lookup
+ * @return {TweenPropertySiblings}
+ */
+const getTweenSiblings = (target, property, lookup = '_rep') => {
+ const lookupMap = lookups[lookup];
+ let targetLookup = lookupMap.get(target);
+ if (!targetLookup) {
+ targetLookup = {};
+ lookupMap.set(target, targetLookup);
+ }
+ return targetLookup[property] ? targetLookup[property] : targetLookup[property] = {
+ _head: null,
+ _tail: null,
+ }
+};
+
+/**
+ * @param {Tween} p
+ * @param {Tween} c
+ * @return {Number|Boolean}
+ */
+const addTweenSortMethod = (p, c) => {
+ return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime;
+};
+
+/**
+ * @param {Tween} tween
+ */
+const overrideTween = tween => {
+ tween._isOverlapped = 1;
+ tween._isOverridden = 1;
+ tween._changeDuration = minValue;
+ tween._currentTime = minValue;
+};
+
+/**
+ * @param {Tween} tween
+ * @param {TweenPropertySiblings} siblings
+ * @return {Tween}
+ */
+const composeTween = (tween, siblings) => {
+
+ const tweenCompositionType = tween._composition;
+
+ // Handle replaced tweens
+
+ if (tweenCompositionType === compositionTypes.replace) {
+
+ const tweenAbsStartTime = tween._absoluteStartTime;
+
+ addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep');
+
+ const prevSibling = tween._prevRep;
+
+ // Update the previous siblings for composition replace tweens
+
+ if (prevSibling) {
+
+ const prevParent = prevSibling.parent;
+ const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration;
+
+ // Handle looped animations tween
+
+ if (
+ // Check if the previous tween is from a different animation
+ tween.parent.id !== prevParent.id &&
+ // Check if the animation has loops
+ prevParent.iterationCount> 1 &&
+ // Check if _absoluteChangeEndTime of last loop overlaps the current tween
+ prevAbsEndTime + (prevParent.duration - prevParent.iterationDuration) > tweenAbsStartTime
+ ) {
+
+ // TODO: Find a way to only override the iterations overlapping with the tween
+ overrideTween(prevSibling);
+
+ let prevPrevSibling = prevSibling._prevRep;
+
+ // If the tween was part of a set of keyframes, override its siblings
+ while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) {
+ overrideTween(prevPrevSibling);
+ prevPrevSibling = prevPrevSibling._prevRep;
+ }
+
+ }
+
+ const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay;
+
+ if (prevAbsEndTime > absoluteUpdateStartTime) {
+
+ const prevChangeStartTime = prevSibling._startTime;
+ const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration);
+ // Rounding is necessary here to minimize floating point errors when working in seconds
+ const updatedPrevChangeDuration = round(absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime, 12);
+
+ prevSibling._changeDuration = updatedPrevChangeDuration;
+ prevSibling._currentTime = updatedPrevChangeDuration;
+ prevSibling._isOverlapped = 1;
+
+ // Override the previous tween if its new _changeDuration is lower than minValue
+ // TODO: See if it's even neceseeary to test against minValue, checking for 0 might be enough
+ if (updatedPrevChangeDuration < minValue) {
+ overrideTween(prevSibling);
+ }
+ }
+
+ // Pause (and cancel) the parent if it only contains overlapped tweens
+
+ let pausePrevParentAnimation = true;
+
+ forEachChildren(prevParent, (/** @type Tween */t) => {
+ if (!t._isOverlapped) pausePrevParentAnimation = false;
+ });
+
+ if (pausePrevParentAnimation) {
+ const prevParentTL = prevParent.parent;
+ if (prevParentTL) {
+ let pausePrevParentTL = true;
+ forEachChildren(prevParentTL, (/** @type JSAnimation */a) => {
+ if (a !== prevParent) {
+ forEachChildren(a, (/** @type Tween */t) => {
+ if (!t._isOverlapped) pausePrevParentTL = false;
+ });
+ }
+ });
+ if (pausePrevParentTL) {
+ prevParentTL.cancel();
+ }
+ } else {
+ prevParent.cancel();
+ // Previously, calling .cancel() on a timeline child would affect the render order of other children
+ // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop
+ // This is no longer needed since timeline tween composition is now handled separately
+ // Keeping this here for reference
+ // prevParent.completed = true;
+ // prevParent.pause();
+ }
+ }
+
+ }
+
+ // let nextSibling = tween._nextRep;
+
+ // // All the next siblings are automatically overridden
+
+ // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) {
+ // while (nextSibling) {
+ // overrideTween(nextSibling);
+ // nextSibling = nextSibling._nextRep;
+ // }
+ // }
+
+ // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) {
+ // while (nextSibling) {
+ // overrideTween(nextSibling);
+ // console.log(tween.id, nextSibling.id);
+ // nextSibling = nextSibling._nextRep;
+ // }
+ // }
+
+ // Handle additive tweens composition
+
+ } else if (tweenCompositionType === compositionTypes.blend) {
+
+ const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add');
+ const additiveAnimation = addAdditiveAnimation(lookups._add);
+
+ let lookupTween = additiveTweenSiblings._head;
+
+ if (!lookupTween) {
+ lookupTween = { ...tween };
+ lookupTween._composition = compositionTypes.replace;
+ lookupTween._updateDuration = minValue;
+ lookupTween._startTime = 0;
+ lookupTween._numbers = cloneArray(tween._fromNumbers);
+ lookupTween._number = 0;
+ lookupTween._next = null;
+ lookupTween._prev = null;
+ addChild(additiveTweenSiblings, lookupTween);
+ addChild(additiveAnimation, lookupTween);
+ }
+
+ // Convert the values of TO to FROM and set TO to 0
+
+ const toNumber = tween._toNumber;
+ tween._fromNumber = lookupTween._fromNumber - toNumber;
+ tween._toNumber = 0;
+ tween._numbers = cloneArray(tween._fromNumbers);
+ tween._number = 0;
+ lookupTween._fromNumber = toNumber;
+
+ if (tween._toNumbers) {
+ const toNumbers = cloneArray(tween._toNumbers);
+ if (toNumbers) {
+ toNumbers.forEach((value, i) => {
+ tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value;
+ tween._toNumbers[i] = 0;
+ });
+ }
+ lookupTween._fromNumbers = toNumbers;
+ }
+
+ addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd');
+
+ }
+
+ return tween;
+
+};
+
+/**
+ * @param {Tween} tween
+ * @return {Tween}
+ */
+const removeTweenSliblings = tween => {
+ const tweenComposition = tween._composition;
+ if (tweenComposition !== compositionTypes.none) {
+ const tweenTarget = tween.target;
+ const tweenProperty = tween.property;
+ const replaceTweensLookup = lookups._rep;
+ const replaceTargetProps = replaceTweensLookup.get(tweenTarget);
+ const tweenReplaceSiblings = replaceTargetProps[tweenProperty];
+ removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep');
+ if (tweenComposition === compositionTypes.blend) {
+ const addTweensLookup = lookups._add;
+ const addTargetProps = addTweensLookup.get(tweenTarget);
+ if (!addTargetProps) return;
+ const additiveTweenSiblings = addTargetProps[tweenProperty];
+ const additiveAnimation = additive.animation;
+ removeChild(additiveTweenSiblings, tween, '_prevAdd', '_nextAdd');
+ // If only one tween is left in the additive lookup, it's the tween lookup
+ const lookupTween = additiveTweenSiblings._head;
+ if (lookupTween && lookupTween === additiveTweenSiblings._tail) {
+ removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd');
+ removeChild(additiveAnimation, lookupTween);
+ let shouldClean = true;
+ for (let prop in addTargetProps) {
+ if (addTargetProps[prop]._head) {
+ shouldClean = false;
+ break;
+ }
+ }
+ if (shouldClean) {
+ addTweensLookup.delete(tweenTarget);
+ }
+ }
+ }
+ }
+ return tween;
+};
+
+/**
+ * @param {TargetsArray} targetsArray
+ * @param {JSAnimation} animation
+ * @param {String} [propertyName]
+ * @return {Boolean}
+ */
+const removeTargetsFromJSAnimation = (targetsArray, animation, propertyName) => {
+ let tweensMatchesTargets = false;
+ forEachChildren(animation, (/**@type {Tween} */tween) => {
+ const tweenTarget = tween.target;
+ if (targetsArray.includes(tweenTarget)) {
+ const tweenName = tween.property;
+ const tweenType = tween._tweenType;
+ const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
+ if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
+ // Make sure to flag the previous CSS transform tween to renderTransform
+ if (tween.parent._tail === tween &&
+ tween._tweenType === tweenTypes.TRANSFORM &&
+ tween._prev &&
+ tween._prev._tweenType === tweenTypes.TRANSFORM
+ ) {
+ tween._prev._renderTransforms = 1;
+ }
+ // Removes the tween from the selected animation
+ removeChild(animation, tween);
+ // Detach the tween from its siblings to make sure blended tweens are correctlly removed
+ removeTweenSliblings(tween);
+ tweensMatchesTargets = true;
+ }
+ }
+ }, true);
+ return tweensMatchesTargets;
+};
+
+/**
+ * @param {TargetsArray} targetsArray
+ * @param {Renderable} [renderable]
+ * @param {String} [propertyName]
+ */
+const removeTargetsFromRenderable = (targetsArray, renderable, propertyName) => {
+ const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine);
+ let removeMatches;
+ if (parent._hasChildren) {
+ let iterationDuration = 0;
+ forEachChildren(parent, (/** @type {Renderable} */child) => {
+ if (!child._hasChildren) {
+ removeMatches = removeTargetsFromJSAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName);
+ // Remove the child from its parent if no tweens and no children left after the removal
+ if (removeMatches && !child._head) {
+ child.cancel();
+ removeChild(parent, child);
+ } else {
+ // Calculate the new iterationDuration value to handle onComplete with last child in render()
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > iterationDuration) {
+ iterationDuration = childDur;
+ }
+ }
+ }
+ // Make sure to also remove engine's children targets
+ // NOTE: Avoid recursion?
+ if (child._head) {
+ removeTargetsFromRenderable(targetsArray, child, propertyName);
+ } else {
+ child._hasChildren = false;
+ }
+ }, true);
+ // Update iterationDuration value to handle onComplete with last child in render()
+ if (!isUnd(/** @type {Renderable} */(parent).iterationDuration)) {
+ /** @type {Renderable} */(parent).iterationDuration = iterationDuration;
+ }
+ } else {
+ removeMatches = removeTargetsFromJSAnimation(
+ targetsArray,
+ /** @type {JSAnimation} */(parent),
+ propertyName
+ );
+ }
+ if (removeMatches && !parent._head) {
+ parent._hasChildren = false;
+ // Cancel the parent if there are no tweens and no children left after the removal
+ // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
+ if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel();
+ }
+};
+
+export { composeTween, getTweenSiblings, overrideTween, removeTargetsFromRenderable, removeTweenSliblings };
diff --git a/dist/modules/animation/index.cjs b/dist/modules/animation/index.cjs
new file mode 100644
index 00000000..d756951d
--- /dev/null
+++ b/dist/modules/animation/index.cjs
@@ -0,0 +1,15 @@
+/**
+ * Anime.js - animation - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var animation = require('./animation.cjs');
+
+
+
+exports.JSAnimation = animation.JSAnimation;
+exports.animate = animation.animate;
diff --git a/dist/modules/animation/index.d.ts b/dist/modules/animation/index.d.ts
new file mode 100644
index 00000000..6adc421e
--- /dev/null
+++ b/dist/modules/animation/index.d.ts
@@ -0,0 +1 @@
+export * from "./animation.js";
diff --git a/dist/modules/animation/index.js b/dist/modules/animation/index.js
new file mode 100644
index 00000000..a88d099c
--- /dev/null
+++ b/dist/modules/animation/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - animation - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { JSAnimation, animate } from './animation.js';
diff --git a/dist/modules/core/clock.cjs b/dist/modules/core/clock.cjs
new file mode 100644
index 00000000..e6ad3550
--- /dev/null
+++ b/dist/modules/core/clock.cjs
@@ -0,0 +1,110 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('./consts.cjs');
+var helpers = require('./helpers.cjs');
+
+/**
+ * @import {
+ * Tickable,
+ * Tween,
+ * } from '../types/index.js'
+*/
+
+/*
+ * Base class to control framerate and playback rate.
+ * Inherited by Engine, Timer, Animation and Timeline.
+ */
+class Clock {
+
+ /** @param {Number} [initTime] */
+ constructor(initTime = 0) {
+ /** @type {Number} */
+ this.deltaTime = 0;
+ /** @type {Number} */
+ this._currentTime = initTime;
+ /** @type {Number} */
+ this._elapsedTime = initTime;
+ /** @type {Number} */
+ this._startTime = initTime;
+ /** @type {Number} */
+ this._lastTime = initTime;
+ /** @type {Number} */
+ this._scheduledTime = 0;
+ /** @type {Number} */
+ this._frameDuration = helpers.round(consts.K / consts.maxFps, 0);
+ /** @type {Number} */
+ this._fps = consts.maxFps;
+ /** @type {Number} */
+ this._speed = 1;
+ /** @type {Boolean} */
+ this._hasChildren = false;
+ /** @type {Tickable|Tween} */
+ this._head = null;
+ /** @type {Tickable|Tween} */
+ this._tail = null;
+ }
+
+ get fps() {
+ return this._fps;
+ }
+
+ set fps(frameRate) {
+ const previousFrameDuration = this._frameDuration;
+ const fr = +frameRate;
+ const fps = fr < consts.minValue ? consts.minValue : fr;
+ const frameDuration = helpers.round(consts.K / fps, 0);
+ this._fps = fps;
+ this._frameDuration = frameDuration;
+ this._scheduledTime += frameDuration - previousFrameDuration;
+ }
+
+ get speed() {
+ return this._speed;
+ }
+
+ set speed(playbackRate) {
+ const pbr = +playbackRate;
+ this._speed = pbr < consts.minValue ? consts.minValue : pbr;
+ }
+
+ /**
+ * @param {Number} time
+ * @return {tickModes}
+ */
+ requestTick(time) {
+ const scheduledTime = this._scheduledTime;
+ const elapsedTime = this._elapsedTime;
+ this._elapsedTime += (time - elapsedTime);
+ // If the elapsed time is lower than the scheduled time
+ // this means not enough time has passed to hit one frameDuration
+ // so skip that frame
+ if (elapsedTime < scheduledTime) return consts.tickModes.NONE;
+ const frameDuration = this._frameDuration;
+ const frameDelta = elapsedTime - scheduledTime;
+ // Ensures that _scheduledTime progresses in steps of at least 1 frameDuration.
+ // Skips ahead if the actual elapsed time is higher.
+ this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta;
+ return consts.tickModes.AUTO;
+ }
+
+ /**
+ * @param {Number} time
+ * @return {Number}
+ */
+ computeDeltaTime(time) {
+ const delta = time - this._lastTime;
+ this.deltaTime = delta;
+ this._lastTime = time;
+ return delta;
+ }
+
+}
+
+exports.Clock = Clock;
diff --git a/dist/modules/core/clock.d.ts b/dist/modules/core/clock.d.ts
new file mode 100644
index 00000000..d757d6af
--- /dev/null
+++ b/dist/modules/core/clock.d.ts
@@ -0,0 +1,51 @@
+/**
+ * @import {
+ * Tickable,
+ * Tween,
+ * } from '../types/index.js'
+*/
+export class Clock {
+ /** @param {Number} [initTime] */
+ constructor(initTime?: number);
+ /** @type {Number} */
+ deltaTime: number;
+ /** @type {Number} */
+ _currentTime: number;
+ /** @type {Number} */
+ _elapsedTime: number;
+ /** @type {Number} */
+ _startTime: number;
+ /** @type {Number} */
+ _lastTime: number;
+ /** @type {Number} */
+ _scheduledTime: number;
+ /** @type {Number} */
+ _frameDuration: number;
+ /** @type {Number} */
+ _fps: number;
+ /** @type {Number} */
+ _speed: number;
+ /** @type {Boolean} */
+ _hasChildren: boolean;
+ /** @type {Tickable|Tween} */
+ _head: Tickable | Tween;
+ /** @type {Tickable|Tween} */
+ _tail: Tickable | Tween;
+ set fps(frameRate: number);
+ get fps(): number;
+ set speed(playbackRate: number);
+ get speed(): number;
+ /**
+ * @param {Number} time
+ * @return {tickModes}
+ */
+ requestTick(time: number): tickModes;
+ /**
+ * @param {Number} time
+ * @return {Number}
+ */
+ computeDeltaTime(time: number): number;
+}
+import type { Tickable } from '../types/index.js';
+import type { Tween } from '../types/index.js';
+import { tickModes } from './consts.js';
diff --git a/dist/modules/core/clock.js b/dist/modules/core/clock.js
new file mode 100644
index 00000000..f59aabd3
--- /dev/null
+++ b/dist/modules/core/clock.js
@@ -0,0 +1,108 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { K, maxFps, minValue, tickModes } from './consts.js';
+import { round } from './helpers.js';
+
+/**
+ * @import {
+ * Tickable,
+ * Tween,
+ * } from '../types/index.js'
+*/
+
+/*
+ * Base class to control framerate and playback rate.
+ * Inherited by Engine, Timer, Animation and Timeline.
+ */
+class Clock {
+
+ /** @param {Number} [initTime] */
+ constructor(initTime = 0) {
+ /** @type {Number} */
+ this.deltaTime = 0;
+ /** @type {Number} */
+ this._currentTime = initTime;
+ /** @type {Number} */
+ this._elapsedTime = initTime;
+ /** @type {Number} */
+ this._startTime = initTime;
+ /** @type {Number} */
+ this._lastTime = initTime;
+ /** @type {Number} */
+ this._scheduledTime = 0;
+ /** @type {Number} */
+ this._frameDuration = round(K / maxFps, 0);
+ /** @type {Number} */
+ this._fps = maxFps;
+ /** @type {Number} */
+ this._speed = 1;
+ /** @type {Boolean} */
+ this._hasChildren = false;
+ /** @type {Tickable|Tween} */
+ this._head = null;
+ /** @type {Tickable|Tween} */
+ this._tail = null;
+ }
+
+ get fps() {
+ return this._fps;
+ }
+
+ set fps(frameRate) {
+ const previousFrameDuration = this._frameDuration;
+ const fr = +frameRate;
+ const fps = fr < minValue ? minValue : fr;
+ const frameDuration = round(K / fps, 0);
+ this._fps = fps;
+ this._frameDuration = frameDuration;
+ this._scheduledTime += frameDuration - previousFrameDuration;
+ }
+
+ get speed() {
+ return this._speed;
+ }
+
+ set speed(playbackRate) {
+ const pbr = +playbackRate;
+ this._speed = pbr < minValue ? minValue : pbr;
+ }
+
+ /**
+ * @param {Number} time
+ * @return {tickModes}
+ */
+ requestTick(time) {
+ const scheduledTime = this._scheduledTime;
+ const elapsedTime = this._elapsedTime;
+ this._elapsedTime += (time - elapsedTime);
+ // If the elapsed time is lower than the scheduled time
+ // this means not enough time has passed to hit one frameDuration
+ // so skip that frame
+ if (elapsedTime < scheduledTime) return tickModes.NONE;
+ const frameDuration = this._frameDuration;
+ const frameDelta = elapsedTime - scheduledTime;
+ // Ensures that _scheduledTime progresses in steps of at least 1 frameDuration.
+ // Skips ahead if the actual elapsed time is higher.
+ this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta;
+ return tickModes.AUTO;
+ }
+
+ /**
+ * @param {Number} time
+ * @return {Number}
+ */
+ computeDeltaTime(time) {
+ const delta = time - this._lastTime;
+ this.deltaTime = delta;
+ this._lastTime = time;
+ return delta;
+ }
+
+}
+
+export { Clock };
diff --git a/dist/modules/core/colors.cjs b/dist/modules/core/colors.cjs
new file mode 100644
index 00000000..b3325398
--- /dev/null
+++ b/dist/modules/core/colors.cjs
@@ -0,0 +1,102 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('./consts.cjs');
+var helpers = require('./helpers.cjs');
+
+/**
+ * @import {
+ * ColorArray,
+ * } from '../types/index.js'
+*/
+
+/**
+ * RGB / RGBA Color value string -> RGBA values array
+ * @param {String} rgbValue
+ * @return {ColorArray}
+ */
+const rgbToRgba = rgbValue => {
+ const rgba = consts.rgbExecRgx.exec(rgbValue) || consts.rgbaExecRgx.exec(rgbValue);
+ const a = !helpers.isUnd(rgba[4]) ? +rgba[4] : 1;
+ return [
+ +rgba[1],
+ +rgba[2],
+ +rgba[3],
+ a
+ ]
+};
+
+/**
+ * HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array
+ * @param {String} hexValue
+ * @return {ColorArray}
+ */
+const hexToRgba = hexValue => {
+ const hexLength = hexValue.length;
+ const isShort = hexLength === 4 || hexLength === 5;
+ return [
+ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]),
+ +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]),
+ +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]),
+ ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1)
+ ]
+};
+
+/**
+ * @param {Number} p
+ * @param {Number} q
+ * @param {Number} t
+ * @return {Number}
+ */
+const hue2rgb = (p, q, t) => {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ return t < 1 / 6 ? p + (q - p) * 6 * t :
+ t < 1 / 2 ? q :
+ t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 :
+ p;
+};
+
+/**
+ * HSL / HSLA Color value string -> RGBA values array
+ * @param {String} hslValue
+ * @return {ColorArray}
+ */
+const hslToRgba = hslValue => {
+ const hsla = consts.hslExecRgx.exec(hslValue) || consts.hslaExecRgx.exec(hslValue);
+ const h = +hsla[1] / 360;
+ const s = +hsla[2] / 100;
+ const l = +hsla[3] / 100;
+ const a = !helpers.isUnd(hsla[4]) ? +hsla[4] : 1;
+ let r, g, b;
+ if (s === 0) {
+ r = g = b = l;
+ } else {
+ const q = l < .5 ? l * (1 + s) : l + s - l * s;
+ const p = 2 * l - q;
+ r = helpers.round(hue2rgb(p, q, h + 1 / 3) * 255, 0);
+ g = helpers.round(hue2rgb(p, q, h) * 255, 0);
+ b = helpers.round(hue2rgb(p, q, h - 1 / 3) * 255, 0);
+ }
+ return [r, g, b, a];
+};
+
+/**
+ * All in one color converter that converts a color string value into an array of RGBA values
+ * @param {String} colorString
+ * @return {ColorArray}
+ */
+const convertColorStringValuesToRgbaArray = colorString => {
+ return helpers.isRgb(colorString) ? rgbToRgba(colorString) :
+ helpers.isHex(colorString) ? hexToRgba(colorString) :
+ helpers.isHsl(colorString) ? hslToRgba(colorString) :
+ [0, 0, 0, 1];
+};
+
+exports.convertColorStringValuesToRgbaArray = convertColorStringValuesToRgbaArray;
diff --git a/dist/modules/core/colors.d.ts b/dist/modules/core/colors.d.ts
new file mode 100644
index 00000000..f29716c8
--- /dev/null
+++ b/dist/modules/core/colors.d.ts
@@ -0,0 +1,2 @@
+export function convertColorStringValuesToRgbaArray(colorString: string): ColorArray;
+import type { ColorArray } from '../types/index.js';
diff --git a/dist/modules/core/colors.js b/dist/modules/core/colors.js
new file mode 100644
index 00000000..3c6549ec
--- /dev/null
+++ b/dist/modules/core/colors.js
@@ -0,0 +1,100 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { rgbExecRgx, rgbaExecRgx, hslExecRgx, hslaExecRgx } from './consts.js';
+import { isRgb, isHex, isHsl, isUnd, round } from './helpers.js';
+
+/**
+ * @import {
+ * ColorArray,
+ * } from '../types/index.js'
+*/
+
+/**
+ * RGB / RGBA Color value string -> RGBA values array
+ * @param {String} rgbValue
+ * @return {ColorArray}
+ */
+const rgbToRgba = rgbValue => {
+ const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue);
+ const a = !isUnd(rgba[4]) ? +rgba[4] : 1;
+ return [
+ +rgba[1],
+ +rgba[2],
+ +rgba[3],
+ a
+ ]
+};
+
+/**
+ * HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array
+ * @param {String} hexValue
+ * @return {ColorArray}
+ */
+const hexToRgba = hexValue => {
+ const hexLength = hexValue.length;
+ const isShort = hexLength === 4 || hexLength === 5;
+ return [
+ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]),
+ +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]),
+ +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]),
+ ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1)
+ ]
+};
+
+/**
+ * @param {Number} p
+ * @param {Number} q
+ * @param {Number} t
+ * @return {Number}
+ */
+const hue2rgb = (p, q, t) => {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ return t < 1 / 6 ? p + (q - p) * 6 * t :
+ t < 1 / 2 ? q :
+ t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 :
+ p;
+};
+
+/**
+ * HSL / HSLA Color value string -> RGBA values array
+ * @param {String} hslValue
+ * @return {ColorArray}
+ */
+const hslToRgba = hslValue => {
+ const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue);
+ const h = +hsla[1] / 360;
+ const s = +hsla[2] / 100;
+ const l = +hsla[3] / 100;
+ const a = !isUnd(hsla[4]) ? +hsla[4] : 1;
+ let r, g, b;
+ if (s === 0) {
+ r = g = b = l;
+ } else {
+ const q = l < .5 ? l * (1 + s) : l + s - l * s;
+ const p = 2 * l - q;
+ r = round(hue2rgb(p, q, h + 1 / 3) * 255, 0);
+ g = round(hue2rgb(p, q, h) * 255, 0);
+ b = round(hue2rgb(p, q, h - 1 / 3) * 255, 0);
+ }
+ return [r, g, b, a];
+};
+
+/**
+ * All in one color converter that converts a color string value into an array of RGBA values
+ * @param {String} colorString
+ * @return {ColorArray}
+ */
+const convertColorStringValuesToRgbaArray = colorString => {
+ return isRgb(colorString) ? rgbToRgba(colorString) :
+ isHex(colorString) ? hexToRgba(colorString) :
+ isHsl(colorString) ? hslToRgba(colorString) :
+ [0, 0, 0, 1];
+};
+
+export { convertColorStringValuesToRgbaArray };
diff --git a/dist/modules/core/consts.cjs b/dist/modules/core/consts.cjs
new file mode 100644
index 00000000..b6d6832f
--- /dev/null
+++ b/dist/modules/core/consts.cjs
@@ -0,0 +1,154 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+// Environments
+
+// TODO: Do we need to check if we're running inside a worker ?
+const isBrowser = typeof window !== 'undefined';
+
+/** @type {Window & {AnimeJS: Array}|null} */
+const win = isBrowser ? /** @type {Window & {AnimeJS: Array}} */(/** @type {unknown} */(window)) : null;
+
+/** @type {Document|null} */
+const doc = isBrowser ? document : null;
+
+// Enums
+
+/** @enum {Number} */
+const tweenTypes = {
+ OBJECT: 0,
+ ATTRIBUTE: 1,
+ CSS: 2,
+ TRANSFORM: 3,
+ CSS_VAR: 4,
+};
+
+/** @enum {Number} */
+const valueTypes = {
+ NUMBER: 0,
+ UNIT: 1,
+ COLOR: 2,
+ COMPLEX: 3,
+};
+
+/** @enum {Number} */
+const tickModes = {
+ NONE: 0,
+ AUTO: 1,
+ FORCE: 2,
+};
+
+/** @enum {Number} */
+const compositionTypes = {
+ replace: 0,
+ none: 1,
+ blend: 2,
+};
+
+// Cache symbols
+
+const isRegisteredTargetSymbol = Symbol();
+const isDomSymbol = Symbol();
+const isSvgSymbol = Symbol();
+const transformsSymbol = Symbol();
+const morphPointsSymbol = Symbol();
+const proxyTargetSymbol = Symbol();
+
+// Numbers
+
+const minValue = 1e-11;
+const maxValue = 1e12;
+const K = 1e3;
+const maxFps = 120;
+
+// Strings
+
+const emptyString = '';
+const shortTransforms = /*#__PURE__*/ (() => {
+ const map = new Map();
+ map.set('x', 'translateX');
+ map.set('y', 'translateY');
+ map.set('z', 'translateZ');
+ return map;
+})();
+
+const validTransforms = [
+ 'translateX',
+ 'translateY',
+ 'translateZ',
+ 'rotate',
+ 'rotateX',
+ 'rotateY',
+ 'rotateZ',
+ 'scale',
+ 'scaleX',
+ 'scaleY',
+ 'scaleZ',
+ 'skew',
+ 'skewX',
+ 'skewY',
+ 'perspective',
+ 'matrix',
+ 'matrix3d',
+];
+
+const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {});
+
+// Functions
+
+/** @return {void} */
+const noop = () => {};
+
+// Regex
+
+const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;
+const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;
+const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
+const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;
+const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
+// export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g;
+const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;
+// export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i;
+const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;
+const lowerCaseRgx = /([a-z])([A-Z])/g;
+const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in ()
+const relativeValuesExecRgx = /(\*=|\+=|-=)/;
+
+exports.K = K;
+exports.compositionTypes = compositionTypes;
+exports.digitWithExponentRgx = digitWithExponentRgx;
+exports.doc = doc;
+exports.emptyString = emptyString;
+exports.hexTestRgx = hexTestRgx;
+exports.hslExecRgx = hslExecRgx;
+exports.hslaExecRgx = hslaExecRgx;
+exports.isBrowser = isBrowser;
+exports.isDomSymbol = isDomSymbol;
+exports.isRegisteredTargetSymbol = isRegisteredTargetSymbol;
+exports.isSvgSymbol = isSvgSymbol;
+exports.lowerCaseRgx = lowerCaseRgx;
+exports.maxFps = maxFps;
+exports.maxValue = maxValue;
+exports.minValue = minValue;
+exports.morphPointsSymbol = morphPointsSymbol;
+exports.noop = noop;
+exports.proxyTargetSymbol = proxyTargetSymbol;
+exports.relativeValuesExecRgx = relativeValuesExecRgx;
+exports.rgbExecRgx = rgbExecRgx;
+exports.rgbaExecRgx = rgbaExecRgx;
+exports.shortTransforms = shortTransforms;
+exports.tickModes = tickModes;
+exports.transformsExecRgx = transformsExecRgx;
+exports.transformsFragmentStrings = transformsFragmentStrings;
+exports.transformsSymbol = transformsSymbol;
+exports.tweenTypes = tweenTypes;
+exports.unitsExecRgx = unitsExecRgx;
+exports.validTransforms = validTransforms;
+exports.valueTypes = valueTypes;
+exports.win = win;
diff --git a/dist/modules/core/consts.d.ts b/dist/modules/core/consts.d.ts
new file mode 100644
index 00000000..6f31bde6
--- /dev/null
+++ b/dist/modules/core/consts.d.ts
@@ -0,0 +1,59 @@
+export const isBrowser: boolean;
+/** @type {Window & {AnimeJS: Array}|null} */
+export const win: (Window & {
+ AnimeJS: any[];
+}) | null;
+/** @type {Document|null} */
+export const doc: Document | null;
+export type tweenTypes = number;
+export namespace tweenTypes {
+ let OBJECT: number;
+ let ATTRIBUTE: number;
+ let CSS: number;
+ let TRANSFORM: number;
+ let CSS_VAR: number;
+}
+export type valueTypes = number;
+export namespace valueTypes {
+ let NUMBER: number;
+ let UNIT: number;
+ let COLOR: number;
+ let COMPLEX: number;
+}
+export type tickModes = number;
+export namespace tickModes {
+ let NONE: number;
+ let AUTO: number;
+ let FORCE: number;
+}
+export type compositionTypes = number;
+export namespace compositionTypes {
+ let replace: number;
+ let none: number;
+ let blend: number;
+}
+export const isRegisteredTargetSymbol: unique symbol;
+export const isDomSymbol: unique symbol;
+export const isSvgSymbol: unique symbol;
+export const transformsSymbol: unique symbol;
+export const morphPointsSymbol: unique symbol;
+export const proxyTargetSymbol: unique symbol;
+export const minValue: 1e-11;
+export const maxValue: 1000000000000;
+export const K: 1000;
+export const maxFps: 120;
+export const emptyString: "";
+export const shortTransforms: Map<any, any>;
+export const validTransforms: string[];
+export const transformsFragmentStrings: {};
+export function noop(): void;
+export const hexTestRgx: RegExp;
+export const rgbExecRgx: RegExp;
+export const rgbaExecRgx: RegExp;
+export const hslExecRgx: RegExp;
+export const hslaExecRgx: RegExp;
+export const digitWithExponentRgx: RegExp;
+export const unitsExecRgx: RegExp;
+export const lowerCaseRgx: RegExp;
+export const transformsExecRgx: RegExp;
+export const relativeValuesExecRgx: RegExp;
diff --git a/dist/modules/core/consts.js b/dist/modules/core/consts.js
new file mode 100644
index 00000000..ade70d3e
--- /dev/null
+++ b/dist/modules/core/consts.js
@@ -0,0 +1,121 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+// Environments
+
+// TODO: Do we need to check if we're running inside a worker ?
+const isBrowser = typeof window !== 'undefined';
+
+/** @type {Window & {AnimeJS: Array}|null} */
+const win = isBrowser ? /** @type {Window & {AnimeJS: Array}} */(/** @type {unknown} */(window)) : null;
+
+/** @type {Document|null} */
+const doc = isBrowser ? document : null;
+
+// Enums
+
+/** @enum {Number} */
+const tweenTypes = {
+ OBJECT: 0,
+ ATTRIBUTE: 1,
+ CSS: 2,
+ TRANSFORM: 3,
+ CSS_VAR: 4,
+};
+
+/** @enum {Number} */
+const valueTypes = {
+ NUMBER: 0,
+ UNIT: 1,
+ COLOR: 2,
+ COMPLEX: 3,
+};
+
+/** @enum {Number} */
+const tickModes = {
+ NONE: 0,
+ AUTO: 1,
+ FORCE: 2,
+};
+
+/** @enum {Number} */
+const compositionTypes = {
+ replace: 0,
+ none: 1,
+ blend: 2,
+};
+
+// Cache symbols
+
+const isRegisteredTargetSymbol = Symbol();
+const isDomSymbol = Symbol();
+const isSvgSymbol = Symbol();
+const transformsSymbol = Symbol();
+const morphPointsSymbol = Symbol();
+const proxyTargetSymbol = Symbol();
+
+// Numbers
+
+const minValue = 1e-11;
+const maxValue = 1e12;
+const K = 1e3;
+const maxFps = 120;
+
+// Strings
+
+const emptyString = '';
+const shortTransforms = /*#__PURE__*/ (() => {
+ const map = new Map();
+ map.set('x', 'translateX');
+ map.set('y', 'translateY');
+ map.set('z', 'translateZ');
+ return map;
+})();
+
+const validTransforms = [
+ 'translateX',
+ 'translateY',
+ 'translateZ',
+ 'rotate',
+ 'rotateX',
+ 'rotateY',
+ 'rotateZ',
+ 'scale',
+ 'scaleX',
+ 'scaleY',
+ 'scaleZ',
+ 'skew',
+ 'skewX',
+ 'skewY',
+ 'perspective',
+ 'matrix',
+ 'matrix3d',
+];
+
+const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {});
+
+// Functions
+
+/** @return {void} */
+const noop = () => {};
+
+// Regex
+
+const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;
+const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;
+const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
+const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;
+const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
+// export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g;
+const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;
+// export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i;
+const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;
+const lowerCaseRgx = /([a-z])([A-Z])/g;
+const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in ()
+const relativeValuesExecRgx = /(\*=|\+=|-=)/;
+
+export { K, compositionTypes, digitWithExponentRgx, doc, emptyString, hexTestRgx, hslExecRgx, hslaExecRgx, isBrowser, isDomSymbol, isRegisteredTargetSymbol, isSvgSymbol, lowerCaseRgx, maxFps, maxValue, minValue, morphPointsSymbol, noop, proxyTargetSymbol, relativeValuesExecRgx, rgbExecRgx, rgbaExecRgx, shortTransforms, tickModes, transformsExecRgx, transformsFragmentStrings, transformsSymbol, tweenTypes, unitsExecRgx, validTransforms, valueTypes, win };
diff --git a/dist/modules/core/globals.cjs b/dist/modules/core/globals.cjs
new file mode 100644
index 00000000..c4028ca0
--- /dev/null
+++ b/dist/modules/core/globals.cjs
@@ -0,0 +1,77 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('./consts.cjs');
+
+/**
+ * @import {
+ * DefaultsParams,
+ * DOMTarget,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * Scope,
+ * } from '../scope/index.js'
+*/
+
+/** @type {DefaultsParams} */
+const defaults = {
+ id: null,
+ keyframes: null,
+ playbackEase: null,
+ playbackRate: 1,
+ frameRate: consts.maxFps,
+ loop: 0,
+ reversed: false,
+ alternate: false,
+ autoplay: true,
+ duration: consts.K,
+ delay: 0,
+ loopDelay: 0,
+ ease: 'out(2)',
+ composition: consts.compositionTypes.replace,
+ modifier: v => v,
+ onBegin: consts.noop,
+ onBeforeUpdate: consts.noop,
+ onUpdate: consts.noop,
+ onLoop: consts.noop,
+ onPause: consts.noop,
+ onComplete: consts.noop,
+ onRender: consts.noop,
+};
+
+const scope = {
+ /** @type {Scope} */
+ current: null,
+ /** @type {Document|DOMTarget} */
+ root: consts.doc,
+};
+
+const globals = {
+ /** @type {DefaultsParams} */
+ defaults,
+ /** @type {Number} */
+ precision: 4,
+ /** @type {Number} equals 1 in ms mode, 0.001 in s mode */
+ timeScale: 1,
+ /** @type {Number} */
+ tickThreshold: 200,
+};
+
+const globalVersions = { version: '4.2.0', engine: null };
+
+if (consts.isBrowser) {
+ if (!consts.win.AnimeJS) consts.win.AnimeJS = [];
+ consts.win.AnimeJS.push(globalVersions);
+}
+
+exports.defaults = defaults;
+exports.globalVersions = globalVersions;
+exports.globals = globals;
+exports.scope = scope;
diff --git a/dist/modules/core/globals.d.ts b/dist/modules/core/globals.d.ts
new file mode 100644
index 00000000..88e1227f
--- /dev/null
+++ b/dist/modules/core/globals.d.ts
@@ -0,0 +1,29 @@
+/**
+ * @import {
+ * DefaultsParams,
+ * DOMTarget,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * Scope,
+ * } from '../scope/index.js'
+*/
+/** @type {DefaultsParams} */
+export const defaults: DefaultsParams;
+export namespace scope {
+ export let current: Scope;
+ export { doc as root };
+}
+export namespace globals {
+ export { defaults };
+ export let precision: number;
+ export let timeScale: number;
+ export let tickThreshold: number;
+}
+export namespace globalVersions {
+ let version: string;
+ let engine: any;
+}
+import type { DefaultsParams } from '../types/index.js';
+import type { Scope } from '../scope/index.js';
+import { doc } from './consts.js';
diff --git a/dist/modules/core/globals.js b/dist/modules/core/globals.js
new file mode 100644
index 00000000..0b2e065a
--- /dev/null
+++ b/dist/modules/core/globals.js
@@ -0,0 +1,72 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { isBrowser, win, noop, maxFps, K, compositionTypes, doc } from './consts.js';
+
+/**
+ * @import {
+ * DefaultsParams,
+ * DOMTarget,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * Scope,
+ * } from '../scope/index.js'
+*/
+
+/** @type {DefaultsParams} */
+const defaults = {
+ id: null,
+ keyframes: null,
+ playbackEase: null,
+ playbackRate: 1,
+ frameRate: maxFps,
+ loop: 0,
+ reversed: false,
+ alternate: false,
+ autoplay: true,
+ duration: K,
+ delay: 0,
+ loopDelay: 0,
+ ease: 'out(2)',
+ composition: compositionTypes.replace,
+ modifier: v => v,
+ onBegin: noop,
+ onBeforeUpdate: noop,
+ onUpdate: noop,
+ onLoop: noop,
+ onPause: noop,
+ onComplete: noop,
+ onRender: noop,
+};
+
+const scope = {
+ /** @type {Scope} */
+ current: null,
+ /** @type {Document|DOMTarget} */
+ root: doc,
+};
+
+const globals = {
+ /** @type {DefaultsParams} */
+ defaults,
+ /** @type {Number} */
+ precision: 4,
+ /** @type {Number} equals 1 in ms mode, 0.001 in s mode */
+ timeScale: 1,
+ /** @type {Number} */
+ tickThreshold: 200,
+};
+
+const globalVersions = { version: '4.2.0', engine: null };
+
+if (isBrowser) {
+ if (!win.AnimeJS) win.AnimeJS = [];
+ win.AnimeJS.push(globalVersions);
+}
+
+export { defaults, globalVersions, globals, scope };
diff --git a/dist/modules/core/helpers.cjs b/dist/modules/core/helpers.cjs
new file mode 100644
index 00000000..8b468aa2
--- /dev/null
+++ b/dist/modules/core/helpers.cjs
@@ -0,0 +1,304 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('./consts.cjs');
+var globals = require('./globals.cjs');
+
+/**
+ * @import {
+ * Target,
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
+// Strings
+
+/**
+ * @param {String} str
+ * @return {String}
+ */
+const toLowerCase = str => str.replace(consts.lowerCaseRgx, '$1-$2').toLowerCase();
+
+/**
+ * Prioritize this method instead of regex when possible
+ * @param {String} str
+ * @param {String} sub
+ * @return {Boolean}
+ */
+const stringStartsWith = (str, sub) => str.indexOf(sub) === 0;
+
+// Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement.
+const now = Date.now;
+
+// Types checkers
+
+const isArr = Array.isArray;
+/**@param {any} a @return {a is Record<String, any>} */
+const isObj = a => a && a.constructor === Object;
+/**@param {any} a @return {a is Number} */
+const isNum = a => typeof a === 'number' && !isNaN(a);
+/**@param {any} a @return {a is String} */
+const isStr = a => typeof a === 'string';
+/**@param {any} a @return {a is Function} */
+const isFnc = a => typeof a === 'function';
+/**@param {any} a @return {a is undefined} */
+const isUnd = a => typeof a === 'undefined';
+/**@param {any} a @return {a is null | undefined} */
+const isNil = a => isUnd(a) || a === null;
+/**@param {any} a @return {a is SVGElement} */
+const isSvg = a => consts.isBrowser && a instanceof SVGElement;
+/**@param {any} a @return {Boolean} */
+const isHex = a => consts.hexTestRgx.test(a);
+/**@param {any} a @return {Boolean} */
+const isRgb = a => stringStartsWith(a, 'rgb');
+/**@param {any} a @return {Boolean} */
+const isHsl = a => stringStartsWith(a, 'hsl');
+/**@param {any} a @return {Boolean} */
+const isCol = a => isHex(a) || isRgb(a) || isHsl(a);
+/**@param {any} a @return {Boolean} */
+const isKey = a => !globals.globals.defaults.hasOwnProperty(a);
+
+// SVG
+
+// Consider the following as CSS animation
+// CSS opacity animation has better default values (opacity: 1 instead of 0))
+// rotate is more commonly intended to be used as a transform
+const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
+
+/**
+ * @param {Target} el
+ * @param {String} propertyName
+ * @return {Boolean}
+ */
+const isValidSVGAttribute = (el, propertyName) => {
+ if (svgCssReservedProperties.includes(propertyName)) return false;
+ if (el.getAttribute(propertyName) || propertyName in el) {
+ if (propertyName === 'scale') { // Scale
+ const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
+ // Only consider scale as a valid SVG attribute on filter element
+ return elParentNode && elParentNode.tagName === 'filter';
+ }
+ return true;
+ }
+};
+
+// Number
+
+/**
+ * @param {Number|String} str
+ * @return {Number}
+ */
+const parseNumber = str => isStr(str) ?
+ parseFloat(/** @type {String} */(str)) :
+ /** @type {Number} */(str);
+
+// Math
+
+const pow = Math.pow;
+const sqrt = Math.sqrt;
+const sin = Math.sin;
+const cos = Math.cos;
+const abs = Math.abs;
+const exp = Math.exp;
+const ceil = Math.ceil;
+const floor = Math.floor;
+const asin = Math.asin;
+const max = Math.max;
+const atan2 = Math.atan2;
+const PI = Math.PI;
+const _round = Math.round;
+
+/**
+ * Clamps a value between min and max bounds
+ *
+ * @param {Number} v - Value to clamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {Number}
+ */
+const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
+
+const powCache = {};
+
+/**
+ * Rounds a number to specified decimal places
+ *
+ * @param {Number} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {Number}
+ */
+const round = (v, decimalLength) => {
+ if (decimalLength < 0) return v;
+ if (!decimalLength) return _round(v);
+ let p = powCache[decimalLength];
+ if (!p) p = powCache[decimalLength] = 10 ** decimalLength;
+ return _round(v * p) / p;
+};
+
+/**
+ * Snaps a value to nearest increment or array value
+ *
+ * @param {Number} v - Value to snap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {Number}
+ */
+const snap = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
+
+/**
+ * Linear interpolation between two values
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
+ */
+const lerp = (start, end, factor) => start + (end - start) * factor;
+
+/**
+ * Replaces infinity with maximum safe value
+ *
+ * @param {Number} v - Value to check
+ * @return {Number}
+ */
+const clampInfinity = v => v === Infinity ? consts.maxValue : v === -Infinity ? -consts.maxValue : v;
+
+/**
+ * Normalizes time value with minimum threshold
+ *
+ * @param {Number} v - Time value to normalize
+ * @return {Number}
+ */
+const normalizeTime = v => v <= consts.minValue ? consts.minValue : clampInfinity(round(v, 11));
+
+// Arrays
+
+/**
+ * @template T
+ * @param {T[]} a
+ * @return {T[]}
+ */
+const cloneArray = a => isArr(a) ? [ ...a ] : a;
+
+// Objects
+
+/**
+ * @template T
+ * @template U
+ * @param {T} o1
+ * @param {U} o2
+ * @return {T & U}
+ */
+const mergeObjects = (o1, o2) => {
+ const merged = /** @type {T & U} */({ ...o1 });
+ for (let p in o2) {
+ const o1p = /** @type {T & U} */(o1)[p];
+ merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p;
+ } return merged;
+};
+
+// Linked lists
+
+/**
+ * @param {Object} parent
+ * @param {Function} callback
+ * @param {Boolean} [reverse]
+ * @param {String} [prevProp]
+ * @param {String} [nextProp]
+ * @return {void}
+ */
+const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => {
+ let next = parent._head;
+ let adjustedNextProp = nextProp;
+ if (reverse) {
+ next = parent._tail;
+ adjustedNextProp = prevProp;
+ }
+ while (next) {
+ const currentNext = next[adjustedNextProp];
+ callback(next);
+ next = currentNext;
+ }
+};
+
+/**
+ * @param {Object} parent
+ * @param {Object} child
+ * @param {String} [prevProp]
+ * @param {String} [nextProp]
+ * @return {void}
+ */
+const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => {
+ const prev = child[prevProp];
+ const next = child[nextProp];
+ prev ? prev[nextProp] = next : parent._head = next;
+ next ? next[prevProp] = prev : parent._tail = prev;
+ child[prevProp] = null;
+ child[nextProp] = null;
+};
+
+/**
+ * @param {Object} parent
+ * @param {Object} child
+ * @param {Function} [sortMethod]
+ * @param {String} prevProp
+ * @param {String} nextProp
+ * @return {void}
+ */
+const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => {
+ let prev = parent._tail;
+ while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp];
+ const next = prev ? prev[nextProp] : parent._head;
+ prev ? prev[nextProp] = child : parent._head = child;
+ next ? next[prevProp] = child : parent._tail = child;
+ child[prevProp] = prev;
+ child[nextProp] = next;
+};
+
+exports.PI = PI;
+exports._round = _round;
+exports.abs = abs;
+exports.addChild = addChild;
+exports.asin = asin;
+exports.atan2 = atan2;
+exports.ceil = ceil;
+exports.clamp = clamp;
+exports.clampInfinity = clampInfinity;
+exports.cloneArray = cloneArray;
+exports.cos = cos;
+exports.exp = exp;
+exports.floor = floor;
+exports.forEachChildren = forEachChildren;
+exports.isArr = isArr;
+exports.isCol = isCol;
+exports.isFnc = isFnc;
+exports.isHex = isHex;
+exports.isHsl = isHsl;
+exports.isKey = isKey;
+exports.isNil = isNil;
+exports.isNum = isNum;
+exports.isObj = isObj;
+exports.isRgb = isRgb;
+exports.isStr = isStr;
+exports.isSvg = isSvg;
+exports.isUnd = isUnd;
+exports.isValidSVGAttribute = isValidSVGAttribute;
+exports.lerp = lerp;
+exports.max = max;
+exports.mergeObjects = mergeObjects;
+exports.normalizeTime = normalizeTime;
+exports.now = now;
+exports.parseNumber = parseNumber;
+exports.pow = pow;
+exports.removeChild = removeChild;
+exports.round = round;
+exports.sin = sin;
+exports.snap = snap;
+exports.sqrt = sqrt;
+exports.stringStartsWith = stringStartsWith;
+exports.toLowerCase = toLowerCase;
diff --git a/dist/modules/core/helpers.d.ts b/dist/modules/core/helpers.d.ts
new file mode 100644
index 00000000..705538a8
--- /dev/null
+++ b/dist/modules/core/helpers.d.ts
@@ -0,0 +1,43 @@
+export function toLowerCase(str: string): string;
+export function stringStartsWith(str: string, sub: string): boolean;
+export const now: () => number;
+export const isArr: (arg: any) => arg is any[];
+export function isObj(a: any): a is Record<string, any>;
+export function isNum(a: any): a is number;
+export function isStr(a: any): a is string;
+export function isFnc(a: any): a is Function;
+export function isUnd(a: any): a is undefined;
+export function isNil(a: any): a is null | undefined;
+export function isSvg(a: any): a is SVGElement;
+export function isHex(a: any): boolean;
+export function isRgb(a: any): boolean;
+export function isHsl(a: any): boolean;
+export function isCol(a: any): boolean;
+export function isKey(a: any): boolean;
+export function isValidSVGAttribute(el: Target, propertyName: string): boolean;
+export function parseNumber(str: number | string): number;
+export const pow: (x: number, y: number) => number;
+export const sqrt: (x: number) => number;
+export const sin: (x: number) => number;
+export const cos: (x: number) => number;
+export const abs: (x: number) => number;
+export const exp: (x: number) => number;
+export const ceil: (x: number) => number;
+export const floor: (x: number) => number;
+export const asin: (x: number) => number;
+export const max: (...values: number[]) => number;
+export const atan2: (y: number, x: number) => number;
+export const PI: number;
+export const _round: (x: number) => number;
+export function clamp(v: number, min: number, max: number): number;
+export function round(v: number, decimalLength: number): number;
+export function snap(v: number, increment: number | Array<number>): number;
+export function lerp(start: number, end: number, factor: number): number;
+export function clampInfinity(v: number): number;
+export function normalizeTime(v: number): number;
+export function cloneArray<T>(a: T[]): T[];
+export function mergeObjects<T, U>(o1: T, o2: U): T & U;
+export function forEachChildren(parent: any, callback: Function, reverse?: boolean, prevProp?: string, nextProp?: string): void;
+export function removeChild(parent: any, child: any, prevProp?: string, nextProp?: string): void;
+export function addChild(parent: any, child: any, sortMethod?: Function, prevProp?: string, nextProp?: string): void;
+import type { Target } from '../types/index.js';
diff --git a/dist/modules/core/helpers.js b/dist/modules/core/helpers.js
new file mode 100644
index 00000000..8cd1c894
--- /dev/null
+++ b/dist/modules/core/helpers.js
@@ -0,0 +1,261 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { isBrowser, maxValue, minValue, hexTestRgx, lowerCaseRgx } from './consts.js';
+import { globals } from './globals.js';
+
+/**
+ * @import {
+ * Target,
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
+// Strings
+
+/**
+ * @param {String} str
+ * @return {String}
+ */
+const toLowerCase = str => str.replace(lowerCaseRgx, '$1-$2').toLowerCase();
+
+/**
+ * Prioritize this method instead of regex when possible
+ * @param {String} str
+ * @param {String} sub
+ * @return {Boolean}
+ */
+const stringStartsWith = (str, sub) => str.indexOf(sub) === 0;
+
+// Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement.
+const now = Date.now;
+
+// Types checkers
+
+const isArr = Array.isArray;
+/**@param {any} a @return {a is Record<String, any>} */
+const isObj = a => a && a.constructor === Object;
+/**@param {any} a @return {a is Number} */
+const isNum = a => typeof a === 'number' && !isNaN(a);
+/**@param {any} a @return {a is String} */
+const isStr = a => typeof a === 'string';
+/**@param {any} a @return {a is Function} */
+const isFnc = a => typeof a === 'function';
+/**@param {any} a @return {a is undefined} */
+const isUnd = a => typeof a === 'undefined';
+/**@param {any} a @return {a is null | undefined} */
+const isNil = a => isUnd(a) || a === null;
+/**@param {any} a @return {a is SVGElement} */
+const isSvg = a => isBrowser && a instanceof SVGElement;
+/**@param {any} a @return {Boolean} */
+const isHex = a => hexTestRgx.test(a);
+/**@param {any} a @return {Boolean} */
+const isRgb = a => stringStartsWith(a, 'rgb');
+/**@param {any} a @return {Boolean} */
+const isHsl = a => stringStartsWith(a, 'hsl');
+/**@param {any} a @return {Boolean} */
+const isCol = a => isHex(a) || isRgb(a) || isHsl(a);
+/**@param {any} a @return {Boolean} */
+const isKey = a => !globals.defaults.hasOwnProperty(a);
+
+// SVG
+
+// Consider the following as CSS animation
+// CSS opacity animation has better default values (opacity: 1 instead of 0))
+// rotate is more commonly intended to be used as a transform
+const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
+
+/**
+ * @param {Target} el
+ * @param {String} propertyName
+ * @return {Boolean}
+ */
+const isValidSVGAttribute = (el, propertyName) => {
+ if (svgCssReservedProperties.includes(propertyName)) return false;
+ if (el.getAttribute(propertyName) || propertyName in el) {
+ if (propertyName === 'scale') { // Scale
+ const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
+ // Only consider scale as a valid SVG attribute on filter element
+ return elParentNode && elParentNode.tagName === 'filter';
+ }
+ return true;
+ }
+};
+
+// Number
+
+/**
+ * @param {Number|String} str
+ * @return {Number}
+ */
+const parseNumber = str => isStr(str) ?
+ parseFloat(/** @type {String} */(str)) :
+ /** @type {Number} */(str);
+
+// Math
+
+const pow = Math.pow;
+const sqrt = Math.sqrt;
+const sin = Math.sin;
+const cos = Math.cos;
+const abs = Math.abs;
+const exp = Math.exp;
+const ceil = Math.ceil;
+const floor = Math.floor;
+const asin = Math.asin;
+const max = Math.max;
+const atan2 = Math.atan2;
+const PI = Math.PI;
+const _round = Math.round;
+
+/**
+ * Clamps a value between min and max bounds
+ *
+ * @param {Number} v - Value to clamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {Number}
+ */
+const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
+
+const powCache = {};
+
+/**
+ * Rounds a number to specified decimal places
+ *
+ * @param {Number} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {Number}
+ */
+const round = (v, decimalLength) => {
+ if (decimalLength < 0) return v;
+ if (!decimalLength) return _round(v);
+ let p = powCache[decimalLength];
+ if (!p) p = powCache[decimalLength] = 10 ** decimalLength;
+ return _round(v * p) / p;
+};
+
+/**
+ * Snaps a value to nearest increment or array value
+ *
+ * @param {Number} v - Value to snap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {Number}
+ */
+const snap = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
+
+/**
+ * Linear interpolation between two values
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
+ */
+const lerp = (start, end, factor) => start + (end - start) * factor;
+
+/**
+ * Replaces infinity with maximum safe value
+ *
+ * @param {Number} v - Value to check
+ * @return {Number}
+ */
+const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v;
+
+/**
+ * Normalizes time value with minimum threshold
+ *
+ * @param {Number} v - Time value to normalize
+ * @return {Number}
+ */
+const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round(v, 11));
+
+// Arrays
+
+/**
+ * @template T
+ * @param {T[]} a
+ * @return {T[]}
+ */
+const cloneArray = a => isArr(a) ? [ ...a ] : a;
+
+// Objects
+
+/**
+ * @template T
+ * @template U
+ * @param {T} o1
+ * @param {U} o2
+ * @return {T & U}
+ */
+const mergeObjects = (o1, o2) => {
+ const merged = /** @type {T & U} */({ ...o1 });
+ for (let p in o2) {
+ const o1p = /** @type {T & U} */(o1)[p];
+ merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p;
+ } return merged;
+};
+
+// Linked lists
+
+/**
+ * @param {Object} parent
+ * @param {Function} callback
+ * @param {Boolean} [reverse]
+ * @param {String} [prevProp]
+ * @param {String} [nextProp]
+ * @return {void}
+ */
+const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => {
+ let next = parent._head;
+ let adjustedNextProp = nextProp;
+ if (reverse) {
+ next = parent._tail;
+ adjustedNextProp = prevProp;
+ }
+ while (next) {
+ const currentNext = next[adjustedNextProp];
+ callback(next);
+ next = currentNext;
+ }
+};
+
+/**
+ * @param {Object} parent
+ * @param {Object} child
+ * @param {String} [prevProp]
+ * @param {String} [nextProp]
+ * @return {void}
+ */
+const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => {
+ const prev = child[prevProp];
+ const next = child[nextProp];
+ prev ? prev[nextProp] = next : parent._head = next;
+ next ? next[prevProp] = prev : parent._tail = prev;
+ child[prevProp] = null;
+ child[nextProp] = null;
+};
+
+/**
+ * @param {Object} parent
+ * @param {Object} child
+ * @param {Function} [sortMethod]
+ * @param {String} prevProp
+ * @param {String} nextProp
+ * @return {void}
+ */
+const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => {
+ let prev = parent._tail;
+ while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp];
+ const next = prev ? prev[nextProp] : parent._head;
+ prev ? prev[nextProp] = child : parent._head = child;
+ next ? next[prevProp] = child : parent._tail = child;
+ child[prevProp] = prev;
+ child[nextProp] = next;
+};
+
+export { PI, _round, abs, addChild, asin, atan2, ceil, clamp, clampInfinity, cloneArray, cos, exp, floor, forEachChildren, isArr, isCol, isFnc, isHex, isHsl, isKey, isNil, isNum, isObj, isRgb, isStr, isSvg, isUnd, isValidSVGAttribute, lerp, max, mergeObjects, normalizeTime, now, parseNumber, pow, removeChild, round, sin, snap, sqrt, stringStartsWith, toLowerCase };
diff --git a/dist/modules/core/render.cjs b/dist/modules/core/render.cjs
new file mode 100644
index 00000000..b34f27cd
--- /dev/null
+++ b/dist/modules/core/render.cjs
@@ -0,0 +1,389 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var globals = require('./globals.cjs');
+var consts = require('./consts.cjs');
+var helpers = require('./helpers.cjs');
+
+/**
+ * @import {
+ * Tickable,
+ * Renderable,
+ * CallbackArgument,
+ * Tween,
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
+
+/**
+ * @param {Tickable} tickable
+ * @param {Number} time
+ * @param {Number} muteCallbacks
+ * @param {Number} internalRender
+ * @param {tickModes} tickMode
+ * @return {Number}
+ */
+const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
+
+ const parent = tickable.parent;
+ const duration = tickable.duration;
+ const completed = tickable.completed;
+ const iterationDuration = tickable.iterationDuration;
+ const iterationCount = tickable.iterationCount;
+ const _currentIteration = tickable._currentIteration;
+ const _loopDelay = tickable._loopDelay;
+ const _reversed = tickable._reversed;
+ const _alternate = tickable._alternate;
+ const _hasChildren = tickable._hasChildren;
+ const tickableDelay = tickable._delay;
+ const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime
+
+ const tickableEndTime = tickableDelay + iterationDuration;
+ const tickableAbsoluteTime = time - tickableDelay;
+ const tickablePrevTime = helpers.clamp(tickablePrevAbsoluteTime, -tickableDelay, duration);
+ const tickableCurrentTime = helpers.clamp(tickableAbsoluteTime, -tickableDelay, duration);
+ const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime;
+ const isCurrentTimeAboveZero = tickableCurrentTime > 0;
+ const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration;
+ const isSetter = duration <= consts.minValue;
+ const forcedTick = tickMode === consts.tickModes.FORCE;
+
+ let isOdd = 0;
+ let iterationElapsedTime = tickableAbsoluteTime;
+ // Render checks
+ // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer
+ let hasRendered = 0;
+
+ // Execute the "expensive" iterations calculations only when necessary
+ if (iterationCount > 1) {
+ // bitwise NOT operator seems to be generally faster than Math.floor() across browsers
+ const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay)));
+ tickable._currentIteration = helpers.clamp(currentIteration, 0, iterationCount);
+ // Prevent the iteration count to go above the max iterations when reaching the end of the animation
+ if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--;
+ isOdd = tickable._currentIteration % 2;
+ iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0;
+ }
+
+ // Checks if exactly one of _reversed and (_alternate && isOdd) is true
+ const isReversed = _reversed ^ (_alternate && isOdd);
+ const _ease = /** @type {Renderable} */(tickable)._ease;
+ let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime;
+ if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0;
+ const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed;
+
+ tickable._currentTime = tickableAbsoluteTime;
+ tickable._iterationTime = iterationTime;
+ tickable.backwards = isRunningBackwards;
+
+ if (isCurrentTimeAboveZero && !tickable.began) {
+ tickable.began = true;
+ if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) {
+ tickable.onBegin(/** @type {CallbackArgument} */(tickable));
+ }
+ } else if (tickableAbsoluteTime <= 0) {
+ tickable.began = false;
+ }
+
+ // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function
+ // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values
+ if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) {
+ tickable.onLoop(/** @type {CallbackArgument} */(tickable));
+ }
+
+ if (
+ forcedTick ||
+ tickMode === consts.tickModes.AUTO && (
+ time >= tickableDelay && time <= tickableEndTime || // Normal render
+ time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state
+ time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state
+ ) ||
+ iterationTime >= tickableEndTime && tickablePrevTime !== duration ||
+ iterationTime <= tickableDelay && tickablePrevTime > 0 ||
+ time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation
+ isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped
+ ) {
+
+ if (isCurrentTimeAboveZero) {
+ // Trigger onUpdate callback before rendering
+ tickable.computeDeltaTime(tickablePrevTime);
+ if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable));
+ }
+
+ // Start tweens rendering
+ if (!_hasChildren) {
+
+ // Time has jumped more than globals.tickThreshold so consider this tick manual
+ const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.globals.tickThreshold;
+ const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime;
+
+ // Only Animation can have tweens, Timer returns undefined
+ let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head);
+ let tweenTarget;
+ let tweenStyle;
+ let tweenTargetTransforms;
+ let tweenTargetTransformsProperties;
+ let tweenTransformsNeedUpdate = 0;
+
+ while (tween) {
+
+ const tweenComposition = tween._composition;
+ const tweenCurrentTime = tween._currentTime;
+ const tweenChangeDuration = tween._changeDuration;
+ const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration;
+ const tweenNextRep = tween._nextRep;
+ const tweenPrevRep = tween._prevRep;
+ const tweenHasComposition = tweenComposition !== consts.compositionTypes.none;
+
+ if ((forcedRender || (
+ (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) &&
+ (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime)
+ )) && (!tweenHasComposition || (
+ !tween._isOverridden &&
+ (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) &&
+ (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) &&
+ (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay)))
+ ))
+ ) {
+
+ const tweenNewTime = tween._currentTime = helpers.clamp(iterationTime - tween._startTime, 0, tweenChangeDuration);
+ const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration);
+ const tweenModifier = tween._modifier;
+ const tweenValueType = tween._valueType;
+ const tweenType = tween._tweenType;
+ const tweenIsObject = tweenType === consts.tweenTypes.OBJECT;
+ const tweenIsNumber = tweenValueType === consts.valueTypes.NUMBER;
+ // Only round the in-between frames values if the final value is a string
+ const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.globals.precision;
+
+ // Recompose tween value
+ /** @type {String|Number} */
+ let value;
+ /** @type {Number} */
+ let number;
+
+ if (tweenIsNumber) {
+ value = number = /** @type {Number} */(tweenModifier(helpers.round(helpers.lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
+ } else if (tweenValueType === consts.valueTypes.UNIT) {
+ // Rounding the values speed up string composition
+ number = /** @type {Number} */(tweenModifier(helpers.round(helpers.lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
+ value = `${number}${tween._unit}`;
+ } else if (tweenValueType === consts.valueTypes.COLOR) {
+ const fn = tween._fromNumbers;
+ const tn = tween._toNumbers;
+ const r = helpers.round(helpers.clamp(/** @type {Number} */(tweenModifier(helpers.lerp(fn[0], tn[0], tweenProgress))), 0, 255), 0);
+ const g = helpers.round(helpers.clamp(/** @type {Number} */(tweenModifier(helpers.lerp(fn[1], tn[1], tweenProgress))), 0, 255), 0);
+ const b = helpers.round(helpers.clamp(/** @type {Number} */(tweenModifier(helpers.lerp(fn[2], tn[2], tweenProgress))), 0, 255), 0);
+ const a = helpers.clamp(/** @type {Number} */(tweenModifier(helpers.round(helpers.lerp(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
+ value = `rgba(${r},${g},${b},${a})`;
+ if (tweenHasComposition) {
+ const ns = tween._numbers;
+ ns[0] = r;
+ ns[1] = g;
+ ns[2] = b;
+ ns[3] = a;
+ }
+ } else if (tweenValueType === consts.valueTypes.COMPLEX) {
+ value = tween._strings[0];
+ for (let j = 0, l = tween._toNumbers.length; j < l; j++) {
+ const n = /** @type {Number} */(tweenModifier(helpers.round(helpers.lerp(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
+ const s = tween._strings[j + 1];
+ value += `${s ? n + s : n}`;
+ if (tweenHasComposition) {
+ tween._numbers[j] = n;
+ }
+ }
+ }
+
+ // For additive tweens and Animatables
+ if (tweenHasComposition) {
+ tween._number = number;
+ }
+
+ if (!internalRender && tweenComposition !== consts.compositionTypes.blend) {
+
+ const tweenProperty = tween.property;
+ tweenTarget = tween.target;
+
+ if (tweenIsObject) {
+ tweenTarget[tweenProperty] = value;
+ } else if (tweenType === consts.tweenTypes.ATTRIBUTE) {
+ /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value));
+ } else {
+ tweenStyle = /** @type {DOMTarget} */(tweenTarget).style;
+ if (tweenType === consts.tweenTypes.TRANSFORM) {
+ if (tweenTarget !== tweenTargetTransforms) {
+ tweenTargetTransforms = tweenTarget;
+ // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage.
+ tweenTargetTransformsProperties = tweenTarget[consts.transformsSymbol];
+ }
+ tweenTargetTransformsProperties[tweenProperty] = value;
+ tweenTransformsNeedUpdate = 1;
+ } else if (tweenType === consts.tweenTypes.CSS) {
+ tweenStyle[tweenProperty] = value;
+ } else if (tweenType === consts.tweenTypes.CSS_VAR) {
+ tweenStyle.setProperty(tweenProperty,/** @type {String} */(value));
+ }
+ }
+
+ if (isCurrentTimeAboveZero) hasRendered = 1;
+
+ } else {
+ // Used for composing timeline tweens without having to do a real render
+ tween._value = value;
+ }
+
+ }
+
+ // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax
+ // to reduce memory usage on string composition
+ if (tweenTransformsNeedUpdate && tween._renderTransforms) {
+ let str = consts.emptyString;
+ for (let key in tweenTargetTransformsProperties) {
+ str += `${consts.transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `;
+ }
+ tweenStyle.transform = str;
+ tweenTransformsNeedUpdate = 0;
+ }
+
+ tween = tween._next;
+ }
+
+ if (!muteCallbacks && hasRendered) {
+ /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable));
+ }
+ }
+
+ if (!muteCallbacks && isCurrentTimeAboveZero) {
+ tickable.onUpdate(/** @type {CallbackArgument} */(tickable));
+ }
+
+ }
+
+ // End tweens rendering
+
+ // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards
+ if (parent && isSetter) {
+ if (!muteCallbacks && (
+ (parent.began && !isRunningBackwards && tickableAbsoluteTime >= duration && !completed) ||
+ (isRunningBackwards && tickableAbsoluteTime <= consts.minValue && completed)
+ )) {
+ tickable.onComplete(/** @type {CallbackArgument} */(tickable));
+ tickable.completed = !isRunningBackwards;
+ }
+ // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops
+ } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) {
+ if (iterationCount === Infinity) {
+ // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer
+ tickable._startTime += tickable.duration;
+ } else if (tickable._currentIteration >= iterationCount - 1) {
+ // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick
+ tickable.paused = true;
+ if (!completed && !_hasChildren) {
+ // If the tickable has children, triggers onComplete() only when all children have completed in the tick function
+ tickable.completed = true;
+ if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) {
+ tickable.onComplete(/** @type {CallbackArgument} */(tickable));
+ tickable._resolve(/** @type {CallbackArgument} */(tickable));
+ }
+ }
+ }
+ // Otherwise set the completed flag to false
+ } else {
+ tickable.completed = false;
+ }
+
+ // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ?
+ return hasRendered;
+};
+
+/**
+ * @param {Tickable} tickable
+ * @param {Number} time
+ * @param {Number} muteCallbacks
+ * @param {Number} internalRender
+ * @param {Number} tickMode
+ * @return {void}
+ */
+const tick = (tickable, time, muteCallbacks, internalRender, tickMode) => {
+ const _currentIteration = tickable._currentIteration;
+ render(tickable, time, muteCallbacks, internalRender, tickMode);
+ if (tickable._hasChildren) {
+ const tl = /** @type {Timeline} */(tickable);
+ const tlIsRunningBackwards = tl.backwards;
+ const tlChildrenTime = internalRender ? time : tl._iterationTime;
+ const tlCildrenTickTime = helpers.now();
+
+ let tlChildrenHasRendered = 0;
+ let tlChildrenHaveCompleted = true;
+
+ // If the timeline has looped forward, we need to manually triggers children skipped callbacks
+ if (!internalRender && tl._currentIteration !== _currentIteration) {
+ const tlIterationDuration = tl.iterationDuration;
+ helpers.forEachChildren(tl, (/** @type {JSAnimation} */child) => {
+ if (!tlIsRunningBackwards) {
+ // Force an internal render to trigger the callbacks if the child has not completed on loop
+ if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) {
+ render(child, tlIterationDuration, muteCallbacks, 1, consts.tickModes.FORCE);
+ }
+ // Reset their began and completed flags to allow retrigering callbacks on the next iteration
+ child.began = false;
+ child.completed = false;
+ } else {
+ const childDuration = child.duration;
+ const childStartTime = child._offset + child._delay;
+ const childEndTime = childStartTime + childDuration;
+ // Triggers the onComplete callback on reverse for children on the edges of the timeline
+ if (!muteCallbacks && childDuration <= consts.minValue && (!childStartTime || childEndTime === tlIterationDuration)) {
+ child.onComplete(child);
+ }
+ }
+ });
+ if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl));
+ }
+
+ helpers.forEachChildren(tl, (/** @type {JSAnimation} */child) => {
+ const childTime = helpers.round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds
+ const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode;
+ tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode);
+ if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false;
+ }, tlIsRunningBackwards);
+
+ // Renders on timeline are triggered by its children so it needs to be set after rendering the children
+ if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl));
+
+ // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end
+ if ((tlChildrenHaveCompleted || tlIsRunningBackwards) && tl._currentTime >= tl.duration) {
+ // Make sure the paused flag is false in case it has been skipped in the render function
+ tl.paused = true;
+ if (!tl.completed) {
+ tl.completed = true;
+ if (!muteCallbacks) {
+ tl.onComplete(/** @type {CallbackArgument} */(tl));
+ tl._resolve(/** @type {CallbackArgument} */(tl));
+ }
+ }
+ }
+ }
+};
+
+exports.render = render;
+exports.tick = tick;
diff --git a/dist/modules/core/render.d.ts b/dist/modules/core/render.d.ts
new file mode 100644
index 00000000..66f93abc
--- /dev/null
+++ b/dist/modules/core/render.d.ts
@@ -0,0 +1,4 @@
+export function render(tickable: Tickable, time: number, muteCallbacks: number, internalRender: number, tickMode: tickModes): number;
+export function tick(tickable: Tickable, time: number, muteCallbacks: number, internalRender: number, tickMode: number): void;
+import type { Tickable } from '../types/index.js';
+import { tickModes } from './consts.js';
diff --git a/dist/modules/core/render.js b/dist/modules/core/render.js
new file mode 100644
index 00000000..49ef8287
--- /dev/null
+++ b/dist/modules/core/render.js
@@ -0,0 +1,386 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { globals } from './globals.js';
+import { minValue, tickModes, valueTypes, compositionTypes, tweenTypes, transformsSymbol, transformsFragmentStrings, emptyString } from './consts.js';
+import { forEachChildren, round, now, clamp, lerp } from './helpers.js';
+
+/**
+ * @import {
+ * Tickable,
+ * Renderable,
+ * CallbackArgument,
+ * Tween,
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
+
+/**
+ * @param {Tickable} tickable
+ * @param {Number} time
+ * @param {Number} muteCallbacks
+ * @param {Number} internalRender
+ * @param {tickModes} tickMode
+ * @return {Number}
+ */
+const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
+
+ const parent = tickable.parent;
+ const duration = tickable.duration;
+ const completed = tickable.completed;
+ const iterationDuration = tickable.iterationDuration;
+ const iterationCount = tickable.iterationCount;
+ const _currentIteration = tickable._currentIteration;
+ const _loopDelay = tickable._loopDelay;
+ const _reversed = tickable._reversed;
+ const _alternate = tickable._alternate;
+ const _hasChildren = tickable._hasChildren;
+ const tickableDelay = tickable._delay;
+ const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime
+
+ const tickableEndTime = tickableDelay + iterationDuration;
+ const tickableAbsoluteTime = time - tickableDelay;
+ const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration);
+ const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration);
+ const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime;
+ const isCurrentTimeAboveZero = tickableCurrentTime > 0;
+ const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration;
+ const isSetter = duration <= minValue;
+ const forcedTick = tickMode === tickModes.FORCE;
+
+ let isOdd = 0;
+ let iterationElapsedTime = tickableAbsoluteTime;
+ // Render checks
+ // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer
+ let hasRendered = 0;
+
+ // Execute the "expensive" iterations calculations only when necessary
+ if (iterationCount > 1) {
+ // bitwise NOT operator seems to be generally faster than Math.floor() across browsers
+ const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay)));
+ tickable._currentIteration = clamp(currentIteration, 0, iterationCount);
+ // Prevent the iteration count to go above the max iterations when reaching the end of the animation
+ if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--;
+ isOdd = tickable._currentIteration % 2;
+ iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0;
+ }
+
+ // Checks if exactly one of _reversed and (_alternate && isOdd) is true
+ const isReversed = _reversed ^ (_alternate && isOdd);
+ const _ease = /** @type {Renderable} */(tickable)._ease;
+ let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime;
+ if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0;
+ const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed;
+
+ tickable._currentTime = tickableAbsoluteTime;
+ tickable._iterationTime = iterationTime;
+ tickable.backwards = isRunningBackwards;
+
+ if (isCurrentTimeAboveZero && !tickable.began) {
+ tickable.began = true;
+ if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) {
+ tickable.onBegin(/** @type {CallbackArgument} */(tickable));
+ }
+ } else if (tickableAbsoluteTime <= 0) {
+ tickable.began = false;
+ }
+
+ // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function
+ // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values
+ if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) {
+ tickable.onLoop(/** @type {CallbackArgument} */(tickable));
+ }
+
+ if (
+ forcedTick ||
+ tickMode === tickModes.AUTO && (
+ time >= tickableDelay && time <= tickableEndTime || // Normal render
+ time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state
+ time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state
+ ) ||
+ iterationTime >= tickableEndTime && tickablePrevTime !== duration ||
+ iterationTime <= tickableDelay && tickablePrevTime > 0 ||
+ time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation
+ isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped
+ ) {
+
+ if (isCurrentTimeAboveZero) {
+ // Trigger onUpdate callback before rendering
+ tickable.computeDeltaTime(tickablePrevTime);
+ if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable));
+ }
+
+ // Start tweens rendering
+ if (!_hasChildren) {
+
+ // Time has jumped more than globals.tickThreshold so consider this tick manual
+ const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold;
+ const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime;
+
+ // Only Animation can have tweens, Timer returns undefined
+ let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head);
+ let tweenTarget;
+ let tweenStyle;
+ let tweenTargetTransforms;
+ let tweenTargetTransformsProperties;
+ let tweenTransformsNeedUpdate = 0;
+
+ while (tween) {
+
+ const tweenComposition = tween._composition;
+ const tweenCurrentTime = tween._currentTime;
+ const tweenChangeDuration = tween._changeDuration;
+ const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration;
+ const tweenNextRep = tween._nextRep;
+ const tweenPrevRep = tween._prevRep;
+ const tweenHasComposition = tweenComposition !== compositionTypes.none;
+
+ if ((forcedRender || (
+ (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) &&
+ (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime)
+ )) && (!tweenHasComposition || (
+ !tween._isOverridden &&
+ (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) &&
+ (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) &&
+ (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay)))
+ ))
+ ) {
+
+ const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration);
+ const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration);
+ const tweenModifier = tween._modifier;
+ const tweenValueType = tween._valueType;
+ const tweenType = tween._tweenType;
+ const tweenIsObject = tweenType === tweenTypes.OBJECT;
+ const tweenIsNumber = tweenValueType === valueTypes.NUMBER;
+ // Only round the in-between frames values if the final value is a string
+ const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision;
+
+ // Recompose tween value
+ /** @type {String|Number} */
+ let value;
+ /** @type {Number} */
+ let number;
+
+ if (tweenIsNumber) {
+ value = number = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
+ } else if (tweenValueType === valueTypes.UNIT) {
+ // Rounding the values speed up string composition
+ number = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
+ value = `${number}${tween._unit}`;
+ } else if (tweenValueType === valueTypes.COLOR) {
+ const fn = tween._fromNumbers;
+ const tn = tween._toNumbers;
+ const r = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[0], tn[0], tweenProgress))), 0, 255), 0);
+ const g = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[1], tn[1], tweenProgress))), 0, 255), 0);
+ const b = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[2], tn[2], tweenProgress))), 0, 255), 0);
+ const a = clamp(/** @type {Number} */(tweenModifier(round(lerp(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
+ value = `rgba(${r},${g},${b},${a})`;
+ if (tweenHasComposition) {
+ const ns = tween._numbers;
+ ns[0] = r;
+ ns[1] = g;
+ ns[2] = b;
+ ns[3] = a;
+ }
+ } else if (tweenValueType === valueTypes.COMPLEX) {
+ value = tween._strings[0];
+ for (let j = 0, l = tween._toNumbers.length; j < l; j++) {
+ const n = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
+ const s = tween._strings[j + 1];
+ value += `${s ? n + s : n}`;
+ if (tweenHasComposition) {
+ tween._numbers[j] = n;
+ }
+ }
+ }
+
+ // For additive tweens and Animatables
+ if (tweenHasComposition) {
+ tween._number = number;
+ }
+
+ if (!internalRender && tweenComposition !== compositionTypes.blend) {
+
+ const tweenProperty = tween.property;
+ tweenTarget = tween.target;
+
+ if (tweenIsObject) {
+ tweenTarget[tweenProperty] = value;
+ } else if (tweenType === tweenTypes.ATTRIBUTE) {
+ /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value));
+ } else {
+ tweenStyle = /** @type {DOMTarget} */(tweenTarget).style;
+ if (tweenType === tweenTypes.TRANSFORM) {
+ if (tweenTarget !== tweenTargetTransforms) {
+ tweenTargetTransforms = tweenTarget;
+ // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage.
+ tweenTargetTransformsProperties = tweenTarget[transformsSymbol];
+ }
+ tweenTargetTransformsProperties[tweenProperty] = value;
+ tweenTransformsNeedUpdate = 1;
+ } else if (tweenType === tweenTypes.CSS) {
+ tweenStyle[tweenProperty] = value;
+ } else if (tweenType === tweenTypes.CSS_VAR) {
+ tweenStyle.setProperty(tweenProperty,/** @type {String} */(value));
+ }
+ }
+
+ if (isCurrentTimeAboveZero) hasRendered = 1;
+
+ } else {
+ // Used for composing timeline tweens without having to do a real render
+ tween._value = value;
+ }
+
+ }
+
+ // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax
+ // to reduce memory usage on string composition
+ if (tweenTransformsNeedUpdate && tween._renderTransforms) {
+ let str = emptyString;
+ for (let key in tweenTargetTransformsProperties) {
+ str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `;
+ }
+ tweenStyle.transform = str;
+ tweenTransformsNeedUpdate = 0;
+ }
+
+ tween = tween._next;
+ }
+
+ if (!muteCallbacks && hasRendered) {
+ /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable));
+ }
+ }
+
+ if (!muteCallbacks && isCurrentTimeAboveZero) {
+ tickable.onUpdate(/** @type {CallbackArgument} */(tickable));
+ }
+
+ }
+
+ // End tweens rendering
+
+ // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards
+ if (parent && isSetter) {
+ if (!muteCallbacks && (
+ (parent.began && !isRunningBackwards && tickableAbsoluteTime >= duration && !completed) ||
+ (isRunningBackwards && tickableAbsoluteTime <= minValue && completed)
+ )) {
+ tickable.onComplete(/** @type {CallbackArgument} */(tickable));
+ tickable.completed = !isRunningBackwards;
+ }
+ // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops
+ } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) {
+ if (iterationCount === Infinity) {
+ // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer
+ tickable._startTime += tickable.duration;
+ } else if (tickable._currentIteration >= iterationCount - 1) {
+ // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick
+ tickable.paused = true;
+ if (!completed && !_hasChildren) {
+ // If the tickable has children, triggers onComplete() only when all children have completed in the tick function
+ tickable.completed = true;
+ if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) {
+ tickable.onComplete(/** @type {CallbackArgument} */(tickable));
+ tickable._resolve(/** @type {CallbackArgument} */(tickable));
+ }
+ }
+ }
+ // Otherwise set the completed flag to false
+ } else {
+ tickable.completed = false;
+ }
+
+ // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ?
+ return hasRendered;
+};
+
+/**
+ * @param {Tickable} tickable
+ * @param {Number} time
+ * @param {Number} muteCallbacks
+ * @param {Number} internalRender
+ * @param {Number} tickMode
+ * @return {void}
+ */
+const tick = (tickable, time, muteCallbacks, internalRender, tickMode) => {
+ const _currentIteration = tickable._currentIteration;
+ render(tickable, time, muteCallbacks, internalRender, tickMode);
+ if (tickable._hasChildren) {
+ const tl = /** @type {Timeline} */(tickable);
+ const tlIsRunningBackwards = tl.backwards;
+ const tlChildrenTime = internalRender ? time : tl._iterationTime;
+ const tlCildrenTickTime = now();
+
+ let tlChildrenHasRendered = 0;
+ let tlChildrenHaveCompleted = true;
+
+ // If the timeline has looped forward, we need to manually triggers children skipped callbacks
+ if (!internalRender && tl._currentIteration !== _currentIteration) {
+ const tlIterationDuration = tl.iterationDuration;
+ forEachChildren(tl, (/** @type {JSAnimation} */child) => {
+ if (!tlIsRunningBackwards) {
+ // Force an internal render to trigger the callbacks if the child has not completed on loop
+ if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) {
+ render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE);
+ }
+ // Reset their began and completed flags to allow retrigering callbacks on the next iteration
+ child.began = false;
+ child.completed = false;
+ } else {
+ const childDuration = child.duration;
+ const childStartTime = child._offset + child._delay;
+ const childEndTime = childStartTime + childDuration;
+ // Triggers the onComplete callback on reverse for children on the edges of the timeline
+ if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) {
+ child.onComplete(child);
+ }
+ }
+ });
+ if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl));
+ }
+
+ forEachChildren(tl, (/** @type {JSAnimation} */child) => {
+ const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds
+ const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode;
+ tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode);
+ if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false;
+ }, tlIsRunningBackwards);
+
+ // Renders on timeline are triggered by its children so it needs to be set after rendering the children
+ if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl));
+
+ // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end
+ if ((tlChildrenHaveCompleted || tlIsRunningBackwards) && tl._currentTime >= tl.duration) {
+ // Make sure the paused flag is false in case it has been skipped in the render function
+ tl.paused = true;
+ if (!tl.completed) {
+ tl.completed = true;
+ if (!muteCallbacks) {
+ tl.onComplete(/** @type {CallbackArgument} */(tl));
+ tl._resolve(/** @type {CallbackArgument} */(tl));
+ }
+ }
+ }
+ }
+};
+
+export { render, tick };
diff --git a/dist/modules/core/styles.cjs b/dist/modules/core/styles.cjs
new file mode 100644
index 00000000..6122d629
--- /dev/null
+++ b/dist/modules/core/styles.cjs
@@ -0,0 +1,116 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('./consts.cjs');
+var helpers = require('./helpers.cjs');
+
+const propertyNamesCache = {};
+
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+* @import {
+* Target,
+* DOMTarget,
+* Renderable,
+* Tween,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {String} propertyName
+ * @param {Target} target
+ * @param {tweenTypes} tweenType
+ * @return {String}
+ */
+const sanitizePropertyName = (propertyName, target, tweenType) => {
+ if (tweenType === consts.tweenTypes.TRANSFORM) {
+ const t = consts.shortTransforms.get(propertyName);
+ return t ? t : propertyName;
+ } else if (
+ tweenType === consts.tweenTypes.CSS ||
+ // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
+ // but properties like "baseFrequency" should stay in lowerCamelCase
+ (tweenType === consts.tweenTypes.ATTRIBUTE && (helpers.isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
+ ) {
+ const cachedPropertyName = propertyNamesCache[propertyName];
+ if (cachedPropertyName) {
+ return cachedPropertyName;
+ } else {
+ const lowerCaseName = propertyName ? helpers.toLowerCase(propertyName) : propertyName;
+ propertyNamesCache[propertyName] = lowerCaseName;
+ return lowerCaseName;
+ }
+ } else {
+ return propertyName;
+ }
+};
+
+/**
+ * @template {Renderable} T
+ * @param {T} renderable
+ * @return {T}
+ */
+const cleanInlineStyles = renderable => {
+ // Allow cleanInlineStyles() to be called on timelines
+ if (renderable._hasChildren) {
+ helpers.forEachChildren(renderable, cleanInlineStyles, true);
+ } else {
+ const animation = /** @type {JSAnimation} */(renderable);
+ animation.pause();
+ helpers.forEachChildren(animation, (/** @type {Tween} */tween) => {
+ const tweenProperty = tween.property;
+ const tweenTarget = tween.target;
+ if (tweenTarget[consts.isDomSymbol]) {
+ const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
+ const originalInlinedValue = animation._inlineStyles[tweenProperty];
+ if (tween._tweenType === consts.tweenTypes.TRANSFORM) {
+ const cachedTransforms = tweenTarget[consts.transformsSymbol];
+ if (helpers.isUnd(originalInlinedValue) || originalInlinedValue === consts.emptyString) {
+ delete cachedTransforms[tweenProperty];
+ } else {
+ cachedTransforms[tweenProperty] = originalInlinedValue;
+ }
+ if (tween._renderTransforms) {
+ if (!Object.keys(cachedTransforms).length) {
+ targetStyle.removeProperty('transform');
+ } else {
+ let str = consts.emptyString;
+ for (let key in cachedTransforms) {
+ str += consts.transformsFragmentStrings[key] + cachedTransforms[key] + ') ';
+ }
+ targetStyle.transform = str;
+ }
+ }
+ } else {
+ if (helpers.isUnd(originalInlinedValue) || originalInlinedValue === consts.emptyString) {
+ targetStyle.removeProperty(tweenProperty);
+ } else {
+ targetStyle[tweenProperty] = originalInlinedValue;
+ }
+ }
+ if (animation._tail === tween) {
+ animation.targets.forEach(t => {
+ if (t.getAttribute && t.getAttribute('style') === consts.emptyString) {
+ t.removeAttribute('style');
+ } });
+ }
+ }
+ });
+ }
+ return renderable;
+};
+
+exports.cleanInlineStyles = cleanInlineStyles;
+exports.sanitizePropertyName = sanitizePropertyName;
diff --git a/dist/modules/core/styles.d.ts b/dist/modules/core/styles.d.ts
new file mode 100644
index 00000000..8be6491e
--- /dev/null
+++ b/dist/modules/core/styles.d.ts
@@ -0,0 +1,5 @@
+export function sanitizePropertyName(propertyName: string, target: Target, tweenType: tweenTypes): string;
+export function cleanInlineStyles<T extends Renderable>(renderable: T): T;
+import type { Target } from '../types/index.js';
+import { tweenTypes } from './consts.js';
+import type { Renderable } from '../types/index.js';
diff --git a/dist/modules/core/styles.js b/dist/modules/core/styles.js
new file mode 100644
index 00000000..c55c2093
--- /dev/null
+++ b/dist/modules/core/styles.js
@@ -0,0 +1,113 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { tweenTypes, shortTransforms, isDomSymbol, transformsSymbol, emptyString, transformsFragmentStrings } from './consts.js';
+import { forEachChildren, isSvg, toLowerCase, isUnd } from './helpers.js';
+
+const propertyNamesCache = {};
+
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+* @import {
+* Target,
+* DOMTarget,
+* Renderable,
+* Tween,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {String} propertyName
+ * @param {Target} target
+ * @param {tweenTypes} tweenType
+ * @return {String}
+ */
+const sanitizePropertyName = (propertyName, target, tweenType) => {
+ if (tweenType === tweenTypes.TRANSFORM) {
+ const t = shortTransforms.get(propertyName);
+ return t ? t : propertyName;
+ } else if (
+ tweenType === tweenTypes.CSS ||
+ // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
+ // but properties like "baseFrequency" should stay in lowerCamelCase
+ (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
+ ) {
+ const cachedPropertyName = propertyNamesCache[propertyName];
+ if (cachedPropertyName) {
+ return cachedPropertyName;
+ } else {
+ const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
+ propertyNamesCache[propertyName] = lowerCaseName;
+ return lowerCaseName;
+ }
+ } else {
+ return propertyName;
+ }
+};
+
+/**
+ * @template {Renderable} T
+ * @param {T} renderable
+ * @return {T}
+ */
+const cleanInlineStyles = renderable => {
+ // Allow cleanInlineStyles() to be called on timelines
+ if (renderable._hasChildren) {
+ forEachChildren(renderable, cleanInlineStyles, true);
+ } else {
+ const animation = /** @type {JSAnimation} */(renderable);
+ animation.pause();
+ forEachChildren(animation, (/** @type {Tween} */tween) => {
+ const tweenProperty = tween.property;
+ const tweenTarget = tween.target;
+ if (tweenTarget[isDomSymbol]) {
+ const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
+ const originalInlinedValue = animation._inlineStyles[tweenProperty];
+ if (tween._tweenType === tweenTypes.TRANSFORM) {
+ const cachedTransforms = tweenTarget[transformsSymbol];
+ if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
+ delete cachedTransforms[tweenProperty];
+ } else {
+ cachedTransforms[tweenProperty] = originalInlinedValue;
+ }
+ if (tween._renderTransforms) {
+ if (!Object.keys(cachedTransforms).length) {
+ targetStyle.removeProperty('transform');
+ } else {
+ let str = emptyString;
+ for (let key in cachedTransforms) {
+ str += transformsFragmentStrings[key] + cachedTransforms[key] + ') ';
+ }
+ targetStyle.transform = str;
+ }
+ }
+ } else {
+ if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
+ targetStyle.removeProperty(tweenProperty);
+ } else {
+ targetStyle[tweenProperty] = originalInlinedValue;
+ }
+ }
+ if (animation._tail === tween) {
+ animation.targets.forEach(t => {
+ if (t.getAttribute && t.getAttribute('style') === emptyString) {
+ t.removeAttribute('style');
+ } });
+ }
+ }
+ });
+ }
+ return renderable;
+};
+
+export { cleanInlineStyles, sanitizePropertyName };
diff --git a/dist/modules/core/targets.cjs b/dist/modules/core/targets.cjs
new file mode 100644
index 00000000..b365b9af
--- /dev/null
+++ b/dist/modules/core/targets.cjs
@@ -0,0 +1,136 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var globals = require('./globals.cjs');
+var consts = require('./consts.cjs');
+var helpers = require('./helpers.cjs');
+
+/**
+* @import {
+* DOMTarget,
+* DOMTargetsParam,
+* JSTargetsArray,
+* TargetsParam,
+* JSTargetsParam,
+* TargetsArray,
+* DOMTargetsArray,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {DOMTargetsParam|TargetsParam} v
+ * @return {NodeList|HTMLCollection}
+ */
+function getNodeList(v) {
+ const n = helpers.isStr(v) ? globals.scope.root.querySelectorAll(v) : v;
+ if (n instanceof NodeList || n instanceof HTMLCollection) return n;
+}
+
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+function parseTargets(targets) {
+ if (helpers.isNil(targets)) return /** @type {TargetsArray} */([]);
+ if (!consts.isBrowser) return /** @type {JSTargetsArray} */(helpers.isArr(targets) && targets.flat(Infinity) || [targets]);
+ if (helpers.isArr(targets)) {
+ const flattened = targets.flat(Infinity);
+ /** @type {TargetsArray} */
+ const parsed = [];
+ for (let i = 0, l = flattened.length; i < l; i++) {
+ const item = flattened[i];
+ if (!helpers.isNil(item)) {
+ const nodeList = getNodeList(item);
+ if (nodeList) {
+ for (let j = 0, jl = nodeList.length; j < jl; j++) {
+ const subItem = nodeList[j];
+ if (!helpers.isNil(subItem)) {
+ let isDuplicate = false;
+ for (let k = 0, kl = parsed.length; k < kl; k++) {
+ if (parsed[k] === subItem) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ parsed.push(subItem);
+ }
+ }
+ }
+ } else {
+ let isDuplicate = false;
+ for (let j = 0, jl = parsed.length; j < jl; j++) {
+ if (parsed[j] === item) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ parsed.push(item);
+ }
+ }
+ }
+ }
+ return parsed;
+ }
+ const nodeList = getNodeList(targets);
+ if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList));
+ return /** @type {TargetsArray} */([targets]);
+}
+
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+function registerTargets(targets) {
+ const parsedTargetsArray = parseTargets(targets);
+ const parsedTargetsLength = parsedTargetsArray.length;
+ if (parsedTargetsLength) {
+ for (let i = 0; i < parsedTargetsLength; i++) {
+ const target = parsedTargetsArray[i];
+ if (!target[consts.isRegisteredTargetSymbol]) {
+ target[consts.isRegisteredTargetSymbol] = true;
+ const isSvgType = helpers.isSvg(target);
+ const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType;
+ if (isDom) {
+ target[consts.isDomSymbol] = true;
+ target[consts.isSvgSymbol] = isSvgType;
+ target[consts.transformsSymbol] = {};
+ }
+ }
+ }
+ }
+ return parsedTargetsArray;
+}
+
+exports.getNodeList = getNodeList;
+exports.parseTargets = parseTargets;
+exports.registerTargets = registerTargets;
diff --git a/dist/modules/core/targets.d.ts b/dist/modules/core/targets.d.ts
new file mode 100644
index 00000000..90f8b7a5
--- /dev/null
+++ b/dist/modules/core/targets.d.ts
@@ -0,0 +1,118 @@
+/**
+* @import {
+* DOMTarget,
+* DOMTargetsParam,
+* JSTargetsArray,
+* TargetsParam,
+* JSTargetsParam,
+* TargetsArray,
+* DOMTargetsArray,
+* } from '../types/index.js'
+*/
+/**
+ * @param {DOMTargetsParam|TargetsParam} v
+ * @return {NodeList|HTMLCollection}
+ */
+export function getNodeList(v: DOMTargetsParam | TargetsParam): NodeList | HTMLCollection;
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+export function parseTargets(targets: DOMTargetsParam): DOMTargetsArray;
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+export function parseTargets(targets: JSTargetsParam): JSTargetsArray;
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+export function parseTargets(targets: TargetsParam): TargetsArray;
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+export function registerTargets(targets: DOMTargetsParam): DOMTargetsArray;
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+export function registerTargets(targets: JSTargetsParam): JSTargetsArray;
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+export function registerTargets(targets: TargetsParam): TargetsArray;
+import type { DOMTargetsParam } from '../types/index.js';
+import type { TargetsParam } from '../types/index.js';
+import type { DOMTargetsArray } from '../types/index.js';
+import type { JSTargetsParam } from '../types/index.js';
+import type { JSTargetsArray } from '../types/index.js';
+import type { TargetsArray } from '../types/index.js';
diff --git a/dist/modules/core/targets.js b/dist/modules/core/targets.js
new file mode 100644
index 00000000..9da193f8
--- /dev/null
+++ b/dist/modules/core/targets.js
@@ -0,0 +1,132 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { scope } from './globals.js';
+import { isRegisteredTargetSymbol, isDomSymbol, isSvgSymbol, transformsSymbol, isBrowser } from './consts.js';
+import { isSvg, isNil, isArr, isStr } from './helpers.js';
+
+/**
+* @import {
+* DOMTarget,
+* DOMTargetsParam,
+* JSTargetsArray,
+* TargetsParam,
+* JSTargetsParam,
+* TargetsArray,
+* DOMTargetsArray,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {DOMTargetsParam|TargetsParam} v
+ * @return {NodeList|HTMLCollection}
+ */
+function getNodeList(v) {
+ const n = isStr(v) ? scope.root.querySelectorAll(v) : v;
+ if (n instanceof NodeList || n instanceof HTMLCollection) return n;
+}
+
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+function parseTargets(targets) {
+ if (isNil(targets)) return /** @type {TargetsArray} */([]);
+ if (!isBrowser) return /** @type {JSTargetsArray} */(isArr(targets) && targets.flat(Infinity) || [targets]);
+ if (isArr(targets)) {
+ const flattened = targets.flat(Infinity);
+ /** @type {TargetsArray} */
+ const parsed = [];
+ for (let i = 0, l = flattened.length; i < l; i++) {
+ const item = flattened[i];
+ if (!isNil(item)) {
+ const nodeList = getNodeList(item);
+ if (nodeList) {
+ for (let j = 0, jl = nodeList.length; j < jl; j++) {
+ const subItem = nodeList[j];
+ if (!isNil(subItem)) {
+ let isDuplicate = false;
+ for (let k = 0, kl = parsed.length; k < kl; k++) {
+ if (parsed[k] === subItem) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ parsed.push(subItem);
+ }
+ }
+ }
+ } else {
+ let isDuplicate = false;
+ for (let j = 0, jl = parsed.length; j < jl; j++) {
+ if (parsed[j] === item) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ if (!isDuplicate) {
+ parsed.push(item);
+ }
+ }
+ }
+ }
+ return parsed;
+ }
+ const nodeList = getNodeList(targets);
+ if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList));
+ return /** @type {TargetsArray} */([targets]);
+}
+
+/**
+ * @overload
+ * @param {DOMTargetsParam} targets
+ * @return {DOMTargetsArray}
+ *
+ * @overload
+ * @param {JSTargetsParam} targets
+ * @return {JSTargetsArray}
+ *
+ * @overload
+ * @param {TargetsParam} targets
+ * @return {TargetsArray}
+ *
+ * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
+ */
+function registerTargets(targets) {
+ const parsedTargetsArray = parseTargets(targets);
+ const parsedTargetsLength = parsedTargetsArray.length;
+ if (parsedTargetsLength) {
+ for (let i = 0; i < parsedTargetsLength; i++) {
+ const target = parsedTargetsArray[i];
+ if (!target[isRegisteredTargetSymbol]) {
+ target[isRegisteredTargetSymbol] = true;
+ const isSvgType = isSvg(target);
+ const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType;
+ if (isDom) {
+ target[isDomSymbol] = true;
+ target[isSvgSymbol] = isSvgType;
+ target[transformsSymbol] = {};
+ }
+ }
+ }
+ }
+ return parsedTargetsArray;
+}
+
+export { getNodeList, parseTargets, registerTargets };
diff --git a/dist/modules/core/transforms.cjs b/dist/modules/core/transforms.cjs
new file mode 100644
index 00000000..1285e52e
--- /dev/null
+++ b/dist/modules/core/transforms.cjs
@@ -0,0 +1,49 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('./consts.cjs');
+var helpers = require('./helpers.cjs');
+
+/**
+* @import {
+* DOMTarget,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {DOMTarget} target
+ * @param {String} propName
+ * @param {Object} animationInlineStyles
+ * @return {String}
+ */
+const parseInlineTransforms = (target, propName, animationInlineStyles) => {
+ const inlineTransforms = target.style.transform;
+ let inlinedStylesPropertyValue;
+ if (inlineTransforms) {
+ const cachedTransforms = target[consts.transformsSymbol];
+ let t; while (t = consts.transformsExecRgx.exec(inlineTransforms)) {
+ const inlinePropertyName = t[1];
+ // const inlinePropertyValue = t[2];
+ const inlinePropertyValue = t[2].slice(1, -1);
+ cachedTransforms[inlinePropertyName] = inlinePropertyValue;
+ if (inlinePropertyName === propName) {
+ inlinedStylesPropertyValue = inlinePropertyValue;
+ // Store the new parsed inline styles if animationInlineStyles is provided
+ if (animationInlineStyles) {
+ animationInlineStyles[propName] = inlinePropertyValue;
+ }
+ }
+ }
+ }
+ return inlineTransforms && !helpers.isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue :
+ helpers.stringStartsWith(propName, 'scale') ? '1' :
+ helpers.stringStartsWith(propName, 'rotate') || helpers.stringStartsWith(propName, 'skew') ? '0deg' : '0px';
+};
+
+exports.parseInlineTransforms = parseInlineTransforms;
diff --git a/dist/modules/core/transforms.d.ts b/dist/modules/core/transforms.d.ts
new file mode 100644
index 00000000..d393500d
--- /dev/null
+++ b/dist/modules/core/transforms.d.ts
@@ -0,0 +1,2 @@
+export function parseInlineTransforms(target: DOMTarget, propName: string, animationInlineStyles: any): string;
+import type { DOMTarget } from '../types/index.js';
diff --git a/dist/modules/core/transforms.js b/dist/modules/core/transforms.js
new file mode 100644
index 00000000..b8101781
--- /dev/null
+++ b/dist/modules/core/transforms.js
@@ -0,0 +1,47 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { transformsSymbol, transformsExecRgx } from './consts.js';
+import { isUnd, stringStartsWith } from './helpers.js';
+
+/**
+* @import {
+* DOMTarget,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {DOMTarget} target
+ * @param {String} propName
+ * @param {Object} animationInlineStyles
+ * @return {String}
+ */
+const parseInlineTransforms = (target, propName, animationInlineStyles) => {
+ const inlineTransforms = target.style.transform;
+ let inlinedStylesPropertyValue;
+ if (inlineTransforms) {
+ const cachedTransforms = target[transformsSymbol];
+ let t; while (t = transformsExecRgx.exec(inlineTransforms)) {
+ const inlinePropertyName = t[1];
+ // const inlinePropertyValue = t[2];
+ const inlinePropertyValue = t[2].slice(1, -1);
+ cachedTransforms[inlinePropertyName] = inlinePropertyValue;
+ if (inlinePropertyName === propName) {
+ inlinedStylesPropertyValue = inlinePropertyValue;
+ // Store the new parsed inline styles if animationInlineStyles is provided
+ if (animationInlineStyles) {
+ animationInlineStyles[propName] = inlinePropertyValue;
+ }
+ }
+ }
+ }
+ return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue :
+ stringStartsWith(propName, 'scale') ? '1' :
+ stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px';
+};
+
+export { parseInlineTransforms };
diff --git a/dist/modules/core/units.cjs b/dist/modules/core/units.cjs
new file mode 100644
index 00000000..9da3a8c4
--- /dev/null
+++ b/dist/modules/core/units.cjs
@@ -0,0 +1,67 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('./consts.cjs');
+var helpers = require('./helpers.cjs');
+
+const angleUnitsMap = { 'deg': 1, 'rad': 180 / helpers.PI, 'turn': 360 };
+const convertedValuesCache = {};
+
+/**
+* @import {
+* DOMTarget,
+* TweenDecomposedValue,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {DOMTarget} el
+ * @param {TweenDecomposedValue} decomposedValue
+ * @param {String} unit
+ * @param {Boolean} [force]
+ * @return {TweenDecomposedValue}
+ */
+const convertValueUnit = (el, decomposedValue, unit, force = false) => {
+ const currentUnit = decomposedValue.u;
+ const currentNumber = decomposedValue.n;
+ if (decomposedValue.t === consts.valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary
+ return decomposedValue;
+ }
+ const cachedKey = currentNumber + currentUnit + unit;
+ const cached = convertedValuesCache[cachedKey];
+ if (!helpers.isUnd(cached) && !force) {
+ decomposedValue.n = cached;
+ } else {
+ let convertedValue;
+ if (currentUnit in angleUnitsMap) {
+ convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit];
+ } else {
+ const baseline = 100;
+ const tempEl = /** @type {DOMTarget} */(el.cloneNode());
+ const parentNode = el.parentNode;
+ const parentEl = (parentNode && (parentNode !== consts.doc)) ? parentNode : consts.doc.body;
+ parentEl.appendChild(tempEl);
+ const elStyle = tempEl.style;
+ elStyle.width = baseline + currentUnit;
+ const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
+ elStyle.width = baseline + unit;
+ const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
+ const factor = currentUnitWidth / newUnitWidth;
+ parentEl.removeChild(tempEl);
+ convertedValue = factor * currentNumber;
+ }
+ decomposedValue.n = convertedValue;
+ convertedValuesCache[cachedKey] = convertedValue;
+ }
+ decomposedValue.t === consts.valueTypes.UNIT;
+ decomposedValue.u = unit;
+ return decomposedValue;
+};
+
+exports.convertValueUnit = convertValueUnit;
diff --git a/dist/modules/core/units.d.ts b/dist/modules/core/units.d.ts
new file mode 100644
index 00000000..e7d80239
--- /dev/null
+++ b/dist/modules/core/units.d.ts
@@ -0,0 +1,3 @@
+export function convertValueUnit(el: DOMTarget, decomposedValue: TweenDecomposedValue, unit: string, force?: boolean): TweenDecomposedValue;
+import type { DOMTarget } from '../types/index.js';
+import type { TweenDecomposedValue } from '../types/index.js';
diff --git a/dist/modules/core/units.js b/dist/modules/core/units.js
new file mode 100644
index 00000000..c2e33eca
--- /dev/null
+++ b/dist/modules/core/units.js
@@ -0,0 +1,65 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { valueTypes, doc } from './consts.js';
+import { isUnd, PI } from './helpers.js';
+
+const angleUnitsMap = { 'deg': 1, 'rad': 180 / PI, 'turn': 360 };
+const convertedValuesCache = {};
+
+/**
+* @import {
+* DOMTarget,
+* TweenDecomposedValue,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {DOMTarget} el
+ * @param {TweenDecomposedValue} decomposedValue
+ * @param {String} unit
+ * @param {Boolean} [force]
+ * @return {TweenDecomposedValue}
+ */
+const convertValueUnit = (el, decomposedValue, unit, force = false) => {
+ const currentUnit = decomposedValue.u;
+ const currentNumber = decomposedValue.n;
+ if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary
+ return decomposedValue;
+ }
+ const cachedKey = currentNumber + currentUnit + unit;
+ const cached = convertedValuesCache[cachedKey];
+ if (!isUnd(cached) && !force) {
+ decomposedValue.n = cached;
+ } else {
+ let convertedValue;
+ if (currentUnit in angleUnitsMap) {
+ convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit];
+ } else {
+ const baseline = 100;
+ const tempEl = /** @type {DOMTarget} */(el.cloneNode());
+ const parentNode = el.parentNode;
+ const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body;
+ parentEl.appendChild(tempEl);
+ const elStyle = tempEl.style;
+ elStyle.width = baseline + currentUnit;
+ const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
+ elStyle.width = baseline + unit;
+ const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
+ const factor = currentUnitWidth / newUnitWidth;
+ parentEl.removeChild(tempEl);
+ convertedValue = factor * currentNumber;
+ }
+ decomposedValue.n = convertedValue;
+ convertedValuesCache[cachedKey] = convertedValue;
+ }
+ decomposedValue.t === valueTypes.UNIT;
+ decomposedValue.u = unit;
+ return decomposedValue;
+};
+
+export { convertValueUnit };
diff --git a/dist/modules/core/values.cjs b/dist/modules/core/values.cjs
new file mode 100644
index 00000000..0844803c
--- /dev/null
+++ b/dist/modules/core/values.cjs
@@ -0,0 +1,215 @@
+/**
+ * Anime.js - core - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('./consts.cjs');
+var helpers = require('./helpers.cjs');
+var transforms = require('./transforms.cjs');
+var colors = require('./colors.cjs');
+
+/**
+* @import {
+* Target,
+* DOMTarget,
+* Tween,
+* TweenPropValue,
+* TweenDecomposedValue,
+* } from '../types/index.js'
+*/
+
+/**
+ * @template T, D
+ * @param {T|undefined} targetValue
+ * @param {D} defaultValue
+ * @return {T|D}
+ */
+const setValue = (targetValue, defaultValue) => {
+ return helpers.isUnd(targetValue) ? defaultValue : targetValue;
+};
+
+/**
+ * @param {TweenPropValue} value
+ * @param {Target} target
+ * @param {Number} index
+ * @param {Number} total
+ * @param {Object} [store]
+ * @return {any}
+ */
+const getFunctionValue = (value, target, index, total, store) => {
+ if (helpers.isFnc(value)) {
+ const func = () => {
+ const computed = /** @type {Function} */(value)(target, index, total);
+ // Fallback to 0 if the function returns undefined / NaN / null / false / 0
+ return !isNaN(+computed) ? +computed : computed || 0;
+ };
+ if (store) {
+ store.func = func;
+ }
+ return func();
+ } else {
+ return value;
+ }
+};
+
+/**
+ * @param {Target} target
+ * @param {String} prop
+ * @return {tweenTypes}
+ */
+const getTweenType = (target, prop) => {
+ return !target[consts.isDomSymbol] ? consts.tweenTypes.OBJECT :
+ // Handle SVG attributes
+ target[consts.isSvgSymbol] && helpers.isValidSVGAttribute(target, prop) ? consts.tweenTypes.ATTRIBUTE :
+ // Handle CSS Transform properties differently than CSS to allow individual animations
+ consts.validTransforms.includes(prop) || consts.shortTransforms.get(prop) ? consts.tweenTypes.TRANSFORM :
+ // CSS variables
+ helpers.stringStartsWith(prop, '--') ? consts.tweenTypes.CSS_VAR :
+ // All other CSS properties
+ prop in /** @type {DOMTarget} */(target).style ? consts.tweenTypes.CSS :
+ // Handle other DOM Attributes
+ prop in target ? consts.tweenTypes.OBJECT :
+ consts.tweenTypes.ATTRIBUTE;
+};
+
+/**
+ * @param {DOMTarget} target
+ * @param {String} propName
+ * @param {Object} animationInlineStyles
+ * @return {String}
+ */
+const getCSSValue = (target, propName, animationInlineStyles) => {
+ const inlineStyles = target.style[propName];
+ if (inlineStyles && animationInlineStyles) {
+ animationInlineStyles[propName] = inlineStyles;
+ }
+ const value = inlineStyles || getComputedStyle(target[consts.proxyTargetSymbol] || target).getPropertyValue(propName);
+ return value === 'auto' ? '0' : value;
+};
+
+/**
+ * @param {Target} target
+ * @param {String} propName
+ * @param {tweenTypes} [tweenType]
+ * @param {Object|void} [animationInlineStyles]
+ * @return {String|Number}
+ */
+const getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => {
+ const type = !helpers.isUnd(tweenType) ? tweenType : getTweenType(target, propName);
+ return type === consts.tweenTypes.OBJECT ? target[propName] || 0 :
+ type === consts.tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) :
+ type === consts.tweenTypes.TRANSFORM ? transforms.parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) :
+ type === consts.tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() :
+ getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles);
+};
+
+/**
+ * @param {Number} x
+ * @param {Number} y
+ * @param {String} operator
+ * @return {Number}
+ */
+const getRelativeValue = (x, y, operator) => {
+ return operator === '-' ? x - y :
+ operator === '+' ? x + y :
+ x * y;
+};
+
+/** @return {TweenDecomposedValue} */
+const createDecomposedValueTargetObject = () => {
+ return {
+ /** @type {valueTypes} */
+ t: consts.valueTypes.NUMBER,
+ n: 0,
+ u: null,
+ o: null,
+ d: null,
+ s: null,
+ }
+};
+
+/**
+ * @param {String|Number} rawValue
+ * @param {TweenDecomposedValue} targetObject
+ * @return {TweenDecomposedValue}
+ */
+const decomposeRawValue = (rawValue, targetObject) => {
+ /** @type {valueTypes} */
+ targetObject.t = consts.valueTypes.NUMBER;
+ targetObject.n = 0;
+ targetObject.u = null;
+ targetObject.o = null;
+ targetObject.d = null;
+ targetObject.s = null;
+ if (!rawValue) return targetObject;
+ const num = +rawValue;
+ if (!isNaN(num)) {
+ // It's a number
+ targetObject.n = num;
+ return targetObject;
+ } else {
+ // let str = /** @type {String} */(rawValue).trim();
+ let str = /** @type {String} */(rawValue);
+ // Parsing operators (+=, -=, *=) manually is much faster than using regex here
+ if (str[1] === '=') {
+ targetObject.o = str[0];
+ str = str.slice(2);
+ }
+ // Skip exec regex if the value type is complex or color to avoid long regex backtracking
+ const unitMatch = str.includes(' ') ? false : consts.unitsExecRgx.exec(str);
+ if (unitMatch) {
+ // Has a number and a unit
+ targetObject.t = consts.valueTypes.UNIT;
+ targetObject.n = +unitMatch[1];
+ targetObject.u = unitMatch[2];
+ return targetObject;
+ } else if (targetObject.o) {
+ // Has an operator (+=, -=, *=)
+ targetObject.n = +str;
+ return targetObject;
+ } else if (helpers.isCol(str)) {
+ // Is a color
+ targetObject.t = consts.valueTypes.COLOR;
+ targetObject.d = colors.convertColorStringValuesToRgbaArray(str);
+ return targetObject;
+ } else {
+ // Is a more complex string (generally svg coords, calc() or filters CSS values)
+ const matchedNumbers = str.match(consts.digitWithExponentRgx);
+ targetObject.t = consts.valueTypes.COMPLEX;
+ targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : [];
+ targetObject.s = str.split(consts.digitWithExponentRgx) || [];
+ return targetObject;
+ }
+ }
+};
+
+/**
+ * @param {Tween} tween
+ * @param {TweenDecomposedValue} targetObject
+ * @return {TweenDecomposedValue}
+ */
+const decomposeTweenValue = (tween, targetObject) => {
+ targetObject.t = tween._valueType;
+ targetObject.n = tween._toNumber;
+ targetObject.u = tween._unit;
+ targetObject.o = null;
+ targetObject.d = helpers.cloneArray(tween._toNumbers);
+ targetObject.s = helpers.cloneArray(tween._strings);
+ return targetObject;
+};
+
+const decomposedOriginalValue = createDecomposedValueTargetObject();
+
+exports.createDecomposedValueTargetObject = createDecomposedValueTargetObject;
+exports.decomposeRawValue = decomposeRawValue;
+exports.decomposeTweenValue = decomposeTweenValue;
+exports.decomposedOriginalValue = decomposedOriginalValue;
+exports.getFunctionValue = getFunctionValue;
+exports.getOriginalAnimatableValue = getOriginalAnimatableValue;
+exports.getRelativeValue = getRelativeValue;
+exports.getTweenType = getTweenType;
+exports.setValue = setValue;
diff --git a/dist/modules/core/values.d.ts b/dist/modules/core/values.d.ts
new file mode 100644
index 00000000..e4fd7d88
--- /dev/null
+++ b/dist/modules/core/values.d.ts
@@ -0,0 +1,14 @@
+export function setValue<T, D>(targetValue: T | undefined, defaultValue: D): T | D;
+export function getFunctionValue(value: TweenPropValue, target: Target, index: number, total: number, store?: any): any;
+export function getTweenType(target: Target, prop: string): tweenTypes;
+export function getOriginalAnimatableValue(target: Target, propName: string, tweenType?: tweenTypes, animationInlineStyles?: any | void): string | number;
+export function getRelativeValue(x: number, y: number, operator: string): number;
+export function createDecomposedValueTargetObject(): TweenDecomposedValue;
+export function decomposeRawValue(rawValue: string | number, targetObject: TweenDecomposedValue): TweenDecomposedValue;
+export function decomposeTweenValue(tween: Tween, targetObject: TweenDecomposedValue): TweenDecomposedValue;
+export const decomposedOriginalValue: TweenDecomposedValue;
+import type { TweenPropValue } from '../types/index.js';
+import type { Target } from '../types/index.js';
+import { tweenTypes } from './consts.js';
+import type { TweenDecomposedValue } from '../types/index.js';
+import type { Tween } from '../types/index.js';
diff --git a/dist/modules/core/values.js b/dist/modules/core/values.js
new file mode 100644
index 00000000..58b311ae
--- /dev/null
+++ b/dist/modules/core/values.js
@@ -0,0 +1,205 @@
+/**
+ * Anime.js - core - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { tweenTypes, isDomSymbol, isSvgSymbol, validTransforms, shortTransforms, valueTypes, unitsExecRgx, digitWithExponentRgx, proxyTargetSymbol } from './consts.js';
+import { isValidSVGAttribute, stringStartsWith, isUnd, isCol, isFnc, cloneArray } from './helpers.js';
+import { parseInlineTransforms } from './transforms.js';
+import { convertColorStringValuesToRgbaArray } from './colors.js';
+
+/**
+* @import {
+* Target,
+* DOMTarget,
+* Tween,
+* TweenPropValue,
+* TweenDecomposedValue,
+* } from '../types/index.js'
+*/
+
+/**
+ * @template T, D
+ * @param {T|undefined} targetValue
+ * @param {D} defaultValue
+ * @return {T|D}
+ */
+const setValue = (targetValue, defaultValue) => {
+ return isUnd(targetValue) ? defaultValue : targetValue;
+};
+
+/**
+ * @param {TweenPropValue} value
+ * @param {Target} target
+ * @param {Number} index
+ * @param {Number} total
+ * @param {Object} [store]
+ * @return {any}
+ */
+const getFunctionValue = (value, target, index, total, store) => {
+ if (isFnc(value)) {
+ const func = () => {
+ const computed = /** @type {Function} */(value)(target, index, total);
+ // Fallback to 0 if the function returns undefined / NaN / null / false / 0
+ return !isNaN(+computed) ? +computed : computed || 0;
+ };
+ if (store) {
+ store.func = func;
+ }
+ return func();
+ } else {
+ return value;
+ }
+};
+
+/**
+ * @param {Target} target
+ * @param {String} prop
+ * @return {tweenTypes}
+ */
+const getTweenType = (target, prop) => {
+ return !target[isDomSymbol] ? tweenTypes.OBJECT :
+ // Handle SVG attributes
+ target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE :
+ // Handle CSS Transform properties differently than CSS to allow individual animations
+ validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM :
+ // CSS variables
+ stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR :
+ // All other CSS properties
+ prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS :
+ // Handle other DOM Attributes
+ prop in target ? tweenTypes.OBJECT :
+ tweenTypes.ATTRIBUTE;
+};
+
+/**
+ * @param {DOMTarget} target
+ * @param {String} propName
+ * @param {Object} animationInlineStyles
+ * @return {String}
+ */
+const getCSSValue = (target, propName, animationInlineStyles) => {
+ const inlineStyles = target.style[propName];
+ if (inlineStyles && animationInlineStyles) {
+ animationInlineStyles[propName] = inlineStyles;
+ }
+ const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName);
+ return value === 'auto' ? '0' : value;
+};
+
+/**
+ * @param {Target} target
+ * @param {String} propName
+ * @param {tweenTypes} [tweenType]
+ * @param {Object|void} [animationInlineStyles]
+ * @return {String|Number}
+ */
+const getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => {
+ const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName);
+ return type === tweenTypes.OBJECT ? target[propName] || 0 :
+ type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) :
+ type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) :
+ type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() :
+ getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles);
+};
+
+/**
+ * @param {Number} x
+ * @param {Number} y
+ * @param {String} operator
+ * @return {Number}
+ */
+const getRelativeValue = (x, y, operator) => {
+ return operator === '-' ? x - y :
+ operator === '+' ? x + y :
+ x * y;
+};
+
+/** @return {TweenDecomposedValue} */
+const createDecomposedValueTargetObject = () => {
+ return {
+ /** @type {valueTypes} */
+ t: valueTypes.NUMBER,
+ n: 0,
+ u: null,
+ o: null,
+ d: null,
+ s: null,
+ }
+};
+
+/**
+ * @param {String|Number} rawValue
+ * @param {TweenDecomposedValue} targetObject
+ * @return {TweenDecomposedValue}
+ */
+const decomposeRawValue = (rawValue, targetObject) => {
+ /** @type {valueTypes} */
+ targetObject.t = valueTypes.NUMBER;
+ targetObject.n = 0;
+ targetObject.u = null;
+ targetObject.o = null;
+ targetObject.d = null;
+ targetObject.s = null;
+ if (!rawValue) return targetObject;
+ const num = +rawValue;
+ if (!isNaN(num)) {
+ // It's a number
+ targetObject.n = num;
+ return targetObject;
+ } else {
+ // let str = /** @type {String} */(rawValue).trim();
+ let str = /** @type {String} */(rawValue);
+ // Parsing operators (+=, -=, *=) manually is much faster than using regex here
+ if (str[1] === '=') {
+ targetObject.o = str[0];
+ str = str.slice(2);
+ }
+ // Skip exec regex if the value type is complex or color to avoid long regex backtracking
+ const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str);
+ if (unitMatch) {
+ // Has a number and a unit
+ targetObject.t = valueTypes.UNIT;
+ targetObject.n = +unitMatch[1];
+ targetObject.u = unitMatch[2];
+ return targetObject;
+ } else if (targetObject.o) {
+ // Has an operator (+=, -=, *=)
+ targetObject.n = +str;
+ return targetObject;
+ } else if (isCol(str)) {
+ // Is a color
+ targetObject.t = valueTypes.COLOR;
+ targetObject.d = convertColorStringValuesToRgbaArray(str);
+ return targetObject;
+ } else {
+ // Is a more complex string (generally svg coords, calc() or filters CSS values)
+ const matchedNumbers = str.match(digitWithExponentRgx);
+ targetObject.t = valueTypes.COMPLEX;
+ targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : [];
+ targetObject.s = str.split(digitWithExponentRgx) || [];
+ return targetObject;
+ }
+ }
+};
+
+/**
+ * @param {Tween} tween
+ * @param {TweenDecomposedValue} targetObject
+ * @return {TweenDecomposedValue}
+ */
+const decomposeTweenValue = (tween, targetObject) => {
+ targetObject.t = tween._valueType;
+ targetObject.n = tween._toNumber;
+ targetObject.u = tween._unit;
+ targetObject.o = null;
+ targetObject.d = cloneArray(tween._toNumbers);
+ targetObject.s = cloneArray(tween._strings);
+ return targetObject;
+};
+
+const decomposedOriginalValue = createDecomposedValueTargetObject();
+
+export { createDecomposedValueTargetObject, decomposeRawValue, decomposeTweenValue, decomposedOriginalValue, getFunctionValue, getOriginalAnimatableValue, getRelativeValue, getTweenType, setValue };
diff --git a/dist/modules/draggable/draggable.cjs b/dist/modules/draggable/draggable.cjs
new file mode 100644
index 00000000..56a65cfa
--- /dev/null
+++ b/dist/modules/draggable/draggable.cjs
@@ -0,0 +1,1226 @@
+/**
+ * Anime.js - draggable - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var globals = require('../core/globals.cjs');
+var consts = require('../core/consts.cjs');
+var targets = require('../core/targets.cjs');
+var helpers = require('../core/helpers.cjs');
+var values = require('../core/values.cjs');
+var number = require('../utils/number.cjs');
+var timer = require('../timer/timer.cjs');
+var animation = require('../animation/animation.cjs');
+var composition = require('../animation/composition.cjs');
+var animatable = require('../animatable/animatable.cjs');
+var eases = require('../easings/eases.cjs');
+var spring = require('../spring/spring.cjs');
+var target = require('../utils/target.cjs');
+
+/**
+ * @import {
+ * DOMTarget,
+ * DOMTargetSelector,
+ * DraggableCursorParams,
+ * TargetsParam,
+ * DraggableParams,
+ * EasingFunction,
+ * Callback,
+ * AnimatableParams,
+ * DraggableAxisParam,
+ * AnimatableObject,
+ * EasingParam,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
+
+/**
+ * @param {Event} e
+ */
+const preventDefault = e => {
+ if (e.cancelable) e.preventDefault();
+};
+
+class DOMProxy {
+ /** @param {Object} el */
+ constructor(el) {
+ this.el = el;
+ this.zIndex = 0;
+ this.parentElement = null;
+ this.classList = {
+ add: consts.noop,
+ remove: consts.noop,
+ };
+ }
+
+ get x() { return this.el.x || 0 };
+ set x(v) { this.el.x = v; };
+
+ get y() { return this.el.y || 0 };
+ set y(v) { this.el.y = v; };
+
+ get width() { return this.el.width || 0 };
+ set width(v) { this.el.width = v; };
+
+ get height() { return this.el.height || 0 };
+ set height(v) { this.el.height = v; };
+
+ getBoundingClientRect() {
+ return {
+ top: this.y,
+ right: this.x,
+ bottom: this.y + this.height,
+ left: this.x + this.width,
+ }
+ }
+}
+
+class Transforms {
+ /**
+ * @param {DOMTarget|DOMProxy} $el
+ */
+ constructor($el) {
+ this.$el = $el;
+ this.inlineTransforms = [];
+ this.point = new DOMPoint();
+ this.inversedMatrix = this.getMatrix().inverse();
+ }
+
+ /**
+ * @param {Number} x
+ * @param {Number} y
+ * @return {DOMPoint}
+ */
+ normalizePoint(x, y) {
+ this.point.x = x;
+ this.point.y = y;
+ return this.point.matrixTransform(this.inversedMatrix);
+ }
+
+ /**
+ * @callback TraverseParentsCallback
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ */
+
+ /**
+ * @param {TraverseParentsCallback} cb
+ */
+ traverseUp(cb) {
+ let $el = /** @type {DOMTarget|Document} */(this.$el.parentElement), i = 0;
+ while ($el && $el !== consts.doc) {
+ cb(/** @type {DOMTarget} */($el), i);
+ $el = /** @type {DOMTarget} */($el.parentElement);
+ i++;
+ }
+ }
+
+ getMatrix() {
+ const matrix = new DOMMatrix();
+ this.traverseUp($el => {
+ const transformValue = getComputedStyle($el).transform;
+ if (transformValue) {
+ const elMatrix = new DOMMatrix(transformValue);
+ matrix.preMultiplySelf(elMatrix);
+ }
+ });
+ return matrix;
+ }
+
+ remove() {
+ this.traverseUp(($el, i) => {
+ this.inlineTransforms[i] = $el.style.transform;
+ $el.style.transform = 'none';
+ });
+ }
+
+ revert() {
+ this.traverseUp(($el, i) => {
+ const ct = this.inlineTransforms[i];
+ if (ct === '') {
+ $el.style.removeProperty('transform');
+ } else {
+ $el.style.transform = ct;
+ }
+ });
+ }
+}
+
+/**
+ * @template {Array<Number>|DOMTargetSelector|String|Number|Boolean|Function|DraggableCursorParams} T
+ * @param {T | ((draggable: Draggable) => T)} value
+ * @param {Draggable} draggable
+ * @return {T}
+ */
+const parseDraggableFunctionParameter = (value, draggable) => value && helpers.isFnc(value) ? /** @type {Function} */(value)(draggable) : /** @type {T} */(value);
+
+let zIndex = 0;
+
+class Draggable {
+ /**
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
+ */
+ constructor(target$1, parameters = {}) {
+ if (!target$1) return;
+ if (globals.scope.current) globals.scope.current.register(this);
+ const paramX = parameters.x;
+ const paramY = parameters.y;
+ const trigger = parameters.trigger;
+ const modifier = parameters.modifier;
+ const ease = parameters.releaseEase;
+ const customEase = ease && eases.parseEase(ease);
+ const hasSpring = !helpers.isUnd(ease) && !helpers.isUnd(/** @type {Spring} */(ease).ease);
+ const xProp = /** @type {String} */(helpers.isObj(paramX) && !helpers.isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX');
+ const yProp = /** @type {String} */(helpers.isObj(paramY) && !helpers.isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY');
+ const container = parseDraggableFunctionParameter(parameters.container, this);
+ this.containerArray = helpers.isArr(container) ? container : null;
+ this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? targets.parseTargets(/** @type {DOMTarget} */(container))[0] : consts.doc.body);
+ this.useWin = this.$container === consts.doc.body;
+ /** @type {Window | HTMLElement} */
+ this.$scrollContainer = this.useWin ? consts.win : this.$container;
+ this.$target = /** @type {HTMLElement} */(helpers.isObj(target$1) ? new DOMProxy(target$1) : targets.parseTargets(target$1)[0]);
+ this.$trigger = /** @type {HTMLElement} */(targets.parseTargets(trigger ? trigger : target$1)[0]);
+ this.fixed = target.get(this.$target, 'position') === 'fixed';
+ // Refreshable parameters
+ this.isFinePointer = true;
+ /** @type {[Number, Number, Number, Number]} */
+ this.containerPadding = [0, 0, 0, 0];
+ /** @type {Number} */
+ this.containerFriction = 0;
+ /** @type {Number} */
+ this.releaseContainerFriction = 0;
+ /** @type {Number|Array<Number>} */
+ this.snapX = 0;
+ /** @type {Number|Array<Number>} */
+ this.snapY = 0;
+ /** @type {Number} */
+ this.scrollSpeed = 0;
+ /** @type {Number} */
+ this.scrollThreshold = 0;
+ /** @type {Number} */
+ this.dragSpeed = 0;
+ /** @type {Number} */
+ this.maxVelocity = 0;
+ /** @type {Number} */
+ this.minVelocity = 0;
+ /** @type {Number} */
+ this.velocityMultiplier = 0;
+ /** @type {Boolean|DraggableCursorParams} */
+ this.cursor = false;
+ /** @type {Spring} */
+ this.releaseXSpring = hasSpring ? /** @type {Spring} */(ease) : spring.createSpring({
+ mass: values.setValue(parameters.releaseMass, 1),
+ stiffness: values.setValue(parameters.releaseStiffness, 80),
+ damping: values.setValue(parameters.releaseDamping, 20),
+ });
+ /** @type {Spring} */
+ this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : spring.createSpring({
+ mass: values.setValue(parameters.releaseMass, 1),
+ stiffness: values.setValue(parameters.releaseStiffness, 80),
+ damping: values.setValue(parameters.releaseDamping, 20),
+ });
+ /** @type {EasingFunction} */
+ this.releaseEase = customEase || eases.eases.outQuint;
+ /** @type {Boolean} */
+ this.hasReleaseSpring = hasSpring;
+ /** @type {Callback<this>} */
+ this.onGrab = parameters.onGrab || consts.noop;
+ /** @type {Callback<this>} */
+ this.onDrag = parameters.onDrag || consts.noop;
+ /** @type {Callback<this>} */
+ this.onRelease = parameters.onRelease || consts.noop;
+ /** @type {Callback<this>} */
+ this.onUpdate = parameters.onUpdate || consts.noop;
+ /** @type {Callback<this>} */
+ this.onSettle = parameters.onSettle || consts.noop;
+ /** @type {Callback<this>} */
+ this.onSnap = parameters.onSnap || consts.noop;
+ /** @type {Callback<this>} */
+ this.onResize = parameters.onResize || consts.noop;
+ /** @type {Callback<this>} */
+ this.onAfterResize = parameters.onAfterResize || consts.noop;
+ /** @type {[Number, Number]} */
+ this.disabled = [0, 0];
+ /** @type {AnimatableParams} */
+ const animatableParams = {};
+ if (modifier) animatableParams.modifier = modifier;
+ if (helpers.isUnd(paramX) || paramX === true) {
+ animatableParams[xProp] = 0;
+ } else if (helpers.isObj(paramX)) {
+ const paramXObject = /** @type {DraggableAxisParam} */(paramX);
+ const animatableXParams = {};
+ if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier;
+ if (paramXObject.composition) animatableXParams.composition = paramXObject.composition;
+ animatableParams[xProp] = animatableXParams;
+ } else if (paramX === false) {
+ animatableParams[xProp] = 0;
+ this.disabled[0] = 1;
+ }
+ if (helpers.isUnd(paramY) || paramY === true) {
+ animatableParams[yProp] = 0;
+ } else if (helpers.isObj(paramY)) {
+ const paramYObject = /** @type {DraggableAxisParam} */(paramY);
+ const animatableYParams = {};
+ if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier;
+ if (paramYObject.composition) animatableYParams.composition = paramYObject.composition;
+ animatableParams[yProp] = animatableYParams;
+ } else if (paramY === false) {
+ animatableParams[yProp] = 0;
+ this.disabled[1] = 1;
+ }
+ /** @type {AnimatableObject} */
+ this.animate = /** @type {AnimatableObject} */(new animatable.Animatable(this.$target, animatableParams));
+ // Internal props
+ this.xProp = xProp;
+ this.yProp = yProp;
+ this.destX = 0;
+ this.destY = 0;
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.scroll = {x: 0, y: 0};
+ /** @type {[Number, Number, Number, Number]} */
+ this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y
+ /** @type {[Number, Number]} */
+ this.snapped = [0, 0]; // x, y
+ /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */
+ this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2
+ /** @type {[Number, Number]} */
+ this.scrollView = [0, 0]; // w, h
+ /** @type {[Number, Number, Number, Number]} */
+ this.dragArea = [0, 0, 0, 0]; // x, y, w, h
+ /** @type {[Number, Number, Number, Number]} */
+ this.containerBounds = [-consts.maxValue, consts.maxValue, consts.maxValue, -consts.maxValue]; // t, r, b, l
+ /** @type {[Number, Number, Number, Number]} */
+ this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l
+ /** @type {[Number, Number, Number, Number]} */
+ this.targetBounds = [0, 0, 0, 0]; // t, r, b, l
+ /** @type {[Number, Number]} */
+ this.window = [0, 0]; // w, h
+ /** @type {[Number, Number, Number]} */
+ this.velocityStack = [0, 0, 0];
+ /** @type {Number} */
+ this.velocityStackIndex = 0;
+ /** @type {Number} */
+ this.velocityTime = helpers.now();
+ /** @type {Number} */
+ this.velocity = 0;
+ /** @type {Number} */
+ this.angle = 0;
+ /** @type {JSAnimation} */
+ this.cursorStyles = null;
+ /** @type {JSAnimation} */
+ this.triggerStyles = null;
+ /** @type {JSAnimation} */
+ this.bodyStyles = null;
+ /** @type {JSAnimation} */
+ this.targetStyles = null;
+ /** @type {JSAnimation} */
+ this.touchActionStyles = null;
+ this.transforms = new Transforms(this.$target);
+ this.overshootCoords = { x: 0, y: 0 };
+ this.overshootTicker = new timer.Timer({
+ autoplay: false,
+ onUpdate: () => {
+ this.updated = true;
+ this.manual = true;
+ // Use a duration of 1 to prevent the animatable from completing immediately to prevent issues with onSettle()
+ // https://github.com/juliangarnier/anime/issues/1045
+ if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 1);
+ if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 1);
+ },
+ onComplete: () => {
+ this.manual = false;
+ if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0);
+ if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0);
+ },
+ }, null, 0).init();
+ this.updateTicker = new timer.Timer({ autoplay: false, onUpdate: () => this.update() }, null,0,).init();
+ this.contained = !helpers.isUnd(container);
+ this.manual = false;
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.enabled = false;
+ this.initialized = false;
+ this.activeProp = this.disabled[1] ? xProp : yProp;
+ this.animate.callbacks.onRender = () => {
+ const hasUpdated = this.updated;
+ const hasMoved = this.grabbed && hasUpdated;
+ const hasReleased = !hasMoved && this.released;
+ const x = this.x;
+ const y = this.y;
+ const dx = x - this.coords[2];
+ const dy = y - this.coords[3];
+ this.deltaX = dx;
+ this.deltaY = dy;
+ this.coords[2] = x;
+ this.coords[3] = y;
+ // Check if dx or dy are not 0 to check if the draggable has actually moved
+ // https://github.com/juliangarnier/anime/issues/1032
+ if (hasUpdated && (dx || dy)) {
+ this.onUpdate(this);
+ }
+ if (!hasReleased) {
+ this.updated = false;
+ } else {
+ this.computeVelocity(dx, dy);
+ this.angle = helpers.atan2(dy, dx);
+ }
+ };
+ this.animate.callbacks.onComplete = () => {
+ if ((!this.grabbed && this.released)) {
+ // Set released to false before calling onSettle to avoid recursion
+ this.released = false;
+ }
+ if (!this.manual) {
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.onSettle(this);
+ }
+ };
+ this.resizeTicker = new timer.Timer({
+ autoplay: false,
+ duration: 150 * globals.globals.timeScale,
+ onComplete: () => {
+ this.onResize(this);
+ this.refresh();
+ this.onAfterResize(this);
+ },
+ }).init();
+ this.parameters = parameters;
+ this.resizeObserver = new ResizeObserver(() => {
+ if (this.initialized) {
+ this.resizeTicker.restart();
+ } else {
+ this.initialized = true;
+ }
+ });
+ this.enable();
+ this.refresh();
+ this.resizeObserver.observe(this.$container);
+ if (!helpers.isObj(target$1)) this.resizeObserver.observe(this.$target);
+ }
+
+ /**
+ * @param {Number} dx
+ * @param {Number} dy
+ * @return {Number}
+ */
+ computeVelocity(dx, dy) {
+ const prevTime = this.velocityTime;
+ const curTime = helpers.now();
+ const elapsed = curTime - prevTime;
+ if (elapsed < 17) return this.velocity;
+ this.velocityTime = curTime;
+ const velocityStack = this.velocityStack;
+ const vMul = this.velocityMultiplier;
+ const minV = this.minVelocity;
+ const maxV = this.maxVelocity;
+ const vi = this.velocityStackIndex;
+ velocityStack[vi] = helpers.round(helpers.clamp((helpers.sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5);
+ const velocity = helpers.max(velocityStack[0], velocityStack[1], velocityStack[2]);
+ this.velocity = velocity;
+ this.velocityStackIndex = (vi + 1) % 3;
+ return velocity;
+ }
+
+ /**
+ * @param {Number} x
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setX(x, muteUpdateCallback = false) {
+ if (this.disabled[0]) return;
+ const v = helpers.round(x, 5);
+ this.overshootTicker.pause();
+ this.manual = true;
+ this.updated = !muteUpdateCallback;
+ this.destX = v;
+ this.snapped[0] = helpers.snap(v, this.snapX);
+ this.animate[this.xProp](v, 0);
+ this.manual = false;
+ return this;
+ }
+
+ /**
+ * @param {Number} y
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setY(y, muteUpdateCallback = false) {
+ if (this.disabled[1]) return;
+ const v = helpers.round(y, 5);
+ this.overshootTicker.pause();
+ this.manual = true;
+ this.updated = !muteUpdateCallback;
+ this.destY = v;
+ this.snapped[1] = helpers.snap(v, this.snapY);
+ this.animate[this.yProp](v, 0);
+ this.manual = false;
+ return this;
+ }
+
+ get x() {
+ return helpers.round(/** @type {Number} */(this.animate[this.xProp]()), globals.globals.precision);
+ }
+
+ set x(x) {
+ this.setX(x, false);
+ }
+
+ get y() {
+ return helpers.round(/** @type {Number} */(this.animate[this.yProp]()), globals.globals.precision);
+ }
+
+ set y(y) {
+ this.setY(y, false);
+ }
+
+ get progressX() {
+ return number.mapRange(this.x, this.containerBounds[3], this.containerBounds[1], 0, 1);
+ }
+
+ set progressX(x) {
+ this.setX(number.mapRange(x, 0, 1, this.containerBounds[3], this.containerBounds[1]), false);
+ }
+
+ get progressY() {
+ return number.mapRange(this.y, this.containerBounds[0], this.containerBounds[2], 0, 1);
+ }
+
+ set progressY(y) {
+ this.setY(number.mapRange(y, 0, 1, this.containerBounds[0], this.containerBounds[2]), false);
+ }
+
+ updateScrollCoords() {
+ const sx = helpers.round(this.useWin ? consts.win.scrollX : this.$container.scrollLeft, 0);
+ const sy = helpers.round(this.useWin ? consts.win.scrollY : this.$container.scrollTop, 0);
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const threshold = this.scrollThreshold;
+ this.scroll.x = sx;
+ this.scroll.y = sy;
+ this.scrollBounds[0] = sy - this.targetBounds[0] + cpt - threshold;
+ this.scrollBounds[1] = sx - this.targetBounds[1] - cpr + threshold;
+ this.scrollBounds[2] = sy - this.targetBounds[2] - cpb + threshold;
+ this.scrollBounds[3] = sx - this.targetBounds[3] + cpl - threshold;
+ }
+
+ updateBoundingValues() {
+ const $container = this.$container;
+ // Return early if no $container defined to prevents error when reading scrollWidth / scrollHeight
+ // https://github.com/juliangarnier/anime/issues/1064
+ if (!$container) return;
+ const cx = this.x;
+ const cy = this.y;
+ const cx2 = this.coords[2];
+ const cy2 = this.coords[3];
+ // Prevents interfering with the scroll area in cases the target is outside of the container
+ // Make sure the temp coords are also adjuset to prevents wrong delta calculation on updates
+ this.coords[2] = 0;
+ this.coords[3] = 0;
+ this.setX(0, true);
+ this.setY(0, true);
+ this.transforms.remove();
+ const iw = this.window[0] = consts.win.innerWidth;
+ const ih = this.window[1] = consts.win.innerHeight;
+ const uw = this.useWin;
+ const sw = $container.scrollWidth;
+ const sh = $container.scrollHeight;
+ const fx = this.fixed;
+ const transformContainerRect = $container.getBoundingClientRect();
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ this.dragArea[0] = uw ? 0 : transformContainerRect.left;
+ this.dragArea[1] = uw ? 0 : transformContainerRect.top;
+ this.scrollView[0] = uw ? helpers.clamp(sw, iw, sw) : sw;
+ this.scrollView[1] = uw ? helpers.clamp(sh, ih, sh) : sh;
+ this.updateScrollCoords();
+ const { width, height, left, top, right, bottom } = $container.getBoundingClientRect();
+ this.dragArea[2] = helpers.round(uw ? helpers.clamp(width, iw, iw) : width, 0);
+ this.dragArea[3] = helpers.round(uw ? helpers.clamp(height, ih, ih) : height, 0);
+ const containerOverflow = target.get($container, 'overflow');
+ const visibleOverflow = containerOverflow === 'visible';
+ const hiddenOverflow = containerOverflow === 'hidden';
+ this.canScroll = fx ? false :
+ this.contained &&
+ (($container === consts.doc.body && visibleOverflow) || (!hiddenOverflow && !visibleOverflow)) &&
+ (sw > this.dragArea[2] + cpl - cpr || sh > this.dragArea[3] + cpt - cpb) &&
+ (!this.containerArray || (this.containerArray && !helpers.isArr(this.containerArray)));
+ if (this.contained) {
+ const sx = this.scroll.x;
+ const sy = this.scroll.y;
+ const canScroll = this.canScroll;
+ const targetRect = this.$target.getBoundingClientRect();
+ const hiddenLeft = canScroll ? uw ? 0 : $container.scrollLeft : 0;
+ const hiddenTop = canScroll ? uw ? 0 : $container.scrollTop : 0;
+ const hiddenRight = canScroll ? this.scrollView[0] - hiddenLeft - width : 0;
+ const hiddenBottom = canScroll ? this.scrollView[1] - hiddenTop - height : 0;
+ this.targetBounds[0] = helpers.round((targetRect.top + sy) - (uw ? 0 : top), 0);
+ this.targetBounds[1] = helpers.round((targetRect.right + sx) - (uw ? iw : right), 0);
+ this.targetBounds[2] = helpers.round((targetRect.bottom + sy) - (uw ? ih : bottom), 0);
+ this.targetBounds[3] = helpers.round((targetRect.left + sx) - (uw ? 0 : left), 0);
+ if (this.containerArray) {
+ this.containerBounds[0] = this.containerArray[0] + cpt;
+ this.containerBounds[1] = this.containerArray[1] - cpr;
+ this.containerBounds[2] = this.containerArray[2] - cpb;
+ this.containerBounds[3] = this.containerArray[3] + cpl;
+ } else {
+ this.containerBounds[0] = -helpers.round(targetRect.top - (fx ? helpers.clamp(top, 0, ih) : top) + hiddenTop - cpt, 0);
+ this.containerBounds[1] = -helpers.round(targetRect.right - (fx ? helpers.clamp(right, 0, iw) : right) - hiddenRight + cpr, 0);
+ this.containerBounds[2] = -helpers.round(targetRect.bottom - (fx ? helpers.clamp(bottom, 0, ih) : bottom) - hiddenBottom + cpb, 0);
+ this.containerBounds[3] = -helpers.round(targetRect.left - (fx ? helpers.clamp(left, 0, iw) : left) + hiddenLeft - cpl, 0);
+ }
+ }
+ this.transforms.revert();
+ // Restore coordinates
+ this.coords[2] = cx2;
+ this.coords[3] = cy2;
+ this.setX(cx, true);
+ this.setY(cy, true);
+ }
+
+ /**
+ * @param {Array} bounds
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number}
+ */
+ isOutOfBounds(bounds, x, y) {
+ // Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB
+ if (!this.contained) return 0;
+ const [ bt, br, bb, bl ] = bounds;
+ const [ dx, dy ] = this.disabled;
+ const obx = !dx && x < bl || !dx && x > br;
+ const oby = !dy && y < bt || !dy && y > bb;
+ return obx && !oby ? 1 : !obx && oby ? 2 : obx && oby ? 3 : 0;
+ }
+
+ refresh() {
+ const params = this.parameters;
+ const paramX = params.x;
+ const paramY = params.y;
+ const container = parseDraggableFunctionParameter(params.container, this);
+ const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0;
+ const containerPadding = /** @type {[Number, Number, Number, Number]} */(helpers.isArr(cp) ? cp : [cp, cp, cp, cp]);
+ const cx = this.x;
+ const cy = this.y;
+ const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this);
+ const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' };
+ if (parsedCursorStyles) {
+ const { onHover, onGrab } = /** @type {DraggableCursorParams} */(parsedCursorStyles);
+ if (onHover) cursorStyles.onHover = onHover;
+ if (onGrab) cursorStyles.onGrab = onGrab;
+ }
+ this.containerArray = helpers.isArr(container) ? container : null;
+ this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? targets.parseTargets(/** @type {DOMTarget} */(container))[0] : consts.doc.body);
+ this.useWin = this.$container === consts.doc.body;
+ /** @type {Window | HTMLElement} */
+ this.$scrollContainer = this.useWin ? consts.win : this.$container;
+ this.isFinePointer = matchMedia('(pointer:fine)').matches;
+ this.containerPadding = values.setValue(containerPadding, [0, 0, 0, 0]);
+ this.containerFriction = helpers.clamp(values.setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1);
+ this.releaseContainerFriction = helpers.clamp(values.setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1);
+ this.snapX = parseDraggableFunctionParameter(helpers.isObj(paramX) && !helpers.isUnd(paramX.snap) ? paramX.snap : params.snap, this);
+ this.snapY = parseDraggableFunctionParameter(helpers.isObj(paramY) && !helpers.isUnd(paramY.snap) ? paramY.snap : params.snap, this);
+ this.scrollSpeed = values.setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5);
+ this.scrollThreshold = values.setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20);
+ this.dragSpeed = values.setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1);
+ this.minVelocity = values.setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0);
+ this.maxVelocity = values.setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50);
+ this.velocityMultiplier = values.setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1);
+ this.cursor = parsedCursorStyles === false ? false : cursorStyles;
+ this.updateBoundingValues();
+
+ // const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y);
+ // if (ob === 1 || ob === 3) this.progressX = px;
+ // if (ob === 2 || ob === 3) this.progressY = py;
+
+ // if (this.initialized && this.contained) {
+ // if (this.progressX !== px) this.progressX = px;
+ // if (this.progressY !== py) this.progressY = py;
+ // }
+
+ const [ bt, br, bb, bl ] = this.containerBounds;
+ this.setX(helpers.clamp(cx, bl, br), true);
+ this.setY(helpers.clamp(cy, bt, bb), true);
+ }
+
+ update() {
+ this.updateScrollCoords();
+ if (this.canScroll) {
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const [ sw, sh ] = this.scrollView;
+ const daw = this.dragArea[2];
+ const dah = this.dragArea[3];
+ const csx = this.scroll.x;
+ const csy = this.scroll.y;
+ const nsw = this.$container.scrollWidth;
+ const nsh = this.$container.scrollHeight;
+ const csw = this.useWin ? helpers.clamp(nsw, this.window[0], nsw) : nsw;
+ const csh = this.useWin ? helpers.clamp(nsh, this.window[1], nsh) : nsh;
+ const swd = sw - csw;
+ const shd = sh - csh;
+ // Handle cases where the scrollarea dimensions changes during drag
+ if (this.dragged && swd > 0) {
+ this.coords[0] -= swd;
+ this.scrollView[0] = csw;
+ }
+ if (this.dragged && shd > 0) {
+ this.coords[1] -= shd;
+ this.scrollView[1] = csh;
+ }
+ // Handle autoscroll when target is at the edges of the scroll bounds
+ const s = this.scrollSpeed * 10;
+ const threshold = this.scrollThreshold;
+ const [ x, y ] = this.coords;
+ const [ st, sr, sb, sl ] = this.scrollBounds;
+ const t = helpers.round(helpers.clamp((y - st + cpt) / threshold, -1, 0) * s, 0);
+ const r = helpers.round(helpers.clamp((x - sr - cpr) / threshold, 0, 1) * s, 0);
+ const b = helpers.round(helpers.clamp((y - sb - cpb) / threshold, 0, 1) * s, 0);
+ const l = helpers.round(helpers.clamp((x - sl + cpl) / threshold, -1, 0) * s, 0);
+ if (t || b || l || r) {
+ const [nx, ny] = this.disabled;
+ let scrollX = csx;
+ let scrollY = csy;
+ if (!nx) {
+ scrollX = helpers.round(helpers.clamp(csx + (l || r), 0, sw - daw), 0);
+ this.coords[0] -= csx - scrollX;
+ }
+ if (!ny) {
+ scrollY = helpers.round(helpers.clamp(csy + (t || b), 0, sh - dah), 0);
+ this.coords[1] -= csy - scrollY;
+ }
+ // Note: Safari mobile requires to use different scroll methods depending if using the window or not
+ if (this.useWin) {
+ this.$scrollContainer.scrollBy(-(csx - scrollX), -(csy - scrollY));
+ } else {
+ this.$scrollContainer.scrollTo(scrollX, scrollY);
+ }
+ }
+ }
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
+ this.coords[0] += (px1 - px3) * this.dragSpeed;
+ this.coords[1] += (py1 - py3) * this.dragSpeed;
+ this.pointer[4] = px1;
+ this.pointer[5] = py1;
+ const [ cx, cy ] = this.coords;
+ const [ sx, sy ] = this.snapped;
+ const cf = (1 - this.containerFriction) * this.dragSpeed;
+ this.setX(cx > cr ? cr + (cx - cr) * cf : cx < cl ? cl + (cx - cl) * cf : cx, false);
+ this.setY(cy > cb ? cb + (cy - cb) * cf : cy < ct ? ct + (cy - ct) * cf : cy, false);
+ this.computeVelocity(px1 - px3, py1 - py3);
+ this.angle = helpers.atan2(py1 - py2, px1 - px2);
+ const [ nsx, nsy ] = this.snapped;
+ if (nsx !== sx && this.snapX || nsy !== sy && this.snapY) {
+ this.onSnap(this);
+ }
+ }
+
+ stop() {
+ this.updateTicker.pause();
+ this.overshootTicker.pause();
+ // Pauses the in bounds onRelease animations
+ for (let prop in this.animate.animations) this.animate.animations[prop].pause();
+ composition.removeTargetsFromRenderable([this], null, 'x');
+ composition.removeTargetsFromRenderable([this], null, 'y');
+ composition.removeTargetsFromRenderable([this], null, 'progressX');
+ composition.removeTargetsFromRenderable([this], null, 'progressY');
+ composition.removeTargetsFromRenderable([this.scroll]); // Removes any active animations on the container scroll
+ composition.removeTargetsFromRenderable([this.overshootCoords]); // Removes active overshoot animations
+ return this;
+ }
+
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ scrollInView(duration, gap = 0, ease = eases.eases.inOutQuad) {
+ this.updateScrollCoords();
+ const x = this.destX;
+ const y = this.destY;
+ const scroll = this.scroll;
+ const scrollBounds = this.scrollBounds;
+ const canScroll = this.canScroll;
+ if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) {
+ const [ st, sr, sb, sl ] = scrollBounds;
+ const t = helpers.round(helpers.clamp(y - st, -consts.maxValue, 0), 0);
+ const r = helpers.round(helpers.clamp(x - sr, 0, consts.maxValue), 0);
+ const b = helpers.round(helpers.clamp(y - sb, 0, consts.maxValue), 0);
+ const l = helpers.round(helpers.clamp(x - sl, -consts.maxValue, 0), 0);
+ new animation.JSAnimation(scroll, {
+ x: helpers.round(scroll.x + (l ? l - gap : r ? r + gap : 0), 0),
+ y: helpers.round(scroll.y + (t ? t - gap : b ? b + gap : 0), 0),
+ duration: helpers.isUnd(duration) ? 350 * globals.globals.timeScale : duration,
+ ease,
+ onUpdate: () => {
+ this.canScroll = false;
+ this.$scrollContainer.scrollTo(scroll.x, scroll.y);
+ }
+ }).init().then(() => {
+ this.canScroll = canScroll;
+ });
+ }
+ return this;
+ }
+
+ handleHover() {
+ if (this.isFinePointer && this.cursor && !this.cursorStyles) {
+ this.cursorStyles = target.set(this.$trigger, {
+ cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover
+ });
+ }
+ }
+
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ animateInView(duration, gap = 0, ease = eases.eases.inOutQuad) {
+ this.stop();
+ this.updateBoundingValues();
+ const x = this.x;
+ const y = this.y;
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const bt = this.scroll.y - this.targetBounds[0] + cpt + gap;
+ const br = this.scroll.x - this.targetBounds[1] - cpr - gap;
+ const bb = this.scroll.y - this.targetBounds[2] - cpb - gap;
+ const bl = this.scroll.x - this.targetBounds[3] + cpl + gap;
+ const ob = this.isOutOfBounds([bt, br, bb, bl], x, y);
+ if (ob) {
+ const [ disabledX, disabledY ] = this.disabled;
+ const destX = helpers.clamp(helpers.snap(x, this.snapX), bl, br);
+ const destY = helpers.clamp(helpers.snap(y, this.snapY), bt, bb);
+ const dur = helpers.isUnd(duration) ? 350 * globals.globals.timeScale : duration;
+ if (!disabledX && (ob === 1 || ob === 3)) this.animate[this.xProp](destX, dur, ease);
+ if (!disabledY && (ob === 2 || ob === 3)) this.animate[this.yProp](destY, dur, ease);
+ }
+ return this;
+ }
+
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleDown(e) {
+ const $eTarget = /** @type {HTMLElement} */(e.target);
+ if (this.grabbed || /** @type {HTMLInputElement} */($eTarget).type === 'range') return;
+
+ e.stopPropagation();
+
+ this.grabbed = true;
+ this.released = false;
+ this.stop();
+ this.updateBoundingValues();
+ const touches = /** @type {TouchEvent} */(e).changedTouches;
+ const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
+ const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
+ const { x, y } = this.transforms.normalizePoint(eventX, eventY);
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const cf = (1 - this.containerFriction) * this.dragSpeed;
+ const cx = this.x;
+ const cy = this.y;
+ this.coords[0] = this.coords[2] = !cf ? cx : cx > cr ? cr + (cx - cr) / cf : cx < cl ? cl + (cx - cl) / cf : cx;
+ this.coords[1] = this.coords[3] = !cf ? cy : cy > cb ? cb + (cy - cb) / cf : cy < ct ? ct + (cy - ct) / cf : cy;
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.pointer[2] = x;
+ this.pointer[3] = y;
+ this.pointer[4] = x;
+ this.pointer[5] = y;
+ this.pointer[6] = x;
+ this.pointer[7] = y;
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.angle = 0;
+ if (this.targetStyles) {
+ this.targetStyles.revert();
+ this.targetStyles = null;
+ }
+ const z = /** @type {Number} */(target.get(this.$target, 'zIndex', false));
+ zIndex = (z > zIndex ? z : zIndex) + 1;
+ this.targetStyles = target.set(this.$target, { zIndex });
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+ if (this.cursorStyles) {
+ this.cursorStyles.revert();
+ this.cursorStyles = null;
+ }
+ if (this.isFinePointer && this.cursor) {
+ this.bodyStyles = target.set(consts.doc.body, {
+ cursor: /** @type {DraggableCursorParams} */(this.cursor).onGrab
+ });
+ }
+ this.scrollInView(100, 0, eases.eases.out(3));
+ this.onGrab(this);
+
+ consts.doc.addEventListener('touchmove', this);
+ consts.doc.addEventListener('touchend', this);
+ consts.doc.addEventListener('touchcancel', this);
+ consts.doc.addEventListener('mousemove', this);
+ consts.doc.addEventListener('mouseup', this);
+ consts.doc.addEventListener('selectstart', this);
+ }
+
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleMove(e) {
+ if (!this.grabbed) return;
+ const touches = /** @type {TouchEvent} */(e).changedTouches;
+ const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
+ const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
+ const { x, y } = this.transforms.normalizePoint(eventX, eventY);
+ const movedX = x - this.pointer[6];
+ const movedY = y - this.pointer[7];
+
+ let $parent = /** @type {HTMLElement} */(e.target);
+ let isAtTop = false;
+ let isAtBottom = false;
+ let canTouchScroll = false;
+
+ while (touches && $parent && $parent !== this.$trigger) {
+ const overflowY = target.get($parent, 'overflow-y');
+ if (overflowY !== 'hidden' && overflowY !== 'visible') {
+ const { scrollTop, scrollHeight, clientHeight } = $parent;
+ if (scrollHeight > clientHeight) {
+ canTouchScroll = true;
+ isAtTop = scrollTop <= 3;
+ isAtBottom = scrollTop >= (scrollHeight - clientHeight) - 3;
+ break;
+ }
+ }
+ $parent = $parent.parentElement;
+ }
+
+ if (canTouchScroll && ((!isAtTop && !isAtBottom) || (isAtTop && movedY < 0) || (isAtBottom && movedY > 0))) {
+
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.pointer[2] = x;
+ this.pointer[3] = y;
+ this.pointer[4] = x;
+ this.pointer[5] = y;
+ this.pointer[6] = x;
+ this.pointer[7] = y;
+
+ } else {
+
+ preventDefault(e);
+
+ // Needed to prevents click on handleUp
+ if (!this.triggerStyles) this.triggerStyles = target.set(this.$trigger, { pointerEvents: 'none' });
+ // Needed to prevent page scroll while dragging on touch devvice
+ this.$trigger.addEventListener('touchstart', preventDefault, { passive: false });
+ this.$trigger.addEventListener('touchmove', preventDefault, { passive: false });
+ this.$trigger.addEventListener('touchend', preventDefault);
+
+
+ if ((!this.disabled[0] && helpers.abs(movedX) > 3) || (!this.disabled[1] && helpers.abs(movedY) > 3)) {
+
+ this.updateTicker.resume();
+ this.pointer[2] = this.pointer[0];
+ this.pointer[3] = this.pointer[1];
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.dragged = true;
+ this.released = false;
+ this.onDrag(this);
+ }
+ }
+ }
+
+ handleUp() {
+
+ if (!this.grabbed) return;
+
+ this.updateTicker.pause();
+
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+
+ if (this.bodyStyles) {
+ this.bodyStyles.revert();
+ this.bodyStyles = null;
+ }
+
+ const [ disabledX, disabledY ] = this.disabled;
+ const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const [ sx, sy ] = this.snapped;
+ const springX = this.releaseXSpring;
+ const springY = this.releaseYSpring;
+ const releaseEase = this.releaseEase;
+ const hasReleaseSpring = this.hasReleaseSpring;
+ const overshootCoords = this.overshootCoords;
+ const cx = this.x;
+ const cy = this.y;
+ const pv = this.computeVelocity(px1 - px3, py1 - py3);
+ const pa = this.angle = helpers.atan2(py1 - py2, px1 - px2);
+ const ds = pv * 150;
+ const cf = (1 - this.releaseContainerFriction) * this.dragSpeed;
+ const nx = cx + (helpers.cos(pa) * ds);
+ const ny = cy + (helpers.sin(pa) * ds);
+ const bx = nx > cr ? cr + (nx - cr) * cf : nx < cl ? cl + (nx - cl) * cf : nx;
+ const by = ny > cb ? cb + (ny - cb) * cf : ny < ct ? ct + (ny - ct) * cf : ny;
+ const dx = this.destX = helpers.clamp(helpers.round(helpers.snap(bx, this.snapX), 5), cl, cr);
+ const dy = this.destY = helpers.clamp(helpers.round(helpers.snap(by, this.snapY), 5), ct, cb);
+ const ob = this.isOutOfBounds(this.containerBounds, nx, ny);
+
+ let durationX = 0;
+ let durationY = 0;
+ let easeX = releaseEase;
+ let easeY = releaseEase;
+ let longestReleaseDuration = 0;
+
+ overshootCoords.x = cx;
+ overshootCoords.y = cy;
+
+ if (!disabledX) {
+ const directionX = dx === cr ? cx > cr ? -1 : 1 : cx < cl ? -1 : 1;
+ const distanceX = helpers.round(cx - dx, 0);
+ springX.velocity = disabledY && hasReleaseSpring ? distanceX ? (ds * directionX) / helpers.abs(distanceX) : 0 : pv;
+ const { ease, duration, restDuration } = springX;
+ durationX = cx === dx ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.globals.timeScale);
+ if (hasReleaseSpring) easeX = ease;
+ if (durationX > longestReleaseDuration) longestReleaseDuration = durationX;
+ }
+
+ if (!disabledY) {
+ const directionY = dy === cb ? cy > cb ? -1 : 1 : cy < ct ? -1 : 1;
+ const distanceY = helpers.round(cy - dy, 0);
+ springY.velocity = disabledX && hasReleaseSpring ? distanceY ? (ds * directionY) / helpers.abs(distanceY) : 0 : pv;
+ const { ease, duration, restDuration } = springY;
+ durationY = cy === dy ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.globals.timeScale);
+ if (hasReleaseSpring) easeY = ease;
+ if (durationY > longestReleaseDuration) longestReleaseDuration = durationY;
+ }
+
+ if (!hasReleaseSpring && ob && cf && (durationX || durationY)) {
+
+ const composition = consts.compositionTypes.blend;
+
+ new animation.JSAnimation(overshootCoords, {
+ x: { to: bx, duration: durationX * .65 },
+ y: { to: by, duration: durationY * .65 },
+ ease: releaseEase,
+ composition,
+ }).init();
+
+ new animation.JSAnimation(overshootCoords, {
+ x: { to: dx, duration: durationX },
+ y: { to: dy, duration: durationY },
+ ease: releaseEase,
+ composition,
+ }).init();
+
+ this.overshootTicker.stretch(helpers.max(durationX, durationY)).restart();
+
+ } else {
+
+ if (!disabledX) this.animate[this.xProp](dx, durationX, easeX);
+ if (!disabledY) this.animate[this.yProp](dy, durationY, easeY);
+
+ }
+
+ this.scrollInView(longestReleaseDuration, this.scrollThreshold, releaseEase);
+
+ let hasSnapped = false;
+
+ if (dx !== sx) {
+ this.snapped[0] = dx;
+ if (this.snapX) hasSnapped = true;
+ }
+
+ if (dy !== sy && this.snapY) {
+ this.snapped[1] = dy;
+ if (this.snapY) hasSnapped = true;
+ }
+
+ if (hasSnapped) this.onSnap(this);
+
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = true;
+ this.released = true;
+
+ // It's important to trigger the callback after the release animations to be able to cancel them
+ this.onRelease(this);
+
+ this.$trigger.removeEventListener('touchstart', preventDefault);
+ this.$trigger.removeEventListener('touchmove', preventDefault);
+ this.$trigger.removeEventListener('touchend', preventDefault);
+
+ consts.doc.removeEventListener('touchmove', this);
+ consts.doc.removeEventListener('touchend', this);
+ consts.doc.removeEventListener('touchcancel', this);
+ consts.doc.removeEventListener('mousemove', this);
+ consts.doc.removeEventListener('mouseup', this);
+ consts.doc.removeEventListener('selectstart', this);
+ }
+
+ reset() {
+ this.stop();
+ this.resizeTicker.pause();
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.setX(0, true);
+ this.setY(0, true);
+ this.coords[0] = 0;
+ this.coords[1] = 0;
+ this.pointer[0] = 0;
+ this.pointer[1] = 0;
+ this.pointer[2] = 0;
+ this.pointer[3] = 0;
+ this.pointer[4] = 0;
+ this.pointer[5] = 0;
+ this.pointer[6] = 0;
+ this.pointer[7] = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.angle = 0;
+ return this;
+ }
+
+ enable() {
+ if (!this.enabled) {
+ this.enabled = true;
+ this.$target.classList.remove('is-disabled');
+ this.touchActionStyles = target.set(this.$trigger, {
+ touchAction: this.disabled[0] ? 'pan-x' : this.disabled[1] ? 'pan-y' : 'none'
+ });
+ this.$trigger.addEventListener('touchstart', this, { passive: true });
+ this.$trigger.addEventListener('mousedown', this, { passive: true });
+ this.$trigger.addEventListener('mouseenter', this);
+ }
+ return this;
+ }
+
+ disable() {
+ this.enabled = false;
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.touchActionStyles.revert();
+ if (this.cursorStyles) {
+ this.cursorStyles.revert();
+ this.cursorStyles = null;
+ }
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+ if (this.bodyStyles) {
+ this.bodyStyles.revert();
+ this.bodyStyles = null;
+ }
+ if (this.targetStyles) {
+ this.targetStyles.revert();
+ this.targetStyles = null;
+ }
+ this.$target.classList.add('is-disabled');
+ this.$trigger.removeEventListener('touchstart', this);
+ this.$trigger.removeEventListener('mousedown', this);
+ this.$trigger.removeEventListener('mouseenter', this);
+ consts.doc.removeEventListener('touchmove', this);
+ consts.doc.removeEventListener('touchend', this);
+ consts.doc.removeEventListener('touchcancel', this);
+ consts.doc.removeEventListener('mousemove', this);
+ consts.doc.removeEventListener('mouseup', this);
+ consts.doc.removeEventListener('selectstart', this);
+ return this;
+ }
+
+ revert() {
+ this.reset();
+ this.disable();
+ this.$target.classList.remove('is-disabled');
+ this.updateTicker.revert();
+ this.overshootTicker.revert();
+ this.resizeTicker.revert();
+ this.animate.revert();
+ this.resizeObserver.disconnect();
+ return this;
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'mousedown':
+ this.handleDown(/** @type {MouseEvent} */(e));
+ break;
+ case 'touchstart':
+ this.handleDown(/** @type {TouchEvent} */(e));
+ break;
+ case 'mousemove':
+ this.handleMove(/** @type {MouseEvent} */(e));
+ break;
+ case 'touchmove':
+ this.handleMove(/** @type {TouchEvent} */(e));
+ break;
+ case 'mouseup':
+ this.handleUp();
+ break;
+ case 'touchend':
+ this.handleUp();
+ break;
+ case 'touchcancel':
+ this.handleUp();
+ break;
+ case 'mouseenter':
+ this.handleHover();
+ break;
+ case 'selectstart':
+ preventDefault(e);
+ break;
+ }
+ }
+}
+
+/**
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
+ * @return {Draggable}
+ */
+const createDraggable = (target, parameters) => new Draggable(target, parameters);
+
+exports.Draggable = Draggable;
+exports.createDraggable = createDraggable;
diff --git a/dist/modules/draggable/draggable.d.ts b/dist/modules/draggable/draggable.d.ts
new file mode 100644
index 00000000..f1807895
--- /dev/null
+++ b/dist/modules/draggable/draggable.d.ts
@@ -0,0 +1,272 @@
+export class Draggable {
+ /**
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
+ */
+ constructor(target: TargetsParam, parameters?: DraggableParams);
+ containerArray: number[];
+ $container: HTMLElement;
+ useWin: boolean;
+ /** @type {Window | HTMLElement} */
+ $scrollContainer: Window | HTMLElement;
+ $target: HTMLElement;
+ $trigger: HTMLElement;
+ fixed: boolean;
+ isFinePointer: boolean;
+ /** @type {[Number, Number, Number, Number]} */
+ containerPadding: [number, number, number, number];
+ /** @type {Number} */
+ containerFriction: number;
+ /** @type {Number} */
+ releaseContainerFriction: number;
+ /** @type {Number|Array<Number>} */
+ snapX: number | Array<number>;
+ /** @type {Number|Array<Number>} */
+ snapY: number | Array<number>;
+ /** @type {Number} */
+ scrollSpeed: number;
+ /** @type {Number} */
+ scrollThreshold: number;
+ /** @type {Number} */
+ dragSpeed: number;
+ /** @type {Number} */
+ maxVelocity: number;
+ /** @type {Number} */
+ minVelocity: number;
+ /** @type {Number} */
+ velocityMultiplier: number;
+ /** @type {Boolean|DraggableCursorParams} */
+ cursor: boolean | DraggableCursorParams;
+ /** @type {Spring} */
+ releaseXSpring: Spring;
+ /** @type {Spring} */
+ releaseYSpring: Spring;
+ /** @type {EasingFunction} */
+ releaseEase: EasingFunction;
+ /** @type {Boolean} */
+ hasReleaseSpring: boolean;
+ /** @type {Callback<this>} */
+ onGrab: Callback<this>;
+ /** @type {Callback<this>} */
+ onDrag: Callback<this>;
+ /** @type {Callback<this>} */
+ onRelease: Callback<this>;
+ /** @type {Callback<this>} */
+ onUpdate: Callback<this>;
+ /** @type {Callback<this>} */
+ onSettle: Callback<this>;
+ /** @type {Callback<this>} */
+ onSnap: Callback<this>;
+ /** @type {Callback<this>} */
+ onResize: Callback<this>;
+ /** @type {Callback<this>} */
+ onAfterResize: Callback<this>;
+ /** @type {[Number, Number]} */
+ disabled: [number, number];
+ /** @type {AnimatableObject} */
+ animate: AnimatableObject;
+ xProp: string;
+ yProp: string;
+ destX: number;
+ destY: number;
+ deltaX: number;
+ deltaY: number;
+ scroll: {
+ x: number;
+ y: number;
+ };
+ /** @type {[Number, Number, Number, Number]} */
+ coords: [number, number, number, number];
+ /** @type {[Number, Number]} */
+ snapped: [number, number];
+ /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */
+ pointer: [number, number, number, number, number, number, number, number];
+ /** @type {[Number, Number]} */
+ scrollView: [number, number];
+ /** @type {[Number, Number, Number, Number]} */
+ dragArea: [number, number, number, number];
+ /** @type {[Number, Number, Number, Number]} */
+ containerBounds: [number, number, number, number];
+ /** @type {[Number, Number, Number, Number]} */
+ scrollBounds: [number, number, number, number];
+ /** @type {[Number, Number, Number, Number]} */
+ targetBounds: [number, number, number, number];
+ /** @type {[Number, Number]} */
+ window: [number, number];
+ /** @type {[Number, Number, Number]} */
+ velocityStack: [number, number, number];
+ /** @type {Number} */
+ velocityStackIndex: number;
+ /** @type {Number} */
+ velocityTime: number;
+ /** @type {Number} */
+ velocity: number;
+ /** @type {Number} */
+ angle: number;
+ /** @type {JSAnimation} */
+ cursorStyles: JSAnimation;
+ /** @type {JSAnimation} */
+ triggerStyles: JSAnimation;
+ /** @type {JSAnimation} */
+ bodyStyles: JSAnimation;
+ /** @type {JSAnimation} */
+ targetStyles: JSAnimation;
+ /** @type {JSAnimation} */
+ touchActionStyles: JSAnimation;
+ transforms: Transforms;
+ overshootCoords: {
+ x: number;
+ y: number;
+ };
+ overshootTicker: Timer;
+ updated: boolean;
+ manual: boolean;
+ updateTicker: Timer;
+ contained: boolean;
+ grabbed: boolean;
+ dragged: boolean;
+ released: boolean;
+ canScroll: boolean;
+ enabled: boolean;
+ initialized: boolean;
+ activeProp: string;
+ resizeTicker: Timer;
+ parameters: DraggableParams;
+ resizeObserver: ResizeObserver;
+ /**
+ * @param {Number} dx
+ * @param {Number} dy
+ * @return {Number}
+ */
+ computeVelocity(dx: number, dy: number): number;
+ /**
+ * @param {Number} x
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setX(x: number, muteUpdateCallback?: boolean): this;
+ /**
+ * @param {Number} y
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setY(y: number, muteUpdateCallback?: boolean): this;
+ set x(x: number);
+ get x(): number;
+ set y(y: number);
+ get y(): number;
+ set progressX(x: number);
+ get progressX(): number;
+ set progressY(y: number);
+ get progressY(): number;
+ updateScrollCoords(): void;
+ updateBoundingValues(): void;
+ /**
+ * @param {Array} bounds
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number}
+ */
+ isOutOfBounds(bounds: any[], x: number, y: number): number;
+ refresh(): void;
+ update(): void;
+ stop(): this;
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ scrollInView(duration?: number, gap?: number, ease?: EasingParam): this;
+ handleHover(): void;
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ animateInView(duration?: number, gap?: number, ease?: EasingParam): this;
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleDown(e: MouseEvent | TouchEvent): void;
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleMove(e: MouseEvent | TouchEvent): void;
+ handleUp(): void;
+ reset(): this;
+ enable(): this;
+ disable(): this;
+ revert(): this;
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e: Event): void;
+}
+export function createDraggable(target: TargetsParam, parameters?: DraggableParams): Draggable;
+import type { DraggableCursorParams } from '../types/index.js';
+import type { Spring } from '../spring/spring.js';
+import type { EasingFunction } from '../types/index.js';
+import type { Callback } from '../types/index.js';
+import type { AnimatableObject } from '../types/index.js';
+import { JSAnimation } from '../animation/animation.js';
+declare class Transforms {
+ /**
+ * @param {DOMTarget|DOMProxy} $el
+ */
+ constructor($el: DOMTarget | DOMProxy);
+ $el: DOMTarget | DOMProxy;
+ inlineTransforms: any[];
+ point: DOMPoint;
+ inversedMatrix: DOMMatrix;
+ /**
+ * @param {Number} x
+ * @param {Number} y
+ * @return {DOMPoint}
+ */
+ normalizePoint(x: number, y: number): DOMPoint;
+ /**
+ * @callback TraverseParentsCallback
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ */
+ /**
+ * @param {TraverseParentsCallback} cb
+ */
+ traverseUp(cb: ($el: DOMTarget, i: number) => any): void;
+ getMatrix(): DOMMatrix;
+ remove(): void;
+ revert(): void;
+}
+import { Timer } from '../timer/timer.js';
+import type { DraggableParams } from '../types/index.js';
+import type { EasingParam } from '../types/index.js';
+import type { TargetsParam } from '../types/index.js';
+import type { DOMTarget } from '../types/index.js';
+declare class DOMProxy {
+ /** @param {Object} el */
+ constructor(el: any);
+ el: any;
+ zIndex: number;
+ parentElement: any;
+ classList: {
+ add: () => void;
+ remove: () => void;
+ };
+ set x(v: any);
+ get x(): any;
+ set y(v: any);
+ get y(): any;
+ set width(v: any);
+ get width(): any;
+ set height(v: any);
+ get height(): any;
+ getBoundingClientRect(): {
+ top: any;
+ right: any;
+ bottom: any;
+ left: any;
+ };
+}
+export {};
diff --git a/dist/modules/draggable/draggable.js b/dist/modules/draggable/draggable.js
new file mode 100644
index 00000000..eee2ab05
--- /dev/null
+++ b/dist/modules/draggable/draggable.js
@@ -0,0 +1,1223 @@
+/**
+ * Anime.js - draggable - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { globals, scope } from '../core/globals.js';
+import { doc, win, noop, maxValue, compositionTypes } from '../core/consts.js';
+import { parseTargets } from '../core/targets.js';
+import { isUnd, isObj, isArr, now, atan2, round, max, snap, clamp, abs, sqrt, cos, sin, isFnc } from '../core/helpers.js';
+import { setValue } from '../core/values.js';
+import { mapRange } from '../utils/number.js';
+import { Timer } from '../timer/timer.js';
+import { JSAnimation } from '../animation/animation.js';
+import { removeTargetsFromRenderable } from '../animation/composition.js';
+import { Animatable } from '../animatable/animatable.js';
+import { parseEase, eases } from '../easings/eases.js';
+import { createSpring } from '../spring/spring.js';
+import { get, set } from '../utils/target.js';
+
+/**
+ * @import {
+ * DOMTarget,
+ * DOMTargetSelector,
+ * DraggableCursorParams,
+ * TargetsParam,
+ * DraggableParams,
+ * EasingFunction,
+ * Callback,
+ * AnimatableParams,
+ * DraggableAxisParam,
+ * AnimatableObject,
+ * EasingParam,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
+
+/**
+ * @param {Event} e
+ */
+const preventDefault = e => {
+ if (e.cancelable) e.preventDefault();
+};
+
+class DOMProxy {
+ /** @param {Object} el */
+ constructor(el) {
+ this.el = el;
+ this.zIndex = 0;
+ this.parentElement = null;
+ this.classList = {
+ add: noop,
+ remove: noop,
+ };
+ }
+
+ get x() { return this.el.x || 0 };
+ set x(v) { this.el.x = v; };
+
+ get y() { return this.el.y || 0 };
+ set y(v) { this.el.y = v; };
+
+ get width() { return this.el.width || 0 };
+ set width(v) { this.el.width = v; };
+
+ get height() { return this.el.height || 0 };
+ set height(v) { this.el.height = v; };
+
+ getBoundingClientRect() {
+ return {
+ top: this.y,
+ right: this.x,
+ bottom: this.y + this.height,
+ left: this.x + this.width,
+ }
+ }
+}
+
+class Transforms {
+ /**
+ * @param {DOMTarget|DOMProxy} $el
+ */
+ constructor($el) {
+ this.$el = $el;
+ this.inlineTransforms = [];
+ this.point = new DOMPoint();
+ this.inversedMatrix = this.getMatrix().inverse();
+ }
+
+ /**
+ * @param {Number} x
+ * @param {Number} y
+ * @return {DOMPoint}
+ */
+ normalizePoint(x, y) {
+ this.point.x = x;
+ this.point.y = y;
+ return this.point.matrixTransform(this.inversedMatrix);
+ }
+
+ /**
+ * @callback TraverseParentsCallback
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ */
+
+ /**
+ * @param {TraverseParentsCallback} cb
+ */
+ traverseUp(cb) {
+ let $el = /** @type {DOMTarget|Document} */(this.$el.parentElement), i = 0;
+ while ($el && $el !== doc) {
+ cb(/** @type {DOMTarget} */($el), i);
+ $el = /** @type {DOMTarget} */($el.parentElement);
+ i++;
+ }
+ }
+
+ getMatrix() {
+ const matrix = new DOMMatrix();
+ this.traverseUp($el => {
+ const transformValue = getComputedStyle($el).transform;
+ if (transformValue) {
+ const elMatrix = new DOMMatrix(transformValue);
+ matrix.preMultiplySelf(elMatrix);
+ }
+ });
+ return matrix;
+ }
+
+ remove() {
+ this.traverseUp(($el, i) => {
+ this.inlineTransforms[i] = $el.style.transform;
+ $el.style.transform = 'none';
+ });
+ }
+
+ revert() {
+ this.traverseUp(($el, i) => {
+ const ct = this.inlineTransforms[i];
+ if (ct === '') {
+ $el.style.removeProperty('transform');
+ } else {
+ $el.style.transform = ct;
+ }
+ });
+ }
+}
+
+/**
+ * @template {Array<Number>|DOMTargetSelector|String|Number|Boolean|Function|DraggableCursorParams} T
+ * @param {T | ((draggable: Draggable) => T)} value
+ * @param {Draggable} draggable
+ * @return {T}
+ */
+const parseDraggableFunctionParameter = (value, draggable) => value && isFnc(value) ? /** @type {Function} */(value)(draggable) : /** @type {T} */(value);
+
+let zIndex = 0;
+
+class Draggable {
+ /**
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
+ */
+ constructor(target, parameters = {}) {
+ if (!target) return;
+ if (scope.current) scope.current.register(this);
+ const paramX = parameters.x;
+ const paramY = parameters.y;
+ const trigger = parameters.trigger;
+ const modifier = parameters.modifier;
+ const ease = parameters.releaseEase;
+ const customEase = ease && parseEase(ease);
+ const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
+ const xProp = /** @type {String} */(isObj(paramX) && !isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX');
+ const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY');
+ const container = parseDraggableFunctionParameter(parameters.container, this);
+ this.containerArray = isArr(container) ? container : null;
+ this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body);
+ this.useWin = this.$container === doc.body;
+ /** @type {Window | HTMLElement} */
+ this.$scrollContainer = this.useWin ? win : this.$container;
+ this.$target = /** @type {HTMLElement} */(isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]);
+ this.$trigger = /** @type {HTMLElement} */(parseTargets(trigger ? trigger : target)[0]);
+ this.fixed = get(this.$target, 'position') === 'fixed';
+ // Refreshable parameters
+ this.isFinePointer = true;
+ /** @type {[Number, Number, Number, Number]} */
+ this.containerPadding = [0, 0, 0, 0];
+ /** @type {Number} */
+ this.containerFriction = 0;
+ /** @type {Number} */
+ this.releaseContainerFriction = 0;
+ /** @type {Number|Array<Number>} */
+ this.snapX = 0;
+ /** @type {Number|Array<Number>} */
+ this.snapY = 0;
+ /** @type {Number} */
+ this.scrollSpeed = 0;
+ /** @type {Number} */
+ this.scrollThreshold = 0;
+ /** @type {Number} */
+ this.dragSpeed = 0;
+ /** @type {Number} */
+ this.maxVelocity = 0;
+ /** @type {Number} */
+ this.minVelocity = 0;
+ /** @type {Number} */
+ this.velocityMultiplier = 0;
+ /** @type {Boolean|DraggableCursorParams} */
+ this.cursor = false;
+ /** @type {Spring} */
+ this.releaseXSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({
+ mass: setValue(parameters.releaseMass, 1),
+ stiffness: setValue(parameters.releaseStiffness, 80),
+ damping: setValue(parameters.releaseDamping, 20),
+ });
+ /** @type {Spring} */
+ this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({
+ mass: setValue(parameters.releaseMass, 1),
+ stiffness: setValue(parameters.releaseStiffness, 80),
+ damping: setValue(parameters.releaseDamping, 20),
+ });
+ /** @type {EasingFunction} */
+ this.releaseEase = customEase || eases.outQuint;
+ /** @type {Boolean} */
+ this.hasReleaseSpring = hasSpring;
+ /** @type {Callback<this>} */
+ this.onGrab = parameters.onGrab || noop;
+ /** @type {Callback<this>} */
+ this.onDrag = parameters.onDrag || noop;
+ /** @type {Callback<this>} */
+ this.onRelease = parameters.onRelease || noop;
+ /** @type {Callback<this>} */
+ this.onUpdate = parameters.onUpdate || noop;
+ /** @type {Callback<this>} */
+ this.onSettle = parameters.onSettle || noop;
+ /** @type {Callback<this>} */
+ this.onSnap = parameters.onSnap || noop;
+ /** @type {Callback<this>} */
+ this.onResize = parameters.onResize || noop;
+ /** @type {Callback<this>} */
+ this.onAfterResize = parameters.onAfterResize || noop;
+ /** @type {[Number, Number]} */
+ this.disabled = [0, 0];
+ /** @type {AnimatableParams} */
+ const animatableParams = {};
+ if (modifier) animatableParams.modifier = modifier;
+ if (isUnd(paramX) || paramX === true) {
+ animatableParams[xProp] = 0;
+ } else if (isObj(paramX)) {
+ const paramXObject = /** @type {DraggableAxisParam} */(paramX);
+ const animatableXParams = {};
+ if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier;
+ if (paramXObject.composition) animatableXParams.composition = paramXObject.composition;
+ animatableParams[xProp] = animatableXParams;
+ } else if (paramX === false) {
+ animatableParams[xProp] = 0;
+ this.disabled[0] = 1;
+ }
+ if (isUnd(paramY) || paramY === true) {
+ animatableParams[yProp] = 0;
+ } else if (isObj(paramY)) {
+ const paramYObject = /** @type {DraggableAxisParam} */(paramY);
+ const animatableYParams = {};
+ if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier;
+ if (paramYObject.composition) animatableYParams.composition = paramYObject.composition;
+ animatableParams[yProp] = animatableYParams;
+ } else if (paramY === false) {
+ animatableParams[yProp] = 0;
+ this.disabled[1] = 1;
+ }
+ /** @type {AnimatableObject} */
+ this.animate = /** @type {AnimatableObject} */(new Animatable(this.$target, animatableParams));
+ // Internal props
+ this.xProp = xProp;
+ this.yProp = yProp;
+ this.destX = 0;
+ this.destY = 0;
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.scroll = {x: 0, y: 0};
+ /** @type {[Number, Number, Number, Number]} */
+ this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y
+ /** @type {[Number, Number]} */
+ this.snapped = [0, 0]; // x, y
+ /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */
+ this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2
+ /** @type {[Number, Number]} */
+ this.scrollView = [0, 0]; // w, h
+ /** @type {[Number, Number, Number, Number]} */
+ this.dragArea = [0, 0, 0, 0]; // x, y, w, h
+ /** @type {[Number, Number, Number, Number]} */
+ this.containerBounds = [-maxValue, maxValue, maxValue, -maxValue]; // t, r, b, l
+ /** @type {[Number, Number, Number, Number]} */
+ this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l
+ /** @type {[Number, Number, Number, Number]} */
+ this.targetBounds = [0, 0, 0, 0]; // t, r, b, l
+ /** @type {[Number, Number]} */
+ this.window = [0, 0]; // w, h
+ /** @type {[Number, Number, Number]} */
+ this.velocityStack = [0, 0, 0];
+ /** @type {Number} */
+ this.velocityStackIndex = 0;
+ /** @type {Number} */
+ this.velocityTime = now();
+ /** @type {Number} */
+ this.velocity = 0;
+ /** @type {Number} */
+ this.angle = 0;
+ /** @type {JSAnimation} */
+ this.cursorStyles = null;
+ /** @type {JSAnimation} */
+ this.triggerStyles = null;
+ /** @type {JSAnimation} */
+ this.bodyStyles = null;
+ /** @type {JSAnimation} */
+ this.targetStyles = null;
+ /** @type {JSAnimation} */
+ this.touchActionStyles = null;
+ this.transforms = new Transforms(this.$target);
+ this.overshootCoords = { x: 0, y: 0 };
+ this.overshootTicker = new Timer({
+ autoplay: false,
+ onUpdate: () => {
+ this.updated = true;
+ this.manual = true;
+ // Use a duration of 1 to prevent the animatable from completing immediately to prevent issues with onSettle()
+ // https://github.com/juliangarnier/anime/issues/1045
+ if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 1);
+ if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 1);
+ },
+ onComplete: () => {
+ this.manual = false;
+ if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0);
+ if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0);
+ },
+ }, null, 0).init();
+ this.updateTicker = new Timer({ autoplay: false, onUpdate: () => this.update() }, null,0,).init();
+ this.contained = !isUnd(container);
+ this.manual = false;
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.enabled = false;
+ this.initialized = false;
+ this.activeProp = this.disabled[1] ? xProp : yProp;
+ this.animate.callbacks.onRender = () => {
+ const hasUpdated = this.updated;
+ const hasMoved = this.grabbed && hasUpdated;
+ const hasReleased = !hasMoved && this.released;
+ const x = this.x;
+ const y = this.y;
+ const dx = x - this.coords[2];
+ const dy = y - this.coords[3];
+ this.deltaX = dx;
+ this.deltaY = dy;
+ this.coords[2] = x;
+ this.coords[3] = y;
+ // Check if dx or dy are not 0 to check if the draggable has actually moved
+ // https://github.com/juliangarnier/anime/issues/1032
+ if (hasUpdated && (dx || dy)) {
+ this.onUpdate(this);
+ }
+ if (!hasReleased) {
+ this.updated = false;
+ } else {
+ this.computeVelocity(dx, dy);
+ this.angle = atan2(dy, dx);
+ }
+ };
+ this.animate.callbacks.onComplete = () => {
+ if ((!this.grabbed && this.released)) {
+ // Set released to false before calling onSettle to avoid recursion
+ this.released = false;
+ }
+ if (!this.manual) {
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.onSettle(this);
+ }
+ };
+ this.resizeTicker = new Timer({
+ autoplay: false,
+ duration: 150 * globals.timeScale,
+ onComplete: () => {
+ this.onResize(this);
+ this.refresh();
+ this.onAfterResize(this);
+ },
+ }).init();
+ this.parameters = parameters;
+ this.resizeObserver = new ResizeObserver(() => {
+ if (this.initialized) {
+ this.resizeTicker.restart();
+ } else {
+ this.initialized = true;
+ }
+ });
+ this.enable();
+ this.refresh();
+ this.resizeObserver.observe(this.$container);
+ if (!isObj(target)) this.resizeObserver.observe(this.$target);
+ }
+
+ /**
+ * @param {Number} dx
+ * @param {Number} dy
+ * @return {Number}
+ */
+ computeVelocity(dx, dy) {
+ const prevTime = this.velocityTime;
+ const curTime = now();
+ const elapsed = curTime - prevTime;
+ if (elapsed < 17) return this.velocity;
+ this.velocityTime = curTime;
+ const velocityStack = this.velocityStack;
+ const vMul = this.velocityMultiplier;
+ const minV = this.minVelocity;
+ const maxV = this.maxVelocity;
+ const vi = this.velocityStackIndex;
+ velocityStack[vi] = round(clamp((sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5);
+ const velocity = max(velocityStack[0], velocityStack[1], velocityStack[2]);
+ this.velocity = velocity;
+ this.velocityStackIndex = (vi + 1) % 3;
+ return velocity;
+ }
+
+ /**
+ * @param {Number} x
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setX(x, muteUpdateCallback = false) {
+ if (this.disabled[0]) return;
+ const v = round(x, 5);
+ this.overshootTicker.pause();
+ this.manual = true;
+ this.updated = !muteUpdateCallback;
+ this.destX = v;
+ this.snapped[0] = snap(v, this.snapX);
+ this.animate[this.xProp](v, 0);
+ this.manual = false;
+ return this;
+ }
+
+ /**
+ * @param {Number} y
+ * @param {Boolean} [muteUpdateCallback]
+ * @return {this}
+ */
+ setY(y, muteUpdateCallback = false) {
+ if (this.disabled[1]) return;
+ const v = round(y, 5);
+ this.overshootTicker.pause();
+ this.manual = true;
+ this.updated = !muteUpdateCallback;
+ this.destY = v;
+ this.snapped[1] = snap(v, this.snapY);
+ this.animate[this.yProp](v, 0);
+ this.manual = false;
+ return this;
+ }
+
+ get x() {
+ return round(/** @type {Number} */(this.animate[this.xProp]()), globals.precision);
+ }
+
+ set x(x) {
+ this.setX(x, false);
+ }
+
+ get y() {
+ return round(/** @type {Number} */(this.animate[this.yProp]()), globals.precision);
+ }
+
+ set y(y) {
+ this.setY(y, false);
+ }
+
+ get progressX() {
+ return mapRange(this.x, this.containerBounds[3], this.containerBounds[1], 0, 1);
+ }
+
+ set progressX(x) {
+ this.setX(mapRange(x, 0, 1, this.containerBounds[3], this.containerBounds[1]), false);
+ }
+
+ get progressY() {
+ return mapRange(this.y, this.containerBounds[0], this.containerBounds[2], 0, 1);
+ }
+
+ set progressY(y) {
+ this.setY(mapRange(y, 0, 1, this.containerBounds[0], this.containerBounds[2]), false);
+ }
+
+ updateScrollCoords() {
+ const sx = round(this.useWin ? win.scrollX : this.$container.scrollLeft, 0);
+ const sy = round(this.useWin ? win.scrollY : this.$container.scrollTop, 0);
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const threshold = this.scrollThreshold;
+ this.scroll.x = sx;
+ this.scroll.y = sy;
+ this.scrollBounds[0] = sy - this.targetBounds[0] + cpt - threshold;
+ this.scrollBounds[1] = sx - this.targetBounds[1] - cpr + threshold;
+ this.scrollBounds[2] = sy - this.targetBounds[2] - cpb + threshold;
+ this.scrollBounds[3] = sx - this.targetBounds[3] + cpl - threshold;
+ }
+
+ updateBoundingValues() {
+ const $container = this.$container;
+ // Return early if no $container defined to prevents error when reading scrollWidth / scrollHeight
+ // https://github.com/juliangarnier/anime/issues/1064
+ if (!$container) return;
+ const cx = this.x;
+ const cy = this.y;
+ const cx2 = this.coords[2];
+ const cy2 = this.coords[3];
+ // Prevents interfering with the scroll area in cases the target is outside of the container
+ // Make sure the temp coords are also adjuset to prevents wrong delta calculation on updates
+ this.coords[2] = 0;
+ this.coords[3] = 0;
+ this.setX(0, true);
+ this.setY(0, true);
+ this.transforms.remove();
+ const iw = this.window[0] = win.innerWidth;
+ const ih = this.window[1] = win.innerHeight;
+ const uw = this.useWin;
+ const sw = $container.scrollWidth;
+ const sh = $container.scrollHeight;
+ const fx = this.fixed;
+ const transformContainerRect = $container.getBoundingClientRect();
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ this.dragArea[0] = uw ? 0 : transformContainerRect.left;
+ this.dragArea[1] = uw ? 0 : transformContainerRect.top;
+ this.scrollView[0] = uw ? clamp(sw, iw, sw) : sw;
+ this.scrollView[1] = uw ? clamp(sh, ih, sh) : sh;
+ this.updateScrollCoords();
+ const { width, height, left, top, right, bottom } = $container.getBoundingClientRect();
+ this.dragArea[2] = round(uw ? clamp(width, iw, iw) : width, 0);
+ this.dragArea[3] = round(uw ? clamp(height, ih, ih) : height, 0);
+ const containerOverflow = get($container, 'overflow');
+ const visibleOverflow = containerOverflow === 'visible';
+ const hiddenOverflow = containerOverflow === 'hidden';
+ this.canScroll = fx ? false :
+ this.contained &&
+ (($container === doc.body && visibleOverflow) || (!hiddenOverflow && !visibleOverflow)) &&
+ (sw > this.dragArea[2] + cpl - cpr || sh > this.dragArea[3] + cpt - cpb) &&
+ (!this.containerArray || (this.containerArray && !isArr(this.containerArray)));
+ if (this.contained) {
+ const sx = this.scroll.x;
+ const sy = this.scroll.y;
+ const canScroll = this.canScroll;
+ const targetRect = this.$target.getBoundingClientRect();
+ const hiddenLeft = canScroll ? uw ? 0 : $container.scrollLeft : 0;
+ const hiddenTop = canScroll ? uw ? 0 : $container.scrollTop : 0;
+ const hiddenRight = canScroll ? this.scrollView[0] - hiddenLeft - width : 0;
+ const hiddenBottom = canScroll ? this.scrollView[1] - hiddenTop - height : 0;
+ this.targetBounds[0] = round((targetRect.top + sy) - (uw ? 0 : top), 0);
+ this.targetBounds[1] = round((targetRect.right + sx) - (uw ? iw : right), 0);
+ this.targetBounds[2] = round((targetRect.bottom + sy) - (uw ? ih : bottom), 0);
+ this.targetBounds[3] = round((targetRect.left + sx) - (uw ? 0 : left), 0);
+ if (this.containerArray) {
+ this.containerBounds[0] = this.containerArray[0] + cpt;
+ this.containerBounds[1] = this.containerArray[1] - cpr;
+ this.containerBounds[2] = this.containerArray[2] - cpb;
+ this.containerBounds[3] = this.containerArray[3] + cpl;
+ } else {
+ this.containerBounds[0] = -round(targetRect.top - (fx ? clamp(top, 0, ih) : top) + hiddenTop - cpt, 0);
+ this.containerBounds[1] = -round(targetRect.right - (fx ? clamp(right, 0, iw) : right) - hiddenRight + cpr, 0);
+ this.containerBounds[2] = -round(targetRect.bottom - (fx ? clamp(bottom, 0, ih) : bottom) - hiddenBottom + cpb, 0);
+ this.containerBounds[3] = -round(targetRect.left - (fx ? clamp(left, 0, iw) : left) + hiddenLeft - cpl, 0);
+ }
+ }
+ this.transforms.revert();
+ // Restore coordinates
+ this.coords[2] = cx2;
+ this.coords[3] = cy2;
+ this.setX(cx, true);
+ this.setY(cy, true);
+ }
+
+ /**
+ * @param {Array} bounds
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number}
+ */
+ isOutOfBounds(bounds, x, y) {
+ // Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB
+ if (!this.contained) return 0;
+ const [ bt, br, bb, bl ] = bounds;
+ const [ dx, dy ] = this.disabled;
+ const obx = !dx && x < bl || !dx && x > br;
+ const oby = !dy && y < bt || !dy && y > bb;
+ return obx && !oby ? 1 : !obx && oby ? 2 : obx && oby ? 3 : 0;
+ }
+
+ refresh() {
+ const params = this.parameters;
+ const paramX = params.x;
+ const paramY = params.y;
+ const container = parseDraggableFunctionParameter(params.container, this);
+ const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0;
+ const containerPadding = /** @type {[Number, Number, Number, Number]} */(isArr(cp) ? cp : [cp, cp, cp, cp]);
+ const cx = this.x;
+ const cy = this.y;
+ const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this);
+ const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' };
+ if (parsedCursorStyles) {
+ const { onHover, onGrab } = /** @type {DraggableCursorParams} */(parsedCursorStyles);
+ if (onHover) cursorStyles.onHover = onHover;
+ if (onGrab) cursorStyles.onGrab = onGrab;
+ }
+ this.containerArray = isArr(container) ? container : null;
+ this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body);
+ this.useWin = this.$container === doc.body;
+ /** @type {Window | HTMLElement} */
+ this.$scrollContainer = this.useWin ? win : this.$container;
+ this.isFinePointer = matchMedia('(pointer:fine)').matches;
+ this.containerPadding = setValue(containerPadding, [0, 0, 0, 0]);
+ this.containerFriction = clamp(setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1);
+ this.releaseContainerFriction = clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1);
+ this.snapX = parseDraggableFunctionParameter(isObj(paramX) && !isUnd(paramX.snap) ? paramX.snap : params.snap, this);
+ this.snapY = parseDraggableFunctionParameter(isObj(paramY) && !isUnd(paramY.snap) ? paramY.snap : params.snap, this);
+ this.scrollSpeed = setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5);
+ this.scrollThreshold = setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20);
+ this.dragSpeed = setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1);
+ this.minVelocity = setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0);
+ this.maxVelocity = setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50);
+ this.velocityMultiplier = setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1);
+ this.cursor = parsedCursorStyles === false ? false : cursorStyles;
+ this.updateBoundingValues();
+
+ // const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y);
+ // if (ob === 1 || ob === 3) this.progressX = px;
+ // if (ob === 2 || ob === 3) this.progressY = py;
+
+ // if (this.initialized && this.contained) {
+ // if (this.progressX !== px) this.progressX = px;
+ // if (this.progressY !== py) this.progressY = py;
+ // }
+
+ const [ bt, br, bb, bl ] = this.containerBounds;
+ this.setX(clamp(cx, bl, br), true);
+ this.setY(clamp(cy, bt, bb), true);
+ }
+
+ update() {
+ this.updateScrollCoords();
+ if (this.canScroll) {
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const [ sw, sh ] = this.scrollView;
+ const daw = this.dragArea[2];
+ const dah = this.dragArea[3];
+ const csx = this.scroll.x;
+ const csy = this.scroll.y;
+ const nsw = this.$container.scrollWidth;
+ const nsh = this.$container.scrollHeight;
+ const csw = this.useWin ? clamp(nsw, this.window[0], nsw) : nsw;
+ const csh = this.useWin ? clamp(nsh, this.window[1], nsh) : nsh;
+ const swd = sw - csw;
+ const shd = sh - csh;
+ // Handle cases where the scrollarea dimensions changes during drag
+ if (this.dragged && swd > 0) {
+ this.coords[0] -= swd;
+ this.scrollView[0] = csw;
+ }
+ if (this.dragged && shd > 0) {
+ this.coords[1] -= shd;
+ this.scrollView[1] = csh;
+ }
+ // Handle autoscroll when target is at the edges of the scroll bounds
+ const s = this.scrollSpeed * 10;
+ const threshold = this.scrollThreshold;
+ const [ x, y ] = this.coords;
+ const [ st, sr, sb, sl ] = this.scrollBounds;
+ const t = round(clamp((y - st + cpt) / threshold, -1, 0) * s, 0);
+ const r = round(clamp((x - sr - cpr) / threshold, 0, 1) * s, 0);
+ const b = round(clamp((y - sb - cpb) / threshold, 0, 1) * s, 0);
+ const l = round(clamp((x - sl + cpl) / threshold, -1, 0) * s, 0);
+ if (t || b || l || r) {
+ const [nx, ny] = this.disabled;
+ let scrollX = csx;
+ let scrollY = csy;
+ if (!nx) {
+ scrollX = round(clamp(csx + (l || r), 0, sw - daw), 0);
+ this.coords[0] -= csx - scrollX;
+ }
+ if (!ny) {
+ scrollY = round(clamp(csy + (t || b), 0, sh - dah), 0);
+ this.coords[1] -= csy - scrollY;
+ }
+ // Note: Safari mobile requires to use different scroll methods depending if using the window or not
+ if (this.useWin) {
+ this.$scrollContainer.scrollBy(-(csx - scrollX), -(csy - scrollY));
+ } else {
+ this.$scrollContainer.scrollTo(scrollX, scrollY);
+ }
+ }
+ }
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
+ this.coords[0] += (px1 - px3) * this.dragSpeed;
+ this.coords[1] += (py1 - py3) * this.dragSpeed;
+ this.pointer[4] = px1;
+ this.pointer[5] = py1;
+ const [ cx, cy ] = this.coords;
+ const [ sx, sy ] = this.snapped;
+ const cf = (1 - this.containerFriction) * this.dragSpeed;
+ this.setX(cx > cr ? cr + (cx - cr) * cf : cx < cl ? cl + (cx - cl) * cf : cx, false);
+ this.setY(cy > cb ? cb + (cy - cb) * cf : cy < ct ? ct + (cy - ct) * cf : cy, false);
+ this.computeVelocity(px1 - px3, py1 - py3);
+ this.angle = atan2(py1 - py2, px1 - px2);
+ const [ nsx, nsy ] = this.snapped;
+ if (nsx !== sx && this.snapX || nsy !== sy && this.snapY) {
+ this.onSnap(this);
+ }
+ }
+
+ stop() {
+ this.updateTicker.pause();
+ this.overshootTicker.pause();
+ // Pauses the in bounds onRelease animations
+ for (let prop in this.animate.animations) this.animate.animations[prop].pause();
+ removeTargetsFromRenderable([this], null, 'x');
+ removeTargetsFromRenderable([this], null, 'y');
+ removeTargetsFromRenderable([this], null, 'progressX');
+ removeTargetsFromRenderable([this], null, 'progressY');
+ removeTargetsFromRenderable([this.scroll]); // Removes any active animations on the container scroll
+ removeTargetsFromRenderable([this.overshootCoords]); // Removes active overshoot animations
+ return this;
+ }
+
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ scrollInView(duration, gap = 0, ease = eases.inOutQuad) {
+ this.updateScrollCoords();
+ const x = this.destX;
+ const y = this.destY;
+ const scroll = this.scroll;
+ const scrollBounds = this.scrollBounds;
+ const canScroll = this.canScroll;
+ if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) {
+ const [ st, sr, sb, sl ] = scrollBounds;
+ const t = round(clamp(y - st, -maxValue, 0), 0);
+ const r = round(clamp(x - sr, 0, maxValue), 0);
+ const b = round(clamp(y - sb, 0, maxValue), 0);
+ const l = round(clamp(x - sl, -maxValue, 0), 0);
+ new JSAnimation(scroll, {
+ x: round(scroll.x + (l ? l - gap : r ? r + gap : 0), 0),
+ y: round(scroll.y + (t ? t - gap : b ? b + gap : 0), 0),
+ duration: isUnd(duration) ? 350 * globals.timeScale : duration,
+ ease,
+ onUpdate: () => {
+ this.canScroll = false;
+ this.$scrollContainer.scrollTo(scroll.x, scroll.y);
+ }
+ }).init().then(() => {
+ this.canScroll = canScroll;
+ });
+ }
+ return this;
+ }
+
+ handleHover() {
+ if (this.isFinePointer && this.cursor && !this.cursorStyles) {
+ this.cursorStyles = set(this.$trigger, {
+ cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover
+ });
+ }
+ }
+
+ /**
+ * @param {Number} [duration]
+ * @param {Number} [gap]
+ * @param {EasingParam} [ease]
+ * @return {this}
+ */
+ animateInView(duration, gap = 0, ease = eases.inOutQuad) {
+ this.stop();
+ this.updateBoundingValues();
+ const x = this.x;
+ const y = this.y;
+ const [ cpt, cpr, cpb, cpl ] = this.containerPadding;
+ const bt = this.scroll.y - this.targetBounds[0] + cpt + gap;
+ const br = this.scroll.x - this.targetBounds[1] - cpr - gap;
+ const bb = this.scroll.y - this.targetBounds[2] - cpb - gap;
+ const bl = this.scroll.x - this.targetBounds[3] + cpl + gap;
+ const ob = this.isOutOfBounds([bt, br, bb, bl], x, y);
+ if (ob) {
+ const [ disabledX, disabledY ] = this.disabled;
+ const destX = clamp(snap(x, this.snapX), bl, br);
+ const destY = clamp(snap(y, this.snapY), bt, bb);
+ const dur = isUnd(duration) ? 350 * globals.timeScale : duration;
+ if (!disabledX && (ob === 1 || ob === 3)) this.animate[this.xProp](destX, dur, ease);
+ if (!disabledY && (ob === 2 || ob === 3)) this.animate[this.yProp](destY, dur, ease);
+ }
+ return this;
+ }
+
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleDown(e) {
+ const $eTarget = /** @type {HTMLElement} */(e.target);
+ if (this.grabbed || /** @type {HTMLInputElement} */($eTarget).type === 'range') return;
+
+ e.stopPropagation();
+
+ this.grabbed = true;
+ this.released = false;
+ this.stop();
+ this.updateBoundingValues();
+ const touches = /** @type {TouchEvent} */(e).changedTouches;
+ const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
+ const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
+ const { x, y } = this.transforms.normalizePoint(eventX, eventY);
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const cf = (1 - this.containerFriction) * this.dragSpeed;
+ const cx = this.x;
+ const cy = this.y;
+ this.coords[0] = this.coords[2] = !cf ? cx : cx > cr ? cr + (cx - cr) / cf : cx < cl ? cl + (cx - cl) / cf : cx;
+ this.coords[1] = this.coords[3] = !cf ? cy : cy > cb ? cb + (cy - cb) / cf : cy < ct ? ct + (cy - ct) / cf : cy;
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.pointer[2] = x;
+ this.pointer[3] = y;
+ this.pointer[4] = x;
+ this.pointer[5] = y;
+ this.pointer[6] = x;
+ this.pointer[7] = y;
+ this.deltaX = 0;
+ this.deltaY = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.angle = 0;
+ if (this.targetStyles) {
+ this.targetStyles.revert();
+ this.targetStyles = null;
+ }
+ const z = /** @type {Number} */(get(this.$target, 'zIndex', false));
+ zIndex = (z > zIndex ? z : zIndex) + 1;
+ this.targetStyles = set(this.$target, { zIndex });
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+ if (this.cursorStyles) {
+ this.cursorStyles.revert();
+ this.cursorStyles = null;
+ }
+ if (this.isFinePointer && this.cursor) {
+ this.bodyStyles = set(doc.body, {
+ cursor: /** @type {DraggableCursorParams} */(this.cursor).onGrab
+ });
+ }
+ this.scrollInView(100, 0, eases.out(3));
+ this.onGrab(this);
+
+ doc.addEventListener('touchmove', this);
+ doc.addEventListener('touchend', this);
+ doc.addEventListener('touchcancel', this);
+ doc.addEventListener('mousemove', this);
+ doc.addEventListener('mouseup', this);
+ doc.addEventListener('selectstart', this);
+ }
+
+ /**
+ * @param {MouseEvent|TouchEvent} e
+ */
+ handleMove(e) {
+ if (!this.grabbed) return;
+ const touches = /** @type {TouchEvent} */(e).changedTouches;
+ const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX;
+ const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY;
+ const { x, y } = this.transforms.normalizePoint(eventX, eventY);
+ const movedX = x - this.pointer[6];
+ const movedY = y - this.pointer[7];
+
+ let $parent = /** @type {HTMLElement} */(e.target);
+ let isAtTop = false;
+ let isAtBottom = false;
+ let canTouchScroll = false;
+
+ while (touches && $parent && $parent !== this.$trigger) {
+ const overflowY = get($parent, 'overflow-y');
+ if (overflowY !== 'hidden' && overflowY !== 'visible') {
+ const { scrollTop, scrollHeight, clientHeight } = $parent;
+ if (scrollHeight > clientHeight) {
+ canTouchScroll = true;
+ isAtTop = scrollTop <= 3;
+ isAtBottom = scrollTop >= (scrollHeight - clientHeight) - 3;
+ break;
+ }
+ }
+ $parent = $parent.parentElement;
+ }
+
+ if (canTouchScroll && ((!isAtTop && !isAtBottom) || (isAtTop && movedY < 0) || (isAtBottom && movedY > 0))) {
+
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.pointer[2] = x;
+ this.pointer[3] = y;
+ this.pointer[4] = x;
+ this.pointer[5] = y;
+ this.pointer[6] = x;
+ this.pointer[7] = y;
+
+ } else {
+
+ preventDefault(e);
+
+ // Needed to prevents click on handleUp
+ if (!this.triggerStyles) this.triggerStyles = set(this.$trigger, { pointerEvents: 'none' });
+ // Needed to prevent page scroll while dragging on touch devvice
+ this.$trigger.addEventListener('touchstart', preventDefault, { passive: false });
+ this.$trigger.addEventListener('touchmove', preventDefault, { passive: false });
+ this.$trigger.addEventListener('touchend', preventDefault);
+
+
+ if ((!this.disabled[0] && abs(movedX) > 3) || (!this.disabled[1] && abs(movedY) > 3)) {
+
+ this.updateTicker.resume();
+ this.pointer[2] = this.pointer[0];
+ this.pointer[3] = this.pointer[1];
+ this.pointer[0] = x;
+ this.pointer[1] = y;
+ this.dragged = true;
+ this.released = false;
+ this.onDrag(this);
+ }
+ }
+ }
+
+ handleUp() {
+
+ if (!this.grabbed) return;
+
+ this.updateTicker.pause();
+
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+
+ if (this.bodyStyles) {
+ this.bodyStyles.revert();
+ this.bodyStyles = null;
+ }
+
+ const [ disabledX, disabledY ] = this.disabled;
+ const [ px1, py1, px2, py2, px3, py3 ] = this.pointer;
+ const [ ct, cr, cb, cl ] = this.containerBounds;
+ const [ sx, sy ] = this.snapped;
+ const springX = this.releaseXSpring;
+ const springY = this.releaseYSpring;
+ const releaseEase = this.releaseEase;
+ const hasReleaseSpring = this.hasReleaseSpring;
+ const overshootCoords = this.overshootCoords;
+ const cx = this.x;
+ const cy = this.y;
+ const pv = this.computeVelocity(px1 - px3, py1 - py3);
+ const pa = this.angle = atan2(py1 - py2, px1 - px2);
+ const ds = pv * 150;
+ const cf = (1 - this.releaseContainerFriction) * this.dragSpeed;
+ const nx = cx + (cos(pa) * ds);
+ const ny = cy + (sin(pa) * ds);
+ const bx = nx > cr ? cr + (nx - cr) * cf : nx < cl ? cl + (nx - cl) * cf : nx;
+ const by = ny > cb ? cb + (ny - cb) * cf : ny < ct ? ct + (ny - ct) * cf : ny;
+ const dx = this.destX = clamp(round(snap(bx, this.snapX), 5), cl, cr);
+ const dy = this.destY = clamp(round(snap(by, this.snapY), 5), ct, cb);
+ const ob = this.isOutOfBounds(this.containerBounds, nx, ny);
+
+ let durationX = 0;
+ let durationY = 0;
+ let easeX = releaseEase;
+ let easeY = releaseEase;
+ let longestReleaseDuration = 0;
+
+ overshootCoords.x = cx;
+ overshootCoords.y = cy;
+
+ if (!disabledX) {
+ const directionX = dx === cr ? cx > cr ? -1 : 1 : cx < cl ? -1 : 1;
+ const distanceX = round(cx - dx, 0);
+ springX.velocity = disabledY && hasReleaseSpring ? distanceX ? (ds * directionX) / abs(distanceX) : 0 : pv;
+ const { ease, duration, restDuration } = springX;
+ durationX = cx === dx ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.timeScale);
+ if (hasReleaseSpring) easeX = ease;
+ if (durationX > longestReleaseDuration) longestReleaseDuration = durationX;
+ }
+
+ if (!disabledY) {
+ const directionY = dy === cb ? cy > cb ? -1 : 1 : cy < ct ? -1 : 1;
+ const distanceY = round(cy - dy, 0);
+ springY.velocity = disabledX && hasReleaseSpring ? distanceY ? (ds * directionY) / abs(distanceY) : 0 : pv;
+ const { ease, duration, restDuration } = springY;
+ durationY = cy === dy ? 0 : hasReleaseSpring ? duration : duration - (restDuration * globals.timeScale);
+ if (hasReleaseSpring) easeY = ease;
+ if (durationY > longestReleaseDuration) longestReleaseDuration = durationY;
+ }
+
+ if (!hasReleaseSpring && ob && cf && (durationX || durationY)) {
+
+ const composition = compositionTypes.blend;
+
+ new JSAnimation(overshootCoords, {
+ x: { to: bx, duration: durationX * .65 },
+ y: { to: by, duration: durationY * .65 },
+ ease: releaseEase,
+ composition,
+ }).init();
+
+ new JSAnimation(overshootCoords, {
+ x: { to: dx, duration: durationX },
+ y: { to: dy, duration: durationY },
+ ease: releaseEase,
+ composition,
+ }).init();
+
+ this.overshootTicker.stretch(max(durationX, durationY)).restart();
+
+ } else {
+
+ if (!disabledX) this.animate[this.xProp](dx, durationX, easeX);
+ if (!disabledY) this.animate[this.yProp](dy, durationY, easeY);
+
+ }
+
+ this.scrollInView(longestReleaseDuration, this.scrollThreshold, releaseEase);
+
+ let hasSnapped = false;
+
+ if (dx !== sx) {
+ this.snapped[0] = dx;
+ if (this.snapX) hasSnapped = true;
+ }
+
+ if (dy !== sy && this.snapY) {
+ this.snapped[1] = dy;
+ if (this.snapY) hasSnapped = true;
+ }
+
+ if (hasSnapped) this.onSnap(this);
+
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = true;
+ this.released = true;
+
+ // It's important to trigger the callback after the release animations to be able to cancel them
+ this.onRelease(this);
+
+ this.$trigger.removeEventListener('touchstart', preventDefault);
+ this.$trigger.removeEventListener('touchmove', preventDefault);
+ this.$trigger.removeEventListener('touchend', preventDefault);
+
+ doc.removeEventListener('touchmove', this);
+ doc.removeEventListener('touchend', this);
+ doc.removeEventListener('touchcancel', this);
+ doc.removeEventListener('mousemove', this);
+ doc.removeEventListener('mouseup', this);
+ doc.removeEventListener('selectstart', this);
+ }
+
+ reset() {
+ this.stop();
+ this.resizeTicker.pause();
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.setX(0, true);
+ this.setY(0, true);
+ this.coords[0] = 0;
+ this.coords[1] = 0;
+ this.pointer[0] = 0;
+ this.pointer[1] = 0;
+ this.pointer[2] = 0;
+ this.pointer[3] = 0;
+ this.pointer[4] = 0;
+ this.pointer[5] = 0;
+ this.pointer[6] = 0;
+ this.pointer[7] = 0;
+ this.velocity = 0;
+ this.velocityStack[0] = 0;
+ this.velocityStack[1] = 0;
+ this.velocityStack[2] = 0;
+ this.velocityStackIndex = 0;
+ this.angle = 0;
+ return this;
+ }
+
+ enable() {
+ if (!this.enabled) {
+ this.enabled = true;
+ this.$target.classList.remove('is-disabled');
+ this.touchActionStyles = set(this.$trigger, {
+ touchAction: this.disabled[0] ? 'pan-x' : this.disabled[1] ? 'pan-y' : 'none'
+ });
+ this.$trigger.addEventListener('touchstart', this, { passive: true });
+ this.$trigger.addEventListener('mousedown', this, { passive: true });
+ this.$trigger.addEventListener('mouseenter', this);
+ }
+ return this;
+ }
+
+ disable() {
+ this.enabled = false;
+ this.grabbed = false;
+ this.dragged = false;
+ this.updated = false;
+ this.released = false;
+ this.canScroll = false;
+ this.touchActionStyles.revert();
+ if (this.cursorStyles) {
+ this.cursorStyles.revert();
+ this.cursorStyles = null;
+ }
+ if (this.triggerStyles) {
+ this.triggerStyles.revert();
+ this.triggerStyles = null;
+ }
+ if (this.bodyStyles) {
+ this.bodyStyles.revert();
+ this.bodyStyles = null;
+ }
+ if (this.targetStyles) {
+ this.targetStyles.revert();
+ this.targetStyles = null;
+ }
+ this.$target.classList.add('is-disabled');
+ this.$trigger.removeEventListener('touchstart', this);
+ this.$trigger.removeEventListener('mousedown', this);
+ this.$trigger.removeEventListener('mouseenter', this);
+ doc.removeEventListener('touchmove', this);
+ doc.removeEventListener('touchend', this);
+ doc.removeEventListener('touchcancel', this);
+ doc.removeEventListener('mousemove', this);
+ doc.removeEventListener('mouseup', this);
+ doc.removeEventListener('selectstart', this);
+ return this;
+ }
+
+ revert() {
+ this.reset();
+ this.disable();
+ this.$target.classList.remove('is-disabled');
+ this.updateTicker.revert();
+ this.overshootTicker.revert();
+ this.resizeTicker.revert();
+ this.animate.revert();
+ this.resizeObserver.disconnect();
+ return this;
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'mousedown':
+ this.handleDown(/** @type {MouseEvent} */(e));
+ break;
+ case 'touchstart':
+ this.handleDown(/** @type {TouchEvent} */(e));
+ break;
+ case 'mousemove':
+ this.handleMove(/** @type {MouseEvent} */(e));
+ break;
+ case 'touchmove':
+ this.handleMove(/** @type {TouchEvent} */(e));
+ break;
+ case 'mouseup':
+ this.handleUp();
+ break;
+ case 'touchend':
+ this.handleUp();
+ break;
+ case 'touchcancel':
+ this.handleUp();
+ break;
+ case 'mouseenter':
+ this.handleHover();
+ break;
+ case 'selectstart':
+ preventDefault(e);
+ break;
+ }
+ }
+}
+
+/**
+ * @param {TargetsParam} target
+ * @param {DraggableParams} [parameters]
+ * @return {Draggable}
+ */
+const createDraggable = (target, parameters) => new Draggable(target, parameters);
+
+export { Draggable, createDraggable };
diff --git a/dist/modules/draggable/index.cjs b/dist/modules/draggable/index.cjs
new file mode 100644
index 00000000..60c8a8dc
--- /dev/null
+++ b/dist/modules/draggable/index.cjs
@@ -0,0 +1,15 @@
+/**
+ * Anime.js - draggable - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var draggable = require('./draggable.cjs');
+
+
+
+exports.Draggable = draggable.Draggable;
+exports.createDraggable = draggable.createDraggable;
diff --git a/dist/modules/draggable/index.d.ts b/dist/modules/draggable/index.d.ts
new file mode 100644
index 00000000..cc5802a3
--- /dev/null
+++ b/dist/modules/draggable/index.d.ts
@@ -0,0 +1 @@
+export * from "./draggable.js";
diff --git a/dist/modules/draggable/index.js b/dist/modules/draggable/index.js
new file mode 100644
index 00000000..5d7b901e
--- /dev/null
+++ b/dist/modules/draggable/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - draggable - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { Draggable, createDraggable } from './draggable.js';
diff --git a/dist/modules/easings/cubic-bezier.cjs b/dist/modules/easings/cubic-bezier.cjs
new file mode 100644
index 00000000..8947b525
--- /dev/null
+++ b/dist/modules/easings/cubic-bezier.cjs
@@ -0,0 +1,64 @@
+/**
+ * Anime.js - easings - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+var none = require('./none.cjs');
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Cubic Bezier solver adapted from https://github.com/gre/bezier-easing
+ * (c) 2014 Gaëtan Renaudeau
+ */
+
+/**
+ * @param {Number} aT
+ * @param {Number} aA1
+ * @param {Number} aA2
+ * @return {Number}
+ */
+const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT;
+
+/**
+ * @param {Number} aX
+ * @param {Number} mX1
+ * @param {Number} mX2
+ * @return {Number}
+ */
+const binarySubdivide = (aX, mX1, mX2) => {
+ let aA = 0, aB = 1, currentX, currentT, i = 0;
+ do {
+ currentT = aA + (aB - aA) / 2;
+ currentX = calcBezier(currentT, mX1, mX2) - aX;
+ if (currentX > 0) {
+ aB = currentT;
+ } else {
+ aA = currentT;
+ }
+ } while (helpers.abs(currentX) > .0000001 && ++i < 100);
+ return currentT;
+};
+
+/**
+ * @param {Number} [mX1] The x coordinate of the first point
+ * @param {Number} [mY1] The y coordinate of the first point
+ * @param {Number} [mX2] The x coordinate of the second point
+ * @param {Number} [mY2] The y coordinate of the second point
+ * @return {EasingFunction}
+ */
+
+const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none.none :
+ t => t === 0 || t === 1 ? t :
+ calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
+
+exports.cubicBezier = cubicBezier;
diff --git a/dist/modules/easings/cubic-bezier.d.ts b/dist/modules/easings/cubic-bezier.d.ts
new file mode 100644
index 00000000..31c52a3c
--- /dev/null
+++ b/dist/modules/easings/cubic-bezier.d.ts
@@ -0,0 +1,2 @@
+export function cubicBezier(mX1?: number, mY1?: number, mX2?: number, mY2?: number): EasingFunction;
+import type { EasingFunction } from '../types/index.js';
diff --git a/dist/modules/easings/cubic-bezier.js b/dist/modules/easings/cubic-bezier.js
new file mode 100644
index 00000000..02144717
--- /dev/null
+++ b/dist/modules/easings/cubic-bezier.js
@@ -0,0 +1,62 @@
+/**
+ * Anime.js - easings - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { abs } from '../core/helpers.js';
+import { none } from './none.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Cubic Bezier solver adapted from https://github.com/gre/bezier-easing
+ * (c) 2014 Gaëtan Renaudeau
+ */
+
+/**
+ * @param {Number} aT
+ * @param {Number} aA1
+ * @param {Number} aA2
+ * @return {Number}
+ */
+const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT;
+
+/**
+ * @param {Number} aX
+ * @param {Number} mX1
+ * @param {Number} mX2
+ * @return {Number}
+ */
+const binarySubdivide = (aX, mX1, mX2) => {
+ let aA = 0, aB = 1, currentX, currentT, i = 0;
+ do {
+ currentT = aA + (aB - aA) / 2;
+ currentX = calcBezier(currentT, mX1, mX2) - aX;
+ if (currentX > 0) {
+ aB = currentT;
+ } else {
+ aA = currentT;
+ }
+ } while (abs(currentX) > .0000001 && ++i < 100);
+ return currentT;
+};
+
+/**
+ * @param {Number} [mX1] The x coordinate of the first point
+ * @param {Number} [mY1] The y coordinate of the first point
+ * @param {Number} [mX2] The x coordinate of the second point
+ * @param {Number} [mY2] The y coordinate of the second point
+ * @return {EasingFunction}
+ */
+
+const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none :
+ t => t === 0 || t === 1 ? t :
+ calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
+
+export { cubicBezier };
diff --git a/dist/modules/easings/eases.cjs b/dist/modules/easings/eases.cjs
new file mode 100644
index 00000000..6ccb1715
--- /dev/null
+++ b/dist/modules/easings/eases.cjs
@@ -0,0 +1,149 @@
+/**
+ * Anime.js - easings - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var parser = require('./parser.cjs');
+var none = require('./none.cjs');
+var cubicBezier = require('./cubic-bezier.cjs');
+var steps = require('./steps.cjs');
+var linear = require('./linear.cjs');
+var irregular = require('./irregular.cjs');
+
+/**
+ * @import {
+ * EasingFunction,
+ * EasingFunctionWithParams,
+ * EasingParam,
+ * BackEasing,
+ * ElasticEasing,
+ * PowerEasing,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Easing functions adapted and simplified from https://robertpenner.com/easing/
+ * (c) 2001 Robert Penner
+ */
+
+const halfPI = helpers.PI / 2;
+const doublePI = helpers.PI * 2;
+
+/** @type {Record<String, EasingFunctionWithParams|EasingFunction>} */
+const easeInFunctions = {
+ [consts.emptyString]: parser.easeInPower,
+ Quad: parser.easeInPower(2),
+ Cubic: parser.easeInPower(3),
+ Quart: parser.easeInPower(4),
+ Quint: parser.easeInPower(5),
+ /** @type {EasingFunction} */
+ Sine: t => 1 - helpers.cos(t * halfPI),
+ /** @type {EasingFunction} */
+ Circ: t => 1 - helpers.sqrt(1 - t * t),
+ /** @type {EasingFunction} */
+ Expo: t => t ? helpers.pow(2, 10 * t - 10) : 0,
+ /** @type {EasingFunction} */
+ Bounce: t => {
+ let pow2, b = 4;
+ while (t < ((pow2 = helpers.pow(2, --b)) - 1) / 11);
+ return 1 / helpers.pow(4, 3 - b) - 7.5625 * helpers.pow((pow2 * 3 - 2) / 22 - t, 2);
+ },
+ /** @type {BackEasing} */
+ Back: (overshoot = 1.70158) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t,
+ /** @type {ElasticEasing} */
+ Elastic: (amplitude = 1, period = .3) => {
+ const a = helpers.clamp(+amplitude, 1, 10);
+ const p = helpers.clamp(+period, consts.minValue, 2);
+ const s = (p / doublePI) * helpers.asin(1 / a);
+ const e = doublePI / p;
+ return t => t === 0 || t === 1 ? t : -a * helpers.pow(2, -10 * (1 - t)) * helpers.sin(((1 - t) - s) * e);
+ }
+};
+
+/**
+ * @typedef {Object} EasesFunctions
+ * @property {typeof linear} linear
+ * @property {typeof irregular} irregular
+ * @property {typeof steps} steps
+ * @property {typeof cubicBezier} cubicBezier
+ * @property {PowerEasing} in
+ * @property {PowerEasing} out
+ * @property {PowerEasing} inOut
+ * @property {PowerEasing} outIn
+ * @property {EasingFunction} inQuad
+ * @property {EasingFunction} outQuad
+ * @property {EasingFunction} inOutQuad
+ * @property {EasingFunction} outInQuad
+ * @property {EasingFunction} inCubic
+ * @property {EasingFunction} outCubic
+ * @property {EasingFunction} inOutCubic
+ * @property {EasingFunction} outInCubic
+ * @property {EasingFunction} inQuart
+ * @property {EasingFunction} outQuart
+ * @property {EasingFunction} inOutQuart
+ * @property {EasingFunction} outInQuart
+ * @property {EasingFunction} inQuint
+ * @property {EasingFunction} outQuint
+ * @property {EasingFunction} inOutQuint
+ * @property {EasingFunction} outInQuint
+ * @property {EasingFunction} inSine
+ * @property {EasingFunction} outSine
+ * @property {EasingFunction} inOutSine
+ * @property {EasingFunction} outInSine
+ * @property {EasingFunction} inCirc
+ * @property {EasingFunction} outCirc
+ * @property {EasingFunction} inOutCirc
+ * @property {EasingFunction} outInCirc
+ * @property {EasingFunction} inExpo
+ * @property {EasingFunction} outExpo
+ * @property {EasingFunction} inOutExpo
+ * @property {EasingFunction} outInExpo
+ * @property {EasingFunction} inBounce
+ * @property {EasingFunction} outBounce
+ * @property {EasingFunction} inOutBounce
+ * @property {EasingFunction} outInBounce
+ * @property {BackEasing} inBack
+ * @property {BackEasing} outBack
+ * @property {BackEasing} inOutBack
+ * @property {BackEasing} outInBack
+ * @property {ElasticEasing} inElastic
+ * @property {ElasticEasing} outElastic
+ * @property {ElasticEasing} inOutElastic
+ * @property {ElasticEasing} outInElastic
+ */
+
+const eases = (/*#__PURE__ */ (() => {
+ const list = { linear: linear.linear, irregular: irregular.irregular, steps: steps.steps, cubicBezier: cubicBezier.cubicBezier };
+ for (let type in parser.easeTypes) {
+ for (let name in easeInFunctions) {
+ const easeIn = easeInFunctions[name];
+ const easeType = parser.easeTypes[type];
+ list[type + name] = /** @type {EasingFunctionWithParams|EasingFunction} */(
+ name === consts.emptyString || name === 'Back' || name === 'Elastic' ?
+ (a, b) => easeType(/** @type {EasingFunctionWithParams} */(easeIn)(a, b)) :
+ easeType(/** @type {EasingFunction} */(easeIn))
+ );
+ }
+ }
+ return /** @type {EasesFunctions} */(list);
+})());
+
+/** @type {Record<String, EasingFunction>} */
+const JSEasesLookups = { linear: none.none };
+
+/**
+ * @param {EasingParam} ease
+ * @return {EasingFunction}
+ */
+const parseEase = ease => helpers.isFnc(ease) ? ease :
+ helpers.isStr(ease) ? parser.parseEaseString(/** @type {String} */(ease), eases, JSEasesLookups) :
+ none.none;
+
+exports.eases = eases;
+exports.parseEase = parseEase;
diff --git a/dist/modules/easings/eases.d.ts b/dist/modules/easings/eases.d.ts
new file mode 100644
index 00000000..bf7bf304
--- /dev/null
+++ b/dist/modules/easings/eases.d.ts
@@ -0,0 +1,111 @@
+export namespace eases {
+ export let linear: typeof import("./linear.js").linear;
+ export let irregular: typeof import("./irregular.js").irregular;
+ export let steps: typeof import("./steps.js").steps;
+ export let cubicBezier: typeof import("./cubic-bezier.js").cubicBezier;
+ let _in: PowerEasing;
+ export { _in as in };
+ export let out: PowerEasing;
+ export let inOut: PowerEasing;
+ export let outIn: PowerEasing;
+ export let inQuad: EasingFunction;
+ export let outQuad: EasingFunction;
+ export let inOutQuad: EasingFunction;
+ export let outInQuad: EasingFunction;
+ export let inCubic: EasingFunction;
+ export let outCubic: EasingFunction;
+ export let inOutCubic: EasingFunction;
+ export let outInCubic: EasingFunction;
+ export let inQuart: EasingFunction;
+ export let outQuart: EasingFunction;
+ export let inOutQuart: EasingFunction;
+ export let outInQuart: EasingFunction;
+ export let inQuint: EasingFunction;
+ export let outQuint: EasingFunction;
+ export let inOutQuint: EasingFunction;
+ export let outInQuint: EasingFunction;
+ export let inSine: EasingFunction;
+ export let outSine: EasingFunction;
+ export let inOutSine: EasingFunction;
+ export let outInSine: EasingFunction;
+ export let inCirc: EasingFunction;
+ export let outCirc: EasingFunction;
+ export let inOutCirc: EasingFunction;
+ export let outInCirc: EasingFunction;
+ export let inExpo: EasingFunction;
+ export let outExpo: EasingFunction;
+ export let inOutExpo: EasingFunction;
+ export let outInExpo: EasingFunction;
+ export let inBounce: EasingFunction;
+ export let outBounce: EasingFunction;
+ export let inOutBounce: EasingFunction;
+ export let outInBounce: EasingFunction;
+ export let inBack: BackEasing;
+ export let outBack: BackEasing;
+ export let inOutBack: BackEasing;
+ export let outInBack: BackEasing;
+ export let inElastic: ElasticEasing;
+ export let outElastic: ElasticEasing;
+ export let inOutElastic: ElasticEasing;
+ export let outInElastic: ElasticEasing;
+}
+export function parseEase(ease: EasingParam): EasingFunction;
+export type EasesFunctions = {
+ linear: typeof linear;
+ irregular: typeof irregular;
+ steps: typeof steps;
+ cubicBezier: typeof cubicBezier;
+ in: PowerEasing;
+ out: PowerEasing;
+ inOut: PowerEasing;
+ outIn: PowerEasing;
+ inQuad: EasingFunction;
+ outQuad: EasingFunction;
+ inOutQuad: EasingFunction;
+ outInQuad: EasingFunction;
+ inCubic: EasingFunction;
+ outCubic: EasingFunction;
+ inOutCubic: EasingFunction;
+ outInCubic: EasingFunction;
+ inQuart: EasingFunction;
+ outQuart: EasingFunction;
+ inOutQuart: EasingFunction;
+ outInQuart: EasingFunction;
+ inQuint: EasingFunction;
+ outQuint: EasingFunction;
+ inOutQuint: EasingFunction;
+ outInQuint: EasingFunction;
+ inSine: EasingFunction;
+ outSine: EasingFunction;
+ inOutSine: EasingFunction;
+ outInSine: EasingFunction;
+ inCirc: EasingFunction;
+ outCirc: EasingFunction;
+ inOutCirc: EasingFunction;
+ outInCirc: EasingFunction;
+ inExpo: EasingFunction;
+ outExpo: EasingFunction;
+ inOutExpo: EasingFunction;
+ outInExpo: EasingFunction;
+ inBounce: EasingFunction;
+ outBounce: EasingFunction;
+ inOutBounce: EasingFunction;
+ outInBounce: EasingFunction;
+ inBack: BackEasing;
+ outBack: BackEasing;
+ inOutBack: BackEasing;
+ outInBack: BackEasing;
+ inElastic: ElasticEasing;
+ outElastic: ElasticEasing;
+ inOutElastic: ElasticEasing;
+ outInElastic: ElasticEasing;
+};
+import type { PowerEasing } from '../types/index.js';
+import type { EasingFunction } from '../types/index.js';
+import type { BackEasing } from '../types/index.js';
+import type { ElasticEasing } from '../types/index.js';
+import type { EasingParam } from '../types/index.js';
+import { linear as linear_1 } from './linear.js';
+import { irregular as irregular_1 } from './irregular.js';
+import { steps as steps_1 } from './steps.js';
+import { cubicBezier as cubicBezier_1 } from './cubic-bezier.js';
diff --git a/dist/modules/easings/eases.js b/dist/modules/easings/eases.js
new file mode 100644
index 00000000..1638b9ad
--- /dev/null
+++ b/dist/modules/easings/eases.js
@@ -0,0 +1,146 @@
+/**
+ * Anime.js - easings - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { emptyString, minValue } from '../core/consts.js';
+import { pow, sin, sqrt, cos, isFnc, isStr, clamp, asin, PI } from '../core/helpers.js';
+import { easeTypes, easeInPower, parseEaseString } from './parser.js';
+import { none } from './none.js';
+import { cubicBezier } from './cubic-bezier.js';
+import { steps } from './steps.js';
+import { linear } from './linear.js';
+import { irregular } from './irregular.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * EasingFunctionWithParams,
+ * EasingParam,
+ * BackEasing,
+ * ElasticEasing,
+ * PowerEasing,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Easing functions adapted and simplified from https://robertpenner.com/easing/
+ * (c) 2001 Robert Penner
+ */
+
+const halfPI = PI / 2;
+const doublePI = PI * 2;
+
+/** @type {Record<String, EasingFunctionWithParams|EasingFunction>} */
+const easeInFunctions = {
+ [emptyString]: easeInPower,
+ Quad: easeInPower(2),
+ Cubic: easeInPower(3),
+ Quart: easeInPower(4),
+ Quint: easeInPower(5),
+ /** @type {EasingFunction} */
+ Sine: t => 1 - cos(t * halfPI),
+ /** @type {EasingFunction} */
+ Circ: t => 1 - sqrt(1 - t * t),
+ /** @type {EasingFunction} */
+ Expo: t => t ? pow(2, 10 * t - 10) : 0,
+ /** @type {EasingFunction} */
+ Bounce: t => {
+ let pow2, b = 4;
+ while (t < ((pow2 = pow(2, --b)) - 1) / 11);
+ return 1 / pow(4, 3 - b) - 7.5625 * pow((pow2 * 3 - 2) / 22 - t, 2);
+ },
+ /** @type {BackEasing} */
+ Back: (overshoot = 1.70158) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t,
+ /** @type {ElasticEasing} */
+ Elastic: (amplitude = 1, period = .3) => {
+ const a = clamp(+amplitude, 1, 10);
+ const p = clamp(+period, minValue, 2);
+ const s = (p / doublePI) * asin(1 / a);
+ const e = doublePI / p;
+ return t => t === 0 || t === 1 ? t : -a * pow(2, -10 * (1 - t)) * sin(((1 - t) - s) * e);
+ }
+};
+
+/**
+ * @typedef {Object} EasesFunctions
+ * @property {typeof linear} linear
+ * @property {typeof irregular} irregular
+ * @property {typeof steps} steps
+ * @property {typeof cubicBezier} cubicBezier
+ * @property {PowerEasing} in
+ * @property {PowerEasing} out
+ * @property {PowerEasing} inOut
+ * @property {PowerEasing} outIn
+ * @property {EasingFunction} inQuad
+ * @property {EasingFunction} outQuad
+ * @property {EasingFunction} inOutQuad
+ * @property {EasingFunction} outInQuad
+ * @property {EasingFunction} inCubic
+ * @property {EasingFunction} outCubic
+ * @property {EasingFunction} inOutCubic
+ * @property {EasingFunction} outInCubic
+ * @property {EasingFunction} inQuart
+ * @property {EasingFunction} outQuart
+ * @property {EasingFunction} inOutQuart
+ * @property {EasingFunction} outInQuart
+ * @property {EasingFunction} inQuint
+ * @property {EasingFunction} outQuint
+ * @property {EasingFunction} inOutQuint
+ * @property {EasingFunction} outInQuint
+ * @property {EasingFunction} inSine
+ * @property {EasingFunction} outSine
+ * @property {EasingFunction} inOutSine
+ * @property {EasingFunction} outInSine
+ * @property {EasingFunction} inCirc
+ * @property {EasingFunction} outCirc
+ * @property {EasingFunction} inOutCirc
+ * @property {EasingFunction} outInCirc
+ * @property {EasingFunction} inExpo
+ * @property {EasingFunction} outExpo
+ * @property {EasingFunction} inOutExpo
+ * @property {EasingFunction} outInExpo
+ * @property {EasingFunction} inBounce
+ * @property {EasingFunction} outBounce
+ * @property {EasingFunction} inOutBounce
+ * @property {EasingFunction} outInBounce
+ * @property {BackEasing} inBack
+ * @property {BackEasing} outBack
+ * @property {BackEasing} inOutBack
+ * @property {BackEasing} outInBack
+ * @property {ElasticEasing} inElastic
+ * @property {ElasticEasing} outElastic
+ * @property {ElasticEasing} inOutElastic
+ * @property {ElasticEasing} outInElastic
+ */
+
+const eases = (/*#__PURE__ */ (() => {
+ const list = { linear, irregular, steps, cubicBezier };
+ for (let type in easeTypes) {
+ for (let name in easeInFunctions) {
+ const easeIn = easeInFunctions[name];
+ const easeType = easeTypes[type];
+ list[type + name] = /** @type {EasingFunctionWithParams|EasingFunction} */(
+ name === emptyString || name === 'Back' || name === 'Elastic' ?
+ (a, b) => easeType(/** @type {EasingFunctionWithParams} */(easeIn)(a, b)) :
+ easeType(/** @type {EasingFunction} */(easeIn))
+ );
+ }
+ }
+ return /** @type {EasesFunctions} */(list);
+})());
+
+/** @type {Record<String, EasingFunction>} */
+const JSEasesLookups = { linear: none };
+
+/**
+ * @param {EasingParam} ease
+ * @return {EasingFunction}
+ */
+const parseEase = ease => isFnc(ease) ? ease :
+ isStr(ease) ? parseEaseString(/** @type {String} */(ease), eases, JSEasesLookups) :
+ none;
+
+export { eases, parseEase };
diff --git a/dist/modules/easings/index.cjs b/dist/modules/easings/index.cjs
new file mode 100644
index 00000000..92bdd6b7
--- /dev/null
+++ b/dist/modules/easings/index.cjs
@@ -0,0 +1,24 @@
+/**
+ * Anime.js - easings - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var none = require('./none.cjs');
+var cubicBezier = require('./cubic-bezier.cjs');
+var steps = require('./steps.cjs');
+var linear = require('./linear.cjs');
+var irregular = require('./irregular.cjs');
+var eases = require('./eases.cjs');
+
+
+
+exports.none = none.none;
+exports.cubicBezier = cubicBezier.cubicBezier;
+exports.steps = steps.steps;
+exports.linear = linear.linear;
+exports.irregular = irregular.irregular;
+exports.eases = eases.eases;
diff --git a/dist/modules/easings/index.d.ts b/dist/modules/easings/index.d.ts
new file mode 100644
index 00000000..418a27e5
--- /dev/null
+++ b/dist/modules/easings/index.d.ts
@@ -0,0 +1,6 @@
+export { none } from "./none.js";
+export { cubicBezier } from "./cubic-bezier.js";
+export { steps } from "./steps.js";
+export { linear } from "./linear.js";
+export { irregular } from "./irregular.js";
+export { eases } from "./eases.js";
diff --git a/dist/modules/easings/index.js b/dist/modules/easings/index.js
new file mode 100644
index 00000000..38b22a4a
--- /dev/null
+++ b/dist/modules/easings/index.js
@@ -0,0 +1,13 @@
+/**
+ * Anime.js - easings - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { none } from './none.js';
+export { cubicBezier } from './cubic-bezier.js';
+export { steps } from './steps.js';
+export { linear } from './linear.js';
+export { irregular } from './irregular.js';
+export { eases } from './eases.js';
diff --git a/dist/modules/easings/irregular.cjs b/dist/modules/easings/irregular.cjs
new file mode 100644
index 00000000..acaeadcb
--- /dev/null
+++ b/dist/modules/easings/irregular.cjs
@@ -0,0 +1,41 @@
+/**
+ * Anime.js - easings - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+var linear = require('./linear.cjs');
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Generate random steps
+ * @param {Number} [length] - The number of steps
+ * @param {Number} [randomness] - How strong the randomness is
+ * @return {EasingFunction}
+ */
+const irregular = (length = 10, randomness = 1) => {
+ const values = [0];
+ const total = length - 1;
+ for (let i = 1; i < total; i++) {
+ const previousValue = values[i - 1];
+ const spacing = i / total;
+ const segmentEnd = (i + 1) / total;
+ const randomVariation = spacing + (segmentEnd - spacing) * Math.random();
+ // Mix the even spacing and random variation based on the randomness parameter
+ const randomValue = spacing * (1 - randomness) + randomVariation * randomness;
+ values.push(helpers.clamp(randomValue, previousValue, 1));
+ }
+ values.push(1);
+ return linear.linear(...values);
+};
+
+exports.irregular = irregular;
diff --git a/dist/modules/easings/irregular.d.ts b/dist/modules/easings/irregular.d.ts
new file mode 100644
index 00000000..e56b1247
--- /dev/null
+++ b/dist/modules/easings/irregular.d.ts
@@ -0,0 +1,2 @@
+export function irregular(length?: number, randomness?: number): EasingFunction;
+import type { EasingFunction } from '../types/index.js';
diff --git a/dist/modules/easings/irregular.js b/dist/modules/easings/irregular.js
new file mode 100644
index 00000000..6525d087
--- /dev/null
+++ b/dist/modules/easings/irregular.js
@@ -0,0 +1,39 @@
+/**
+ * Anime.js - easings - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { clamp } from '../core/helpers.js';
+import { linear } from './linear.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Generate random steps
+ * @param {Number} [length] - The number of steps
+ * @param {Number} [randomness] - How strong the randomness is
+ * @return {EasingFunction}
+ */
+const irregular = (length = 10, randomness = 1) => {
+ const values = [0];
+ const total = length - 1;
+ for (let i = 1; i < total; i++) {
+ const previousValue = values[i - 1];
+ const spacing = i / total;
+ const segmentEnd = (i + 1) / total;
+ const randomVariation = spacing + (segmentEnd - spacing) * Math.random();
+ // Mix the even spacing and random variation based on the randomness parameter
+ const randomValue = spacing * (1 - randomness) + randomVariation * randomness;
+ values.push(clamp(randomValue, previousValue, 1));
+ }
+ values.push(1);
+ return linear(...values);
+};
+
+export { irregular };
diff --git a/dist/modules/easings/linear.cjs b/dist/modules/easings/linear.cjs
new file mode 100644
index 00000000..a7182d7a
--- /dev/null
+++ b/dist/modules/easings/linear.cjs
@@ -0,0 +1,59 @@
+/**
+ * Anime.js - easings - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+var none = require('./none.cjs');
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Without parameters, the linear function creates a non-eased transition.
+ * Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points.
+ *
+ * @param {...(String|Number)} args - Points
+ * @return {EasingFunction}
+ */
+const linear = (...args) => {
+ const argsLength = args.length;
+ if (!argsLength) return none.none;
+ const totalPoints = argsLength - 1;
+ const firstArg = args[0];
+ const lastArg = args[totalPoints];
+ const xPoints = [0];
+ const yPoints = [helpers.parseNumber(firstArg)];
+ for (let i = 1; i < totalPoints; i++) {
+ const arg = args[i];
+ const splitValue = helpers.isStr(arg) ?
+ /** @type {String} */(arg).trim().split(' ') :
+ [arg];
+ const value = splitValue[0];
+ const percent = splitValue[1];
+ xPoints.push(!helpers.isUnd(percent) ? helpers.parseNumber(percent) / 100 : i / totalPoints);
+ yPoints.push(helpers.parseNumber(value));
+ }
+ yPoints.push(helpers.parseNumber(lastArg));
+ xPoints.push(1);
+ return function easeLinear(t) {
+ for (let i = 1, l = xPoints.length; i < l; i++) {
+ const currentX = xPoints[i];
+ if (t <= currentX) {
+ const prevX = xPoints[i - 1];
+ const prevY = yPoints[i - 1];
+ return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX);
+ }
+ }
+ return yPoints[yPoints.length - 1];
+ }
+};
+
+exports.linear = linear;
diff --git a/dist/modules/easings/linear.d.ts b/dist/modules/easings/linear.d.ts
new file mode 100644
index 00000000..7916864f
--- /dev/null
+++ b/dist/modules/easings/linear.d.ts
@@ -0,0 +1,2 @@
+export function linear(...args: (string | number)[]): EasingFunction;
+import type { EasingFunction } from '../types/index.js';
diff --git a/dist/modules/easings/linear.js b/dist/modules/easings/linear.js
new file mode 100644
index 00000000..c18f1b82
--- /dev/null
+++ b/dist/modules/easings/linear.js
@@ -0,0 +1,57 @@
+/**
+ * Anime.js - easings - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { isStr, parseNumber, isUnd } from '../core/helpers.js';
+import { none } from './none.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Without parameters, the linear function creates a non-eased transition.
+ * Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points.
+ *
+ * @param {...(String|Number)} args - Points
+ * @return {EasingFunction}
+ */
+const linear = (...args) => {
+ const argsLength = args.length;
+ if (!argsLength) return none;
+ const totalPoints = argsLength - 1;
+ const firstArg = args[0];
+ const lastArg = args[totalPoints];
+ const xPoints = [0];
+ const yPoints = [parseNumber(firstArg)];
+ for (let i = 1; i < totalPoints; i++) {
+ const arg = args[i];
+ const splitValue = isStr(arg) ?
+ /** @type {String} */(arg).trim().split(' ') :
+ [arg];
+ const value = splitValue[0];
+ const percent = splitValue[1];
+ xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints);
+ yPoints.push(parseNumber(value));
+ }
+ yPoints.push(parseNumber(lastArg));
+ xPoints.push(1);
+ return function easeLinear(t) {
+ for (let i = 1, l = xPoints.length; i < l; i++) {
+ const currentX = xPoints[i];
+ if (t <= currentX) {
+ const prevX = xPoints[i - 1];
+ const prevY = yPoints[i - 1];
+ return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX);
+ }
+ }
+ return yPoints[yPoints.length - 1];
+ }
+};
+
+export { linear };
diff --git a/dist/modules/easings/none.cjs b/dist/modules/easings/none.cjs
new file mode 100644
index 00000000..ac17b457
--- /dev/null
+++ b/dist/modules/easings/none.cjs
@@ -0,0 +1,19 @@
+/**
+ * Anime.js - easings - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/** @type {EasingFunction} */
+const none = t => t;
+
+exports.none = none;
diff --git a/dist/modules/easings/none.d.ts b/dist/modules/easings/none.d.ts
new file mode 100644
index 00000000..3acdb834
--- /dev/null
+++ b/dist/modules/easings/none.d.ts
@@ -0,0 +1,8 @@
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+/** @type {EasingFunction} */
+export const none: EasingFunction;
+import type { EasingFunction } from '../types/index.js';
diff --git a/dist/modules/easings/none.js b/dist/modules/easings/none.js
new file mode 100644
index 00000000..5a3a3afc
--- /dev/null
+++ b/dist/modules/easings/none.js
@@ -0,0 +1,17 @@
+/**
+ * Anime.js - easings - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/** @type {EasingFunction} */
+const none = t => t;
+
+export { none };
diff --git a/dist/modules/easings/parser.cjs b/dist/modules/easings/parser.cjs
new file mode 100644
index 00000000..2ebe5cfb
--- /dev/null
+++ b/dist/modules/easings/parser.cjs
@@ -0,0 +1,59 @@
+/**
+ * Anime.js - easings - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+var none = require('./none.cjs');
+
+/**
+ * @import {
+ * EasingFunction,
+ * PowerEasing,
+ * EasingFunctionWithParams,
+ * } from '../types/index.js'
+*/
+
+/** @type {PowerEasing} */
+const easeInPower = (p = 1.68) => t => helpers.pow(t, +p);
+
+/**
+ * @callback EaseType
+ * @param {EasingFunction} Ease
+ * @return {EasingFunction}
+ */
+
+/** @type {Record<String, EaseType>} */
+const easeTypes = {
+ in: easeIn => t => easeIn(t),
+ out: easeIn => t => 1 - easeIn(1 - t),
+ inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2,
+ outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2,
+};
+
+/**
+ * @param {String} string
+ * @param {Record<String, EasingFunctionWithParams|EasingFunction>} easesFunctions
+ * @param {Object} easesLookups
+ * @return {EasingFunction}
+ */
+const parseEaseString = (string, easesFunctions, easesLookups) => {
+ if (easesLookups[string]) return easesLookups[string];
+ if (string.indexOf('(') <= -1) {
+ const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic');
+ const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasingFunctionWithParams} */(easesFunctions[string])() : easesFunctions[string]);
+ return parsedFn ? easesLookups[string] = parsedFn : none.none;
+ } else {
+ const split = string.slice(0, -1).split('(');
+ const parsedFn = /** @type {EasingFunctionWithParams} */(easesFunctions[split[0]]);
+ return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none.none;
+ }
+};
+
+exports.easeInPower = easeInPower;
+exports.easeTypes = easeTypes;
+exports.parseEaseString = parseEaseString;
diff --git a/dist/modules/easings/parser.d.ts b/dist/modules/easings/parser.d.ts
new file mode 100644
index 00000000..4213dcfe
--- /dev/null
+++ b/dist/modules/easings/parser.d.ts
@@ -0,0 +1,21 @@
+/**
+ * @import {
+ * EasingFunction,
+ * PowerEasing,
+ * EasingFunctionWithParams,
+ * } from '../types/index.js'
+*/
+/** @type {PowerEasing} */
+export const easeInPower: PowerEasing;
+/**
+ * @callback EaseType
+ * @param {EasingFunction} Ease
+ * @return {EasingFunction}
+ */
+/** @type {Record<String, EaseType>} */
+export const easeTypes: Record<string, EaseType>;
+export function parseEaseString(string: string, easesFunctions: Record<string, EasingFunctionWithParams | EasingFunction>, easesLookups: any): EasingFunction;
+export type EaseType = (Ease: EasingFunction) => EasingFunction;
+import type { PowerEasing } from '../types/index.js';
+import type { EasingFunctionWithParams } from '../types/index.js';
+import type { EasingFunction } from '../types/index.js';
diff --git a/dist/modules/easings/parser.js b/dist/modules/easings/parser.js
new file mode 100644
index 00000000..9409bf57
--- /dev/null
+++ b/dist/modules/easings/parser.js
@@ -0,0 +1,55 @@
+/**
+ * Anime.js - easings - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { pow } from '../core/helpers.js';
+import { none } from './none.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * PowerEasing,
+ * EasingFunctionWithParams,
+ * } from '../types/index.js'
+*/
+
+/** @type {PowerEasing} */
+const easeInPower = (p = 1.68) => t => pow(t, +p);
+
+/**
+ * @callback EaseType
+ * @param {EasingFunction} Ease
+ * @return {EasingFunction}
+ */
+
+/** @type {Record<String, EaseType>} */
+const easeTypes = {
+ in: easeIn => t => easeIn(t),
+ out: easeIn => t => 1 - easeIn(1 - t),
+ inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2,
+ outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2,
+};
+
+/**
+ * @param {String} string
+ * @param {Record<String, EasingFunctionWithParams|EasingFunction>} easesFunctions
+ * @param {Object} easesLookups
+ * @return {EasingFunction}
+ */
+const parseEaseString = (string, easesFunctions, easesLookups) => {
+ if (easesLookups[string]) return easesLookups[string];
+ if (string.indexOf('(') <= -1) {
+ const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic');
+ const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasingFunctionWithParams} */(easesFunctions[string])() : easesFunctions[string]);
+ return parsedFn ? easesLookups[string] = parsedFn : none;
+ } else {
+ const split = string.slice(0, -1).split('(');
+ const parsedFn = /** @type {EasingFunctionWithParams} */(easesFunctions[split[0]]);
+ return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none;
+ }
+};
+
+export { easeInPower, easeTypes, parseEaseString };
diff --git a/dist/modules/easings/steps.cjs b/dist/modules/easings/steps.cjs
new file mode 100644
index 00000000..484abaed
--- /dev/null
+++ b/dist/modules/easings/steps.cjs
@@ -0,0 +1,30 @@
+/**
+ * Anime.js - easings - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
+ * Only covers 'end' and 'start' jumpterms
+ * @param {Number} steps
+ * @param {Boolean} [fromStart]
+ * @return {EasingFunction}
+ */
+const steps = (steps = 10, fromStart) => {
+ const roundMethod = fromStart ? helpers.ceil : helpers.floor;
+ return t => roundMethod(helpers.clamp(t, 0, 1) * steps) * (1 / steps);
+};
+
+exports.steps = steps;
diff --git a/dist/modules/easings/steps.d.ts b/dist/modules/easings/steps.d.ts
new file mode 100644
index 00000000..89fce078
--- /dev/null
+++ b/dist/modules/easings/steps.d.ts
@@ -0,0 +1,2 @@
+export function steps(steps?: number, fromStart?: boolean): EasingFunction;
+import type { EasingFunction } from '../types/index.js';
diff --git a/dist/modules/easings/steps.js b/dist/modules/easings/steps.js
new file mode 100644
index 00000000..9d6e476c
--- /dev/null
+++ b/dist/modules/easings/steps.js
@@ -0,0 +1,28 @@
+/**
+ * Anime.js - easings - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { ceil, floor, clamp } from '../core/helpers.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
+ * Only covers 'end' and 'start' jumpterms
+ * @param {Number} steps
+ * @param {Boolean} [fromStart]
+ * @return {EasingFunction}
+ */
+const steps = (steps = 10, fromStart) => {
+ const roundMethod = fromStart ? ceil : floor;
+ return t => roundMethod(clamp(t, 0, 1) * steps) * (1 / steps);
+};
+
+export { steps };
diff --git a/dist/modules/engine/engine.cjs b/dist/modules/engine/engine.cjs
new file mode 100644
index 00000000..682b402a
--- /dev/null
+++ b/dist/modules/engine/engine.cjs
@@ -0,0 +1,168 @@
+/**
+ * Anime.js - engine - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var globals = require('../core/globals.cjs');
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var clock = require('../core/clock.cjs');
+var render = require('../core/render.cjs');
+var additive = require('../animation/additive.cjs');
+
+/**
+ * @import {
+ * DefaultsParams,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Tickable,
+ * } from '../types/index.js'
+*/
+
+const engineTickMethod = /*#__PURE__*/ (() => consts.isBrowser ? requestAnimationFrame : setImmediate)();
+const engineCancelMethod = /*#__PURE__*/ (() => consts.isBrowser ? cancelAnimationFrame : clearImmediate)();
+
+class Engine extends clock.Clock {
+
+ /** @param {Number} [initTime] */
+ constructor(initTime) {
+ super(initTime);
+ this.useDefaultMainLoop = true;
+ this.pauseOnDocumentHidden = true;
+ /** @type {DefaultsParams} */
+ this.defaults = globals.defaults;
+ // this.paused = isBrowser && doc.hidden ? true : false;
+ this.paused = true;
+ /** @type {Number|NodeJS.Immediate} */
+ this.reqId = 0;
+ }
+
+ update() {
+ const time = this._currentTime = helpers.now();
+ if (this.requestTick(time)) {
+ this.computeDeltaTime(time);
+ const engineSpeed = this._speed;
+ const engineFps = this._fps;
+ let activeTickable = /** @type {Tickable} */(this._head);
+ while (activeTickable) {
+ const nextTickable = activeTickable._next;
+ if (!activeTickable.paused) {
+ render.tick(
+ activeTickable,
+ (time - activeTickable._startTime) * activeTickable._speed * engineSpeed,
+ 0, // !muteCallbacks
+ 0, // !internalRender
+ activeTickable._fps < engineFps ? activeTickable.requestTick(time) : consts.tickModes.AUTO
+ );
+ } else {
+ helpers.removeChild(this, activeTickable);
+ this._hasChildren = !!this._tail;
+ activeTickable._running = false;
+ if (activeTickable.completed && !activeTickable._cancelled) {
+ activeTickable.cancel();
+ }
+ }
+ activeTickable = nextTickable;
+ }
+ additive.additive.update();
+ }
+ }
+
+ wake() {
+ if (this.useDefaultMainLoop && !this.reqId) {
+ // Imediatly request a tick to update engine._elapsedTime and get accurate offsetPosition calculation in timer.js
+ this.requestTick(helpers.now());
+ this.reqId = engineTickMethod(tickEngine);
+ }
+ return this;
+ }
+
+ pause() {
+ if (!this.reqId) return;
+ this.paused = true;
+ return killEngine();
+ }
+
+ resume() {
+ if (!this.paused) return;
+ this.paused = false;
+ helpers.forEachChildren(this, (/** @type {Tickable} */child) => child.resetTime());
+ return this.wake();
+ }
+
+ // Getter and setter for speed
+ get speed() {
+ return this._speed * (globals.globals.timeScale === 1 ? 1 : consts.K);
+ }
+
+ set speed(playbackRate) {
+ this._speed = playbackRate * globals.globals.timeScale;
+ helpers.forEachChildren(this, (/** @type {Tickable} */child) => child.speed = child._speed);
+ }
+
+ // Getter and setter for timeUnit
+ get timeUnit() {
+ return globals.globals.timeScale === 1 ? 'ms' : 's';
+ }
+
+ set timeUnit(unit) {
+ const secondsScale = 0.001;
+ const isSecond = unit === 's';
+ const newScale = isSecond ? secondsScale : 1;
+ if (globals.globals.timeScale !== newScale) {
+ globals.globals.timeScale = newScale;
+ globals.globals.tickThreshold = 200 * newScale;
+ const scaleFactor = isSecond ? secondsScale : consts.K;
+ /** @type {Number} */
+ (this.defaults.duration) *= scaleFactor;
+ this._speed *= scaleFactor;
+ }
+ }
+
+ // Getter and setter for precision
+ get precision() {
+ return globals.globals.precision;
+ }
+
+ set precision(precision) {
+ globals.globals.precision = precision;
+ }
+
+}
+
+const engine = /*#__PURE__*/(() => {
+ const engine = new Engine(helpers.now());
+ if (consts.isBrowser) {
+ globals.globalVersions.engine = engine;
+ consts.doc.addEventListener('visibilitychange', () => {
+ if (!engine.pauseOnDocumentHidden) return;
+ consts.doc.hidden ? engine.pause() : engine.resume();
+ });
+ }
+ return engine;
+})();
+
+
+const tickEngine = () => {
+ if (engine._head) {
+ engine.reqId = engineTickMethod(tickEngine);
+ engine.update();
+ } else {
+ engine.reqId = 0;
+ }
+};
+
+const killEngine = () => {
+ engineCancelMethod(/** @type {NodeJS.Immediate & Number} */(engine.reqId));
+ engine.reqId = 0;
+ return engine;
+};
+
+exports.engine = engine;
diff --git a/dist/modules/engine/engine.d.ts b/dist/modules/engine/engine.d.ts
new file mode 100644
index 00000000..77bd2d2f
--- /dev/null
+++ b/dist/modules/engine/engine.d.ts
@@ -0,0 +1,21 @@
+export const engine: Engine;
+declare class Engine extends Clock {
+ useDefaultMainLoop: boolean;
+ pauseOnDocumentHidden: boolean;
+ /** @type {DefaultsParams} */
+ defaults: DefaultsParams;
+ paused: boolean;
+ /** @type {Number|NodeJS.Immediate} */
+ reqId: number | NodeJS.Immediate;
+ update(): void;
+ wake(): this;
+ pause(): Engine;
+ resume(): this;
+ set timeUnit(unit: "ms" | "s");
+ get timeUnit(): "ms" | "s";
+ set precision(precision: number);
+ get precision(): number;
+}
+import { Clock } from '../core/clock.js';
+import type { DefaultsParams } from '../types/index.js';
+export {};
diff --git a/dist/modules/engine/engine.js b/dist/modules/engine/engine.js
new file mode 100644
index 00000000..ce5e6542
--- /dev/null
+++ b/dist/modules/engine/engine.js
@@ -0,0 +1,166 @@
+/**
+ * Anime.js - engine - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { globalVersions, defaults, globals } from '../core/globals.js';
+import { isBrowser, doc, tickModes, K } from '../core/consts.js';
+import { now, removeChild, forEachChildren } from '../core/helpers.js';
+import { Clock } from '../core/clock.js';
+import { tick } from '../core/render.js';
+import { additive } from '../animation/additive.js';
+
+/**
+ * @import {
+ * DefaultsParams,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Tickable,
+ * } from '../types/index.js'
+*/
+
+const engineTickMethod = /*#__PURE__*/ (() => isBrowser ? requestAnimationFrame : setImmediate)();
+const engineCancelMethod = /*#__PURE__*/ (() => isBrowser ? cancelAnimationFrame : clearImmediate)();
+
+class Engine extends Clock {
+
+ /** @param {Number} [initTime] */
+ constructor(initTime) {
+ super(initTime);
+ this.useDefaultMainLoop = true;
+ this.pauseOnDocumentHidden = true;
+ /** @type {DefaultsParams} */
+ this.defaults = defaults;
+ // this.paused = isBrowser && doc.hidden ? true : false;
+ this.paused = true;
+ /** @type {Number|NodeJS.Immediate} */
+ this.reqId = 0;
+ }
+
+ update() {
+ const time = this._currentTime = now();
+ if (this.requestTick(time)) {
+ this.computeDeltaTime(time);
+ const engineSpeed = this._speed;
+ const engineFps = this._fps;
+ let activeTickable = /** @type {Tickable} */(this._head);
+ while (activeTickable) {
+ const nextTickable = activeTickable._next;
+ if (!activeTickable.paused) {
+ tick(
+ activeTickable,
+ (time - activeTickable._startTime) * activeTickable._speed * engineSpeed,
+ 0, // !muteCallbacks
+ 0, // !internalRender
+ activeTickable._fps < engineFps ? activeTickable.requestTick(time) : tickModes.AUTO
+ );
+ } else {
+ removeChild(this, activeTickable);
+ this._hasChildren = !!this._tail;
+ activeTickable._running = false;
+ if (activeTickable.completed && !activeTickable._cancelled) {
+ activeTickable.cancel();
+ }
+ }
+ activeTickable = nextTickable;
+ }
+ additive.update();
+ }
+ }
+
+ wake() {
+ if (this.useDefaultMainLoop && !this.reqId) {
+ // Imediatly request a tick to update engine._elapsedTime and get accurate offsetPosition calculation in timer.js
+ this.requestTick(now());
+ this.reqId = engineTickMethod(tickEngine);
+ }
+ return this;
+ }
+
+ pause() {
+ if (!this.reqId) return;
+ this.paused = true;
+ return killEngine();
+ }
+
+ resume() {
+ if (!this.paused) return;
+ this.paused = false;
+ forEachChildren(this, (/** @type {Tickable} */child) => child.resetTime());
+ return this.wake();
+ }
+
+ // Getter and setter for speed
+ get speed() {
+ return this._speed * (globals.timeScale === 1 ? 1 : K);
+ }
+
+ set speed(playbackRate) {
+ this._speed = playbackRate * globals.timeScale;
+ forEachChildren(this, (/** @type {Tickable} */child) => child.speed = child._speed);
+ }
+
+ // Getter and setter for timeUnit
+ get timeUnit() {
+ return globals.timeScale === 1 ? 'ms' : 's';
+ }
+
+ set timeUnit(unit) {
+ const secondsScale = 0.001;
+ const isSecond = unit === 's';
+ const newScale = isSecond ? secondsScale : 1;
+ if (globals.timeScale !== newScale) {
+ globals.timeScale = newScale;
+ globals.tickThreshold = 200 * newScale;
+ const scaleFactor = isSecond ? secondsScale : K;
+ /** @type {Number} */
+ (this.defaults.duration) *= scaleFactor;
+ this._speed *= scaleFactor;
+ }
+ }
+
+ // Getter and setter for precision
+ get precision() {
+ return globals.precision;
+ }
+
+ set precision(precision) {
+ globals.precision = precision;
+ }
+
+}
+
+const engine = /*#__PURE__*/(() => {
+ const engine = new Engine(now());
+ if (isBrowser) {
+ globalVersions.engine = engine;
+ doc.addEventListener('visibilitychange', () => {
+ if (!engine.pauseOnDocumentHidden) return;
+ doc.hidden ? engine.pause() : engine.resume();
+ });
+ }
+ return engine;
+})();
+
+
+const tickEngine = () => {
+ if (engine._head) {
+ engine.reqId = engineTickMethod(tickEngine);
+ engine.update();
+ } else {
+ engine.reqId = 0;
+ }
+};
+
+const killEngine = () => {
+ engineCancelMethod(/** @type {NodeJS.Immediate & Number} */(engine.reqId));
+ engine.reqId = 0;
+ return engine;
+};
+
+export { engine };
diff --git a/dist/modules/engine/index.cjs b/dist/modules/engine/index.cjs
new file mode 100644
index 00000000..aa4884e3
--- /dev/null
+++ b/dist/modules/engine/index.cjs
@@ -0,0 +1,14 @@
+/**
+ * Anime.js - engine - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var engine = require('./engine.cjs');
+
+
+
+exports.engine = engine.engine;
diff --git a/dist/modules/engine/index.d.ts b/dist/modules/engine/index.d.ts
new file mode 100644
index 00000000..3b5227cf
--- /dev/null
+++ b/dist/modules/engine/index.d.ts
@@ -0,0 +1 @@
+export * from "./engine.js";
diff --git a/dist/modules/engine/index.js b/dist/modules/engine/index.js
new file mode 100644
index 00000000..1931588a
--- /dev/null
+++ b/dist/modules/engine/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - engine - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { engine } from './engine.js';
diff --git a/dist/modules/events/index.cjs b/dist/modules/events/index.cjs
new file mode 100644
index 00000000..896b3e2a
--- /dev/null
+++ b/dist/modules/events/index.cjs
@@ -0,0 +1,16 @@
+/**
+ * Anime.js - events - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var scroll = require('./scroll.cjs');
+
+
+
+exports.ScrollObserver = scroll.ScrollObserver;
+exports.onScroll = scroll.onScroll;
+exports.scrollContainers = scroll.scrollContainers;
diff --git a/dist/modules/events/index.d.ts b/dist/modules/events/index.d.ts
new file mode 100644
index 00000000..0c866394
--- /dev/null
+++ b/dist/modules/events/index.d.ts
@@ -0,0 +1 @@
+export * from "./scroll.js";
diff --git a/dist/modules/events/index.js b/dist/modules/events/index.js
new file mode 100644
index 00000000..831e82fe
--- /dev/null
+++ b/dist/modules/events/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - events - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { ScrollObserver, onScroll, scrollContainers } from './scroll.js';
diff --git a/dist/modules/events/scroll.cjs b/dist/modules/events/scroll.cjs
new file mode 100644
index 00000000..99fb1992
--- /dev/null
+++ b/dist/modules/events/scroll.cjs
@@ -0,0 +1,936 @@
+/**
+ * Anime.js - events - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var globals = require('../core/globals.cjs');
+var helpers = require('../core/helpers.cjs');
+var targets = require('../core/targets.cjs');
+var values = require('../core/values.cjs');
+var units = require('../core/units.cjs');
+var timer = require('../timer/timer.cjs');
+var target = require('../utils/target.cjs');
+var time = require('../utils/time.cjs');
+var none = require('../easings/none.cjs');
+var eases = require('../easings/eases.cjs');
+
+/**
+ * @import {
+ * TargetsParam,
+ * EasingFunction,
+ * Callback,
+ * EasingParam,
+ * ScrollThresholdValue,
+ * ScrollObserverParams,
+ * Tickable,
+ * ScrollThresholdParam,
+ * ScrollThresholdCallback,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
+
+/**
+ * @return {Number}
+ */
+const getMaxViewHeight = () => {
+ const $el = consts.doc.createElement('div');
+ consts.doc.body.appendChild($el);
+ $el.style.height = '100lvh';
+ const height = $el.offsetHeight;
+ consts.doc.body.removeChild($el);
+ return height;
+};
+
+/**
+ * @template {ScrollThresholdValue|String|Number|Boolean|Function|Object} T
+ * @param {T | ((observer: ScrollObserver) => T)} value
+ * @param {ScrollObserver} scroller
+ * @return {T}
+ */
+const parseScrollObserverFunctionParameter = (value, scroller) => value && helpers.isFnc(value) ? /** @type {Function} */(value)(scroller) : /** @type {T} */(value);
+
+const scrollContainers = new Map();
+
+class ScrollContainer {
+ /**
+ * @param {HTMLElement} $el
+ */
+ constructor($el) {
+ /** @type {HTMLElement} */
+ this.element = $el;
+ /** @type {Boolean} */
+ this.useWin = this.element === consts.doc.body;
+ /** @type {Number} */
+ this.winWidth = 0;
+ /** @type {Number} */
+ this.winHeight = 0;
+ /** @type {Number} */
+ this.width = 0;
+ /** @type {Number} */
+ this.height = 0;
+ /** @type {Number} */
+ this.left = 0;
+ /** @type {Number} */
+ this.top = 0;
+ /** @type {Number} */
+ this.zIndex = 0;
+ /** @type {Number} */
+ this.scrollX = 0;
+ /** @type {Number} */
+ this.scrollY = 0;
+ /** @type {Number} */
+ this.prevScrollX = 0;
+ /** @type {Number} */
+ this.prevScrollY = 0;
+ /** @type {Number} */
+ this.scrollWidth = 0;
+ /** @type {Number} */
+ this.scrollHeight = 0;
+ /** @type {Number} */
+ this.velocity = 0;
+ /** @type {Boolean} */
+ this.backwardX = false;
+ /** @type {Boolean} */
+ this.backwardY = false;
+ /** @type {Timer} */
+ this.scrollTicker = new timer.Timer({
+ autoplay: false,
+ onBegin: () => this.dataTimer.resume(),
+ onUpdate: () => {
+ const backwards = this.backwardX || this.backwardY;
+ helpers.forEachChildren(this, (/** @type {ScrollObserver} */child) => child.handleScroll(), backwards);
+ },
+ onComplete: () => this.dataTimer.pause()
+ }).init();
+ /** @type {Timer} */
+ this.dataTimer = new timer.Timer({
+ autoplay: false,
+ frameRate: 30,
+ onUpdate: (/** @type {Timer} */self) => {
+ const dt = self.deltaTime;
+ const px = this.prevScrollX;
+ const py = this.prevScrollY;
+ const nx = this.scrollX;
+ const ny = this.scrollY;
+ const dx = px - nx;
+ const dy = py - ny;
+ this.prevScrollX = nx;
+ this.prevScrollY = ny;
+ if (dx) this.backwardX = px > nx;
+ if (dy) this.backwardY = py > ny;
+ this.velocity = helpers.round(dt > 0 ? Math.sqrt(dx * dx + dy * dy) / dt : 0, 5);
+ }
+ }).init();
+ /** @type {Timer} */
+ this.resizeTicker = new timer.Timer({
+ autoplay: false,
+ duration: 250 * globals.globals.timeScale,
+ onComplete: () => {
+ this.updateWindowBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ }
+ }).init();
+ /** @type {Timer} */
+ this.wakeTicker = new timer.Timer({
+ autoplay: false,
+ duration: 500 * globals.globals.timeScale,
+ onBegin: () => {
+ this.scrollTicker.resume();
+ },
+ onComplete: () => {
+ this.scrollTicker.pause();
+ }
+ }).init();
+ /** @type {ScrollObserver} */
+ this._head = null;
+ /** @type {ScrollObserver} */
+ this._tail = null;
+ this.updateScrollCoords();
+ this.updateWindowBounds();
+ this.updateBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ this.resizeObserver = new ResizeObserver(() => this.resizeTicker.restart());
+ this.resizeObserver.observe(this.element);
+ (this.useWin ? consts.win : this.element).addEventListener('scroll', this, false);
+ }
+
+ updateScrollCoords() {
+ const useWin = this.useWin;
+ const $el = this.element;
+ this.scrollX = helpers.round(useWin ? consts.win.scrollX : $el.scrollLeft, 0);
+ this.scrollY = helpers.round(useWin ? consts.win.scrollY : $el.scrollTop, 0);
+ }
+
+ updateWindowBounds() {
+ this.winWidth = consts.win.innerWidth;
+ this.winHeight = getMaxViewHeight();
+ }
+
+ updateBounds() {
+ const style = getComputedStyle(this.element);
+ const $el = this.element;
+ this.scrollWidth = $el.scrollWidth + parseFloat(style.marginLeft) + parseFloat(style.marginRight);
+ this.scrollHeight = $el.scrollHeight + parseFloat(style.marginTop) + parseFloat(style.marginBottom);
+ this.updateWindowBounds();
+ let width, height;
+ if (this.useWin) {
+ width = this.winWidth;
+ height = this.winHeight;
+ } else {
+ const elRect = $el.getBoundingClientRect();
+ width = $el.clientWidth;
+ height = $el.clientHeight;
+ this.top = elRect.top;
+ this.left = elRect.left;
+ }
+ this.width = width;
+ this.height = height;
+ }
+
+ refreshScrollObservers() {
+ helpers.forEachChildren(this, (/** @type {ScrollObserver} */child) => {
+ if (child._debug) {
+ child.removeDebug();
+ }
+ });
+ this.updateBounds();
+ helpers.forEachChildren(this, (/** @type {ScrollObserver} */child) => {
+ child.refresh();
+ if (child._debug) {
+ child.debug();
+ }
+ });
+ }
+
+ refresh() {
+ this.updateWindowBounds();
+ this.updateBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ }
+
+ handleScroll() {
+ this.updateScrollCoords();
+ this.wakeTicker.restart();
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'scroll':
+ this.handleScroll();
+ break;
+ }
+ }
+
+ revert() {
+ this.scrollTicker.cancel();
+ this.dataTimer.cancel();
+ this.resizeTicker.cancel();
+ this.wakeTicker.cancel();
+ this.resizeObserver.disconnect();
+ (this.useWin ? consts.win : this.element).removeEventListener('scroll', this);
+ scrollContainers.delete(this.element);
+ }
+}
+
+/**
+ * @param {TargetsParam} target
+ * @return {ScrollContainer}
+ */
+const registerAndGetScrollContainer = target => {
+ const $el = /** @type {HTMLElement} */(target ? targets.parseTargets(target)[0] || consts.doc.body : consts.doc.body);
+ let scrollContainer = scrollContainers.get($el);
+ if (!scrollContainer) {
+ scrollContainer = new ScrollContainer($el);
+ scrollContainers.set($el, scrollContainer);
+ }
+ return scrollContainer;
+};
+
+/**
+ * @param {HTMLElement} $el
+ * @param {Number|string} v
+ * @param {Number} size
+ * @param {Number} [under]
+ * @param {Number} [over]
+ * @return {Number}
+ */
+const convertValueToPx = ($el, v, size, under, over) => {
+ const clampMin = v === 'min';
+ const clampMax = v === 'max';
+ const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 :
+ v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' :
+ v === 'center' ? '50%' :
+ v;
+ const { n, u } = values.decomposeRawValue(value, values.decomposedOriginalValue);
+ let px = n;
+ if (u === '%') {
+ px = (n / 100) * size;
+ } else if (u) {
+ px = units.convertValueUnit($el, values.decomposedOriginalValue, 'px', true).n;
+ }
+ if (clampMax && under < 0) px += under;
+ if (clampMin && over > 0) px += over;
+ return px;
+};
+
+/**
+ * @param {HTMLElement} $el
+ * @param {ScrollThresholdValue} v
+ * @param {Number} size
+ * @param {Number} [under]
+ * @param {Number} [over]
+ * @return {Number}
+ */
+const parseBoundValue = ($el, v, size, under, over) => {
+ /** @type {Number} */
+ let value;
+ if (helpers.isStr(v)) {
+ const matchedOperator = consts.relativeValuesExecRgx.exec(/** @type {String} */(v));
+ if (matchedOperator) {
+ const splitter = matchedOperator[0];
+ const operator = splitter[0];
+ const splitted = /** @type {String} */(v).split(splitter);
+ const clampMin = splitted[0] === 'min';
+ const clampMax = splitted[0] === 'max';
+ const valueAPx = convertValueToPx($el, splitted[0], size, under, over);
+ const valueBPx = convertValueToPx($el, splitted[1], size, under, over);
+ if (clampMin) {
+ const min = values.getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator);
+ value = min < valueAPx ? valueAPx : min;
+ } else if (clampMax) {
+ const max = values.getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator);
+ value = max > valueAPx ? valueAPx : max;
+ } else {
+ value = values.getRelativeValue(valueAPx, valueBPx, operator);
+ }
+ } else {
+ value = convertValueToPx($el, v, size, under, over);
+ }
+ } else {
+ value = /** @type {Number} */(v);
+ }
+ return helpers.round(value, 0);
+};
+
+/**
+ * @param {JSAnimation} linked
+ * @return {HTMLElement}
+ */
+const getAnimationDomTarget = linked => {
+ let $linkedTarget;
+ const linkedTargets = linked.targets;
+ for (let i = 0, l = linkedTargets.length; i < l; i++) {
+ const target = linkedTargets[i];
+ if (target[consts.isDomSymbol]) {
+ $linkedTarget = /** @type {HTMLElement} */(target);
+ break;
+ }
+ }
+ return $linkedTarget;
+};
+
+let scrollerIndex = 0;
+
+const debugColors = ['#FF4B4B','#FF971B','#FFC730','#F9F640','#7AFF5A','#18FF74','#17E09B','#3CFFEC','#05DBE9','#33B3F1','#638CF9','#C563FE','#FF4FCF','#F93F8A'];
+
+class ScrollObserver {
+ /**
+ * @param {ScrollObserverParams} parameters
+ */
+ constructor(parameters = {}) {
+ if (globals.scope.current) globals.scope.current.register(this);
+ const syncMode = values.setValue(parameters.sync, 'play pause');
+ const ease = syncMode ? eases.parseEase(/** @type {EasingParam} */(syncMode)) : null;
+ const isLinear = syncMode && (syncMode === 'linear' || syncMode === none.none);
+ const isEase = syncMode && !(ease === none.none && !isLinear);
+ const isSmooth = syncMode && (helpers.isNum(syncMode) || syncMode === true || isLinear);
+ const isMethods = syncMode && (helpers.isStr(syncMode) && !isEase && !isSmooth);
+ const syncMethods = isMethods ? /** @type {String} */(syncMode).split(' ').map(
+ (/** @type {String} */m) => () => {
+ const linked = this.linked;
+ return linked && linked[m] ? linked[m]() : null;
+ }
+ ) : null;
+ const biDirSync = isMethods && syncMethods.length > 2;
+ /** @type {Number} */
+ this.index = scrollerIndex++;
+ /** @type {String|Number} */
+ this.id = !helpers.isUnd(parameters.id) ? parameters.id : this.index;
+ /** @type {ScrollContainer} */
+ this.container = registerAndGetScrollContainer(parameters.container);
+ /** @type {HTMLElement} */
+ this.target = null;
+ /** @type {Tickable|WAAPIAnimation} */
+ this.linked = null;
+ /** @type {Boolean} */
+ this.repeat = null;
+ /** @type {Boolean} */
+ this.horizontal = null;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ this.enter = null;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ this.leave = null;
+ /** @type {Boolean} */
+ this.sync = isEase || isSmooth || !!syncMethods;
+ /** @type {EasingFunction} */
+ this.syncEase = isEase ? ease : null;
+ /** @type {Number} */
+ this.syncSmooth = isSmooth ? syncMode === true || isLinear ? 1 : /** @type {Number} */(syncMode) : null;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnter = syncMethods && !biDirSync && syncMethods[0] ? syncMethods[0] : consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeave = syncMethods && !biDirSync && syncMethods[1] ? syncMethods[1] : consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnterForward = syncMethods && biDirSync && syncMethods[0] ? syncMethods[0] : consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeaveForward = syncMethods && biDirSync && syncMethods[1] ? syncMethods[1] : consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnterBackward = syncMethods && biDirSync && syncMethods[2] ? syncMethods[2] : consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeaveBackward = syncMethods && biDirSync && syncMethods[3] ? syncMethods[3] : consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnter = parameters.onEnter || consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeave = parameters.onLeave || consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnterForward = parameters.onEnterForward || consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeaveForward = parameters.onLeaveForward || consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnterBackward = parameters.onEnterBackward || consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeaveBackward = parameters.onLeaveBackward || consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onUpdate = parameters.onUpdate || consts.noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncComplete = parameters.onSyncComplete || consts.noop;
+ /** @type {Boolean} */
+ this.reverted = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Boolean} */
+ this.began = false;
+ /** @type {Boolean} */
+ this.isInView = false;
+ /** @type {Boolean} */
+ this.forceEnter = false;
+ /** @type {Boolean} */
+ this.hasEntered = false;
+ // /** @type {Array.<Number>} */
+ // this.offsets = [];
+ /** @type {Number} */
+ this.offset = 0;
+ /** @type {Number} */
+ this.offsetStart = 0;
+ /** @type {Number} */
+ this.offsetEnd = 0;
+ /** @type {Number} */
+ this.distance = 0;
+ /** @type {Number} */
+ this.prevProgress = 0;
+ /** @type {Array} */
+ this.thresholds = ['start', 'end', 'end', 'start'];
+ /** @type {[Number, Number, Number, Number]} */
+ this.coords = [0, 0, 0, 0];
+ /** @type {JSAnimation} */
+ this.debugStyles = null;
+ /** @type {HTMLElement} */
+ this.$debug = null;
+ /** @type {ScrollObserverParams} */
+ this._params = parameters;
+ /** @type {Boolean} */
+ this._debug = values.setValue(parameters.debug, false);
+ /** @type {ScrollObserver} */
+ this._next = null;
+ /** @type {ScrollObserver} */
+ this._prev = null;
+ helpers.addChild(this.container, this);
+ // Wait for the next frame to add to the container in order to handle calls to link()
+ time.sync(() => {
+ if (this.reverted) return;
+ if (!this.target) {
+ const target = /** @type {HTMLElement} */(targets.parseTargets(parameters.target)[0]);
+ this.target = target || consts.doc.body;
+ this.refresh();
+ }
+ if (this._debug) this.debug();
+ });
+ }
+
+ /**
+ * @param {Tickable|WAAPIAnimation} linked
+ */
+ link(linked) {
+ if (linked) {
+ // Make sure to pause the linked object in case it's added later
+ linked.pause();
+ this.linked = linked;
+ // Try to use a target of the linked object if no target parameters specified
+ if (!this._params.target) {
+ /** @type {HTMLElement} */
+ let $linkedTarget;
+ if (!helpers.isUnd(/** @type {JSAnimation} */(linked).targets)) {
+ $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(linked));
+ } else {
+ helpers.forEachChildren(/** @type {Timeline} */(linked), (/** @type {JSAnimation} */child) => {
+ if (child.targets && !$linkedTarget) {
+ $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(child));
+ }
+ });
+ }
+ // Fallback to body if no target found
+ this.target = $linkedTarget || consts.doc.body;
+ this.refresh();
+ }
+ }
+ return this;
+ }
+
+ get velocity() {
+ return this.container.velocity;
+ }
+
+ get backward() {
+ return this.horizontal ? this.container.backwardX : this.container.backwardY;
+ }
+
+ get scroll() {
+ return this.horizontal ? this.container.scrollX : this.container.scrollY;
+ }
+
+ get progress() {
+ const p = (this.scroll - this.offsetStart) / this.distance;
+ return p === Infinity || isNaN(p) ? 0 : helpers.round(helpers.clamp(p, 0, 1), 6);
+ }
+
+ refresh() {
+ this.reverted = false;
+ const params = this._params;
+ this.repeat = values.setValue(parseScrollObserverFunctionParameter(params.repeat, this), true);
+ this.horizontal = values.setValue(parseScrollObserverFunctionParameter(params.axis, this), 'y') === 'x';
+ this.enter = values.setValue(parseScrollObserverFunctionParameter(params.enter, this), 'end start');
+ this.leave = values.setValue(parseScrollObserverFunctionParameter(params.leave, this), 'start end');
+ this.updateBounds();
+ this.handleScroll();
+ return this;
+ }
+
+ removeDebug() {
+ if (this.$debug) {
+ this.$debug.parentNode.removeChild(this.$debug);
+ this.$debug = null;
+ }
+ if (this.debugStyles) {
+ this.debugStyles.revert();
+ this.$debug = null;
+ }
+ return this;
+ }
+
+ debug() {
+ this.removeDebug();
+ const container = this.container;
+ const isHori = this.horizontal;
+ const $existingDebug = container.element.querySelector(':scope > .animejs-onscroll-debug');
+ const $debug = consts.doc.createElement('div');
+ const $thresholds = consts.doc.createElement('div');
+ const $triggers = consts.doc.createElement('div');
+ const color = debugColors[this.index % debugColors.length];
+ const useWin = container.useWin;
+ const containerWidth = useWin ? container.winWidth : container.width;
+ const containerHeight = useWin ? container.winHeight : container.height;
+ const scrollWidth = container.scrollWidth;
+ const scrollHeight = container.scrollHeight;
+ const size = this.container.width > 360 ? 320 : 260;
+ const offLeft = isHori ? 0 : 10;
+ const offTop = isHori ? 10 : 0;
+ const half = isHori ? 24 : size / 2;
+ const labelHeight = isHori ? half : 15;
+ const labelWidth = isHori ? 60 : half;
+ const labelSize = isHori ? labelWidth : labelHeight;
+ const repeat = isHori ? 'repeat-x' : 'repeat-y';
+ /**
+ * @param {Number} v
+ * @return {String}
+ */
+ const gradientOffset = v => isHori ? '0px '+(v)+'px' : (v)+'px'+' 2px';
+ /**
+ * @param {String} c
+ * @return {String}
+ */
+ const lineCSS = (c) => `linear-gradient(${isHori ? 90 : 0}deg, ${c} 2px, transparent 1px)`;
+ /**
+ * @param {String} p
+ * @param {Number} l
+ * @param {Number} t
+ * @param {Number} w
+ * @param {Number} h
+ * @return {String}
+ */
+ const baseCSS = (p, l, t, w, h) => `position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`;
+ $debug.style.cssText = `${baseCSS('absolute', offLeft, offTop, isHori ? scrollWidth : size, isHori ? size : scrollHeight)}
+ pointer-events: none;
+ z-index: ${this.container.zIndex++};
+ display: flex;
+ flex-direction: ${isHori ? 'column' : 'row'};
+ filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));
+ `;
+ $thresholds.style.cssText = `${baseCSS('sticky', 0, 0, isHori ? containerWidth : half, isHori ? half : containerHeight)}`;
+ if (!$existingDebug) {
+ $thresholds.style.cssText += `background:
+ ${lineCSS('#FFFF')}${gradientOffset(half-10)} / ${isHori ? '100px 100px' : '100px 100px'} ${repeat},
+ ${lineCSS('#FFF8')}${gradientOffset(half-10)} / ${isHori ? '10px 10px' : '10px 10px'} ${repeat};
+ `;
+ }
+ $triggers.style.cssText = `${baseCSS('relative', 0, 0, isHori ? scrollWidth : half, isHori ? half : scrollHeight)}`;
+ if (!$existingDebug) {
+ $triggers.style.cssText += `background:
+ ${lineCSS('#FFFF')}${gradientOffset(0)} / ${isHori ? '100px 10px' : '10px 100px'} ${repeat},
+ ${lineCSS('#FFF8')}${gradientOffset(0)} / ${isHori ? '10px 0px' : '0px 10px'} ${repeat};
+ `;
+ }
+ const labels = [' enter: ', ' leave: '];
+ this.coords.forEach((v, i) => {
+ const isView = i > 1;
+ const value = (isView ? 0 : this.offset) + v;
+ const isTail = i % 2;
+ const isFirst = value < labelSize;
+ const isOver = value > (isView ? isHori ? containerWidth : containerHeight : isHori ? scrollWidth : scrollHeight) - labelSize;
+ const isFlip = (isView ? isTail && !isFirst : !isTail && !isFirst) || isOver;
+ const $label = consts.doc.createElement('div');
+ const $text = consts.doc.createElement('div');
+ const dirProp = isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top';
+ const flipOffset = isFlip ? (isHori ? labelWidth : labelHeight) + (!isView ? isHori ? -1 : -2 : isHori ? -1 : isOver ? 0 : -2) : !isView ? isHori ? 1 : 0 : isHori ? 1 : 0;
+ // $text.innerHTML = `${!isView ? '' : labels[isTail] + ' '}${this.id}: ${this.thresholds[i]} ${isView ? '' : labels[isTail]}`;
+ $text.innerHTML = `${this.id}${labels[isTail]}${this.thresholds[i]}`;
+ $label.style.cssText = `${baseCSS('absolute', 0, 0, labelWidth, labelHeight)}
+ display: flex;
+ flex-direction: ${isHori ? 'column' : 'row'};
+ justify-content: flex-${isView ? 'start' : 'end'};
+ align-items: flex-${isFlip ? 'end' : 'start'};
+ border-${dirProp}: 2px ${isTail ? 'solid' : 'solid'} ${color};
+ `;
+ $text.style.cssText = `
+ overflow: hidden;
+ max-width: ${(size / 2) - 10}px;
+ height: ${labelHeight};
+ margin-${isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'}: -2px;
+ padding: 1px;
+ font-family: ui-monospace, monospace;
+ font-size: 10px;
+ letter-spacing: -.025em;
+ line-height: 9px;
+ font-weight: 600;
+ text-align: ${isHori && isFlip || !isHori && !isView ? 'right' : 'left'};
+ white-space: pre;
+ text-overflow: ellipsis;
+ color: ${isTail ? color : 'rgba(0,0,0,.75)'};
+ background-color: ${isTail ? 'rgba(0,0,0,.65)' : color};
+ border: 2px solid ${isTail ? color : 'transparent'};
+ border-${isHori ? isFlip ? 'top-left' : 'top-right' : isFlip ? 'top-left' : 'bottom-left'}-radius: 5px;
+ border-${isHori ? isFlip ? 'bottom-left' : 'bottom-right' : isFlip ? 'top-right' : 'bottom-right'}-radius: 5px;
+ `;
+ $label.appendChild($text);
+ let position = value - flipOffset + (isHori ? 1 : 0);
+ $label.style[isHori ? 'left' : 'top'] = `${position}px`;
+ // $label.style[isHori ? 'left' : 'top'] = value - flipOffset + (!isFlip && isFirst && !isView ? 1 : isFlip ? 0 : -2) + 'px';
+ (isView ? $thresholds : $triggers).appendChild($label);
+ });
+
+ $debug.appendChild($thresholds);
+ $debug.appendChild($triggers);
+ container.element.appendChild($debug);
+
+ if (!$existingDebug) $debug.classList.add('animejs-onscroll-debug');
+ this.$debug = $debug;
+ const containerPosition = target.get(container.element, 'position');
+ if (containerPosition === 'static') {
+ this.debugStyles = target.set(container.element, { position: 'relative '});
+ }
+
+ }
+
+ updateBounds() {
+ if (this._debug) {
+ this.removeDebug();
+ }
+ let stickys;
+ const $target = this.target;
+ const container = this.container;
+ const isHori = this.horizontal;
+ const linked = this.linked;
+ let linkedTime;
+ let $el = $target;
+ // let offsetX = 0;
+ // let offsetY = 0;
+ // let $offsetParent = $el;
+ /** @type {Element} */
+ if (linked) {
+ linkedTime = linked.currentTime;
+ linked.seek(0, true);
+ }
+ /* Old implementation to get offset and targetSize before fixing https://github.com/juliangarnier/anime/issues/1021
+ // const isContainerStatic = get(container.element, 'position') === 'static' ? set(container.element, { position: 'relative '}) : false;
+ // while ($el && $el !== container.element && $el !== doc.body) {
+ // const isSticky = get($el, 'position') === 'sticky' ?
+ // set($el, { position: 'static' }) :
+ // false;
+ // if ($el === $offsetParent) {
+ // offsetX += $el.offsetLeft || 0;
+ // offsetY += $el.offsetTop || 0;
+ // $offsetParent = $el.offsetParent;
+ // }
+ // $el = /** @type {HTMLElement} */($el.parentElement);
+ // if (isSticky) {
+ // if (!stickys) stickys = [];
+ // stickys.push(isSticky);
+ // }
+ // }
+ // if (isContainerStatic) isContainerStatic.revert();
+ // const offset = isHori ? offsetX : offsetY;
+ // const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight;
+
+ while ($el && $el !== container.element && $el !== consts.doc.body) {
+ const isSticky = target.get($el, 'position') === 'sticky' ? target.set($el, { position: 'static' }) : false;
+ $el = $el.parentElement;
+ if (isSticky) {
+ if (!stickys) stickys = [];
+ stickys.push(isSticky);
+ }
+ }
+ const rect = $target.getBoundingClientRect();
+ const offset = isHori ? rect.left + container.scrollX - container.left : rect.top + container.scrollY - container.top;
+ const targetSize = isHori ? rect.width : rect.height;
+ const containerSize = isHori ? container.width : container.height;
+ const scrollSize = isHori ? container.scrollWidth : container.scrollHeight;
+ const maxScroll = scrollSize - containerSize;
+ const enter = this.enter;
+ const leave = this.leave;
+
+ /** @type {ScrollThresholdValue} */
+ let enterTarget = 'start';
+ /** @type {ScrollThresholdValue} */
+ let leaveTarget = 'end';
+ /** @type {ScrollThresholdValue} */
+ let enterContainer = 'end';
+ /** @type {ScrollThresholdValue} */
+ let leaveContainer = 'start';
+
+ if (helpers.isStr(enter)) {
+ const splitted = /** @type {String} */(enter).split(' ');
+ enterContainer = splitted[0];
+ enterTarget = splitted.length > 1 ? splitted[1] : enterTarget;
+ } else if (helpers.isObj(enter)) {
+ const e = /** @type {ScrollThresholdParam} */(enter);
+ if (!helpers.isUnd(e.container)) enterContainer = e.container;
+ if (!helpers.isUnd(e.target)) enterTarget = e.target;
+ } else if (helpers.isNum(enter)) {
+ enterContainer = /** @type {Number} */(enter);
+ }
+
+ if (helpers.isStr(leave)) {
+ const splitted = /** @type {String} */(leave).split(' ');
+ leaveContainer = splitted[0];
+ leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget;
+ } else if (helpers.isObj(leave)) {
+ const t = /** @type {ScrollThresholdParam} */(leave);
+ if (!helpers.isUnd(t.container)) leaveContainer = t.container;
+ if (!helpers.isUnd(t.target)) leaveTarget = t.target;
+ } else if (helpers.isNum(leave)) {
+ leaveContainer = /** @type {Number} */(leave);
+ }
+
+ const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize);
+ const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize);
+ const under = (parsedEnterTarget + offset) - containerSize;
+ const over = (parsedLeaveTarget + offset) - maxScroll;
+ const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over);
+ const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over);
+ const offsetStart = parsedEnterTarget + offset - parsedEnterContainer;
+ const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer;
+ const scrollDelta = offsetEnd - offsetStart;
+ // this.offsets[0] = offsetX;
+ // this.offsets[1] = offsetY;
+ this.offset = offset;
+ this.offsetStart = offsetStart;
+ this.offsetEnd = offsetEnd;
+ this.distance = scrollDelta <= 0 ? 0 : scrollDelta;
+ this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer];
+ this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer];
+ if (stickys) {
+ stickys.forEach(sticky => sticky.revert());
+ }
+ if (linked) {
+ linked.seek(linkedTime, true);
+ }
+ if (this._debug) {
+ this.debug();
+ }
+ }
+
+ handleScroll() {
+ const linked = this.linked;
+ const sync = this.sync;
+ const syncEase = this.syncEase;
+ const syncSmooth = this.syncSmooth;
+ const shouldSeek = linked && (syncEase || syncSmooth);
+ const isHori = this.horizontal;
+ const container = this.container;
+ const scroll = this.scroll;
+ const isBefore = scroll <= this.offsetStart;
+ const isAfter = scroll >= this.offsetEnd;
+ const isInView = !isBefore && !isAfter;
+ const isOnTheEdge = scroll === this.offsetStart || scroll === this.offsetEnd;
+ const forceEnter = !this.hasEntered && isOnTheEdge;
+ const $debug = this._debug && this.$debug;
+ let hasUpdated = false;
+ let syncCompleted = false;
+ let p = this.progress;
+
+ if (isBefore && this.began) {
+ this.began = false;
+ }
+
+ if (p > 0 && !this.began) {
+ this.began = true;
+ }
+
+ if (shouldSeek) {
+ const lp = linked.progress;
+ if (syncSmooth && helpers.isNum(syncSmooth)) {
+ if (/** @type {Number} */(syncSmooth) < 1) {
+ const step = 0.0001;
+ const snap = lp < p && p === 1 ? step : lp > p && !p ? -step : 0;
+ p = helpers.round(helpers.lerp(lp, p, helpers.lerp(.01, .2, /** @type {Number} */(syncSmooth))) + snap, 6);
+ }
+ } else if (syncEase) {
+ p = syncEase(p);
+ }
+ hasUpdated = p !== this.prevProgress;
+ syncCompleted = lp === 1;
+ if (hasUpdated && !syncCompleted && (syncSmooth && lp)) {
+ container.wakeTicker.restart();
+ }
+ }
+
+ if ($debug) {
+ const sticky = isHori ? container.scrollY : container.scrollX;
+ $debug.style[isHori ? 'top' : 'left'] = sticky + 10 + 'px';
+ }
+
+ // Trigger enter callbacks if already in view or when entering the view
+ if ((isInView && !this.isInView) || (forceEnter && !this.forceEnter && !this.hasEntered)) {
+ if (isInView) this.isInView = true;
+ if (!this.forceEnter || !this.hasEntered) {
+ if ($debug && isInView) $debug.style.zIndex = `${this.container.zIndex++}`;
+ this.onSyncEnter(this);
+ this.onEnter(this);
+ if (this.backward) {
+ this.onSyncEnterBackward(this);
+ this.onEnterBackward(this);
+ } else {
+ this.onSyncEnterForward(this);
+ this.onEnterForward(this);
+ }
+ this.hasEntered = true;
+ if (forceEnter) this.forceEnter = true;
+ } else if (isInView) {
+ this.forceEnter = false;
+ }
+ }
+
+ if (isInView || !isInView && this.isInView) {
+ hasUpdated = true;
+ }
+
+ if (hasUpdated) {
+ if (shouldSeek) linked.seek(linked.duration * p);
+ this.onUpdate(this);
+ }
+
+ if (!isInView && this.isInView) {
+ this.isInView = false;
+ this.onSyncLeave(this);
+ this.onLeave(this);
+ if (this.backward) {
+ this.onSyncLeaveBackward(this);
+ this.onLeaveBackward(this);
+ } else {
+ this.onSyncLeaveForward(this);
+ this.onLeaveForward(this);
+ }
+ if (sync && !syncSmooth) {
+ syncCompleted = true;
+ }
+ }
+
+ if (p >= 1 && this.began && !this.completed && (sync && syncCompleted || !sync)) {
+ if (sync) {
+ this.onSyncComplete(this);
+ }
+ this.completed = true;
+ if ((!this.repeat && !linked) || (!this.repeat && linked && linked.completed)) {
+ this.revert();
+ }
+ }
+
+ if (p < 1 && this.completed) {
+ this.completed = false;
+ }
+
+ this.prevProgress = p;
+ }
+
+ revert() {
+ if (this.reverted) return;
+ const container = this.container;
+ helpers.removeChild(container, this);
+ if (!container._head) {
+ container.revert();
+ }
+ if (this._debug) {
+ this.removeDebug();
+ }
+ this.reverted = true;
+ return this;
+ }
+
+}
+
+/**
+ * @param {ScrollObserverParams} [parameters={}]
+ * @return {ScrollObserver}
+ */
+const onScroll = (parameters = {}) => new ScrollObserver(parameters);
+
+exports.ScrollObserver = ScrollObserver;
+exports.onScroll = onScroll;
+exports.scrollContainers = scrollContainers;
diff --git a/dist/modules/events/scroll.d.ts b/dist/modules/events/scroll.d.ts
new file mode 100644
index 00000000..6a06436b
--- /dev/null
+++ b/dist/modules/events/scroll.d.ts
@@ -0,0 +1,189 @@
+export const scrollContainers: Map<any, any>;
+export class ScrollObserver {
+ /**
+ * @param {ScrollObserverParams} parameters
+ */
+ constructor(parameters?: ScrollObserverParams);
+ /** @type {Number} */
+ index: number;
+ /** @type {String|Number} */
+ id: string | number;
+ /** @type {ScrollContainer} */
+ container: ScrollContainer;
+ /** @type {HTMLElement} */
+ target: HTMLElement;
+ /** @type {Tickable|WAAPIAnimation} */
+ linked: Tickable | WAAPIAnimation;
+ /** @type {Boolean} */
+ repeat: boolean;
+ /** @type {Boolean} */
+ horizontal: boolean;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ enter: ScrollThresholdParam | ScrollThresholdValue | ScrollThresholdCallback;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ leave: ScrollThresholdParam | ScrollThresholdValue | ScrollThresholdCallback;
+ /** @type {Boolean} */
+ sync: boolean;
+ /** @type {EasingFunction} */
+ syncEase: EasingFunction;
+ /** @type {Number} */
+ syncSmooth: number;
+ /** @type {Callback<ScrollObserver>} */
+ onSyncEnter: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onSyncLeave: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onSyncEnterForward: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onSyncLeaveForward: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onSyncEnterBackward: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onSyncLeaveBackward: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onEnter: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onLeave: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onEnterForward: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onLeaveForward: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onEnterBackward: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onLeaveBackward: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onUpdate: Callback<ScrollObserver>;
+ /** @type {Callback<ScrollObserver>} */
+ onSyncComplete: Callback<ScrollObserver>;
+ /** @type {Boolean} */
+ reverted: boolean;
+ /** @type {Boolean} */
+ completed: boolean;
+ /** @type {Boolean} */
+ began: boolean;
+ /** @type {Boolean} */
+ isInView: boolean;
+ /** @type {Boolean} */
+ forceEnter: boolean;
+ /** @type {Boolean} */
+ hasEntered: boolean;
+ /** @type {Number} */
+ offset: number;
+ /** @type {Number} */
+ offsetStart: number;
+ /** @type {Number} */
+ offsetEnd: number;
+ /** @type {Number} */
+ distance: number;
+ /** @type {Number} */
+ prevProgress: number;
+ /** @type {Array} */
+ thresholds: any[];
+ /** @type {[Number, Number, Number, Number]} */
+ coords: [number, number, number, number];
+ /** @type {JSAnimation} */
+ debugStyles: JSAnimation;
+ /** @type {HTMLElement} */
+ $debug: HTMLElement;
+ /** @type {ScrollObserverParams} */
+ _params: ScrollObserverParams;
+ /** @type {Boolean} */
+ _debug: boolean;
+ /** @type {ScrollObserver} */
+ _next: ScrollObserver;
+ /** @type {ScrollObserver} */
+ _prev: ScrollObserver;
+ /**
+ * @param {Tickable|WAAPIAnimation} linked
+ */
+ link(linked: Tickable | WAAPIAnimation): this;
+ get velocity(): number;
+ get backward(): boolean;
+ get scroll(): number;
+ get progress(): number;
+ refresh(): this;
+ removeDebug(): this;
+ debug(): void;
+ updateBounds(): void;
+ handleScroll(): void;
+ revert(): this;
+}
+export function onScroll(parameters?: ScrollObserverParams): ScrollObserver;
+declare class ScrollContainer {
+ /**
+ * @param {HTMLElement} $el
+ */
+ constructor($el: HTMLElement);
+ /** @type {HTMLElement} */
+ element: HTMLElement;
+ /** @type {Boolean} */
+ useWin: boolean;
+ /** @type {Number} */
+ winWidth: number;
+ /** @type {Number} */
+ winHeight: number;
+ /** @type {Number} */
+ width: number;
+ /** @type {Number} */
+ height: number;
+ /** @type {Number} */
+ left: number;
+ /** @type {Number} */
+ top: number;
+ /** @type {Number} */
+ zIndex: number;
+ /** @type {Number} */
+ scrollX: number;
+ /** @type {Number} */
+ scrollY: number;
+ /** @type {Number} */
+ prevScrollX: number;
+ /** @type {Number} */
+ prevScrollY: number;
+ /** @type {Number} */
+ scrollWidth: number;
+ /** @type {Number} */
+ scrollHeight: number;
+ /** @type {Number} */
+ velocity: number;
+ /** @type {Boolean} */
+ backwardX: boolean;
+ /** @type {Boolean} */
+ backwardY: boolean;
+ /** @type {Timer} */
+ scrollTicker: Timer;
+ /** @type {Timer} */
+ dataTimer: Timer;
+ /** @type {Timer} */
+ resizeTicker: Timer;
+ /** @type {Timer} */
+ wakeTicker: Timer;
+ /** @type {ScrollObserver} */
+ _head: ScrollObserver;
+ /** @type {ScrollObserver} */
+ _tail: ScrollObserver;
+ resizeObserver: ResizeObserver;
+ updateScrollCoords(): void;
+ updateWindowBounds(): void;
+ updateBounds(): void;
+ refreshScrollObservers(): void;
+ refresh(): void;
+ handleScroll(): void;
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e: Event): void;
+ revert(): void;
+}
+import type { Tickable } from '../types/index.js';
+import type { WAAPIAnimation } from '../waapi/waapi.js';
+import type { ScrollThresholdParam } from '../types/index.js';
+import type { ScrollThresholdValue } from '../types/index.js';
+import type { ScrollThresholdCallback } from '../types/index.js';
+import type { EasingFunction } from '../types/index.js';
+import type { Callback } from '../types/index.js';
+import type { JSAnimation } from '../animation/animation.js';
+import type { ScrollObserverParams } from '../types/index.js';
+import { Timer } from '../timer/timer.js';
+export {};
diff --git a/dist/modules/events/scroll.js b/dist/modules/events/scroll.js
new file mode 100644
index 00000000..02b95054
--- /dev/null
+++ b/dist/modules/events/scroll.js
@@ -0,0 +1,932 @@
+/**
+ * Anime.js - events - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { noop, doc, isDomSymbol, relativeValuesExecRgx, win } from '../core/consts.js';
+import { scope, globals } from '../core/globals.js';
+import { isUnd, isNum, addChild, forEachChildren, round, isStr, isObj, removeChild, clamp, lerp, isFnc } from '../core/helpers.js';
+import { parseTargets } from '../core/targets.js';
+import { setValue, getRelativeValue, decomposeRawValue, decomposedOriginalValue } from '../core/values.js';
+import { convertValueUnit } from '../core/units.js';
+import { Timer } from '../timer/timer.js';
+import { get, set } from '../utils/target.js';
+import { sync } from '../utils/time.js';
+import { none } from '../easings/none.js';
+import { parseEase } from '../easings/eases.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * EasingFunction,
+ * Callback,
+ * EasingParam,
+ * ScrollThresholdValue,
+ * ScrollObserverParams,
+ * Tickable,
+ * ScrollThresholdParam,
+ * ScrollThresholdCallback,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
+
+/**
+ * @return {Number}
+ */
+const getMaxViewHeight = () => {
+ const $el = doc.createElement('div');
+ doc.body.appendChild($el);
+ $el.style.height = '100lvh';
+ const height = $el.offsetHeight;
+ doc.body.removeChild($el);
+ return height;
+};
+
+/**
+ * @template {ScrollThresholdValue|String|Number|Boolean|Function|Object} T
+ * @param {T | ((observer: ScrollObserver) => T)} value
+ * @param {ScrollObserver} scroller
+ * @return {T}
+ */
+const parseScrollObserverFunctionParameter = (value, scroller) => value && isFnc(value) ? /** @type {Function} */(value)(scroller) : /** @type {T} */(value);
+
+const scrollContainers = new Map();
+
+class ScrollContainer {
+ /**
+ * @param {HTMLElement} $el
+ */
+ constructor($el) {
+ /** @type {HTMLElement} */
+ this.element = $el;
+ /** @type {Boolean} */
+ this.useWin = this.element === doc.body;
+ /** @type {Number} */
+ this.winWidth = 0;
+ /** @type {Number} */
+ this.winHeight = 0;
+ /** @type {Number} */
+ this.width = 0;
+ /** @type {Number} */
+ this.height = 0;
+ /** @type {Number} */
+ this.left = 0;
+ /** @type {Number} */
+ this.top = 0;
+ /** @type {Number} */
+ this.zIndex = 0;
+ /** @type {Number} */
+ this.scrollX = 0;
+ /** @type {Number} */
+ this.scrollY = 0;
+ /** @type {Number} */
+ this.prevScrollX = 0;
+ /** @type {Number} */
+ this.prevScrollY = 0;
+ /** @type {Number} */
+ this.scrollWidth = 0;
+ /** @type {Number} */
+ this.scrollHeight = 0;
+ /** @type {Number} */
+ this.velocity = 0;
+ /** @type {Boolean} */
+ this.backwardX = false;
+ /** @type {Boolean} */
+ this.backwardY = false;
+ /** @type {Timer} */
+ this.scrollTicker = new Timer({
+ autoplay: false,
+ onBegin: () => this.dataTimer.resume(),
+ onUpdate: () => {
+ const backwards = this.backwardX || this.backwardY;
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => child.handleScroll(), backwards);
+ },
+ onComplete: () => this.dataTimer.pause()
+ }).init();
+ /** @type {Timer} */
+ this.dataTimer = new Timer({
+ autoplay: false,
+ frameRate: 30,
+ onUpdate: (/** @type {Timer} */self) => {
+ const dt = self.deltaTime;
+ const px = this.prevScrollX;
+ const py = this.prevScrollY;
+ const nx = this.scrollX;
+ const ny = this.scrollY;
+ const dx = px - nx;
+ const dy = py - ny;
+ this.prevScrollX = nx;
+ this.prevScrollY = ny;
+ if (dx) this.backwardX = px > nx;
+ if (dy) this.backwardY = py > ny;
+ this.velocity = round(dt > 0 ? Math.sqrt(dx * dx + dy * dy) / dt : 0, 5);
+ }
+ }).init();
+ /** @type {Timer} */
+ this.resizeTicker = new Timer({
+ autoplay: false,
+ duration: 250 * globals.timeScale,
+ onComplete: () => {
+ this.updateWindowBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ }
+ }).init();
+ /** @type {Timer} */
+ this.wakeTicker = new Timer({
+ autoplay: false,
+ duration: 500 * globals.timeScale,
+ onBegin: () => {
+ this.scrollTicker.resume();
+ },
+ onComplete: () => {
+ this.scrollTicker.pause();
+ }
+ }).init();
+ /** @type {ScrollObserver} */
+ this._head = null;
+ /** @type {ScrollObserver} */
+ this._tail = null;
+ this.updateScrollCoords();
+ this.updateWindowBounds();
+ this.updateBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ this.resizeObserver = new ResizeObserver(() => this.resizeTicker.restart());
+ this.resizeObserver.observe(this.element);
+ (this.useWin ? win : this.element).addEventListener('scroll', this, false);
+ }
+
+ updateScrollCoords() {
+ const useWin = this.useWin;
+ const $el = this.element;
+ this.scrollX = round(useWin ? win.scrollX : $el.scrollLeft, 0);
+ this.scrollY = round(useWin ? win.scrollY : $el.scrollTop, 0);
+ }
+
+ updateWindowBounds() {
+ this.winWidth = win.innerWidth;
+ this.winHeight = getMaxViewHeight();
+ }
+
+ updateBounds() {
+ const style = getComputedStyle(this.element);
+ const $el = this.element;
+ this.scrollWidth = $el.scrollWidth + parseFloat(style.marginLeft) + parseFloat(style.marginRight);
+ this.scrollHeight = $el.scrollHeight + parseFloat(style.marginTop) + parseFloat(style.marginBottom);
+ this.updateWindowBounds();
+ let width, height;
+ if (this.useWin) {
+ width = this.winWidth;
+ height = this.winHeight;
+ } else {
+ const elRect = $el.getBoundingClientRect();
+ width = $el.clientWidth;
+ height = $el.clientHeight;
+ this.top = elRect.top;
+ this.left = elRect.left;
+ }
+ this.width = width;
+ this.height = height;
+ }
+
+ refreshScrollObservers() {
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => {
+ if (child._debug) {
+ child.removeDebug();
+ }
+ });
+ this.updateBounds();
+ forEachChildren(this, (/** @type {ScrollObserver} */child) => {
+ child.refresh();
+ if (child._debug) {
+ child.debug();
+ }
+ });
+ }
+
+ refresh() {
+ this.updateWindowBounds();
+ this.updateBounds();
+ this.refreshScrollObservers();
+ this.handleScroll();
+ }
+
+ handleScroll() {
+ this.updateScrollCoords();
+ this.wakeTicker.restart();
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'scroll':
+ this.handleScroll();
+ break;
+ }
+ }
+
+ revert() {
+ this.scrollTicker.cancel();
+ this.dataTimer.cancel();
+ this.resizeTicker.cancel();
+ this.wakeTicker.cancel();
+ this.resizeObserver.disconnect();
+ (this.useWin ? win : this.element).removeEventListener('scroll', this);
+ scrollContainers.delete(this.element);
+ }
+}
+
+/**
+ * @param {TargetsParam} target
+ * @return {ScrollContainer}
+ */
+const registerAndGetScrollContainer = target => {
+ const $el = /** @type {HTMLElement} */(target ? parseTargets(target)[0] || doc.body : doc.body);
+ let scrollContainer = scrollContainers.get($el);
+ if (!scrollContainer) {
+ scrollContainer = new ScrollContainer($el);
+ scrollContainers.set($el, scrollContainer);
+ }
+ return scrollContainer;
+};
+
+/**
+ * @param {HTMLElement} $el
+ * @param {Number|string} v
+ * @param {Number} size
+ * @param {Number} [under]
+ * @param {Number} [over]
+ * @return {Number}
+ */
+const convertValueToPx = ($el, v, size, under, over) => {
+ const clampMin = v === 'min';
+ const clampMax = v === 'max';
+ const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 :
+ v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' :
+ v === 'center' ? '50%' :
+ v;
+ const { n, u } = decomposeRawValue(value, decomposedOriginalValue);
+ let px = n;
+ if (u === '%') {
+ px = (n / 100) * size;
+ } else if (u) {
+ px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n;
+ }
+ if (clampMax && under < 0) px += under;
+ if (clampMin && over > 0) px += over;
+ return px;
+};
+
+/**
+ * @param {HTMLElement} $el
+ * @param {ScrollThresholdValue} v
+ * @param {Number} size
+ * @param {Number} [under]
+ * @param {Number} [over]
+ * @return {Number}
+ */
+const parseBoundValue = ($el, v, size, under, over) => {
+ /** @type {Number} */
+ let value;
+ if (isStr(v)) {
+ const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v));
+ if (matchedOperator) {
+ const splitter = matchedOperator[0];
+ const operator = splitter[0];
+ const splitted = /** @type {String} */(v).split(splitter);
+ const clampMin = splitted[0] === 'min';
+ const clampMax = splitted[0] === 'max';
+ const valueAPx = convertValueToPx($el, splitted[0], size, under, over);
+ const valueBPx = convertValueToPx($el, splitted[1], size, under, over);
+ if (clampMin) {
+ const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator);
+ value = min < valueAPx ? valueAPx : min;
+ } else if (clampMax) {
+ const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator);
+ value = max > valueAPx ? valueAPx : max;
+ } else {
+ value = getRelativeValue(valueAPx, valueBPx, operator);
+ }
+ } else {
+ value = convertValueToPx($el, v, size, under, over);
+ }
+ } else {
+ value = /** @type {Number} */(v);
+ }
+ return round(value, 0);
+};
+
+/**
+ * @param {JSAnimation} linked
+ * @return {HTMLElement}
+ */
+const getAnimationDomTarget = linked => {
+ let $linkedTarget;
+ const linkedTargets = linked.targets;
+ for (let i = 0, l = linkedTargets.length; i < l; i++) {
+ const target = linkedTargets[i];
+ if (target[isDomSymbol]) {
+ $linkedTarget = /** @type {HTMLElement} */(target);
+ break;
+ }
+ }
+ return $linkedTarget;
+};
+
+let scrollerIndex = 0;
+
+const debugColors = ['#FF4B4B','#FF971B','#FFC730','#F9F640','#7AFF5A','#18FF74','#17E09B','#3CFFEC','#05DBE9','#33B3F1','#638CF9','#C563FE','#FF4FCF','#F93F8A'];
+
+class ScrollObserver {
+ /**
+ * @param {ScrollObserverParams} parameters
+ */
+ constructor(parameters = {}) {
+ if (scope.current) scope.current.register(this);
+ const syncMode = setValue(parameters.sync, 'play pause');
+ const ease = syncMode ? parseEase(/** @type {EasingParam} */(syncMode)) : null;
+ const isLinear = syncMode && (syncMode === 'linear' || syncMode === none);
+ const isEase = syncMode && !(ease === none && !isLinear);
+ const isSmooth = syncMode && (isNum(syncMode) || syncMode === true || isLinear);
+ const isMethods = syncMode && (isStr(syncMode) && !isEase && !isSmooth);
+ const syncMethods = isMethods ? /** @type {String} */(syncMode).split(' ').map(
+ (/** @type {String} */m) => () => {
+ const linked = this.linked;
+ return linked && linked[m] ? linked[m]() : null;
+ }
+ ) : null;
+ const biDirSync = isMethods && syncMethods.length > 2;
+ /** @type {Number} */
+ this.index = scrollerIndex++;
+ /** @type {String|Number} */
+ this.id = !isUnd(parameters.id) ? parameters.id : this.index;
+ /** @type {ScrollContainer} */
+ this.container = registerAndGetScrollContainer(parameters.container);
+ /** @type {HTMLElement} */
+ this.target = null;
+ /** @type {Tickable|WAAPIAnimation} */
+ this.linked = null;
+ /** @type {Boolean} */
+ this.repeat = null;
+ /** @type {Boolean} */
+ this.horizontal = null;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ this.enter = null;
+ /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */
+ this.leave = null;
+ /** @type {Boolean} */
+ this.sync = isEase || isSmooth || !!syncMethods;
+ /** @type {EasingFunction} */
+ this.syncEase = isEase ? ease : null;
+ /** @type {Number} */
+ this.syncSmooth = isSmooth ? syncMode === true || isLinear ? 1 : /** @type {Number} */(syncMode) : null;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnter = syncMethods && !biDirSync && syncMethods[0] ? syncMethods[0] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeave = syncMethods && !biDirSync && syncMethods[1] ? syncMethods[1] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnterForward = syncMethods && biDirSync && syncMethods[0] ? syncMethods[0] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeaveForward = syncMethods && biDirSync && syncMethods[1] ? syncMethods[1] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncEnterBackward = syncMethods && biDirSync && syncMethods[2] ? syncMethods[2] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncLeaveBackward = syncMethods && biDirSync && syncMethods[3] ? syncMethods[3] : noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnter = parameters.onEnter || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeave = parameters.onLeave || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnterForward = parameters.onEnterForward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeaveForward = parameters.onLeaveForward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onEnterBackward = parameters.onEnterBackward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onLeaveBackward = parameters.onLeaveBackward || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onUpdate = parameters.onUpdate || noop;
+ /** @type {Callback<ScrollObserver>} */
+ this.onSyncComplete = parameters.onSyncComplete || noop;
+ /** @type {Boolean} */
+ this.reverted = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Boolean} */
+ this.began = false;
+ /** @type {Boolean} */
+ this.isInView = false;
+ /** @type {Boolean} */
+ this.forceEnter = false;
+ /** @type {Boolean} */
+ this.hasEntered = false;
+ // /** @type {Array.<Number>} */
+ // this.offsets = [];
+ /** @type {Number} */
+ this.offset = 0;
+ /** @type {Number} */
+ this.offsetStart = 0;
+ /** @type {Number} */
+ this.offsetEnd = 0;
+ /** @type {Number} */
+ this.distance = 0;
+ /** @type {Number} */
+ this.prevProgress = 0;
+ /** @type {Array} */
+ this.thresholds = ['start', 'end', 'end', 'start'];
+ /** @type {[Number, Number, Number, Number]} */
+ this.coords = [0, 0, 0, 0];
+ /** @type {JSAnimation} */
+ this.debugStyles = null;
+ /** @type {HTMLElement} */
+ this.$debug = null;
+ /** @type {ScrollObserverParams} */
+ this._params = parameters;
+ /** @type {Boolean} */
+ this._debug = setValue(parameters.debug, false);
+ /** @type {ScrollObserver} */
+ this._next = null;
+ /** @type {ScrollObserver} */
+ this._prev = null;
+ addChild(this.container, this);
+ // Wait for the next frame to add to the container in order to handle calls to link()
+ sync(() => {
+ if (this.reverted) return;
+ if (!this.target) {
+ const target = /** @type {HTMLElement} */(parseTargets(parameters.target)[0]);
+ this.target = target || doc.body;
+ this.refresh();
+ }
+ if (this._debug) this.debug();
+ });
+ }
+
+ /**
+ * @param {Tickable|WAAPIAnimation} linked
+ */
+ link(linked) {
+ if (linked) {
+ // Make sure to pause the linked object in case it's added later
+ linked.pause();
+ this.linked = linked;
+ // Try to use a target of the linked object if no target parameters specified
+ if (!this._params.target) {
+ /** @type {HTMLElement} */
+ let $linkedTarget;
+ if (!isUnd(/** @type {JSAnimation} */(linked).targets)) {
+ $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(linked));
+ } else {
+ forEachChildren(/** @type {Timeline} */(linked), (/** @type {JSAnimation} */child) => {
+ if (child.targets && !$linkedTarget) {
+ $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(child));
+ }
+ });
+ }
+ // Fallback to body if no target found
+ this.target = $linkedTarget || doc.body;
+ this.refresh();
+ }
+ }
+ return this;
+ }
+
+ get velocity() {
+ return this.container.velocity;
+ }
+
+ get backward() {
+ return this.horizontal ? this.container.backwardX : this.container.backwardY;
+ }
+
+ get scroll() {
+ return this.horizontal ? this.container.scrollX : this.container.scrollY;
+ }
+
+ get progress() {
+ const p = (this.scroll - this.offsetStart) / this.distance;
+ return p === Infinity || isNaN(p) ? 0 : round(clamp(p, 0, 1), 6);
+ }
+
+ refresh() {
+ this.reverted = false;
+ const params = this._params;
+ this.repeat = setValue(parseScrollObserverFunctionParameter(params.repeat, this), true);
+ this.horizontal = setValue(parseScrollObserverFunctionParameter(params.axis, this), 'y') === 'x';
+ this.enter = setValue(parseScrollObserverFunctionParameter(params.enter, this), 'end start');
+ this.leave = setValue(parseScrollObserverFunctionParameter(params.leave, this), 'start end');
+ this.updateBounds();
+ this.handleScroll();
+ return this;
+ }
+
+ removeDebug() {
+ if (this.$debug) {
+ this.$debug.parentNode.removeChild(this.$debug);
+ this.$debug = null;
+ }
+ if (this.debugStyles) {
+ this.debugStyles.revert();
+ this.$debug = null;
+ }
+ return this;
+ }
+
+ debug() {
+ this.removeDebug();
+ const container = this.container;
+ const isHori = this.horizontal;
+ const $existingDebug = container.element.querySelector(':scope > .animejs-onscroll-debug');
+ const $debug = doc.createElement('div');
+ const $thresholds = doc.createElement('div');
+ const $triggers = doc.createElement('div');
+ const color = debugColors[this.index % debugColors.length];
+ const useWin = container.useWin;
+ const containerWidth = useWin ? container.winWidth : container.width;
+ const containerHeight = useWin ? container.winHeight : container.height;
+ const scrollWidth = container.scrollWidth;
+ const scrollHeight = container.scrollHeight;
+ const size = this.container.width > 360 ? 320 : 260;
+ const offLeft = isHori ? 0 : 10;
+ const offTop = isHori ? 10 : 0;
+ const half = isHori ? 24 : size / 2;
+ const labelHeight = isHori ? half : 15;
+ const labelWidth = isHori ? 60 : half;
+ const labelSize = isHori ? labelWidth : labelHeight;
+ const repeat = isHori ? 'repeat-x' : 'repeat-y';
+ /**
+ * @param {Number} v
+ * @return {String}
+ */
+ const gradientOffset = v => isHori ? '0px '+(v)+'px' : (v)+'px'+' 2px';
+ /**
+ * @param {String} c
+ * @return {String}
+ */
+ const lineCSS = (c) => `linear-gradient(${isHori ? 90 : 0}deg, ${c} 2px, transparent 1px)`;
+ /**
+ * @param {String} p
+ * @param {Number} l
+ * @param {Number} t
+ * @param {Number} w
+ * @param {Number} h
+ * @return {String}
+ */
+ const baseCSS = (p, l, t, w, h) => `position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`;
+ $debug.style.cssText = `${baseCSS('absolute', offLeft, offTop, isHori ? scrollWidth : size, isHori ? size : scrollHeight)}
+ pointer-events: none;
+ z-index: ${this.container.zIndex++};
+ display: flex;
+ flex-direction: ${isHori ? 'column' : 'row'};
+ filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));
+ `;
+ $thresholds.style.cssText = `${baseCSS('sticky', 0, 0, isHori ? containerWidth : half, isHori ? half : containerHeight)}`;
+ if (!$existingDebug) {
+ $thresholds.style.cssText += `background:
+ ${lineCSS('#FFFF')}${gradientOffset(half-10)} / ${isHori ? '100px 100px' : '100px 100px'} ${repeat},
+ ${lineCSS('#FFF8')}${gradientOffset(half-10)} / ${isHori ? '10px 10px' : '10px 10px'} ${repeat};
+ `;
+ }
+ $triggers.style.cssText = `${baseCSS('relative', 0, 0, isHori ? scrollWidth : half, isHori ? half : scrollHeight)}`;
+ if (!$existingDebug) {
+ $triggers.style.cssText += `background:
+ ${lineCSS('#FFFF')}${gradientOffset(0)} / ${isHori ? '100px 10px' : '10px 100px'} ${repeat},
+ ${lineCSS('#FFF8')}${gradientOffset(0)} / ${isHori ? '10px 0px' : '0px 10px'} ${repeat};
+ `;
+ }
+ const labels = [' enter: ', ' leave: '];
+ this.coords.forEach((v, i) => {
+ const isView = i > 1;
+ const value = (isView ? 0 : this.offset) + v;
+ const isTail = i % 2;
+ const isFirst = value < labelSize;
+ const isOver = value > (isView ? isHori ? containerWidth : containerHeight : isHori ? scrollWidth : scrollHeight) - labelSize;
+ const isFlip = (isView ? isTail && !isFirst : !isTail && !isFirst) || isOver;
+ const $label = doc.createElement('div');
+ const $text = doc.createElement('div');
+ const dirProp = isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top';
+ const flipOffset = isFlip ? (isHori ? labelWidth : labelHeight) + (!isView ? isHori ? -1 : -2 : isHori ? -1 : isOver ? 0 : -2) : !isView ? isHori ? 1 : 0 : isHori ? 1 : 0;
+ // $text.innerHTML = `${!isView ? '' : labels[isTail] + ' '}${this.id}: ${this.thresholds[i]} ${isView ? '' : labels[isTail]}`;
+ $text.innerHTML = `${this.id}${labels[isTail]}${this.thresholds[i]}`;
+ $label.style.cssText = `${baseCSS('absolute', 0, 0, labelWidth, labelHeight)}
+ display: flex;
+ flex-direction: ${isHori ? 'column' : 'row'};
+ justify-content: flex-${isView ? 'start' : 'end'};
+ align-items: flex-${isFlip ? 'end' : 'start'};
+ border-${dirProp}: 2px ${isTail ? 'solid' : 'solid'} ${color};
+ `;
+ $text.style.cssText = `
+ overflow: hidden;
+ max-width: ${(size / 2) - 10}px;
+ height: ${labelHeight};
+ margin-${isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'}: -2px;
+ padding: 1px;
+ font-family: ui-monospace, monospace;
+ font-size: 10px;
+ letter-spacing: -.025em;
+ line-height: 9px;
+ font-weight: 600;
+ text-align: ${isHori && isFlip || !isHori && !isView ? 'right' : 'left'};
+ white-space: pre;
+ text-overflow: ellipsis;
+ color: ${isTail ? color : 'rgba(0,0,0,.75)'};
+ background-color: ${isTail ? 'rgba(0,0,0,.65)' : color};
+ border: 2px solid ${isTail ? color : 'transparent'};
+ border-${isHori ? isFlip ? 'top-left' : 'top-right' : isFlip ? 'top-left' : 'bottom-left'}-radius: 5px;
+ border-${isHori ? isFlip ? 'bottom-left' : 'bottom-right' : isFlip ? 'top-right' : 'bottom-right'}-radius: 5px;
+ `;
+ $label.appendChild($text);
+ let position = value - flipOffset + (isHori ? 1 : 0);
+ $label.style[isHori ? 'left' : 'top'] = `${position}px`;
+ // $label.style[isHori ? 'left' : 'top'] = value - flipOffset + (!isFlip && isFirst && !isView ? 1 : isFlip ? 0 : -2) + 'px';
+ (isView ? $thresholds : $triggers).appendChild($label);
+ });
+
+ $debug.appendChild($thresholds);
+ $debug.appendChild($triggers);
+ container.element.appendChild($debug);
+
+ if (!$existingDebug) $debug.classList.add('animejs-onscroll-debug');
+ this.$debug = $debug;
+ const containerPosition = get(container.element, 'position');
+ if (containerPosition === 'static') {
+ this.debugStyles = set(container.element, { position: 'relative '});
+ }
+
+ }
+
+ updateBounds() {
+ if (this._debug) {
+ this.removeDebug();
+ }
+ let stickys;
+ const $target = this.target;
+ const container = this.container;
+ const isHori = this.horizontal;
+ const linked = this.linked;
+ let linkedTime;
+ let $el = $target;
+ // let offsetX = 0;
+ // let offsetY = 0;
+ // let $offsetParent = $el;
+ /** @type {Element} */
+ if (linked) {
+ linkedTime = linked.currentTime;
+ linked.seek(0, true);
+ }
+ /* Old implementation to get offset and targetSize before fixing https://github.com/juliangarnier/anime/issues/1021
+ // const isContainerStatic = get(container.element, 'position') === 'static' ? set(container.element, { position: 'relative '}) : false;
+ // while ($el && $el !== container.element && $el !== doc.body) {
+ // const isSticky = get($el, 'position') === 'sticky' ?
+ // set($el, { position: 'static' }) :
+ // false;
+ // if ($el === $offsetParent) {
+ // offsetX += $el.offsetLeft || 0;
+ // offsetY += $el.offsetTop || 0;
+ // $offsetParent = $el.offsetParent;
+ // }
+ // $el = /** @type {HTMLElement} */($el.parentElement);
+ // if (isSticky) {
+ // if (!stickys) stickys = [];
+ // stickys.push(isSticky);
+ // }
+ // }
+ // if (isContainerStatic) isContainerStatic.revert();
+ // const offset = isHori ? offsetX : offsetY;
+ // const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight;
+
+ while ($el && $el !== container.element && $el !== doc.body) {
+ const isSticky = get($el, 'position') === 'sticky' ? set($el, { position: 'static' }) : false;
+ $el = $el.parentElement;
+ if (isSticky) {
+ if (!stickys) stickys = [];
+ stickys.push(isSticky);
+ }
+ }
+ const rect = $target.getBoundingClientRect();
+ const offset = isHori ? rect.left + container.scrollX - container.left : rect.top + container.scrollY - container.top;
+ const targetSize = isHori ? rect.width : rect.height;
+ const containerSize = isHori ? container.width : container.height;
+ const scrollSize = isHori ? container.scrollWidth : container.scrollHeight;
+ const maxScroll = scrollSize - containerSize;
+ const enter = this.enter;
+ const leave = this.leave;
+
+ /** @type {ScrollThresholdValue} */
+ let enterTarget = 'start';
+ /** @type {ScrollThresholdValue} */
+ let leaveTarget = 'end';
+ /** @type {ScrollThresholdValue} */
+ let enterContainer = 'end';
+ /** @type {ScrollThresholdValue} */
+ let leaveContainer = 'start';
+
+ if (isStr(enter)) {
+ const splitted = /** @type {String} */(enter).split(' ');
+ enterContainer = splitted[0];
+ enterTarget = splitted.length > 1 ? splitted[1] : enterTarget;
+ } else if (isObj(enter)) {
+ const e = /** @type {ScrollThresholdParam} */(enter);
+ if (!isUnd(e.container)) enterContainer = e.container;
+ if (!isUnd(e.target)) enterTarget = e.target;
+ } else if (isNum(enter)) {
+ enterContainer = /** @type {Number} */(enter);
+ }
+
+ if (isStr(leave)) {
+ const splitted = /** @type {String} */(leave).split(' ');
+ leaveContainer = splitted[0];
+ leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget;
+ } else if (isObj(leave)) {
+ const t = /** @type {ScrollThresholdParam} */(leave);
+ if (!isUnd(t.container)) leaveContainer = t.container;
+ if (!isUnd(t.target)) leaveTarget = t.target;
+ } else if (isNum(leave)) {
+ leaveContainer = /** @type {Number} */(leave);
+ }
+
+ const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize);
+ const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize);
+ const under = (parsedEnterTarget + offset) - containerSize;
+ const over = (parsedLeaveTarget + offset) - maxScroll;
+ const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over);
+ const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over);
+ const offsetStart = parsedEnterTarget + offset - parsedEnterContainer;
+ const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer;
+ const scrollDelta = offsetEnd - offsetStart;
+ // this.offsets[0] = offsetX;
+ // this.offsets[1] = offsetY;
+ this.offset = offset;
+ this.offsetStart = offsetStart;
+ this.offsetEnd = offsetEnd;
+ this.distance = scrollDelta <= 0 ? 0 : scrollDelta;
+ this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer];
+ this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer];
+ if (stickys) {
+ stickys.forEach(sticky => sticky.revert());
+ }
+ if (linked) {
+ linked.seek(linkedTime, true);
+ }
+ if (this._debug) {
+ this.debug();
+ }
+ }
+
+ handleScroll() {
+ const linked = this.linked;
+ const sync = this.sync;
+ const syncEase = this.syncEase;
+ const syncSmooth = this.syncSmooth;
+ const shouldSeek = linked && (syncEase || syncSmooth);
+ const isHori = this.horizontal;
+ const container = this.container;
+ const scroll = this.scroll;
+ const isBefore = scroll <= this.offsetStart;
+ const isAfter = scroll >= this.offsetEnd;
+ const isInView = !isBefore && !isAfter;
+ const isOnTheEdge = scroll === this.offsetStart || scroll === this.offsetEnd;
+ const forceEnter = !this.hasEntered && isOnTheEdge;
+ const $debug = this._debug && this.$debug;
+ let hasUpdated = false;
+ let syncCompleted = false;
+ let p = this.progress;
+
+ if (isBefore && this.began) {
+ this.began = false;
+ }
+
+ if (p > 0 && !this.began) {
+ this.began = true;
+ }
+
+ if (shouldSeek) {
+ const lp = linked.progress;
+ if (syncSmooth && isNum(syncSmooth)) {
+ if (/** @type {Number} */(syncSmooth) < 1) {
+ const step = 0.0001;
+ const snap = lp < p && p === 1 ? step : lp > p && !p ? -step : 0;
+ p = round(lerp(lp, p, lerp(.01, .2, /** @type {Number} */(syncSmooth))) + snap, 6);
+ }
+ } else if (syncEase) {
+ p = syncEase(p);
+ }
+ hasUpdated = p !== this.prevProgress;
+ syncCompleted = lp === 1;
+ if (hasUpdated && !syncCompleted && (syncSmooth && lp)) {
+ container.wakeTicker.restart();
+ }
+ }
+
+ if ($debug) {
+ const sticky = isHori ? container.scrollY : container.scrollX;
+ $debug.style[isHori ? 'top' : 'left'] = sticky + 10 + 'px';
+ }
+
+ // Trigger enter callbacks if already in view or when entering the view
+ if ((isInView && !this.isInView) || (forceEnter && !this.forceEnter && !this.hasEntered)) {
+ if (isInView) this.isInView = true;
+ if (!this.forceEnter || !this.hasEntered) {
+ if ($debug && isInView) $debug.style.zIndex = `${this.container.zIndex++}`;
+ this.onSyncEnter(this);
+ this.onEnter(this);
+ if (this.backward) {
+ this.onSyncEnterBackward(this);
+ this.onEnterBackward(this);
+ } else {
+ this.onSyncEnterForward(this);
+ this.onEnterForward(this);
+ }
+ this.hasEntered = true;
+ if (forceEnter) this.forceEnter = true;
+ } else if (isInView) {
+ this.forceEnter = false;
+ }
+ }
+
+ if (isInView || !isInView && this.isInView) {
+ hasUpdated = true;
+ }
+
+ if (hasUpdated) {
+ if (shouldSeek) linked.seek(linked.duration * p);
+ this.onUpdate(this);
+ }
+
+ if (!isInView && this.isInView) {
+ this.isInView = false;
+ this.onSyncLeave(this);
+ this.onLeave(this);
+ if (this.backward) {
+ this.onSyncLeaveBackward(this);
+ this.onLeaveBackward(this);
+ } else {
+ this.onSyncLeaveForward(this);
+ this.onLeaveForward(this);
+ }
+ if (sync && !syncSmooth) {
+ syncCompleted = true;
+ }
+ }
+
+ if (p >= 1 && this.began && !this.completed && (sync && syncCompleted || !sync)) {
+ if (sync) {
+ this.onSyncComplete(this);
+ }
+ this.completed = true;
+ if ((!this.repeat && !linked) || (!this.repeat && linked && linked.completed)) {
+ this.revert();
+ }
+ }
+
+ if (p < 1 && this.completed) {
+ this.completed = false;
+ }
+
+ this.prevProgress = p;
+ }
+
+ revert() {
+ if (this.reverted) return;
+ const container = this.container;
+ removeChild(container, this);
+ if (!container._head) {
+ container.revert();
+ }
+ if (this._debug) {
+ this.removeDebug();
+ }
+ this.reverted = true;
+ return this;
+ }
+
+}
+
+/**
+ * @param {ScrollObserverParams} [parameters={}]
+ * @return {ScrollObserver}
+ */
+const onScroll = (parameters = {}) => new ScrollObserver(parameters);
+
+export { ScrollObserver, onScroll, scrollContainers };
diff --git a/dist/modules/index.cjs b/dist/modules/index.cjs
new file mode 100644
index 00000000..44d05bc3
--- /dev/null
+++ b/dist/modules/index.cjs
@@ -0,0 +1,103 @@
+/**
+ * Anime.js - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var timer = require('./timer/timer.cjs');
+var animation = require('./animation/animation.cjs');
+var timeline = require('./timeline/timeline.cjs');
+var animatable = require('./animatable/animatable.cjs');
+var draggable = require('./draggable/draggable.cjs');
+var scope = require('./scope/scope.cjs');
+var scroll = require('./events/scroll.cjs');
+var spring = require('./spring/spring.cjs');
+var engine = require('./engine/engine.cjs');
+var index = require('./easings/index.cjs');
+var index$1 = require('./utils/index.cjs');
+var index$2 = require('./svg/index.cjs');
+var index$3 = require('./text/index.cjs');
+var waapi = require('./waapi/waapi.cjs');
+var none = require('./easings/none.cjs');
+var cubicBezier = require('./easings/cubic-bezier.cjs');
+var steps = require('./easings/steps.cjs');
+var linear = require('./easings/linear.cjs');
+var irregular = require('./easings/irregular.cjs');
+var eases = require('./easings/eases.cjs');
+var chainable = require('./utils/chainable.cjs');
+var random = require('./utils/random.cjs');
+var time = require('./utils/time.cjs');
+var styles = require('./core/styles.cjs');
+var targets = require('./core/targets.cjs');
+var target = require('./utils/target.cjs');
+var stagger = require('./utils/stagger.cjs');
+var motionpath = require('./svg/motionpath.cjs');
+var drawable = require('./svg/drawable.cjs');
+var morphto = require('./svg/morphto.cjs');
+var split = require('./text/split.cjs');
+
+
+
+exports.Timer = timer.Timer;
+exports.createTimer = timer.createTimer;
+exports.JSAnimation = animation.JSAnimation;
+exports.animate = animation.animate;
+exports.Timeline = timeline.Timeline;
+exports.createTimeline = timeline.createTimeline;
+exports.Animatable = animatable.Animatable;
+exports.createAnimatable = animatable.createAnimatable;
+exports.Draggable = draggable.Draggable;
+exports.createDraggable = draggable.createDraggable;
+exports.Scope = scope.Scope;
+exports.createScope = scope.createScope;
+exports.ScrollObserver = scroll.ScrollObserver;
+exports.onScroll = scroll.onScroll;
+exports.scrollContainers = scroll.scrollContainers;
+exports.Spring = spring.Spring;
+exports.createSpring = spring.createSpring;
+exports.engine = engine.engine;
+exports.easings = index;
+exports.utils = index$1;
+exports.svg = index$2;
+exports.text = index$3;
+exports.WAAPIAnimation = waapi.WAAPIAnimation;
+exports.waapi = waapi.waapi;
+exports.none = none.none;
+exports.cubicBezier = cubicBezier.cubicBezier;
+exports.steps = steps.steps;
+exports.linear = linear.linear;
+exports.irregular = irregular.irregular;
+exports.eases = eases.eases;
+exports.clamp = chainable.clamp;
+exports.damp = chainable.damp;
+exports.degToRad = chainable.degToRad;
+exports.lerp = chainable.lerp;
+exports.mapRange = chainable.mapRange;
+exports.padEnd = chainable.padEnd;
+exports.padStart = chainable.padStart;
+exports.radToDeg = chainable.radToDeg;
+exports.round = chainable.round;
+exports.roundPad = chainable.roundPad;
+exports.snap = chainable.snap;
+exports.wrap = chainable.wrap;
+exports.createSeededRandom = random.createSeededRandom;
+exports.random = random.random;
+exports.randomPick = random.randomPick;
+exports.shuffle = random.shuffle;
+exports.keepTime = time.keepTime;
+exports.sync = time.sync;
+exports.cleanInlineStyles = styles.cleanInlineStyles;
+exports.$ = targets.registerTargets;
+exports.get = target.get;
+exports.remove = target.remove;
+exports.set = target.set;
+exports.stagger = stagger.stagger;
+exports.createMotionPath = motionpath.createMotionPath;
+exports.createDrawable = drawable.createDrawable;
+exports.morphTo = morphto.morphTo;
+exports.TextSplitter = split.TextSplitter;
+exports.split = split.split;
+exports.splitText = split.splitText;
diff --git a/dist/modules/index.d.ts b/dist/modules/index.d.ts
new file mode 100644
index 00000000..f11be9dc
--- /dev/null
+++ b/dist/modules/index.d.ts
@@ -0,0 +1,19 @@
+export * from "./timer/index.js";
+export * from "./animation/index.js";
+export * from "./timeline/index.js";
+export * from "./animatable/index.js";
+export * from "./draggable/index.js";
+export * from "./scope/index.js";
+export * from "./events/index.js";
+export * from "./spring/index.js";
+export * from "./engine/index.js";
+export * from "./easings/index.js";
+export * from "./utils/index.js";
+export * from "./svg/index.js";
+export * from "./text/index.js";
+export * from "./waapi/index.js";
+export * from "./types/index.js";
+export * as easings from "./easings/index.js";
+export * as utils from "./utils/index.js";
+export * as svg from "./svg/index.js";
+export * as text from "./text/index.js";
diff --git a/dist/modules/index.js b/dist/modules/index.js
new file mode 100644
index 00000000..f98e9dff
--- /dev/null
+++ b/dist/modules/index.js
@@ -0,0 +1,42 @@
+/**
+ * Anime.js - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { Timer, createTimer } from './timer/timer.js';
+export { JSAnimation, animate } from './animation/animation.js';
+export { Timeline, createTimeline } from './timeline/timeline.js';
+export { Animatable, createAnimatable } from './animatable/animatable.js';
+export { Draggable, createDraggable } from './draggable/draggable.js';
+export { Scope, createScope } from './scope/scope.js';
+export { ScrollObserver, onScroll, scrollContainers } from './events/scroll.js';
+export { Spring, createSpring } from './spring/spring.js';
+export { engine } from './engine/engine.js';
+import * as index from './easings/index.js';
+export { index as easings };
+import * as index$1 from './utils/index.js';
+export { index$1 as utils };
+import * as index$2 from './svg/index.js';
+export { index$2 as svg };
+import * as index$3 from './text/index.js';
+export { index$3 as text };
+export { WAAPIAnimation, waapi } from './waapi/waapi.js';
+export { none } from './easings/none.js';
+export { cubicBezier } from './easings/cubic-bezier.js';
+export { steps } from './easings/steps.js';
+export { linear } from './easings/linear.js';
+export { irregular } from './easings/irregular.js';
+export { eases } from './easings/eases.js';
+export { clamp, damp, degToRad, lerp, mapRange, padEnd, padStart, radToDeg, round, roundPad, snap, wrap } from './utils/chainable.js';
+export { createSeededRandom, random, randomPick, shuffle } from './utils/random.js';
+export { keepTime, sync } from './utils/time.js';
+export { cleanInlineStyles } from './core/styles.js';
+export { registerTargets as $ } from './core/targets.js';
+export { get, remove, set } from './utils/target.js';
+export { stagger } from './utils/stagger.js';
+export { createMotionPath } from './svg/motionpath.js';
+export { createDrawable } from './svg/drawable.js';
+export { morphTo } from './svg/morphto.js';
+export { TextSplitter, split, splitText } from './text/split.js';
diff --git a/dist/modules/scope/index.cjs b/dist/modules/scope/index.cjs
new file mode 100644
index 00000000..05014c5a
--- /dev/null
+++ b/dist/modules/scope/index.cjs
@@ -0,0 +1,15 @@
+/**
+ * Anime.js - scope - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var scope = require('./scope.cjs');
+
+
+
+exports.Scope = scope.Scope;
+exports.createScope = scope.createScope;
diff --git a/dist/modules/scope/index.d.ts b/dist/modules/scope/index.d.ts
new file mode 100644
index 00000000..467f3f15
--- /dev/null
+++ b/dist/modules/scope/index.d.ts
@@ -0,0 +1 @@
+export * from "./scope.js";
diff --git a/dist/modules/scope/index.js b/dist/modules/scope/index.js
new file mode 100644
index 00000000..c5916d4c
--- /dev/null
+++ b/dist/modules/scope/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - scope - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { Scope, createScope } from './scope.js';
diff --git a/dist/modules/scope/scope.cjs b/dist/modules/scope/scope.cjs
new file mode 100644
index 00000000..710f6287
--- /dev/null
+++ b/dist/modules/scope/scope.cjs
@@ -0,0 +1,254 @@
+/**
+ * Anime.js - scope - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var globals = require('../core/globals.cjs');
+var helpers = require('../core/helpers.cjs');
+var targets = require('../core/targets.cjs');
+var time = require('../utils/time.cjs');
+
+/**
+ * @import {
+ * Tickable,
+ * ScopeParams,
+ * DOMTarget,
+ * ReactRef,
+ * AngularRef,
+ * DOMTargetSelector,
+ * DefaultsParams,
+ * ScopeConstructorCallback,
+ * ScopeCleanupCallback,
+ * Revertible,
+ * ScopeMethod,
+ * ScopedCallback,
+ * } from '../types/index.js'
+*/
+
+class Scope {
+ /** @param {ScopeParams} [parameters] */
+ constructor(parameters = {}) {
+ if (globals.scope.current) globals.scope.current.register(this);
+ const rootParam = parameters.root;
+ /** @type {Document|DOMTarget} */
+ let root = consts.doc;
+ if (rootParam) {
+ root = /** @type {ReactRef} */(rootParam).current ||
+ /** @type {AngularRef} */(rootParam).nativeElement ||
+ targets.parseTargets(/** @type {DOMTargetSelector} */(rootParam))[0] ||
+ consts.doc;
+ }
+ const scopeDefaults = parameters.defaults;
+ const globalDefault = globals.globals.defaults;
+ const mediaQueries = parameters.mediaQueries;
+ /** @type {DefaultsParams} */
+ this.defaults = scopeDefaults ? helpers.mergeObjects(scopeDefaults, globalDefault) : globalDefault;
+ /** @type {Document|DOMTarget} */
+ this.root = root;
+ /** @type {Array<ScopeConstructorCallback>} */
+ this.constructors = [];
+ /** @type {Array<ScopeCleanupCallback>} */
+ this.revertConstructors = [];
+ /** @type {Array<Revertible>} */
+ this.revertibles = [];
+ /** @type {Array<ScopeConstructorCallback | ((scope: this) => Tickable)>} */
+ this.constructorsOnce = [];
+ /** @type {Array<ScopeCleanupCallback>} */
+ this.revertConstructorsOnce = [];
+ /** @type {Array<Revertible>} */
+ this.revertiblesOnce = [];
+ /** @type {Boolean} */
+ this.once = false;
+ /** @type {Number} */
+ this.onceIndex = 0;
+ /** @type {Record<String, ScopeMethod>} */
+ this.methods = {};
+ /** @type {Record<String, Boolean>} */
+ this.matches = {};
+ /** @type {Record<String, MediaQueryList>} */
+ this.mediaQueryLists = {};
+ /** @type {Record<String, any>} */
+ this.data = {};
+ if (mediaQueries) {
+ for (let mq in mediaQueries) {
+ const _mq = consts.win.matchMedia(mediaQueries[mq]);
+ this.mediaQueryLists[mq] = _mq;
+ _mq.addEventListener('change', this);
+ }
+ }
+ }
+
+ /**
+ * @param {Revertible} revertible
+ */
+ register(revertible) {
+ const store = this.once ? this.revertiblesOnce : this.revertibles;
+ store.push(revertible);
+ }
+
+ /**
+ * @template T
+ * @param {ScopedCallback<T>} cb
+ * @return {T}
+ */
+ execute(cb) {
+ let activeScope = globals.scope.current;
+ let activeRoot = globals.scope.root;
+ let activeDefaults = globals.globals.defaults;
+ globals.scope.current = this;
+ globals.scope.root = this.root;
+ globals.globals.defaults = this.defaults;
+ const mqs = this.mediaQueryLists;
+ for (let mq in mqs) this.matches[mq] = mqs[mq].matches;
+ const returned = cb(this);
+ globals.scope.current = activeScope;
+ globals.scope.root = activeRoot;
+ globals.globals.defaults = activeDefaults;
+ return returned;
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ this.onceIndex = 0;
+ this.execute(() => {
+ let i = this.revertibles.length;
+ let y = this.revertConstructors.length;
+ while (i--) this.revertibles[i].revert();
+ while (y--) this.revertConstructors[y](this);
+ this.revertibles.length = 0;
+ this.revertConstructors.length = 0;
+ this.constructors.forEach((/** @type {ScopeConstructorCallback} */constructor) => {
+ const revertConstructor = constructor(this);
+ if (helpers.isFnc(revertConstructor)) {
+ this.revertConstructors.push(revertConstructor);
+ }
+ });
+ });
+ return this;
+ }
+
+ /**
+ * @overload
+ * @param {String} a1
+ * @param {ScopeMethod} a2
+ * @return {this}
+ *
+ * @overload
+ * @param {ScopeConstructorCallback} a1
+ * @return {this}
+ *
+ * @param {String|ScopeConstructorCallback} a1
+ * @param {ScopeMethod} [a2]
+ */
+ add(a1, a2) {
+ this.once = false;
+ if (helpers.isFnc(a1)) {
+ const constructor = /** @type {ScopeConstructorCallback} */(a1);
+ this.constructors.push(constructor);
+ this.execute(() => {
+ const revertConstructor = constructor(this);
+ if (helpers.isFnc(revertConstructor)) {
+ this.revertConstructors.push(revertConstructor);
+ }
+ });
+ } else {
+ this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args));
+ }
+ return this;
+ }
+
+ /**
+ * @param {ScopeConstructorCallback} scopeConstructorCallback
+ * @return {this}
+ */
+ addOnce(scopeConstructorCallback) {
+ this.once = true;
+ if (helpers.isFnc(scopeConstructorCallback)) {
+ const currentIndex = this.onceIndex++;
+ const tracked = this.constructorsOnce[currentIndex];
+ if (tracked) return this;
+ const constructor = /** @type {ScopeConstructorCallback} */(scopeConstructorCallback);
+ this.constructorsOnce[currentIndex] = constructor;
+ this.execute(() => {
+ const revertConstructor = constructor(this);
+ if (helpers.isFnc(revertConstructor)) {
+ this.revertConstructorsOnce.push(revertConstructor);
+ }
+ });
+ }
+ return this;
+ }
+
+ /**
+ * @param {(scope: this) => Tickable} cb
+ * @return {Tickable}
+ */
+ keepTime(cb) {
+ this.once = true;
+ const currentIndex = this.onceIndex++;
+ const tracked = /** @type {(scope: this) => Tickable} */(this.constructorsOnce[currentIndex]);
+ if (helpers.isFnc(tracked)) return tracked(this);
+ const constructor = /** @type {(scope: this) => Tickable} */(time.keepTime(cb));
+ this.constructorsOnce[currentIndex] = constructor;
+ let trackedTickable;
+ this.execute(() => {
+ trackedTickable = constructor(this);
+ });
+ return trackedTickable;
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'change':
+ this.refresh();
+ break;
+ }
+ }
+
+ revert() {
+ const revertibles = this.revertibles;
+ const revertConstructors = this.revertConstructors;
+ const revertiblesOnce = this.revertiblesOnce;
+ const revertConstructorsOnce = this.revertConstructorsOnce;
+ const mqs = this.mediaQueryLists;
+ let i = revertibles.length;
+ let j = revertConstructors.length;
+ let k = revertiblesOnce.length;
+ let l = revertConstructorsOnce.length;
+ while (i--) revertibles[i].revert();
+ while (j--) revertConstructors[j](this);
+ while (k--) revertiblesOnce[k].revert();
+ while (l--) revertConstructorsOnce[l](this);
+ for (let mq in mqs) mqs[mq].removeEventListener('change', this);
+ revertibles.length = 0;
+ revertConstructors.length = 0;
+ this.constructors.length = 0;
+ revertiblesOnce.length = 0;
+ revertConstructorsOnce.length = 0;
+ this.constructorsOnce.length = 0;
+ this.onceIndex = 0;
+ this.matches = {};
+ this.methods = {};
+ this.mediaQueryLists = {};
+ this.data = {};
+ }
+}
+
+/**
+ * @param {ScopeParams} [params]
+ * @return {Scope}
+ */
+const createScope = params => new Scope(params);
+
+exports.Scope = Scope;
+exports.createScope = createScope;
diff --git a/dist/modules/scope/scope.d.ts b/dist/modules/scope/scope.d.ts
new file mode 100644
index 00000000..3390bac8
--- /dev/null
+++ b/dist/modules/scope/scope.d.ts
@@ -0,0 +1,115 @@
+/**
+ * @import {
+ * Tickable,
+ * ScopeParams,
+ * DOMTarget,
+ * ReactRef,
+ * AngularRef,
+ * DOMTargetSelector,
+ * DefaultsParams,
+ * ScopeConstructorCallback,
+ * ScopeCleanupCallback,
+ * Revertible,
+ * ScopeMethod,
+ * ScopedCallback,
+ * } from '../types/index.js'
+*/
+export class Scope {
+ /** @param {ScopeParams} [parameters] */
+ constructor(parameters?: ScopeParams);
+ /** @type {DefaultsParams} */
+ defaults: DefaultsParams;
+ /** @type {Document|DOMTarget} */
+ root: Document | DOMTarget;
+ /** @type {Array<ScopeConstructorCallback>} */
+ constructors: Array<ScopeConstructorCallback>;
+ /** @type {Array<ScopeCleanupCallback>} */
+ revertConstructors: Array<ScopeCleanupCallback>;
+ /** @type {Array<Revertible>} */
+ revertibles: Array<Revertible>;
+ /** @type {Array<ScopeConstructorCallback | ((scope: this) => Tickable)>} */
+ constructorsOnce: Array<ScopeConstructorCallback | ((scope: this) => Tickable)>;
+ /** @type {Array<ScopeCleanupCallback>} */
+ revertConstructorsOnce: Array<ScopeCleanupCallback>;
+ /** @type {Array<Revertible>} */
+ revertiblesOnce: Array<Revertible>;
+ /** @type {Boolean} */
+ once: boolean;
+ /** @type {Number} */
+ onceIndex: number;
+ /** @type {Record<String, ScopeMethod>} */
+ methods: Record<string, ScopeMethod>;
+ /** @type {Record<String, Boolean>} */
+ matches: Record<string, boolean>;
+ /** @type {Record<String, MediaQueryList>} */
+ mediaQueryLists: Record<string, MediaQueryList>;
+ /** @type {Record<String, any>} */
+ data: Record<string, any>;
+ /**
+ * @param {Revertible} revertible
+ */
+ register(revertible: Revertible): void;
+ /**
+ * @template T
+ * @param {ScopedCallback<T>} cb
+ * @return {T}
+ */
+ execute<T>(cb: ScopedCallback<T>): T;
+ /**
+ * @return {this}
+ */
+ refresh(): this;
+ /**
+ * @overload
+ * @param {String} a1
+ * @param {ScopeMethod} a2
+ * @return {this}
+ *
+ * @overload
+ * @param {ScopeConstructorCallback} a1
+ * @return {this}
+ *
+ * @param {String|ScopeConstructorCallback} a1
+ * @param {ScopeMethod} [a2]
+ */
+ add(a1: string, a2: ScopeMethod): this;
+ /**
+ * @overload
+ * @param {String} a1
+ * @param {ScopeMethod} a2
+ * @return {this}
+ *
+ * @overload
+ * @param {ScopeConstructorCallback} a1
+ * @return {this}
+ *
+ * @param {String|ScopeConstructorCallback} a1
+ * @param {ScopeMethod} [a2]
+ */
+ add(a1: ScopeConstructorCallback): this;
+ /**
+ * @param {ScopeConstructorCallback} scopeConstructorCallback
+ * @return {this}
+ */
+ addOnce(scopeConstructorCallback: ScopeConstructorCallback): this;
+ /**
+ * @param {(scope: this) => Tickable} cb
+ * @return {Tickable}
+ */
+ keepTime(cb: (scope: this) => Tickable): Tickable;
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e: Event): void;
+ revert(): void;
+}
+export function createScope(params?: ScopeParams): Scope;
+import type { DefaultsParams } from '../types/index.js';
+import type { DOMTarget } from '../types/index.js';
+import type { ScopeConstructorCallback } from '../types/index.js';
+import type { ScopeCleanupCallback } from '../types/index.js';
+import type { Revertible } from '../types/index.js';
+import type { Tickable } from '../types/index.js';
+import type { ScopeMethod } from '../types/index.js';
+import type { ScopedCallback } from '../types/index.js';
+import type { ScopeParams } from '../types/index.js';
diff --git a/dist/modules/scope/scope.js b/dist/modules/scope/scope.js
new file mode 100644
index 00000000..4e00a9b9
--- /dev/null
+++ b/dist/modules/scope/scope.js
@@ -0,0 +1,251 @@
+/**
+ * Anime.js - scope - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { doc, win } from '../core/consts.js';
+import { globals, scope } from '../core/globals.js';
+import { mergeObjects, isFnc } from '../core/helpers.js';
+import { parseTargets } from '../core/targets.js';
+import { keepTime } from '../utils/time.js';
+
+/**
+ * @import {
+ * Tickable,
+ * ScopeParams,
+ * DOMTarget,
+ * ReactRef,
+ * AngularRef,
+ * DOMTargetSelector,
+ * DefaultsParams,
+ * ScopeConstructorCallback,
+ * ScopeCleanupCallback,
+ * Revertible,
+ * ScopeMethod,
+ * ScopedCallback,
+ * } from '../types/index.js'
+*/
+
+class Scope {
+ /** @param {ScopeParams} [parameters] */
+ constructor(parameters = {}) {
+ if (scope.current) scope.current.register(this);
+ const rootParam = parameters.root;
+ /** @type {Document|DOMTarget} */
+ let root = doc;
+ if (rootParam) {
+ root = /** @type {ReactRef} */(rootParam).current ||
+ /** @type {AngularRef} */(rootParam).nativeElement ||
+ parseTargets(/** @type {DOMTargetSelector} */(rootParam))[0] ||
+ doc;
+ }
+ const scopeDefaults = parameters.defaults;
+ const globalDefault = globals.defaults;
+ const mediaQueries = parameters.mediaQueries;
+ /** @type {DefaultsParams} */
+ this.defaults = scopeDefaults ? mergeObjects(scopeDefaults, globalDefault) : globalDefault;
+ /** @type {Document|DOMTarget} */
+ this.root = root;
+ /** @type {Array<ScopeConstructorCallback>} */
+ this.constructors = [];
+ /** @type {Array<ScopeCleanupCallback>} */
+ this.revertConstructors = [];
+ /** @type {Array<Revertible>} */
+ this.revertibles = [];
+ /** @type {Array<ScopeConstructorCallback | ((scope: this) => Tickable)>} */
+ this.constructorsOnce = [];
+ /** @type {Array<ScopeCleanupCallback>} */
+ this.revertConstructorsOnce = [];
+ /** @type {Array<Revertible>} */
+ this.revertiblesOnce = [];
+ /** @type {Boolean} */
+ this.once = false;
+ /** @type {Number} */
+ this.onceIndex = 0;
+ /** @type {Record<String, ScopeMethod>} */
+ this.methods = {};
+ /** @type {Record<String, Boolean>} */
+ this.matches = {};
+ /** @type {Record<String, MediaQueryList>} */
+ this.mediaQueryLists = {};
+ /** @type {Record<String, any>} */
+ this.data = {};
+ if (mediaQueries) {
+ for (let mq in mediaQueries) {
+ const _mq = win.matchMedia(mediaQueries[mq]);
+ this.mediaQueryLists[mq] = _mq;
+ _mq.addEventListener('change', this);
+ }
+ }
+ }
+
+ /**
+ * @param {Revertible} revertible
+ */
+ register(revertible) {
+ const store = this.once ? this.revertiblesOnce : this.revertibles;
+ store.push(revertible);
+ }
+
+ /**
+ * @template T
+ * @param {ScopedCallback<T>} cb
+ * @return {T}
+ */
+ execute(cb) {
+ let activeScope = scope.current;
+ let activeRoot = scope.root;
+ let activeDefaults = globals.defaults;
+ scope.current = this;
+ scope.root = this.root;
+ globals.defaults = this.defaults;
+ const mqs = this.mediaQueryLists;
+ for (let mq in mqs) this.matches[mq] = mqs[mq].matches;
+ const returned = cb(this);
+ scope.current = activeScope;
+ scope.root = activeRoot;
+ globals.defaults = activeDefaults;
+ return returned;
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ this.onceIndex = 0;
+ this.execute(() => {
+ let i = this.revertibles.length;
+ let y = this.revertConstructors.length;
+ while (i--) this.revertibles[i].revert();
+ while (y--) this.revertConstructors[y](this);
+ this.revertibles.length = 0;
+ this.revertConstructors.length = 0;
+ this.constructors.forEach((/** @type {ScopeConstructorCallback} */constructor) => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructors.push(revertConstructor);
+ }
+ });
+ });
+ return this;
+ }
+
+ /**
+ * @overload
+ * @param {String} a1
+ * @param {ScopeMethod} a2
+ * @return {this}
+ *
+ * @overload
+ * @param {ScopeConstructorCallback} a1
+ * @return {this}
+ *
+ * @param {String|ScopeConstructorCallback} a1
+ * @param {ScopeMethod} [a2]
+ */
+ add(a1, a2) {
+ this.once = false;
+ if (isFnc(a1)) {
+ const constructor = /** @type {ScopeConstructorCallback} */(a1);
+ this.constructors.push(constructor);
+ this.execute(() => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructors.push(revertConstructor);
+ }
+ });
+ } else {
+ this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args));
+ }
+ return this;
+ }
+
+ /**
+ * @param {ScopeConstructorCallback} scopeConstructorCallback
+ * @return {this}
+ */
+ addOnce(scopeConstructorCallback) {
+ this.once = true;
+ if (isFnc(scopeConstructorCallback)) {
+ const currentIndex = this.onceIndex++;
+ const tracked = this.constructorsOnce[currentIndex];
+ if (tracked) return this;
+ const constructor = /** @type {ScopeConstructorCallback} */(scopeConstructorCallback);
+ this.constructorsOnce[currentIndex] = constructor;
+ this.execute(() => {
+ const revertConstructor = constructor(this);
+ if (isFnc(revertConstructor)) {
+ this.revertConstructorsOnce.push(revertConstructor);
+ }
+ });
+ }
+ return this;
+ }
+
+ /**
+ * @param {(scope: this) => Tickable} cb
+ * @return {Tickable}
+ */
+ keepTime(cb) {
+ this.once = true;
+ const currentIndex = this.onceIndex++;
+ const tracked = /** @type {(scope: this) => Tickable} */(this.constructorsOnce[currentIndex]);
+ if (isFnc(tracked)) return tracked(this);
+ const constructor = /** @type {(scope: this) => Tickable} */(keepTime(cb));
+ this.constructorsOnce[currentIndex] = constructor;
+ let trackedTickable;
+ this.execute(() => {
+ trackedTickable = constructor(this);
+ });
+ return trackedTickable;
+ }
+
+ /**
+ * @param {Event} e
+ */
+ handleEvent(e) {
+ switch (e.type) {
+ case 'change':
+ this.refresh();
+ break;
+ }
+ }
+
+ revert() {
+ const revertibles = this.revertibles;
+ const revertConstructors = this.revertConstructors;
+ const revertiblesOnce = this.revertiblesOnce;
+ const revertConstructorsOnce = this.revertConstructorsOnce;
+ const mqs = this.mediaQueryLists;
+ let i = revertibles.length;
+ let j = revertConstructors.length;
+ let k = revertiblesOnce.length;
+ let l = revertConstructorsOnce.length;
+ while (i--) revertibles[i].revert();
+ while (j--) revertConstructors[j](this);
+ while (k--) revertiblesOnce[k].revert();
+ while (l--) revertConstructorsOnce[l](this);
+ for (let mq in mqs) mqs[mq].removeEventListener('change', this);
+ revertibles.length = 0;
+ revertConstructors.length = 0;
+ this.constructors.length = 0;
+ revertiblesOnce.length = 0;
+ revertConstructorsOnce.length = 0;
+ this.constructorsOnce.length = 0;
+ this.onceIndex = 0;
+ this.matches = {};
+ this.methods = {};
+ this.mediaQueryLists = {};
+ this.data = {};
+ }
+}
+
+/**
+ * @param {ScopeParams} [params]
+ * @return {Scope}
+ */
+const createScope = params => new Scope(params);
+
+export { Scope, createScope };
diff --git a/dist/modules/spring/index.cjs b/dist/modules/spring/index.cjs
new file mode 100644
index 00000000..9638c053
--- /dev/null
+++ b/dist/modules/spring/index.cjs
@@ -0,0 +1,15 @@
+/**
+ * Anime.js - spring - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var spring = require('./spring.cjs');
+
+
+
+exports.Spring = spring.Spring;
+exports.createSpring = spring.createSpring;
diff --git a/dist/modules/spring/index.d.ts b/dist/modules/spring/index.d.ts
new file mode 100644
index 00000000..b0e21f92
--- /dev/null
+++ b/dist/modules/spring/index.d.ts
@@ -0,0 +1 @@
+export * from "./spring.js";
diff --git a/dist/modules/spring/index.js b/dist/modules/spring/index.js
new file mode 100644
index 00000000..7dffbca5
--- /dev/null
+++ b/dist/modules/spring/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - spring - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { Spring, createSpring } from './spring.js';
diff --git a/dist/modules/spring/spring.cjs b/dist/modules/spring/spring.cjs
new file mode 100644
index 00000000..0acba085
--- /dev/null
+++ b/dist/modules/spring/spring.cjs
@@ -0,0 +1,133 @@
+/**
+ * Anime.js - spring - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var globals = require('../core/globals.cjs');
+var helpers = require('../core/helpers.cjs');
+var values = require('../core/values.cjs');
+
+/**
+ * @import {
+ * EasingFunction,
+ * SpringParams,
+ * } from '../types/index.js'
+*/
+
+/*
+ * Spring ease solver adapted from https://webkit.org/demos/spring/spring.js
+ * (c) 2016 Webkit - Apple Inc
+ */
+
+const maxSpringParamValue = consts.K * 10;
+
+class Spring {
+ /**
+ * @param {SpringParams} [parameters]
+ */
+ constructor(parameters = {}) {
+ this.timeStep = .02; // Interval fed to the solver to calculate duration
+ this.restThreshold = .0005; // Values below this threshold are considered resting position
+ this.restDuration = 200; // Duration in ms used to check if the spring is resting after reaching restThreshold
+ this.maxDuration = 60000; // The maximum allowed spring duration in ms (default 1 min)
+ this.maxRestSteps = this.restDuration / this.timeStep / consts.K; // How many steps allowed after reaching restThreshold before stopping the duration calculation
+ this.maxIterations = this.maxDuration / this.timeStep / consts.K; // Calculate the maximum iterations allowed based on maxDuration
+ this.m = helpers.clamp(values.setValue(parameters.mass, 1), 0, maxSpringParamValue);
+ this.s = helpers.clamp(values.setValue(parameters.stiffness, 100), 1, maxSpringParamValue);
+ this.d = helpers.clamp(values.setValue(parameters.damping, 10), .1, maxSpringParamValue);
+ this.v = helpers.clamp(values.setValue(parameters.velocity, 0), -maxSpringParamValue, maxSpringParamValue);
+ this.w0 = 0;
+ this.zeta = 0;
+ this.wd = 0;
+ this.b = 0;
+ this.solverDuration = 0;
+ this.duration = 0;
+ this.compute();
+ /** @type {EasingFunction} */
+ this.ease = t => t === 0 || t === 1 ? t : this.solve(t * this.solverDuration);
+ }
+
+ /** @type {EasingFunction} */
+ solve(time) {
+ const { zeta, w0, wd, b } = this;
+ let t = time;
+ if (zeta < 1) {
+ t = helpers.exp(-t * zeta * w0) * (1 * helpers.cos(wd * t) + b * helpers.sin(wd * t));
+ } else {
+ t = (1 + b * t) * helpers.exp(-t * w0);
+ }
+ return 1 - t;
+ }
+
+ compute() {
+ const { maxRestSteps, maxIterations, restThreshold, timeStep, m, d, s, v } = this;
+ const w0 = this.w0 = helpers.clamp(helpers.sqrt(s / m), consts.minValue, consts.K);
+ const zeta = this.zeta = d / (2 * helpers.sqrt(s * m));
+ const wd = this.wd = zeta < 1 ? w0 * helpers.sqrt(1 - zeta * zeta) : 0;
+ this.b = zeta < 1 ? (zeta * w0 + -v) / wd : -v + w0;
+ let solverTime = 0;
+ let restSteps = 0;
+ let iterations = 0;
+ while (restSteps < maxRestSteps && iterations < maxIterations) {
+ if (helpers.abs(1 - this.solve(solverTime)) < restThreshold) {
+ restSteps++;
+ } else {
+ restSteps = 0;
+ }
+ this.solverDuration = solverTime;
+ solverTime += timeStep;
+ iterations++;
+ }
+ this.duration = helpers.round(this.solverDuration * consts.K, 0) * globals.globals.timeScale;
+ }
+
+ get mass() {
+ return this.m;
+ }
+
+ set mass(v) {
+ this.m = helpers.clamp(values.setValue(v, 1), 0, maxSpringParamValue);
+ this.compute();
+ }
+
+ get stiffness() {
+ return this.s;
+ }
+
+ set stiffness(v) {
+ this.s = helpers.clamp(values.setValue(v, 100), 1, maxSpringParamValue);
+ this.compute();
+ }
+
+ get damping() {
+ return this.d;
+ }
+
+ set damping(v) {
+ this.d = helpers.clamp(values.setValue(v, 10), .1, maxSpringParamValue);
+ this.compute();
+ }
+
+ get velocity() {
+ return this.v;
+ }
+
+ set velocity(v) {
+ this.v = helpers.clamp(values.setValue(v, 0), -maxSpringParamValue, maxSpringParamValue);
+ this.compute();
+ }
+}
+
+/**
+ * @param {SpringParams} [parameters]
+ * @returns {Spring}
+ */
+const createSpring = (parameters) => new Spring(parameters);
+
+exports.Spring = Spring;
+exports.createSpring = createSpring;
diff --git a/dist/modules/spring/spring.d.ts b/dist/modules/spring/spring.d.ts
new file mode 100644
index 00000000..2b00317f
--- /dev/null
+++ b/dist/modules/spring/spring.d.ts
@@ -0,0 +1,37 @@
+export class Spring {
+ /**
+ * @param {SpringParams} [parameters]
+ */
+ constructor(parameters?: SpringParams);
+ timeStep: number;
+ restThreshold: number;
+ restDuration: number;
+ maxDuration: number;
+ maxRestSteps: number;
+ maxIterations: number;
+ m: number;
+ s: number;
+ d: number;
+ v: number;
+ w0: number;
+ zeta: number;
+ wd: number;
+ b: number;
+ solverDuration: number;
+ duration: number;
+ /** @type {EasingFunction} */
+ ease: EasingFunction;
+ solve(time: number): number;
+ compute(): void;
+ set mass(v: number);
+ get mass(): number;
+ set stiffness(v: number);
+ get stiffness(): number;
+ set damping(v: number);
+ get damping(): number;
+ set velocity(v: number);
+ get velocity(): number;
+}
+export function createSpring(parameters?: SpringParams): Spring;
+import type { EasingFunction } from '../types/index.js';
+import type { SpringParams } from '../types/index.js';
diff --git a/dist/modules/spring/spring.js b/dist/modules/spring/spring.js
new file mode 100644
index 00000000..4028b209
--- /dev/null
+++ b/dist/modules/spring/spring.js
@@ -0,0 +1,130 @@
+/**
+ * Anime.js - spring - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { K, minValue } from '../core/consts.js';
+import { globals } from '../core/globals.js';
+import { clamp, sqrt, abs, round, exp, cos, sin } from '../core/helpers.js';
+import { setValue } from '../core/values.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * SpringParams,
+ * } from '../types/index.js'
+*/
+
+/*
+ * Spring ease solver adapted from https://webkit.org/demos/spring/spring.js
+ * (c) 2016 Webkit - Apple Inc
+ */
+
+const maxSpringParamValue = K * 10;
+
+class Spring {
+ /**
+ * @param {SpringParams} [parameters]
+ */
+ constructor(parameters = {}) {
+ this.timeStep = .02; // Interval fed to the solver to calculate duration
+ this.restThreshold = .0005; // Values below this threshold are considered resting position
+ this.restDuration = 200; // Duration in ms used to check if the spring is resting after reaching restThreshold
+ this.maxDuration = 60000; // The maximum allowed spring duration in ms (default 1 min)
+ this.maxRestSteps = this.restDuration / this.timeStep / K; // How many steps allowed after reaching restThreshold before stopping the duration calculation
+ this.maxIterations = this.maxDuration / this.timeStep / K; // Calculate the maximum iterations allowed based on maxDuration
+ this.m = clamp(setValue(parameters.mass, 1), 0, maxSpringParamValue);
+ this.s = clamp(setValue(parameters.stiffness, 100), 1, maxSpringParamValue);
+ this.d = clamp(setValue(parameters.damping, 10), .1, maxSpringParamValue);
+ this.v = clamp(setValue(parameters.velocity, 0), -maxSpringParamValue, maxSpringParamValue);
+ this.w0 = 0;
+ this.zeta = 0;
+ this.wd = 0;
+ this.b = 0;
+ this.solverDuration = 0;
+ this.duration = 0;
+ this.compute();
+ /** @type {EasingFunction} */
+ this.ease = t => t === 0 || t === 1 ? t : this.solve(t * this.solverDuration);
+ }
+
+ /** @type {EasingFunction} */
+ solve(time) {
+ const { zeta, w0, wd, b } = this;
+ let t = time;
+ if (zeta < 1) {
+ t = exp(-t * zeta * w0) * (1 * cos(wd * t) + b * sin(wd * t));
+ } else {
+ t = (1 + b * t) * exp(-t * w0);
+ }
+ return 1 - t;
+ }
+
+ compute() {
+ const { maxRestSteps, maxIterations, restThreshold, timeStep, m, d, s, v } = this;
+ const w0 = this.w0 = clamp(sqrt(s / m), minValue, K);
+ const zeta = this.zeta = d / (2 * sqrt(s * m));
+ const wd = this.wd = zeta < 1 ? w0 * sqrt(1 - zeta * zeta) : 0;
+ this.b = zeta < 1 ? (zeta * w0 + -v) / wd : -v + w0;
+ let solverTime = 0;
+ let restSteps = 0;
+ let iterations = 0;
+ while (restSteps < maxRestSteps && iterations < maxIterations) {
+ if (abs(1 - this.solve(solverTime)) < restThreshold) {
+ restSteps++;
+ } else {
+ restSteps = 0;
+ }
+ this.solverDuration = solverTime;
+ solverTime += timeStep;
+ iterations++;
+ }
+ this.duration = round(this.solverDuration * K, 0) * globals.timeScale;
+ }
+
+ get mass() {
+ return this.m;
+ }
+
+ set mass(v) {
+ this.m = clamp(setValue(v, 1), 0, maxSpringParamValue);
+ this.compute();
+ }
+
+ get stiffness() {
+ return this.s;
+ }
+
+ set stiffness(v) {
+ this.s = clamp(setValue(v, 100), 1, maxSpringParamValue);
+ this.compute();
+ }
+
+ get damping() {
+ return this.d;
+ }
+
+ set damping(v) {
+ this.d = clamp(setValue(v, 10), .1, maxSpringParamValue);
+ this.compute();
+ }
+
+ get velocity() {
+ return this.v;
+ }
+
+ set velocity(v) {
+ this.v = clamp(setValue(v, 0), -maxSpringParamValue, maxSpringParamValue);
+ this.compute();
+ }
+}
+
+/**
+ * @param {SpringParams} [parameters]
+ * @returns {Spring}
+ */
+const createSpring = (parameters) => new Spring(parameters);
+
+export { Spring, createSpring };
diff --git a/dist/modules/svg/drawable.cjs b/dist/modules/svg/drawable.cjs
new file mode 100644
index 00000000..6df66c46
--- /dev/null
+++ b/dist/modules/svg/drawable.cjs
@@ -0,0 +1,119 @@
+/**
+ * Anime.js - svg - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var targets = require('../core/targets.cjs');
+
+/**
+ * @import {
+ * TargetsParam,
+ * DrawableSVGGeometry,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {SVGGeometryElement} [$el]
+ * @return {Number}
+ */
+const getScaleFactor = $el => {
+ let scaleFactor = 1;
+ if ($el && $el.getCTM) {
+ const ctm = $el.getCTM();
+ if (ctm) {
+ const scaleX = helpers.sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
+ const scaleY = helpers.sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
+ scaleFactor = (scaleX + scaleY) / 2;
+ }
+ }
+ return scaleFactor;
+};
+
+/**
+ * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
+ * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
+ * @param {number} start - Starting position (0-1)
+ * @param {number} end - Ending position (0-1)
+ * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
+ */
+const createDrawableProxy = ($el, start, end) => {
+ const pathLength = consts.K;
+ const computedStyles = getComputedStyle($el);
+ const strokeLineCap = computedStyles.strokeLinecap;
+ // @ts-ignore
+ const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
+ let currentCap = strokeLineCap;
+
+ const proxy = new Proxy($el, {
+ get(target, property) {
+ const value = target[property];
+ if (property === consts.proxyTargetSymbol) return target;
+ if (property === 'setAttribute') {
+ return (...args) => {
+ if (args[0] === 'draw') {
+ const value = args[1];
+ const values = value.split(' ');
+ const v1 = +values[0];
+ const v2 = +values[1];
+ // TOTO: Benchmark if performing two slices is more performant than one split
+ // const spaceIndex = value.indexOf(' ');
+ // const v1 = round(+value.slice(0, spaceIndex), precision);
+ // const v2 = round(+value.slice(spaceIndex + 1), precision);
+ const scaleFactor = getScaleFactor($scalled);
+ const os = v1 * -pathLength * scaleFactor;
+ const d1 = (v2 * pathLength * scaleFactor) + os;
+ const d2 = (pathLength * scaleFactor +
+ ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
+ if (strokeLineCap !== 'butt') {
+ const newCap = v1 === v2 ? 'butt' : strokeLineCap;
+ if (currentCap !== newCap) {
+ target.style.strokeLinecap = `${newCap}`;
+ currentCap = newCap;
+ }
+ }
+ target.setAttribute('stroke-dashoffset', `${os}`);
+ target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
+ }
+ return Reflect.apply(value, target, args);
+ };
+ }
+
+ if (helpers.isFnc(value)) {
+ return (...args) => Reflect.apply(value, target, args);
+ } else {
+ return value;
+ }
+ }
+ });
+
+ if ($el.getAttribute('pathLength') !== `${pathLength}`) {
+ $el.setAttribute('pathLength', `${pathLength}`);
+ proxy.setAttribute('draw', `${start} ${end}`);
+ }
+
+ return /** @type {DrawableSVGGeometry} */(proxy);
+};
+
+/**
+ * Creates drawable proxies for multiple SVG elements.
+ * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
+ * @param {number} [start=0] - Starting position (0-1)
+ * @param {number} [end=0] - Ending position (0-1)
+ * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
+ */
+const createDrawable = (selector, start = 0, end = 0) => {
+ const els = targets.parseTargets(selector);
+ return els.map($el => createDrawableProxy(
+ /** @type {SVGGeometryElement} */($el),
+ start,
+ end
+ ));
+};
+
+exports.createDrawable = createDrawable;
diff --git a/dist/modules/svg/drawable.d.ts b/dist/modules/svg/drawable.d.ts
new file mode 100644
index 00000000..197e96be
--- /dev/null
+++ b/dist/modules/svg/drawable.d.ts
@@ -0,0 +1,3 @@
+export function createDrawable(selector: TargetsParam, start?: number, end?: number): Array<DrawableSVGGeometry>;
+import type { TargetsParam } from '../types/index.js';
+import type { DrawableSVGGeometry } from '../types/index.js';
diff --git a/dist/modules/svg/drawable.js b/dist/modules/svg/drawable.js
new file mode 100644
index 00000000..ae5229a5
--- /dev/null
+++ b/dist/modules/svg/drawable.js
@@ -0,0 +1,117 @@
+/**
+ * Anime.js - svg - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { proxyTargetSymbol, K } from '../core/consts.js';
+import { isFnc, sqrt } from '../core/helpers.js';
+import { parseTargets } from '../core/targets.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * DrawableSVGGeometry,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {SVGGeometryElement} [$el]
+ * @return {Number}
+ */
+const getScaleFactor = $el => {
+ let scaleFactor = 1;
+ if ($el && $el.getCTM) {
+ const ctm = $el.getCTM();
+ if (ctm) {
+ const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
+ const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
+ scaleFactor = (scaleX + scaleY) / 2;
+ }
+ }
+ return scaleFactor;
+};
+
+/**
+ * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
+ * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
+ * @param {number} start - Starting position (0-1)
+ * @param {number} end - Ending position (0-1)
+ * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
+ */
+const createDrawableProxy = ($el, start, end) => {
+ const pathLength = K;
+ const computedStyles = getComputedStyle($el);
+ const strokeLineCap = computedStyles.strokeLinecap;
+ // @ts-ignore
+ const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
+ let currentCap = strokeLineCap;
+
+ const proxy = new Proxy($el, {
+ get(target, property) {
+ const value = target[property];
+ if (property === proxyTargetSymbol) return target;
+ if (property === 'setAttribute') {
+ return (...args) => {
+ if (args[0] === 'draw') {
+ const value = args[1];
+ const values = value.split(' ');
+ const v1 = +values[0];
+ const v2 = +values[1];
+ // TOTO: Benchmark if performing two slices is more performant than one split
+ // const spaceIndex = value.indexOf(' ');
+ // const v1 = round(+value.slice(0, spaceIndex), precision);
+ // const v2 = round(+value.slice(spaceIndex + 1), precision);
+ const scaleFactor = getScaleFactor($scalled);
+ const os = v1 * -pathLength * scaleFactor;
+ const d1 = (v2 * pathLength * scaleFactor) + os;
+ const d2 = (pathLength * scaleFactor +
+ ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
+ if (strokeLineCap !== 'butt') {
+ const newCap = v1 === v2 ? 'butt' : strokeLineCap;
+ if (currentCap !== newCap) {
+ target.style.strokeLinecap = `${newCap}`;
+ currentCap = newCap;
+ }
+ }
+ target.setAttribute('stroke-dashoffset', `${os}`);
+ target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
+ }
+ return Reflect.apply(value, target, args);
+ };
+ }
+
+ if (isFnc(value)) {
+ return (...args) => Reflect.apply(value, target, args);
+ } else {
+ return value;
+ }
+ }
+ });
+
+ if ($el.getAttribute('pathLength') !== `${pathLength}`) {
+ $el.setAttribute('pathLength', `${pathLength}`);
+ proxy.setAttribute('draw', `${start} ${end}`);
+ }
+
+ return /** @type {DrawableSVGGeometry} */(proxy);
+};
+
+/**
+ * Creates drawable proxies for multiple SVG elements.
+ * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
+ * @param {number} [start=0] - Starting position (0-1)
+ * @param {number} [end=0] - Ending position (0-1)
+ * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
+ */
+const createDrawable = (selector, start = 0, end = 0) => {
+ const els = parseTargets(selector);
+ return els.map($el => createDrawableProxy(
+ /** @type {SVGGeometryElement} */($el),
+ start,
+ end
+ ));
+};
+
+export { createDrawable };
diff --git a/dist/modules/svg/helpers.cjs b/dist/modules/svg/helpers.cjs
new file mode 100644
index 00000000..d1b26c00
--- /dev/null
+++ b/dist/modules/svg/helpers.cjs
@@ -0,0 +1,30 @@
+/**
+ * Anime.js - svg - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+var targets = require('../core/targets.cjs');
+
+/**
+ * @import {
+ * TargetsParam,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {TargetsParam} path
+ * @return {SVGGeometryElement|void}
+ */
+const getPath = path => {
+ const parsedTargets = targets.parseTargets(path);
+ const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
+ if (!$parsedSvg || !helpers.isSvg($parsedSvg)) return console.warn(`${path} is not a valid SVGGeometryElement`);
+ return $parsedSvg;
+};
+
+exports.getPath = getPath;
diff --git a/dist/modules/svg/helpers.d.ts b/dist/modules/svg/helpers.d.ts
new file mode 100644
index 00000000..6f3fbbf1
--- /dev/null
+++ b/dist/modules/svg/helpers.d.ts
@@ -0,0 +1,2 @@
+export function getPath(path: TargetsParam): SVGGeometryElement | void;
+import type { TargetsParam } from '../types/index.js';
diff --git a/dist/modules/svg/helpers.js b/dist/modules/svg/helpers.js
new file mode 100644
index 00000000..5aeef3a3
--- /dev/null
+++ b/dist/modules/svg/helpers.js
@@ -0,0 +1,28 @@
+/**
+ * Anime.js - svg - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { isSvg } from '../core/helpers.js';
+import { parseTargets } from '../core/targets.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {TargetsParam} path
+ * @return {SVGGeometryElement|void}
+ */
+const getPath = path => {
+ const parsedTargets = parseTargets(path);
+ const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
+ if (!$parsedSvg || !isSvg($parsedSvg)) return console.warn(`${path} is not a valid SVGGeometryElement`);
+ return $parsedSvg;
+};
+
+export { getPath };
diff --git a/dist/modules/svg/index.cjs b/dist/modules/svg/index.cjs
new file mode 100644
index 00000000..2819cfc5
--- /dev/null
+++ b/dist/modules/svg/index.cjs
@@ -0,0 +1,18 @@
+/**
+ * Anime.js - svg - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var motionpath = require('./motionpath.cjs');
+var drawable = require('./drawable.cjs');
+var morphto = require('./morphto.cjs');
+
+
+
+exports.createMotionPath = motionpath.createMotionPath;
+exports.createDrawable = drawable.createDrawable;
+exports.morphTo = morphto.morphTo;
diff --git a/dist/modules/svg/index.d.ts b/dist/modules/svg/index.d.ts
new file mode 100644
index 00000000..967004e6
--- /dev/null
+++ b/dist/modules/svg/index.d.ts
@@ -0,0 +1,3 @@
+export { createMotionPath } from "./motionpath.js";
+export { createDrawable } from "./drawable.js";
+export { morphTo } from "./morphto.js";
diff --git a/dist/modules/svg/index.js b/dist/modules/svg/index.js
new file mode 100644
index 00000000..a402730a
--- /dev/null
+++ b/dist/modules/svg/index.js
@@ -0,0 +1,10 @@
+/**
+ * Anime.js - svg - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { createMotionPath } from './motionpath.js';
+export { createDrawable } from './drawable.js';
+export { morphTo } from './morphto.js';
diff --git a/dist/modules/svg/morphto.cjs b/dist/modules/svg/morphto.cjs
new file mode 100644
index 00000000..e7777c3f
--- /dev/null
+++ b/dist/modules/svg/morphto.cjs
@@ -0,0 +1,58 @@
+/**
+ * Anime.js - svg - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers$1 = require('../core/helpers.cjs');
+var helpers = require('./helpers.cjs');
+
+/**
+ * @import {
+ * TargetsParam,
+ * FunctionValue
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {TargetsParam} path2
+ * @param {Number} [precision]
+ * @return {FunctionValue}
+ */
+const morphTo = (path2, precision = .33) => ($path1) => {
+ const $path2 = /** @type {SVGGeometryElement} */(helpers.getPath(path2));
+ if (!$path2) return;
+ const isPath = $path1.tagName === 'path';
+ const separator = isPath ? ' ' : ',';
+ const previousPoints = $path1[consts.morphPointsSymbol];
+ if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
+
+ let v1 = '', v2 = '';
+
+ if (!precision) {
+ v1 = $path1.getAttribute(isPath ? 'd' : 'points');
+ v2 = $path2.getAttribute(isPath ? 'd' : 'points');
+ } else {
+ const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
+ const length2 = $path2.getTotalLength();
+ const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
+ for (let i = 0; i < maxPoints; i++) {
+ const t = i / (maxPoints - 1);
+ const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
+ const pointOnPath2 = $path2.getPointAtLength(length2 * t);
+ const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
+ v1 += prefix + helpers$1.round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
+ v2 += prefix + helpers$1.round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
+ }
+ }
+
+ $path1[consts.morphPointsSymbol] = v2;
+
+ return [v1, v2];
+};
+
+exports.morphTo = morphTo;
diff --git a/dist/modules/svg/morphto.d.ts b/dist/modules/svg/morphto.d.ts
new file mode 100644
index 00000000..2c390a5b
--- /dev/null
+++ b/dist/modules/svg/morphto.d.ts
@@ -0,0 +1,3 @@
+export function morphTo(path2: TargetsParam, precision?: number): FunctionValue;
+import type { TargetsParam } from '../types/index.js';
+import type { FunctionValue } from '../types/index.js';
diff --git a/dist/modules/svg/morphto.js b/dist/modules/svg/morphto.js
new file mode 100644
index 00000000..829d68c2
--- /dev/null
+++ b/dist/modules/svg/morphto.js
@@ -0,0 +1,56 @@
+/**
+ * Anime.js - svg - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { morphPointsSymbol } from '../core/consts.js';
+import { round } from '../core/helpers.js';
+import { getPath } from './helpers.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * FunctionValue
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {TargetsParam} path2
+ * @param {Number} [precision]
+ * @return {FunctionValue}
+ */
+const morphTo = (path2, precision = .33) => ($path1) => {
+ const $path2 = /** @type {SVGGeometryElement} */(getPath(path2));
+ if (!$path2) return;
+ const isPath = $path1.tagName === 'path';
+ const separator = isPath ? ' ' : ',';
+ const previousPoints = $path1[morphPointsSymbol];
+ if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
+
+ let v1 = '', v2 = '';
+
+ if (!precision) {
+ v1 = $path1.getAttribute(isPath ? 'd' : 'points');
+ v2 = $path2.getAttribute(isPath ? 'd' : 'points');
+ } else {
+ const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
+ const length2 = $path2.getTotalLength();
+ const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
+ for (let i = 0; i < maxPoints; i++) {
+ const t = i / (maxPoints - 1);
+ const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
+ const pointOnPath2 = $path2.getPointAtLength(length2 * t);
+ const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
+ v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
+ v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
+ }
+ }
+
+ $path1[morphPointsSymbol] = v2;
+
+ return [v1, v2];
+};
+
+export { morphTo };
diff --git a/dist/modules/svg/motionpath.cjs b/dist/modules/svg/motionpath.cjs
new file mode 100644
index 00000000..8449cc6a
--- /dev/null
+++ b/dist/modules/svg/motionpath.cjs
@@ -0,0 +1,79 @@
+/**
+ * Anime.js - svg - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers$1 = require('../core/helpers.cjs');
+var helpers = require('./helpers.cjs');
+
+/**
+ * @import {
+ * TargetsParam,
+ * FunctionValue,
+ * TweenObjectValue,
+ * TweenModifier,
+ * } from '../types/index.js'
+*/
+
+// Motion path animation
+
+/**
+ * @param {SVGGeometryElement} $path
+ * @param {Number} progress
+ * @param {Number}lookup
+ * @return {DOMPoint}
+ */
+const getPathPoint = ($path, progress, lookup = 0) => {
+ return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0);
+};
+
+/**
+ * @param {SVGGeometryElement} $path
+ * @param {String} pathProperty
+ * @return {FunctionValue}
+ */
+const getPathProgess = ($path, pathProperty) => {
+ return $el => {
+ const totalLength = +($path.getTotalLength());
+ const inSvg = $el[consts.isSvgSymbol];
+ const ctm = $path.getCTM();
+ /** @type {TweenObjectValue} */
+ return {
+ from: 0,
+ to: totalLength,
+ /** @type {TweenModifier} */
+ modifier: progress => {
+ if (pathProperty === 'a') {
+ const p0 = getPathPoint($path, progress, -1);
+ const p1 = getPathPoint($path, progress, 1);
+ return helpers$1.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / helpers$1.PI;
+ } else {
+ const p = getPathPoint($path, progress, 0);
+ return pathProperty === 'x' ?
+ inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
+ inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
+ }
+ }
+ }
+ }
+};
+
+/**
+ * @param {TargetsParam} path
+ */
+const createMotionPath = path => {
+ const $path = helpers.getPath(path);
+ if (!$path) return;
+ return {
+ translateX: getPathProgess($path, 'x'),
+ translateY: getPathProgess($path, 'y'),
+ rotate: getPathProgess($path, 'a'),
+ }
+};
+
+exports.createMotionPath = createMotionPath;
diff --git a/dist/modules/svg/motionpath.d.ts b/dist/modules/svg/motionpath.d.ts
new file mode 100644
index 00000000..0e9e666d
--- /dev/null
+++ b/dist/modules/svg/motionpath.d.ts
@@ -0,0 +1,7 @@
+export function createMotionPath(path: TargetsParam): {
+ translateX: FunctionValue;
+ translateY: FunctionValue;
+ rotate: FunctionValue;
+};
+import type { TargetsParam } from '../types/index.js';
+import type { FunctionValue } from '../types/index.js';
diff --git a/dist/modules/svg/motionpath.js b/dist/modules/svg/motionpath.js
new file mode 100644
index 00000000..78b1449f
--- /dev/null
+++ b/dist/modules/svg/motionpath.js
@@ -0,0 +1,77 @@
+/**
+ * Anime.js - svg - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { isSvgSymbol } from '../core/consts.js';
+import { atan2, PI } from '../core/helpers.js';
+import { getPath } from './helpers.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * FunctionValue,
+ * TweenObjectValue,
+ * TweenModifier,
+ * } from '../types/index.js'
+*/
+
+// Motion path animation
+
+/**
+ * @param {SVGGeometryElement} $path
+ * @param {Number} progress
+ * @param {Number}lookup
+ * @return {DOMPoint}
+ */
+const getPathPoint = ($path, progress, lookup = 0) => {
+ return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0);
+};
+
+/**
+ * @param {SVGGeometryElement} $path
+ * @param {String} pathProperty
+ * @return {FunctionValue}
+ */
+const getPathProgess = ($path, pathProperty) => {
+ return $el => {
+ const totalLength = +($path.getTotalLength());
+ const inSvg = $el[isSvgSymbol];
+ const ctm = $path.getCTM();
+ /** @type {TweenObjectValue} */
+ return {
+ from: 0,
+ to: totalLength,
+ /** @type {TweenModifier} */
+ modifier: progress => {
+ if (pathProperty === 'a') {
+ const p0 = getPathPoint($path, progress, -1);
+ const p1 = getPathPoint($path, progress, 1);
+ return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI;
+ } else {
+ const p = getPathPoint($path, progress, 0);
+ return pathProperty === 'x' ?
+ inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
+ inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
+ }
+ }
+ }
+ }
+};
+
+/**
+ * @param {TargetsParam} path
+ */
+const createMotionPath = path => {
+ const $path = getPath(path);
+ if (!$path) return;
+ return {
+ translateX: getPathProgess($path, 'x'),
+ translateY: getPathProgess($path, 'y'),
+ rotate: getPathProgess($path, 'a'),
+ }
+};
+
+export { createMotionPath };
diff --git a/dist/modules/text/index.cjs b/dist/modules/text/index.cjs
new file mode 100644
index 00000000..698a0ea0
--- /dev/null
+++ b/dist/modules/text/index.cjs
@@ -0,0 +1,16 @@
+/**
+ * Anime.js - text - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var split = require('./split.cjs');
+
+
+
+exports.TextSplitter = split.TextSplitter;
+exports.split = split.split;
+exports.splitText = split.splitText;
diff --git a/dist/modules/text/index.d.ts b/dist/modules/text/index.d.ts
new file mode 100644
index 00000000..35a025e6
--- /dev/null
+++ b/dist/modules/text/index.d.ts
@@ -0,0 +1 @@
+export * from "./split.js";
diff --git a/dist/modules/text/index.js b/dist/modules/text/index.js
new file mode 100644
index 00000000..bc221d29
--- /dev/null
+++ b/dist/modules/text/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - text - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { TextSplitter, split, splitText } from './split.js';
diff --git a/dist/modules/text/split.cjs b/dist/modules/text/split.cjs
new file mode 100644
index 00000000..eaab4417
--- /dev/null
+++ b/dist/modules/text/split.cjs
@@ -0,0 +1,488 @@
+/**
+ * Anime.js - text - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var globals = require('../core/globals.cjs');
+var helpers = require('../core/helpers.cjs');
+var targets = require('../core/targets.cjs');
+var values = require('../core/values.cjs');
+var time = require('../utils/time.cjs');
+
+/**
+ * @import {
+ * Tickable,
+ * DOMTarget,
+ * SplitTemplateParams,
+ * SplitFunctionValue,
+ * TextSplitterParams,
+ * } from '../types/index.js'
+*/
+
+const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter;
+const valueRgx = /\{value\}/g;
+const indexRgx = /\{i\}/g;
+const whiteSpaceGroupRgx = /(\s+)/;
+const whiteSpaceRgx = /^\s+$/;
+const lineType = 'line';
+const wordType = 'word';
+const charType = 'char';
+const dataLine = `data-line`;
+
+/**
+ * @typedef {Object} Segment
+ * @property {String} segment
+ * @property {Boolean} [isWordLike]
+ */
+
+/**
+ * @typedef {Object} Segmenter
+ * @property {function(String): Iterable<Segment>} segment
+ */
+
+/** @type {Segmenter} */
+let wordSegmenter = null;
+/** @type {Segmenter} */
+let graphemeSegmenter = null;
+let $splitTemplate = null;
+
+/**
+ * @param {Segment} seg
+ * @return {Boolean}
+ */
+const isSegmentWordLike = seg => {
+ return seg.isWordLike ||
+ seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later
+ helpers.isNum(+seg.segment); // Safari doesn't considers numbers as words
+};
+
+/**
+ * @param {HTMLElement} $el
+ */
+const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true');
+
+/**
+ * @param {DOMTarget} $el
+ * @param {String} type
+ * @return {Array<HTMLElement>}
+ */
+const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))];
+
+const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' };
+
+/**
+ * @param {HTMLElement} $el
+ */
+const filterEmptyElements = $el => {
+ if (!$el.childElementCount && !$el.textContent.trim()) {
+ const $parent = $el.parentElement;
+ $el.remove();
+ if ($parent) filterEmptyElements($parent);
+ }
+};
+
+/**
+ * @param {HTMLElement} $el
+ * @param {Number} lineIndex
+ * @param {Set<HTMLElement>} bin
+ * @returns {Set<HTMLElement>}
+ */
+const filterLineElements = ($el, lineIndex, bin) => {
+ const dataLineAttr = $el.getAttribute(dataLine);
+ if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') bin.add($el);
+ let i = $el.childElementCount;
+ while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin);
+ return bin;
+};
+
+/**
+ * @param {'line'|'word'|'char'} type
+ * @param {SplitTemplateParams} params
+ * @return {String}
+ */
+const generateTemplate = (type, params = {}) => {
+ let template = ``;
+ const classString = helpers.isStr(params.class) ? ` class="${params.class}"` : '';
+ const cloneType = values.setValue(params.clone, false);
+ const wrapType = values.setValue(params.wrap, false);
+ const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false;
+ if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`;
+ template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`;
+ if (cloneType) {
+ const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0';
+ const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0';
+ template += `<span>{value}</span>`;
+ template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`;
+ } else {
+ template += `{value}`;
+ }
+ template += `</span>`;
+ if (wrapType) template += `</span>`;
+ return template;
+};
+
+/**
+ * @param {String|SplitFunctionValue} htmlTemplate
+ * @param {Array<HTMLElement>} store
+ * @param {Node|HTMLElement} node
+ * @param {DocumentFragment} $parentFragment
+ * @param {'line'|'word'|'char'} type
+ * @param {Boolean} debug
+ * @param {Number} lineIndex
+ * @param {Number} [wordIndex]
+ * @param {Number} [charIndex]
+ * @return {HTMLElement}
+ */
+const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => {
+ const isLine = type === lineType;
+ const isChar = type === charType;
+ const className = `_${type}_`;
+ const template = helpers.isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate;
+ const displayStyle = isLine ? 'block' : 'inline-block';
+ $splitTemplate.innerHTML = template
+ .replace(valueRgx, `<i class="${className}"></i>`)
+ .replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`);
+ const $content = $splitTemplate.content;
+ const $highestParent = /** @type {HTMLElement} */($content.firstElementChild);
+ const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent;
+ const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`));
+ const replacablesLength = $replacables.length;
+ if (replacablesLength) {
+ $highestParent.style.display = displayStyle;
+ $split.style.display = displayStyle;
+ $split.setAttribute(dataLine, `${lineIndex}`);
+ if (!isLine) {
+ $split.setAttribute('data-word', `${wordIndex}`);
+ if (isChar) $split.setAttribute('data-char', `${charIndex}`);
+ }
+ let i = replacablesLength;
+ while (i--) {
+ const $replace = $replacables[i];
+ const $closestParent = $replace.parentElement;
+ $closestParent.style.display = displayStyle;
+ if (isLine) {
+ $closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML;
+ } else {
+ $closestParent.replaceChild(node.cloneNode(true), $replace);
+ }
+ }
+ store.push($split);
+ $parentFragment.appendChild($content);
+ } else {
+ console.warn(`The expression "{value}" is missing from the provided template.`);
+ }
+ if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`;
+ return $highestParent;
+};
+
+/**
+ * A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
+ * @class
+ */
+class TextSplitter {
+ /**
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ */
+ constructor(target, parameters = {}) {
+ // Only init segmenters when needed
+ if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : {
+ segment: (text) => {
+ const segments = [];
+ const words = text.split(whiteSpaceGroupRgx);
+ for (let i = 0, l = words.length; i < l; i++) {
+ const segment = words[i];
+ segments.push({
+ segment,
+ isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like
+ });
+ }
+ return segments;
+ }
+ };
+ if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : {
+ segment: text => [...text].map(char => ({ segment: char }))
+ };
+ if (!$splitTemplate && consts.isBrowser) $splitTemplate = consts.doc.createElement('template');
+ if (globals.scope.current) globals.scope.current.register(this);
+ const { words, chars, lines, accessible, includeSpaces, debug } = parameters;
+ const $target = /** @type {HTMLElement} */((target = helpers.isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (targets.getNodeList(target) || [])[0]);
+ const lineParams = lines === true ? {} : lines;
+ const wordParams = words === true || helpers.isUnd(words) ? {} : words;
+ const charParams = chars === true ? {} : chars;
+ this.debug = values.setValue(debug, false);
+ this.includeSpaces = values.setValue(includeSpaces, false);
+ this.accessible = values.setValue(accessible, true);
+ this.linesOnly = lineParams && (!wordParams && !charParams);
+ /** @type {String|false|SplitFunctionValue} */
+ this.lineTemplate = helpers.isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams;
+ /** @type {String|false|SplitFunctionValue} */
+ this.wordTemplate = helpers.isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams;
+ /** @type {String|false|SplitFunctionValue} */
+ this.charTemplate = helpers.isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams;
+ this.$target = $target;
+ this.html = $target && $target.innerHTML;
+ this.lines = [];
+ this.words = [];
+ this.chars = [];
+ this.effects = [];
+ this.effectsCleanups = [];
+ this.cache = null;
+ this.ready = false;
+ this.width = 0;
+ this.resizeTimeout = null;
+ const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split();
+ // Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback
+ this.resizeObserver = new ResizeObserver(() => {
+ // Use a setTimeout instead of a Timer for better tree shaking
+ clearTimeout(this.resizeTimeout);
+ this.resizeTimeout = setTimeout(() => {
+ const currentWidth = /** @type {HTMLElement} */($target).offsetWidth;
+ if (currentWidth === this.width) return;
+ this.width = currentWidth;
+ handleSplit();
+ }, 150);
+ });
+ // Only declare the font ready promise when splitting by lines and not alreay split
+ if (this.lineTemplate && !this.ready) {
+ consts.doc.fonts.ready.then(handleSplit);
+ } else {
+ handleSplit();
+ }
+ $target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.');
+ }
+
+ /**
+ * @param {(...args: any[]) => Tickable | (() => void)} effect
+ * @return this
+ */
+ addEffect(effect) {
+ if (!helpers.isFnc(effect)) return console.warn('Effect must return a function.');
+ const refreshableEffect = time.keepTime(effect);
+ this.effects.push(refreshableEffect);
+ if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this);
+ return this;
+ }
+
+ revert() {
+ clearTimeout(this.resizeTimeout);
+ this.lines.length = this.words.length = this.chars.length = 0;
+ this.resizeObserver.disconnect();
+ // Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process
+ this.effectsCleanups.forEach(cleanup => helpers.isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert());
+ this.$target.innerHTML = this.html;
+ return this;
+ }
+
+ /**
+ * Recursively processes a node and its children
+ * @param {Node} node
+ */
+ splitNode(node) {
+ const wordTemplate = this.wordTemplate;
+ const charTemplate = this.charTemplate;
+ const includeSpaces = this.includeSpaces;
+ const debug = this.debug;
+ const nodeType = node.nodeType;
+ if (nodeType === 3) {
+ const nodeText = node.nodeValue;
+ // If the nodeText is only whitespace, leave it as is
+ if (nodeText.trim()) {
+ const tempWords = [];
+ const words = this.words;
+ const chars = this.chars;
+ const wordSegments = wordSegmenter.segment(nodeText);
+ const $wordsFragment = consts.doc.createDocumentFragment();
+ let prevSeg = null;
+ for (const wordSegment of wordSegments) {
+ const segment = wordSegment.segment;
+ const isWordLike = isSegmentWordLike(wordSegment);
+ // Determine if this segment should be a new word, first segment always becomes a new word
+ if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) {
+ tempWords.push(segment);
+ } else {
+ // Only concatenate if both current and previous are non-word-like and don't contain spaces
+ const lastWordIndex = tempWords.length - 1;
+ const lastWord = tempWords[lastWordIndex];
+ if (!lastWord.includes(' ') && !segment.includes(' ')) {
+ tempWords[lastWordIndex] += segment;
+ } else {
+ tempWords.push(segment);
+ }
+ }
+ prevSeg = wordSegment;
+ }
+
+ for (let i = 0, l = tempWords.length; i < l; i++) {
+ const word = tempWords[i];
+ if (!word.trim()) {
+ // Preserve whitespace only if includeSpaces is false and if the current space is not the first node
+ if (i && includeSpaces) continue;
+ $wordsFragment.appendChild(consts.doc.createTextNode(word));
+ } else {
+ const nextWord = tempWords[i + 1];
+ const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim();
+ const wordToProcess = word;
+ const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null;
+ const $charsFragment = charTemplate ? consts.doc.createDocumentFragment() : consts.doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word);
+ if (charTemplate) {
+ const charSegmentsArray = [...charSegments];
+ for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) {
+ const charSegment = charSegmentsArray[j];
+ const isLastChar = j === jl - 1;
+ // If this is the last character and includeSpaces is true with a following space, append the space
+ const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment;
+ const $charNode = consts.doc.createTextNode(charText);
+ processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length);
+ }
+ }
+ if (wordTemplate) {
+ processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length);
+ // Chars elements must be re-parsed in the split() method if both words and chars are parsed
+ } else if (charTemplate) {
+ $wordsFragment.appendChild($charsFragment);
+ } else {
+ $wordsFragment.appendChild(consts.doc.createTextNode(word));
+ }
+ // Skip the next iteration if we included a space
+ if (hasWordFollowingSpace) i++;
+ }
+ }
+ node.parentNode.replaceChild($wordsFragment, node);
+ }
+ } else if (nodeType === 1) {
+ // Converting to an array is necessary to work around childNodes pottential mutation
+ const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]);
+ for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]);
+ }
+ }
+
+ /**
+ * @param {Boolean} clearCache
+ * @return {this}
+ */
+ split(clearCache = false) {
+ const $el = this.$target;
+ const isCached = !!this.cache && !clearCache;
+ const lineTemplate = this.lineTemplate;
+ const wordTemplate = this.wordTemplate;
+ const charTemplate = this.charTemplate;
+ const fontsReady = consts.doc.fonts.status !== 'loading';
+ const canSplitLines = lineTemplate && fontsReady;
+ this.ready = !lineTemplate || fontsReady;
+ if (canSplitLines || clearCache) {
+ // No need to revert effects animations here since it's already taken care by the refreshable
+ this.effectsCleanups.forEach(cleanup => helpers.isFnc(cleanup) && cleanup(this));
+ }
+ if (!isCached) {
+ if (clearCache) {
+ $el.innerHTML = this.html;
+ this.words.length = this.chars.length = 0;
+ }
+ this.splitNode($el);
+ this.cache = $el.innerHTML;
+ }
+ if (canSplitLines) {
+ if (isCached) $el.innerHTML = this.cache;
+ this.lines.length = 0;
+ if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
+ }
+ // Always reparse characters after a line reset or if both words and chars are activated
+ if (charTemplate && (canSplitLines || wordTemplate)) {
+ this.chars = getAllTopLevelElements($el, charType);
+ }
+ // Words are used when lines only and prioritized over chars
+ const elementsArray = this.words.length ? this.words : this.chars;
+ let y, linesCount = 0;
+ for (let i = 0, l = elementsArray.length; i < l; i++) {
+ const $el = elementsArray[i];
+ const { top, height } = $el.getBoundingClientRect();
+ if (y && top - y > height * .5) linesCount++;
+ $el.setAttribute(dataLine, `${linesCount}`);
+ const nested = $el.querySelectorAll(`[${dataLine}]`);
+ let c = nested.length;
+ while (c--) nested[c].setAttribute(dataLine, `${linesCount}`);
+ y = top;
+ }
+ if (canSplitLines) {
+ const linesFragment = consts.doc.createDocumentFragment();
+ const parents = new Set();
+ const clones = [];
+ for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) {
+ const $clone = /** @type {HTMLElement} */($el.cloneNode(true));
+ filterLineElements($clone, lineIndex, new Set()).forEach($el => {
+ const $parent = $el.parentElement;
+ if ($parent) parents.add($parent);
+ $el.remove();
+ });
+ clones.push($clone);
+ }
+ parents.forEach(filterEmptyElements);
+ for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) {
+ processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex);
+ }
+ $el.innerHTML = '';
+ $el.appendChild(linesFragment);
+ if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
+ if (charTemplate) this.chars = getAllTopLevelElements($el, charType);
+ }
+ // Remove the word wrappers and clear the words array if lines split only
+ if (this.linesOnly) {
+ const words = this.words;
+ let w = words.length;
+ while (w--) {
+ const $word = words[w];
+ $word.replaceWith($word.textContent);
+ }
+ words.length = 0;
+ }
+ if (this.accessible && (canSplitLines || !isCached)) {
+ const $accessible = consts.doc.createElement('span');
+ // Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html)
+ $accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;
+ // $accessible.setAttribute('tabindex', '-1');
+ $accessible.innerHTML = this.html;
+ $el.insertBefore($accessible, $el.firstChild);
+ this.lines.forEach(setAriaHidden);
+ this.words.forEach(setAriaHidden);
+ this.chars.forEach(setAriaHidden);
+ }
+ this.width = /** @type {HTMLElement} */($el).offsetWidth;
+ if (canSplitLines || clearCache) {
+ this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this));
+ }
+ return this;
+ }
+
+ refresh() {
+ this.split(true);
+ }
+}
+
+/**
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
+ */
+const splitText = (target, parameters) => new TextSplitter(target, parameters);
+
+/**
+ * @deprecated text.split() is deprecated, import splitText() directly, or text.splitText()
+ *
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
+ */
+const split = (target, parameters) => {
+ console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()');
+ return new TextSplitter(target, parameters);
+};
+
+exports.TextSplitter = TextSplitter;
+exports.split = split;
+exports.splitText = splitText;
diff --git a/dist/modules/text/split.d.ts b/dist/modules/text/split.d.ts
new file mode 100644
index 00000000..110bfe3d
--- /dev/null
+++ b/dist/modules/text/split.d.ts
@@ -0,0 +1,62 @@
+/**
+ * A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
+ * @class
+ */
+export class TextSplitter {
+ /**
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ */
+ constructor(target: HTMLElement | NodeList | string | Array<HTMLElement>, parameters?: TextSplitterParams);
+ debug: boolean;
+ includeSpaces: boolean;
+ accessible: boolean;
+ linesOnly: boolean;
+ /** @type {String|false|SplitFunctionValue} */
+ lineTemplate: string | false | SplitFunctionValue;
+ /** @type {String|false|SplitFunctionValue} */
+ wordTemplate: string | false | SplitFunctionValue;
+ /** @type {String|false|SplitFunctionValue} */
+ charTemplate: string | false | SplitFunctionValue;
+ $target: HTMLElement;
+ html: string;
+ lines: any[];
+ words: any[];
+ chars: any[];
+ effects: any[];
+ effectsCleanups: any[];
+ cache: string;
+ ready: boolean;
+ width: number;
+ resizeTimeout: NodeJS.Timeout;
+ resizeObserver: ResizeObserver;
+ /**
+ * @param {(...args: any[]) => Tickable | (() => void)} effect
+ * @return this
+ */
+ addEffect(effect: (...args: any[]) => Tickable | (() => void)): void | this;
+ revert(): this;
+ /**
+ * Recursively processes a node and its children
+ * @param {Node} node
+ */
+ splitNode(node: Node): void;
+ /**
+ * @param {Boolean} clearCache
+ * @return {this}
+ */
+ split(clearCache?: boolean): this;
+ refresh(): void;
+}
+export function splitText(target: HTMLElement | NodeList | string | Array<HTMLElement>, parameters?: TextSplitterParams): TextSplitter;
+export function split(target: HTMLElement | NodeList | string | Array<HTMLElement>, parameters?: TextSplitterParams): TextSplitter;
+export type Segment = {
+ segment: string;
+ isWordLike?: boolean;
+};
+export type Segmenter = {
+ segment: (arg0: string) => Iterable<Segment>;
+};
+import type { SplitFunctionValue } from '../types/index.js';
+import type { Tickable } from '../types/index.js';
+import type { TextSplitterParams } from '../types/index.js';
diff --git a/dist/modules/text/split.js b/dist/modules/text/split.js
new file mode 100644
index 00000000..b089acb6
--- /dev/null
+++ b/dist/modules/text/split.js
@@ -0,0 +1,484 @@
+/**
+ * Anime.js - text - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { isBrowser, doc } from '../core/consts.js';
+import { scope } from '../core/globals.js';
+import { isArr, isObj, isFnc, isUnd, isStr, isNum } from '../core/helpers.js';
+import { getNodeList } from '../core/targets.js';
+import { setValue } from '../core/values.js';
+import { keepTime } from '../utils/time.js';
+
+/**
+ * @import {
+ * Tickable,
+ * DOMTarget,
+ * SplitTemplateParams,
+ * SplitFunctionValue,
+ * TextSplitterParams,
+ * } from '../types/index.js'
+*/
+
+const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter;
+const valueRgx = /\{value\}/g;
+const indexRgx = /\{i\}/g;
+const whiteSpaceGroupRgx = /(\s+)/;
+const whiteSpaceRgx = /^\s+$/;
+const lineType = 'line';
+const wordType = 'word';
+const charType = 'char';
+const dataLine = `data-line`;
+
+/**
+ * @typedef {Object} Segment
+ * @property {String} segment
+ * @property {Boolean} [isWordLike]
+ */
+
+/**
+ * @typedef {Object} Segmenter
+ * @property {function(String): Iterable<Segment>} segment
+ */
+
+/** @type {Segmenter} */
+let wordSegmenter = null;
+/** @type {Segmenter} */
+let graphemeSegmenter = null;
+let $splitTemplate = null;
+
+/**
+ * @param {Segment} seg
+ * @return {Boolean}
+ */
+const isSegmentWordLike = seg => {
+ return seg.isWordLike ||
+ seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later
+ isNum(+seg.segment); // Safari doesn't considers numbers as words
+};
+
+/**
+ * @param {HTMLElement} $el
+ */
+const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true');
+
+/**
+ * @param {DOMTarget} $el
+ * @param {String} type
+ * @return {Array<HTMLElement>}
+ */
+const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))];
+
+const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' };
+
+/**
+ * @param {HTMLElement} $el
+ */
+const filterEmptyElements = $el => {
+ if (!$el.childElementCount && !$el.textContent.trim()) {
+ const $parent = $el.parentElement;
+ $el.remove();
+ if ($parent) filterEmptyElements($parent);
+ }
+};
+
+/**
+ * @param {HTMLElement} $el
+ * @param {Number} lineIndex
+ * @param {Set<HTMLElement>} bin
+ * @returns {Set<HTMLElement>}
+ */
+const filterLineElements = ($el, lineIndex, bin) => {
+ const dataLineAttr = $el.getAttribute(dataLine);
+ if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') bin.add($el);
+ let i = $el.childElementCount;
+ while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin);
+ return bin;
+};
+
+/**
+ * @param {'line'|'word'|'char'} type
+ * @param {SplitTemplateParams} params
+ * @return {String}
+ */
+const generateTemplate = (type, params = {}) => {
+ let template = ``;
+ const classString = isStr(params.class) ? ` class="${params.class}"` : '';
+ const cloneType = setValue(params.clone, false);
+ const wrapType = setValue(params.wrap, false);
+ const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false;
+ if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`;
+ template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`;
+ if (cloneType) {
+ const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0';
+ const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0';
+ template += `<span>{value}</span>`;
+ template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`;
+ } else {
+ template += `{value}`;
+ }
+ template += `</span>`;
+ if (wrapType) template += `</span>`;
+ return template;
+};
+
+/**
+ * @param {String|SplitFunctionValue} htmlTemplate
+ * @param {Array<HTMLElement>} store
+ * @param {Node|HTMLElement} node
+ * @param {DocumentFragment} $parentFragment
+ * @param {'line'|'word'|'char'} type
+ * @param {Boolean} debug
+ * @param {Number} lineIndex
+ * @param {Number} [wordIndex]
+ * @param {Number} [charIndex]
+ * @return {HTMLElement}
+ */
+const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => {
+ const isLine = type === lineType;
+ const isChar = type === charType;
+ const className = `_${type}_`;
+ const template = isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate;
+ const displayStyle = isLine ? 'block' : 'inline-block';
+ $splitTemplate.innerHTML = template
+ .replace(valueRgx, `<i class="${className}"></i>`)
+ .replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`);
+ const $content = $splitTemplate.content;
+ const $highestParent = /** @type {HTMLElement} */($content.firstElementChild);
+ const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent;
+ const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`));
+ const replacablesLength = $replacables.length;
+ if (replacablesLength) {
+ $highestParent.style.display = displayStyle;
+ $split.style.display = displayStyle;
+ $split.setAttribute(dataLine, `${lineIndex}`);
+ if (!isLine) {
+ $split.setAttribute('data-word', `${wordIndex}`);
+ if (isChar) $split.setAttribute('data-char', `${charIndex}`);
+ }
+ let i = replacablesLength;
+ while (i--) {
+ const $replace = $replacables[i];
+ const $closestParent = $replace.parentElement;
+ $closestParent.style.display = displayStyle;
+ if (isLine) {
+ $closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML;
+ } else {
+ $closestParent.replaceChild(node.cloneNode(true), $replace);
+ }
+ }
+ store.push($split);
+ $parentFragment.appendChild($content);
+ } else {
+ console.warn(`The expression "{value}" is missing from the provided template.`);
+ }
+ if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`;
+ return $highestParent;
+};
+
+/**
+ * A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
+ * @class
+ */
+class TextSplitter {
+ /**
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ */
+ constructor(target, parameters = {}) {
+ // Only init segmenters when needed
+ if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : {
+ segment: (text) => {
+ const segments = [];
+ const words = text.split(whiteSpaceGroupRgx);
+ for (let i = 0, l = words.length; i < l; i++) {
+ const segment = words[i];
+ segments.push({
+ segment,
+ isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like
+ });
+ }
+ return segments;
+ }
+ };
+ if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : {
+ segment: text => [...text].map(char => ({ segment: char }))
+ };
+ if (!$splitTemplate && isBrowser) $splitTemplate = doc.createElement('template');
+ if (scope.current) scope.current.register(this);
+ const { words, chars, lines, accessible, includeSpaces, debug } = parameters;
+ const $target = /** @type {HTMLElement} */((target = isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (getNodeList(target) || [])[0]);
+ const lineParams = lines === true ? {} : lines;
+ const wordParams = words === true || isUnd(words) ? {} : words;
+ const charParams = chars === true ? {} : chars;
+ this.debug = setValue(debug, false);
+ this.includeSpaces = setValue(includeSpaces, false);
+ this.accessible = setValue(accessible, true);
+ this.linesOnly = lineParams && (!wordParams && !charParams);
+ /** @type {String|false|SplitFunctionValue} */
+ this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams;
+ /** @type {String|false|SplitFunctionValue} */
+ this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams;
+ /** @type {String|false|SplitFunctionValue} */
+ this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams;
+ this.$target = $target;
+ this.html = $target && $target.innerHTML;
+ this.lines = [];
+ this.words = [];
+ this.chars = [];
+ this.effects = [];
+ this.effectsCleanups = [];
+ this.cache = null;
+ this.ready = false;
+ this.width = 0;
+ this.resizeTimeout = null;
+ const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split();
+ // Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback
+ this.resizeObserver = new ResizeObserver(() => {
+ // Use a setTimeout instead of a Timer for better tree shaking
+ clearTimeout(this.resizeTimeout);
+ this.resizeTimeout = setTimeout(() => {
+ const currentWidth = /** @type {HTMLElement} */($target).offsetWidth;
+ if (currentWidth === this.width) return;
+ this.width = currentWidth;
+ handleSplit();
+ }, 150);
+ });
+ // Only declare the font ready promise when splitting by lines and not alreay split
+ if (this.lineTemplate && !this.ready) {
+ doc.fonts.ready.then(handleSplit);
+ } else {
+ handleSplit();
+ }
+ $target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.');
+ }
+
+ /**
+ * @param {(...args: any[]) => Tickable | (() => void)} effect
+ * @return this
+ */
+ addEffect(effect) {
+ if (!isFnc(effect)) return console.warn('Effect must return a function.');
+ const refreshableEffect = keepTime(effect);
+ this.effects.push(refreshableEffect);
+ if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this);
+ return this;
+ }
+
+ revert() {
+ clearTimeout(this.resizeTimeout);
+ this.lines.length = this.words.length = this.chars.length = 0;
+ this.resizeObserver.disconnect();
+ // Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process
+ this.effectsCleanups.forEach(cleanup => isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert());
+ this.$target.innerHTML = this.html;
+ return this;
+ }
+
+ /**
+ * Recursively processes a node and its children
+ * @param {Node} node
+ */
+ splitNode(node) {
+ const wordTemplate = this.wordTemplate;
+ const charTemplate = this.charTemplate;
+ const includeSpaces = this.includeSpaces;
+ const debug = this.debug;
+ const nodeType = node.nodeType;
+ if (nodeType === 3) {
+ const nodeText = node.nodeValue;
+ // If the nodeText is only whitespace, leave it as is
+ if (nodeText.trim()) {
+ const tempWords = [];
+ const words = this.words;
+ const chars = this.chars;
+ const wordSegments = wordSegmenter.segment(nodeText);
+ const $wordsFragment = doc.createDocumentFragment();
+ let prevSeg = null;
+ for (const wordSegment of wordSegments) {
+ const segment = wordSegment.segment;
+ const isWordLike = isSegmentWordLike(wordSegment);
+ // Determine if this segment should be a new word, first segment always becomes a new word
+ if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) {
+ tempWords.push(segment);
+ } else {
+ // Only concatenate if both current and previous are non-word-like and don't contain spaces
+ const lastWordIndex = tempWords.length - 1;
+ const lastWord = tempWords[lastWordIndex];
+ if (!lastWord.includes(' ') && !segment.includes(' ')) {
+ tempWords[lastWordIndex] += segment;
+ } else {
+ tempWords.push(segment);
+ }
+ }
+ prevSeg = wordSegment;
+ }
+
+ for (let i = 0, l = tempWords.length; i < l; i++) {
+ const word = tempWords[i];
+ if (!word.trim()) {
+ // Preserve whitespace only if includeSpaces is false and if the current space is not the first node
+ if (i && includeSpaces) continue;
+ $wordsFragment.appendChild(doc.createTextNode(word));
+ } else {
+ const nextWord = tempWords[i + 1];
+ const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim();
+ const wordToProcess = word;
+ const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null;
+ const $charsFragment = charTemplate ? doc.createDocumentFragment() : doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word);
+ if (charTemplate) {
+ const charSegmentsArray = [...charSegments];
+ for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) {
+ const charSegment = charSegmentsArray[j];
+ const isLastChar = j === jl - 1;
+ // If this is the last character and includeSpaces is true with a following space, append the space
+ const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment;
+ const $charNode = doc.createTextNode(charText);
+ processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length);
+ }
+ }
+ if (wordTemplate) {
+ processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length);
+ // Chars elements must be re-parsed in the split() method if both words and chars are parsed
+ } else if (charTemplate) {
+ $wordsFragment.appendChild($charsFragment);
+ } else {
+ $wordsFragment.appendChild(doc.createTextNode(word));
+ }
+ // Skip the next iteration if we included a space
+ if (hasWordFollowingSpace) i++;
+ }
+ }
+ node.parentNode.replaceChild($wordsFragment, node);
+ }
+ } else if (nodeType === 1) {
+ // Converting to an array is necessary to work around childNodes pottential mutation
+ const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]);
+ for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]);
+ }
+ }
+
+ /**
+ * @param {Boolean} clearCache
+ * @return {this}
+ */
+ split(clearCache = false) {
+ const $el = this.$target;
+ const isCached = !!this.cache && !clearCache;
+ const lineTemplate = this.lineTemplate;
+ const wordTemplate = this.wordTemplate;
+ const charTemplate = this.charTemplate;
+ const fontsReady = doc.fonts.status !== 'loading';
+ const canSplitLines = lineTemplate && fontsReady;
+ this.ready = !lineTemplate || fontsReady;
+ if (canSplitLines || clearCache) {
+ // No need to revert effects animations here since it's already taken care by the refreshable
+ this.effectsCleanups.forEach(cleanup => isFnc(cleanup) && cleanup(this));
+ }
+ if (!isCached) {
+ if (clearCache) {
+ $el.innerHTML = this.html;
+ this.words.length = this.chars.length = 0;
+ }
+ this.splitNode($el);
+ this.cache = $el.innerHTML;
+ }
+ if (canSplitLines) {
+ if (isCached) $el.innerHTML = this.cache;
+ this.lines.length = 0;
+ if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
+ }
+ // Always reparse characters after a line reset or if both words and chars are activated
+ if (charTemplate && (canSplitLines || wordTemplate)) {
+ this.chars = getAllTopLevelElements($el, charType);
+ }
+ // Words are used when lines only and prioritized over chars
+ const elementsArray = this.words.length ? this.words : this.chars;
+ let y, linesCount = 0;
+ for (let i = 0, l = elementsArray.length; i < l; i++) {
+ const $el = elementsArray[i];
+ const { top, height } = $el.getBoundingClientRect();
+ if (y && top - y > height * .5) linesCount++;
+ $el.setAttribute(dataLine, `${linesCount}`);
+ const nested = $el.querySelectorAll(`[${dataLine}]`);
+ let c = nested.length;
+ while (c--) nested[c].setAttribute(dataLine, `${linesCount}`);
+ y = top;
+ }
+ if (canSplitLines) {
+ const linesFragment = doc.createDocumentFragment();
+ const parents = new Set();
+ const clones = [];
+ for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) {
+ const $clone = /** @type {HTMLElement} */($el.cloneNode(true));
+ filterLineElements($clone, lineIndex, new Set()).forEach($el => {
+ const $parent = $el.parentElement;
+ if ($parent) parents.add($parent);
+ $el.remove();
+ });
+ clones.push($clone);
+ }
+ parents.forEach(filterEmptyElements);
+ for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) {
+ processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex);
+ }
+ $el.innerHTML = '';
+ $el.appendChild(linesFragment);
+ if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
+ if (charTemplate) this.chars = getAllTopLevelElements($el, charType);
+ }
+ // Remove the word wrappers and clear the words array if lines split only
+ if (this.linesOnly) {
+ const words = this.words;
+ let w = words.length;
+ while (w--) {
+ const $word = words[w];
+ $word.replaceWith($word.textContent);
+ }
+ words.length = 0;
+ }
+ if (this.accessible && (canSplitLines || !isCached)) {
+ const $accessible = doc.createElement('span');
+ // Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html)
+ $accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;
+ // $accessible.setAttribute('tabindex', '-1');
+ $accessible.innerHTML = this.html;
+ $el.insertBefore($accessible, $el.firstChild);
+ this.lines.forEach(setAriaHidden);
+ this.words.forEach(setAriaHidden);
+ this.chars.forEach(setAriaHidden);
+ }
+ this.width = /** @type {HTMLElement} */($el).offsetWidth;
+ if (canSplitLines || clearCache) {
+ this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this));
+ }
+ return this;
+ }
+
+ refresh() {
+ this.split(true);
+ }
+}
+
+/**
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
+ */
+const splitText = (target, parameters) => new TextSplitter(target, parameters);
+
+/**
+ * @deprecated text.split() is deprecated, import splitText() directly, or text.splitText()
+ *
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
+ */
+const split = (target, parameters) => {
+ console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()');
+ return new TextSplitter(target, parameters);
+};
+
+export { TextSplitter, split, splitText };
diff --git a/dist/modules/timeline/index.cjs b/dist/modules/timeline/index.cjs
new file mode 100644
index 00000000..ed552676
--- /dev/null
+++ b/dist/modules/timeline/index.cjs
@@ -0,0 +1,15 @@
+/**
+ * Anime.js - timeline - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var timeline = require('./timeline.cjs');
+
+
+
+exports.Timeline = timeline.Timeline;
+exports.createTimeline = timeline.createTimeline;
diff --git a/dist/modules/timeline/index.d.ts b/dist/modules/timeline/index.d.ts
new file mode 100644
index 00000000..3587dfeb
--- /dev/null
+++ b/dist/modules/timeline/index.d.ts
@@ -0,0 +1 @@
+export * from "./timeline.js";
diff --git a/dist/modules/timeline/index.js b/dist/modules/timeline/index.js
new file mode 100644
index 00000000..c6b0352e
--- /dev/null
+++ b/dist/modules/timeline/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - timeline - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { Timeline, createTimeline } from './timeline.js';
diff --git a/dist/modules/timeline/position.cjs b/dist/modules/timeline/position.cjs
new file mode 100644
index 00000000..22550ea5
--- /dev/null
+++ b/dist/modules/timeline/position.cjs
@@ -0,0 +1,72 @@
+/**
+ * Anime.js - timeline - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var values = require('../core/values.cjs');
+
+/**
+ * @import {
+ * Tickable,
+ * TimelinePosition,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from './timeline.js'
+*/
+
+/**
+ * Timeline's children offsets positions parser
+ * @param {Timeline} timeline
+ * @param {String} timePosition
+ * @return {Number}
+ */
+const getPrevChildOffset = (timeline, timePosition) => {
+ if (helpers.stringStartsWith(timePosition, '<')) {
+ const goToPrevAnimationOffset = timePosition[1] === '<';
+ const prevAnimation = /** @type {Tickable} */(timeline._tail);
+ const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
+ return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
+ }
+};
+
+/**
+ * @param {Timeline} timeline
+ * @param {TimelinePosition} [timePosition]
+ * @return {Number}
+ */
+const parseTimelinePosition = (timeline, timePosition) => {
+ let tlDuration = timeline.iterationDuration;
+ if (tlDuration === consts.minValue) tlDuration = 0;
+ if (helpers.isUnd(timePosition)) return tlDuration;
+ if (helpers.isNum(+timePosition)) return +timePosition;
+ const timePosStr = /** @type {String} */(timePosition);
+ const tlLabels = timeline ? timeline.labels : null;
+ const hasLabels = !helpers.isNil(tlLabels);
+ const prevOffset = getPrevChildOffset(timeline, timePosStr);
+ const hasSibling = !helpers.isUnd(prevOffset);
+ const matchedRelativeOperator = consts.relativeValuesExecRgx.exec(timePosStr);
+ if (matchedRelativeOperator) {
+ const fullOperator = matchedRelativeOperator[0];
+ const split = timePosStr.split(fullOperator);
+ const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
+ const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
+ const parsedNumericalOffset = +split[1];
+ return values.getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
+ } else {
+ return hasSibling ? prevOffset :
+ hasLabels ? !helpers.isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
+ tlDuration : tlDuration;
+ }
+};
+
+exports.parseTimelinePosition = parseTimelinePosition;
diff --git a/dist/modules/timeline/position.d.ts b/dist/modules/timeline/position.d.ts
new file mode 100644
index 00000000..6b11ebbb
--- /dev/null
+++ b/dist/modules/timeline/position.d.ts
@@ -0,0 +1,3 @@
+export function parseTimelinePosition(timeline: Timeline, timePosition?: TimelinePosition): number;
+import type { Timeline } from './timeline.js';
+import type { TimelinePosition } from '../types/index.js';
diff --git a/dist/modules/timeline/position.js b/dist/modules/timeline/position.js
new file mode 100644
index 00000000..cd945d37
--- /dev/null
+++ b/dist/modules/timeline/position.js
@@ -0,0 +1,70 @@
+/**
+ * Anime.js - timeline - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { relativeValuesExecRgx, minValue } from '../core/consts.js';
+import { isUnd, isNum, stringStartsWith, isNil } from '../core/helpers.js';
+import { getRelativeValue } from '../core/values.js';
+
+/**
+ * @import {
+ * Tickable,
+ * TimelinePosition,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from './timeline.js'
+*/
+
+/**
+ * Timeline's children offsets positions parser
+ * @param {Timeline} timeline
+ * @param {String} timePosition
+ * @return {Number}
+ */
+const getPrevChildOffset = (timeline, timePosition) => {
+ if (stringStartsWith(timePosition, '<')) {
+ const goToPrevAnimationOffset = timePosition[1] === '<';
+ const prevAnimation = /** @type {Tickable} */(timeline._tail);
+ const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
+ return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
+ }
+};
+
+/**
+ * @param {Timeline} timeline
+ * @param {TimelinePosition} [timePosition]
+ * @return {Number}
+ */
+const parseTimelinePosition = (timeline, timePosition) => {
+ let tlDuration = timeline.iterationDuration;
+ if (tlDuration === minValue) tlDuration = 0;
+ if (isUnd(timePosition)) return tlDuration;
+ if (isNum(+timePosition)) return +timePosition;
+ const timePosStr = /** @type {String} */(timePosition);
+ const tlLabels = timeline ? timeline.labels : null;
+ const hasLabels = !isNil(tlLabels);
+ const prevOffset = getPrevChildOffset(timeline, timePosStr);
+ const hasSibling = !isUnd(prevOffset);
+ const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
+ if (matchedRelativeOperator) {
+ const fullOperator = matchedRelativeOperator[0];
+ const split = timePosStr.split(fullOperator);
+ const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
+ const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
+ const parsedNumericalOffset = +split[1];
+ return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
+ } else {
+ return hasSibling ? prevOffset :
+ hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
+ tlDuration : tlDuration;
+ }
+};
+
+export { parseTimelinePosition };
diff --git a/dist/modules/timeline/timeline.cjs b/dist/modules/timeline/timeline.cjs
new file mode 100644
index 00000000..fe45cb0b
--- /dev/null
+++ b/dist/modules/timeline/timeline.cjs
@@ -0,0 +1,312 @@
+/**
+ * Anime.js - timeline - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var globals = require('../core/globals.cjs');
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var values = require('../core/values.cjs');
+var targets = require('../core/targets.cjs');
+var render = require('../core/render.cjs');
+var styles = require('../core/styles.cjs');
+var composition = require('../animation/composition.cjs');
+var animation = require('../animation/animation.cjs');
+var timer = require('../timer/timer.cjs');
+var eases = require('../easings/eases.cjs');
+var position = require('./position.cjs');
+
+/**
+ * @import {
+ * TargetsParam,
+ * Callback,
+ * Tickable,
+ * TimerParams,
+ * AnimationParams,
+ * Target,
+ * Renderable,
+ * TimelineParams,
+ * DefaultsParams,
+ * TimelinePosition,
+ * StaggerFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @param {Timeline} tl
+ * @return {Number}
+ */
+function getTimelineTotalDuration(tl) {
+ return helpers.clampInfinity(((tl.iterationDuration + tl._loopDelay) * tl.iterationCount) - tl._loopDelay) || consts.minValue;
+}
+
+/**
+ * @overload
+ * @param {TimerParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @return {Timeline}
+ *
+ * @overload
+ * @param {AnimationParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @param {TargetsParam} targets
+ * @param {Number} [index]
+ * @param {Number} [length]
+ * @return {Timeline}
+ *
+ * @param {TimerParams|AnimationParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @param {TargetsParam} [targets]
+ * @param {Number} [index]
+ * @param {Number} [length]
+ */
+function addTlChild(childParams, tl, timePosition, targets, index, length) {
+ const isSetter = helpers.isNum(childParams.duration) && /** @type {Number} */(childParams.duration) <= consts.minValue;
+ // Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position
+ const adjustedPosition = isSetter ? timePosition - consts.minValue : timePosition;
+ render.tick(tl, adjustedPosition, 1, 1, consts.tickModes.AUTO);
+ const tlChild = targets ?
+ new animation.JSAnimation(targets,/** @type {AnimationParams} */(childParams), tl, adjustedPosition, false, index, length) :
+ new timer.Timer(/** @type {TimerParams} */(childParams), tl, adjustedPosition);
+ tlChild.init(1);
+ // TODO: Might be better to insert at a position relative to startTime?
+ helpers.addChild(tl, tlChild);
+ helpers.forEachChildren(tl, (/** @type {Renderable} */child) => {
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > tl.iterationDuration) tl.iterationDuration = childDur;
+ });
+ tl.duration = getTimelineTotalDuration(tl);
+ return tl;
+}
+
+class Timeline extends timer.Timer {
+
+ /**
+ * @param {TimelineParams} [parameters]
+ */
+ constructor(parameters = {}) {
+ super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0);
+ /** @type {Number} */
+ this.duration = 0; // TL duration starts at 0 and grows when adding children
+ /** @type {Record<String, Number>} */
+ this.labels = {};
+ const defaultsParams = parameters.defaults;
+ const globalDefaults = globals.globals.defaults;
+ /** @type {DefaultsParams} */
+ this.defaults = defaultsParams ? helpers.mergeObjects(defaultsParams, globalDefaults) : globalDefaults;
+ /** @type {Callback<this>} */
+ this.onRender = parameters.onRender || globalDefaults.onRender;
+ const tlPlaybackEase = values.setValue(parameters.playbackEase, globalDefaults.playbackEase);
+ this._ease = tlPlaybackEase ? eases.parseEase(tlPlaybackEase) : null;
+ /** @type {Number} */
+ this.iterationDuration = 0;
+ }
+
+ /**
+ * @overload
+ * @param {TargetsParam} a1
+ * @param {AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ * @return {this}
+ *
+ * @overload
+ * @param {TimerParams} a1
+ * @param {TimelinePosition} [a2]
+ * @return {this}
+ *
+ * @param {TargetsParam|TimerParams} a1
+ * @param {TimelinePosition|AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ */
+ add(a1, a2, a3) {
+ const isAnim = helpers.isObj(a2);
+ const isTimer = helpers.isObj(a1);
+ if (isAnim || isTimer) {
+ this._hasChildren = true;
+ if (isAnim) {
+ const childParams = /** @type {AnimationParams} */(a2);
+ // Check for function for children stagger positions
+ if (helpers.isFnc(a3)) {
+ const staggeredPosition = a3;
+ const parsedTargetsArray = targets.parseTargets(/** @type {TargetsParam} */(a1));
+ // Store initial duration before adding new children that will change the duration
+ const tlDuration = this.duration;
+ // Store initial _iterationDuration before adding new children that will change the duration
+ const tlIterationDuration = this.iterationDuration;
+ // Store the original id in order to add specific indexes to the new animations ids
+ const id = childParams.id;
+ let i = 0;
+ /** @type {Number} */
+ const parsedLength = (parsedTargetsArray.length);
+ parsedTargetsArray.forEach((/** @type {Target} */target) => {
+ // Create a new parameter object for each staggered children
+ const staggeredChildParams = { ...childParams };
+ // Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation
+ this.duration = tlDuration;
+ this.iterationDuration = tlIterationDuration;
+ if (!helpers.isUnd(id)) staggeredChildParams.id = id + '-' + i;
+ addTlChild(
+ staggeredChildParams,
+ this,
+ position.parseTimelinePosition(this, staggeredPosition(target, i, parsedLength, this)),
+ target,
+ i,
+ parsedLength
+ );
+ i++;
+ });
+ } else {
+ addTlChild(
+ childParams,
+ this,
+ position.parseTimelinePosition(this, a3),
+ /** @type {TargetsParam} */(a1),
+ );
+ }
+ } else {
+ // It's a Timer
+ addTlChild(
+ /** @type TimerParams */(a1),
+ this,
+ position.parseTimelinePosition(this,a2),
+ );
+ }
+ return this.init(1); // 1 = internalRender
+ }
+ }
+
+ /**
+ * @overload
+ * @param {Tickable} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {WAAPIAnimation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ */
+ sync(synced, position) {
+ if (helpers.isUnd(synced) || synced && helpers.isUnd(synced.pause)) return this;
+ synced.pause();
+ const duration = +(/** @type {globalThis.Animation} */(synced).effect ? /** @type {globalThis.Animation} */(synced).effect.getTiming().duration : /** @type {Tickable} */(synced).duration);
+ return this.add(synced, { currentTime: [0, duration], duration, ease: 'linear' }, position);
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ set(targets, parameters, position) {
+ if (helpers.isUnd(parameters)) return this;
+ parameters.duration = consts.minValue;
+ parameters.composition = consts.compositionTypes.replace;
+ return this.add(targets, parameters, position);
+ }
+
+ /**
+ * @param {Callback<Timer>} callback
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ call(callback, position) {
+ if (helpers.isUnd(callback) || callback && !helpers.isFnc(callback)) return this;
+ return this.add({ duration: 0, onComplete: () => callback(this) }, position);
+ }
+
+ /**
+ * @param {String} labelName
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ */
+ label(labelName, position$1) {
+ if (helpers.isUnd(labelName) || labelName && !helpers.isStr(labelName)) return this;
+ this.labels[labelName] = position.parseTimelinePosition(this, position$1);
+ return this;
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {String} [propertyName]
+ * @return {this}
+ */
+ remove(targets$1, propertyName) {
+ composition.removeTargetsFromRenderable(targets.parseTargets(targets$1), this, propertyName);
+ return this;
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ if (currentDuration === helpers.normalizeTime(newDuration)) return this;
+ const timeScale = newDuration / currentDuration;
+ const labels = this.labels;
+ helpers.forEachChildren(this, (/** @type {JSAnimation} */child) => child.stretch(child.duration * timeScale));
+ for (let labelName in labels) labels[labelName] *= timeScale;
+ return super.stretch(newDuration);
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ helpers.forEachChildren(this, (/** @type {JSAnimation} */child) => {
+ if (child.refresh) child.refresh();
+ });
+ return this;
+ }
+
+ /**
+ * @return {this}
+ */
+ revert() {
+ super.revert();
+ helpers.forEachChildren(this, (/** @type {JSAnimation} */child) => child.revert, true);
+ return styles.cleanInlineStyles(this);
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback) {
+ return super.then(callback);
+ }
+}
+
+/**
+ * @param {TimelineParams} [parameters]
+ * @return {Timeline}
+ */
+const createTimeline = parameters => new Timeline(parameters).init();
+
+exports.Timeline = Timeline;
+exports.createTimeline = createTimeline;
diff --git a/dist/modules/timeline/timeline.d.ts b/dist/modules/timeline/timeline.d.ts
new file mode 100644
index 00000000..e633a01e
--- /dev/null
+++ b/dist/modules/timeline/timeline.d.ts
@@ -0,0 +1,163 @@
+export class Timeline extends Timer {
+ /**
+ * @param {TimelineParams} [parameters]
+ */
+ constructor(parameters?: TimelineParams);
+ /** @type {Record<String, Number>} */
+ labels: Record<string, number>;
+ /** @type {DefaultsParams} */
+ defaults: DefaultsParams;
+ /** @type {Callback<this>} */
+ onRender: Callback<this>;
+ _ease: import("../types/index.js").EasingFunction;
+ /**
+ * @overload
+ * @param {TargetsParam} a1
+ * @param {AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ * @return {this}
+ *
+ * @overload
+ * @param {TimerParams} a1
+ * @param {TimelinePosition} [a2]
+ * @return {this}
+ *
+ * @param {TargetsParam|TimerParams} a1
+ * @param {TimelinePosition|AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ */
+ add(a1: TargetsParam, a2: AnimationParams, a3?: TimelinePosition | StaggerFunction<number | string>): this;
+ /**
+ * @overload
+ * @param {TargetsParam} a1
+ * @param {AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ * @return {this}
+ *
+ * @overload
+ * @param {TimerParams} a1
+ * @param {TimelinePosition} [a2]
+ * @return {this}
+ *
+ * @param {TargetsParam|TimerParams} a1
+ * @param {TimelinePosition|AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ */
+ add(a1: TimerParams, a2?: TimelinePosition): this;
+ /**
+ * @overload
+ * @param {Tickable} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {WAAPIAnimation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ */
+ sync(synced?: Tickable, position?: TimelinePosition): this;
+ /**
+ * @overload
+ * @param {Tickable} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {WAAPIAnimation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ */
+ sync(synced?: globalThis.Animation, position?: TimelinePosition): this;
+ /**
+ * @overload
+ * @param {Tickable} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {WAAPIAnimation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ */
+ sync(synced?: WAAPIAnimation, position?: TimelinePosition): this;
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ set(targets: TargetsParam, parameters: AnimationParams, position?: TimelinePosition): this;
+ /**
+ * @param {Callback<Timer>} callback
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ call(callback: Callback<Timer>, position?: TimelinePosition): this;
+ /**
+ * @param {String} labelName
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ */
+ label(labelName: string, position?: TimelinePosition): this;
+ /**
+ * @param {TargetsParam} targets
+ * @param {String} [propertyName]
+ * @return {this}
+ */
+ remove(targets: TargetsParam, propertyName?: string): this;
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration: number): this;
+ /**
+ * @return {this}
+ */
+ refresh(): this;
+ /**
+ * @return {this}
+ */
+ revert(): this;
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback?: Callback<this>): Promise<any>;
+}
+export function createTimeline(parameters?: TimelineParams): Timeline;
+import { Timer } from '../timer/timer.js';
+import type { DefaultsParams } from '../types/index.js';
+import type { Callback } from '../types/index.js';
+import type { TargetsParam } from '../types/index.js';
+import type { AnimationParams } from '../types/index.js';
+import type { TimelinePosition } from '../types/index.js';
+import type { StaggerFunction } from '../types/index.js';
+import type { TimerParams } from '../types/index.js';
+import type { Tickable } from '../types/index.js';
+import type { WAAPIAnimation } from '../waapi/waapi.js';
+import type { TimelineParams } from '../types/index.js';
diff --git a/dist/modules/timeline/timeline.js b/dist/modules/timeline/timeline.js
new file mode 100644
index 00000000..5357eadd
--- /dev/null
+++ b/dist/modules/timeline/timeline.js
@@ -0,0 +1,309 @@
+/**
+ * Anime.js - timeline - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { globals } from '../core/globals.js';
+import { minValue, compositionTypes, tickModes } from '../core/consts.js';
+import { mergeObjects, isObj, isFnc, isUnd, isStr, normalizeTime, forEachChildren, isNum, addChild, clampInfinity } from '../core/helpers.js';
+import { setValue } from '../core/values.js';
+import { parseTargets } from '../core/targets.js';
+import { tick } from '../core/render.js';
+import { cleanInlineStyles } from '../core/styles.js';
+import { removeTargetsFromRenderable } from '../animation/composition.js';
+import { JSAnimation } from '../animation/animation.js';
+import { Timer } from '../timer/timer.js';
+import { parseEase } from '../easings/eases.js';
+import { parseTimelinePosition } from './position.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * Callback,
+ * Tickable,
+ * TimerParams,
+ * AnimationParams,
+ * Target,
+ * Renderable,
+ * TimelineParams,
+ * DefaultsParams,
+ * TimelinePosition,
+ * StaggerFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @param {Timeline} tl
+ * @return {Number}
+ */
+function getTimelineTotalDuration(tl) {
+ return clampInfinity(((tl.iterationDuration + tl._loopDelay) * tl.iterationCount) - tl._loopDelay) || minValue;
+}
+
+/**
+ * @overload
+ * @param {TimerParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @return {Timeline}
+ *
+ * @overload
+ * @param {AnimationParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @param {TargetsParam} targets
+ * @param {Number} [index]
+ * @param {Number} [length]
+ * @return {Timeline}
+ *
+ * @param {TimerParams|AnimationParams} childParams
+ * @param {Timeline} tl
+ * @param {Number} timePosition
+ * @param {TargetsParam} [targets]
+ * @param {Number} [index]
+ * @param {Number} [length]
+ */
+function addTlChild(childParams, tl, timePosition, targets, index, length) {
+ const isSetter = isNum(childParams.duration) && /** @type {Number} */(childParams.duration) <= minValue;
+ // Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position
+ const adjustedPosition = isSetter ? timePosition - minValue : timePosition;
+ tick(tl, adjustedPosition, 1, 1, tickModes.AUTO);
+ const tlChild = targets ?
+ new JSAnimation(targets,/** @type {AnimationParams} */(childParams), tl, adjustedPosition, false, index, length) :
+ new Timer(/** @type {TimerParams} */(childParams), tl, adjustedPosition);
+ tlChild.init(1);
+ // TODO: Might be better to insert at a position relative to startTime?
+ addChild(tl, tlChild);
+ forEachChildren(tl, (/** @type {Renderable} */child) => {
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > tl.iterationDuration) tl.iterationDuration = childDur;
+ });
+ tl.duration = getTimelineTotalDuration(tl);
+ return tl;
+}
+
+class Timeline extends Timer {
+
+ /**
+ * @param {TimelineParams} [parameters]
+ */
+ constructor(parameters = {}) {
+ super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0);
+ /** @type {Number} */
+ this.duration = 0; // TL duration starts at 0 and grows when adding children
+ /** @type {Record<String, Number>} */
+ this.labels = {};
+ const defaultsParams = parameters.defaults;
+ const globalDefaults = globals.defaults;
+ /** @type {DefaultsParams} */
+ this.defaults = defaultsParams ? mergeObjects(defaultsParams, globalDefaults) : globalDefaults;
+ /** @type {Callback<this>} */
+ this.onRender = parameters.onRender || globalDefaults.onRender;
+ const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase);
+ this._ease = tlPlaybackEase ? parseEase(tlPlaybackEase) : null;
+ /** @type {Number} */
+ this.iterationDuration = 0;
+ }
+
+ /**
+ * @overload
+ * @param {TargetsParam} a1
+ * @param {AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ * @return {this}
+ *
+ * @overload
+ * @param {TimerParams} a1
+ * @param {TimelinePosition} [a2]
+ * @return {this}
+ *
+ * @param {TargetsParam|TimerParams} a1
+ * @param {TimelinePosition|AnimationParams} a2
+ * @param {TimelinePosition|StaggerFunction<Number|String>} [a3]
+ */
+ add(a1, a2, a3) {
+ const isAnim = isObj(a2);
+ const isTimer = isObj(a1);
+ if (isAnim || isTimer) {
+ this._hasChildren = true;
+ if (isAnim) {
+ const childParams = /** @type {AnimationParams} */(a2);
+ // Check for function for children stagger positions
+ if (isFnc(a3)) {
+ const staggeredPosition = a3;
+ const parsedTargetsArray = parseTargets(/** @type {TargetsParam} */(a1));
+ // Store initial duration before adding new children that will change the duration
+ const tlDuration = this.duration;
+ // Store initial _iterationDuration before adding new children that will change the duration
+ const tlIterationDuration = this.iterationDuration;
+ // Store the original id in order to add specific indexes to the new animations ids
+ const id = childParams.id;
+ let i = 0;
+ /** @type {Number} */
+ const parsedLength = (parsedTargetsArray.length);
+ parsedTargetsArray.forEach((/** @type {Target} */target) => {
+ // Create a new parameter object for each staggered children
+ const staggeredChildParams = { ...childParams };
+ // Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation
+ this.duration = tlDuration;
+ this.iterationDuration = tlIterationDuration;
+ if (!isUnd(id)) staggeredChildParams.id = id + '-' + i;
+ addTlChild(
+ staggeredChildParams,
+ this,
+ parseTimelinePosition(this, staggeredPosition(target, i, parsedLength, this)),
+ target,
+ i,
+ parsedLength
+ );
+ i++;
+ });
+ } else {
+ addTlChild(
+ childParams,
+ this,
+ parseTimelinePosition(this, a3),
+ /** @type {TargetsParam} */(a1),
+ );
+ }
+ } else {
+ // It's a Timer
+ addTlChild(
+ /** @type TimerParams */(a1),
+ this,
+ parseTimelinePosition(this,a2),
+ );
+ }
+ return this.init(1); // 1 = internalRender
+ }
+ }
+
+ /**
+ * @overload
+ * @param {Tickable} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @overload
+ * @param {WAAPIAnimation} [synced]
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
+ * @param {TimelinePosition} [position]
+ */
+ sync(synced, position) {
+ if (isUnd(synced) || synced && isUnd(synced.pause)) return this;
+ synced.pause();
+ const duration = +(/** @type {globalThis.Animation} */(synced).effect ? /** @type {globalThis.Animation} */(synced).effect.getTiming().duration : /** @type {Tickable} */(synced).duration);
+ return this.add(synced, { currentTime: [0, duration], duration, ease: 'linear' }, position);
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ set(targets, parameters, position) {
+ if (isUnd(parameters)) return this;
+ parameters.duration = minValue;
+ parameters.composition = compositionTypes.replace;
+ return this.add(targets, parameters, position);
+ }
+
+ /**
+ * @param {Callback<Timer>} callback
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ */
+ call(callback, position) {
+ if (isUnd(callback) || callback && !isFnc(callback)) return this;
+ return this.add({ duration: 0, onComplete: () => callback(this) }, position);
+ }
+
+ /**
+ * @param {String} labelName
+ * @param {TimelinePosition} [position]
+ * @return {this}
+ *
+ */
+ label(labelName, position) {
+ if (isUnd(labelName) || labelName && !isStr(labelName)) return this;
+ this.labels[labelName] = parseTimelinePosition(this, position);
+ return this;
+ }
+
+ /**
+ * @param {TargetsParam} targets
+ * @param {String} [propertyName]
+ * @return {this}
+ */
+ remove(targets, propertyName) {
+ removeTargetsFromRenderable(parseTargets(targets), this, propertyName);
+ return this;
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ if (currentDuration === normalizeTime(newDuration)) return this;
+ const timeScale = newDuration / currentDuration;
+ const labels = this.labels;
+ forEachChildren(this, (/** @type {JSAnimation} */child) => child.stretch(child.duration * timeScale));
+ for (let labelName in labels) labels[labelName] *= timeScale;
+ return super.stretch(newDuration);
+ }
+
+ /**
+ * @return {this}
+ */
+ refresh() {
+ forEachChildren(this, (/** @type {JSAnimation} */child) => {
+ if (child.refresh) child.refresh();
+ });
+ return this;
+ }
+
+ /**
+ * @return {this}
+ */
+ revert() {
+ super.revert();
+ forEachChildren(this, (/** @type {JSAnimation} */child) => child.revert, true);
+ return cleanInlineStyles(this);
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback) {
+ return super.then(callback);
+ }
+}
+
+/**
+ * @param {TimelineParams} [parameters]
+ * @return {Timeline}
+ */
+const createTimeline = parameters => new Timeline(parameters).init();
+
+export { Timeline, createTimeline };
diff --git a/dist/modules/timer/index.cjs b/dist/modules/timer/index.cjs
new file mode 100644
index 00000000..4da67804
--- /dev/null
+++ b/dist/modules/timer/index.cjs
@@ -0,0 +1,15 @@
+/**
+ * Anime.js - timer - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var timer = require('./timer.cjs');
+
+
+
+exports.Timer = timer.Timer;
+exports.createTimer = timer.createTimer;
diff --git a/dist/modules/timer/index.d.ts b/dist/modules/timer/index.d.ts
new file mode 100644
index 00000000..92a825a7
--- /dev/null
+++ b/dist/modules/timer/index.d.ts
@@ -0,0 +1 @@
+export * from "./timer.js";
diff --git a/dist/modules/timer/index.js b/dist/modules/timer/index.js
new file mode 100644
index 00000000..3735ca7f
--- /dev/null
+++ b/dist/modules/timer/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - timer - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { Timer, createTimer } from './timer.js';
diff --git a/dist/modules/timer/timer.cjs b/dist/modules/timer/timer.cjs
new file mode 100644
index 00000000..ad03bede
--- /dev/null
+++ b/dist/modules/timer/timer.cjs
@@ -0,0 +1,491 @@
+/**
+ * Anime.js - timer - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var globals = require('../core/globals.cjs');
+var values = require('../core/values.cjs');
+var render = require('../core/render.cjs');
+var composition = require('../animation/composition.cjs');
+var clock = require('../core/clock.cjs');
+var engine = require('../engine/engine.cjs');
+
+/**
+ * @import {
+ * Callback,
+ * TimerParams,
+ * Renderable,
+ * Tween,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * ScrollObserver,
+ * } from '../events/scroll.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
+
+/**
+ * @param {Timer} timer
+ * @return {Timer}
+ */
+const resetTimerProperties = timer => {
+ timer.paused = true;
+ timer.began = false;
+ timer.completed = false;
+ return timer;
+};
+
+/**
+ * @param {Timer} timer
+ * @return {Timer}
+ */
+const reviveTimer = timer => {
+ if (!timer._cancelled) return timer;
+ if (timer._hasChildren) {
+ helpers.forEachChildren(timer, reviveTimer);
+ } else {
+ helpers.forEachChildren(timer, (/** @type {Tween} tween*/tween) => {
+ if (tween._composition !== consts.compositionTypes.none) {
+ composition.composeTween(tween, composition.getTweenSiblings(tween.target, tween.property));
+ }
+ });
+ }
+ timer._cancelled = 0;
+ return timer;
+};
+
+let timerId = 0;
+
+/**
+ * Base class used to create Timers, Animations and Timelines
+ */
+class Timer extends clock.Clock {
+ /**
+ * @param {TimerParams} [parameters]
+ * @param {Timeline} [parent]
+ * @param {Number} [parentPosition]
+ */
+ constructor(parameters = {}, parent = null, parentPosition = 0) {
+
+ super(0);
+
+ const {
+ id,
+ delay,
+ duration,
+ reversed,
+ alternate,
+ loop,
+ loopDelay,
+ autoplay,
+ frameRate,
+ playbackRate,
+ onComplete,
+ onLoop,
+ onPause,
+ onBegin,
+ onBeforeUpdate,
+ onUpdate,
+ } = parameters;
+
+ if (globals.scope.current) globals.scope.current.register(this);
+
+ const timerInitTime = parent ? 0 : engine.engine._elapsedTime;
+ const timerDefaults = parent ? parent.defaults : globals.globals.defaults;
+ const timerDelay = /** @type {Number} */(helpers.isFnc(delay) || helpers.isUnd(delay) ? timerDefaults.delay : +delay);
+ const timerDuration = helpers.isFnc(duration) || helpers.isUnd(duration) ? Infinity : +duration;
+ const timerLoop = values.setValue(loop, timerDefaults.loop);
+ const timerLoopDelay = values.setValue(loopDelay, timerDefaults.loopDelay);
+ const timerIterationCount = timerLoop === true ||
+ timerLoop === Infinity ||
+ /** @type {Number} */(timerLoop) < 0 ? Infinity :
+ /** @type {Number} */(timerLoop) + 1;
+
+
+ let offsetPosition = 0;
+
+ if (parent) {
+ offsetPosition = parentPosition;
+ } else {
+ // Make sure to tick the engine once if not currently running to get up to date engine._elapsedTime
+ // to avoid big gaps with the following offsetPosition calculation
+ if (!engine.engine.reqId) engine.engine.requestTick(helpers.now());
+ // Make sure to scale the offset position with globals.timeScale to properly handle seconds unit
+ offsetPosition = (engine.engine._elapsedTime - engine.engine._startTime) * globals.globals.timeScale;
+ }
+
+ // Timer's parameters
+ this.id = !helpers.isUnd(id) ? id : ++timerId;
+ /** @type {Timeline} */
+ this.parent = parent;
+ // Total duration of the timer
+ this.duration = helpers.clampInfinity(((timerDuration + timerLoopDelay) * timerIterationCount) - timerLoopDelay) || consts.minValue;
+ /** @type {Boolean} */
+ this.backwards = false;
+ /** @type {Boolean} */
+ this.paused = true;
+ /** @type {Boolean} */
+ this.began = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Callback<this>} */
+ this.onBegin = onBegin || timerDefaults.onBegin;
+ /** @type {Callback<this>} */
+ this.onBeforeUpdate = onBeforeUpdate || timerDefaults.onBeforeUpdate;
+ /** @type {Callback<this>} */
+ this.onUpdate = onUpdate || timerDefaults.onUpdate;
+ /** @type {Callback<this>} */
+ this.onLoop = onLoop || timerDefaults.onLoop;
+ /** @type {Callback<this>} */
+ this.onPause = onPause || timerDefaults.onPause;
+ /** @type {Callback<this>} */
+ this.onComplete = onComplete || timerDefaults.onComplete;
+ /** @type {Number} */
+ this.iterationDuration = timerDuration; // Duration of one loop
+ /** @type {Number} */
+ this.iterationCount = timerIterationCount; // Number of loops
+ /** @type {Boolean|ScrollObserver} */
+ this._autoplay = parent ? false : values.setValue(autoplay, timerDefaults.autoplay);
+ /** @type {Number} */
+ this._offset = offsetPosition;
+ /** @type {Number} */
+ this._delay = timerDelay;
+ /** @type {Number} */
+ this._loopDelay = timerLoopDelay;
+ /** @type {Number} */
+ this._iterationTime = 0;
+ /** @type {Number} */
+ this._currentIteration = 0; // Current loop index
+ /** @type {Function} */
+ this._resolve = consts.noop; // Used by .then()
+ /** @type {Boolean} */
+ this._running = false;
+ /** @type {Number} */
+ this._reversed = +values.setValue(reversed, timerDefaults.reversed);
+ /** @type {Number} */
+ this._reverse = this._reversed;
+ /** @type {Number} */
+ this._cancelled = 0;
+ /** @type {Boolean} */
+ this._alternate = values.setValue(alternate, timerDefaults.alternate);
+ /** @type {Renderable} */
+ this._prev = null;
+ /** @type {Renderable} */
+ this._next = null;
+
+ // Clock's parameters
+ /** @type {Number} */
+ this._elapsedTime = timerInitTime;
+ /** @type {Number} */
+ this._startTime = timerInitTime;
+ /** @type {Number} */
+ this._lastTime = timerInitTime;
+ /** @type {Number} */
+ this._fps = values.setValue(frameRate, timerDefaults.frameRate);
+ /** @type {Number} */
+ this._speed = values.setValue(playbackRate, timerDefaults.playbackRate);
+ }
+
+ get cancelled() {
+ return !!this._cancelled;
+ }
+
+ set cancelled(cancelled) {
+ cancelled ? this.cancel() : this.reset(1).play();
+ }
+
+ get currentTime() {
+ return helpers.clamp(helpers.round(this._currentTime, globals.globals.precision), -this._delay, this.duration);
+ }
+
+ set currentTime(time) {
+ const paused = this.paused;
+ // Pausing the timer is necessary to avoid time jumps on a running instance
+ this.pause().seek(+time);
+ if (!paused) this.resume();
+ }
+
+ get iterationCurrentTime() {
+ return helpers.round(this._iterationTime, globals.globals.precision);
+ }
+
+ set iterationCurrentTime(time) {
+ this.currentTime = (this.iterationDuration * this._currentIteration) + time;
+ }
+
+ get progress() {
+ return helpers.clamp(helpers.round(this._currentTime / this.duration, 10), 0, 1);
+ }
+
+ set progress(progress) {
+ this.currentTime = this.duration * progress;
+ }
+
+ get iterationProgress() {
+ return helpers.clamp(helpers.round(this._iterationTime / this.iterationDuration, 10), 0, 1);
+ }
+
+ set iterationProgress(progress) {
+ const iterationDuration = this.iterationDuration;
+ this.currentTime = (iterationDuration * this._currentIteration) + (iterationDuration * progress);
+ }
+
+ get currentIteration() {
+ return this._currentIteration;
+ }
+
+ set currentIteration(iterationCount) {
+ this.currentTime = (this.iterationDuration * helpers.clamp(+iterationCount, 0, this.iterationCount - 1));
+ }
+
+ get reversed() {
+ return !!this._reversed;
+ }
+
+ set reversed(reverse) {
+ reverse ? this.reverse() : this.play();
+ }
+
+ get speed() {
+ return super.speed;
+ }
+
+ set speed(playbackRate) {
+ super.speed = playbackRate;
+ this.resetTime();
+ }
+
+ /**
+ * @param {Number} internalRender
+ * @return {this}
+ */
+ reset(internalRender = 0) {
+ // If cancelled, revive the timer before rendering in order to have propertly composed tweens siblings
+ reviveTimer(this);
+ if (this._reversed && !this._reverse) this.reversed = false;
+ // Rendering before updating the completed flag to prevent skips and to make sure the properties are not overridden
+ // Setting the iterationTime at the end to force the rendering to happend backwards, otherwise calling .reset() on Timelines might not render children in the right order
+ // NOTE: This is only required for Timelines and might be better to move to the Timeline class?
+ this._iterationTime = this.iterationDuration;
+ // Set tickMode to tickModes.FORCE to force rendering
+ render.tick(this, 0, 1, internalRender, consts.tickModes.FORCE);
+ // Reset timer properties after revive / render to make sure the props are not updated again
+ resetTimerProperties(this);
+ // Also reset children properties
+ if (this._hasChildren) {
+ helpers.forEachChildren(this, resetTimerProperties);
+ }
+ return this;
+ }
+
+ /**
+ * @param {Number} internalRender
+ * @return {this}
+ */
+ init(internalRender = 0) {
+ this.fps = this._fps;
+ this.speed = this._speed;
+ // Manually calling .init() on timelines should render all children intial state
+ // Forces all children to render once then render to 0 when reseted
+ if (!internalRender && this._hasChildren) {
+ render.tick(this, this.duration, 1, internalRender, consts.tickModes.FORCE);
+ }
+ this.reset(internalRender);
+ // Make sure to set autoplay to false to child timers so it doesn't attempt to autoplay / link
+ const autoplay = this._autoplay;
+ if (autoplay === true) {
+ this.resume();
+ } else if (autoplay && !helpers.isUnd(/** @type {ScrollObserver} */(autoplay).linked)) {
+ /** @type {ScrollObserver} */(autoplay).link(this);
+ }
+ return this;
+ }
+
+ /** @return {this} */
+ resetTime() {
+ const timeScale = 1 / (this._speed * engine.engine._speed);
+ // TODO: See if we can safely use engine._elapsedTime here
+ // if (!engine.reqId) engine.requestTick(now())
+ // this._startTime = engine._elapsedTime - (this._currentTime + this._delay) * timeScale;
+ this._startTime = helpers.now() - (this._currentTime + this._delay) * timeScale;
+ return this;
+ }
+
+ /** @return {this} */
+ pause() {
+ if (this.paused) return this;
+ this.paused = true;
+ this.onPause(this);
+ return this;
+ }
+
+ /** @return {this} */
+ resume() {
+ if (!this.paused) return this;
+ this.paused = false;
+ // We can safely imediatly render a timer that has no duration and no children
+ if (this.duration <= consts.minValue && !this._hasChildren) {
+ render.tick(this, consts.minValue, 0, 0, consts.tickModes.FORCE);
+ } else {
+ if (!this._running) {
+ helpers.addChild(engine.engine, this);
+ engine.engine._hasChildren = true;
+ this._running = true;
+ }
+ this.resetTime();
+ // Forces the timer to advance by at least one frame when the next tick occurs
+ this._startTime -= 12;
+ engine.engine.wake();
+ }
+ return this;
+ }
+
+ /** @return {this} */
+ restart() {
+ return this.reset(0).resume();
+ }
+
+ /**
+ * @param {Number} time
+ * @param {Boolean|Number} [muteCallbacks]
+ * @param {Boolean|Number} [internalRender]
+ * @return {this}
+ */
+ seek(time, muteCallbacks = 0, internalRender = 0) {
+ // Recompose the tween siblings in case the timer has been cancelled
+ reviveTimer(this);
+ // If you seek a completed animation, otherwise the next play will starts at 0
+ this.completed = false;
+ const isPaused = this.paused;
+ this.paused = true;
+ // timer, time, muteCallbacks, internalRender, tickMode
+ render.tick(this, time + this._delay, ~~muteCallbacks, ~~internalRender, consts.tickModes.AUTO);
+ return isPaused ? this : this.resume();
+ }
+
+ /** @return {this} */
+ alternate() {
+ const reversed = this._reversed;
+ const count = this.iterationCount;
+ const duration = this.iterationDuration;
+ // Calculate the maximum iterations possible given the iteration duration
+ const iterations = count === Infinity ? helpers.floor(consts.maxValue / duration) : count;
+ this._reversed = +(this._alternate && !(iterations % 2) ? reversed : !reversed);
+ if (count === Infinity) {
+ // Handle infinite loops to loop on themself
+ this.iterationProgress = this._reversed ? 1 - this.iterationProgress : this.iterationProgress;
+ } else {
+ this.seek((duration * iterations) - this._currentTime);
+ }
+ this.resetTime();
+ return this;
+ }
+
+ /** @return {this} */
+ play() {
+ if (this._reversed) this.alternate();
+ return this.resume();
+ }
+
+ /** @return {this} */
+ reverse() {
+ if (!this._reversed) this.alternate();
+ return this.resume();
+ }
+
+ // TODO: Move all the animation / tweens / children related code to Animation / Timeline
+
+ /** @return {this} */
+ cancel() {
+ if (this._hasChildren) {
+ helpers.forEachChildren(this, (/** @type {Renderable} */child) => child.cancel(), true);
+ } else {
+ helpers.forEachChildren(this, composition.removeTweenSliblings);
+ }
+ this._cancelled = 1;
+ // Pausing the timer removes it from the engine
+ return this.pause();
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ const normlizedDuration = helpers.normalizeTime(newDuration);
+ if (currentDuration === normlizedDuration) return this;
+ const timeScale = newDuration / currentDuration;
+ const isSetter = newDuration <= consts.minValue;
+ this.duration = isSetter ? consts.minValue : normlizedDuration;
+ this.iterationDuration = isSetter ? consts.minValue : helpers.normalizeTime(this.iterationDuration * timeScale);
+ this._offset *= timeScale;
+ this._delay *= timeScale;
+ this._loopDelay *= timeScale;
+ return this;
+ }
+
+ /**
+ * Cancels the timer by seeking it back to 0 and reverting the attached scroller if necessary
+ * @return {this}
+ */
+ revert() {
+ render.tick(this, 0, 1, 0, consts.tickModes.AUTO);
+ const ap = /** @type {ScrollObserver} */(this._autoplay);
+ if (ap && ap.linked && ap.linked === this) ap.revert();
+ return this.cancel();
+ }
+
+ /**
+ * Imediatly completes the timer, cancels it and triggers the onComplete callback
+ * @return {this}
+ */
+ complete() {
+ return this.seek(this.duration).cancel();
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback = consts.noop) {
+ const then = this.then;
+ const onResolve = () => {
+ // this.then = null prevents infinite recursion if returned by an async function
+ // https://github.com/juliangarnierorg/anime-beta/issues/26
+ this.then = null;
+ callback(this);
+ this.then = then;
+ this._resolve = consts.noop;
+ };
+ return new Promise(r => {
+ this._resolve = () => r(onResolve());
+ // Make sure to resolve imediatly if the timer has already completed
+ if (this.completed) this._resolve();
+ return this;
+ });
+ }
+
+}
+
+/**
+ * @param {TimerParams} [parameters]
+ * @return {Timer}
+ */
+const createTimer = parameters => new Timer(parameters, null, 0).init();
+
+exports.Timer = Timer;
+exports.createTimer = createTimer;
diff --git a/dist/modules/timer/timer.d.ts b/dist/modules/timer/timer.d.ts
new file mode 100644
index 00000000..6d188ad9
--- /dev/null
+++ b/dist/modules/timer/timer.d.ts
@@ -0,0 +1,141 @@
+/**
+ * Base class used to create Timers, Animations and Timelines
+ */
+export class Timer extends Clock {
+ /**
+ * @param {TimerParams} [parameters]
+ * @param {Timeline} [parent]
+ * @param {Number} [parentPosition]
+ */
+ constructor(parameters?: TimerParams, parent?: Timeline, parentPosition?: number);
+ id: string | number;
+ /** @type {Timeline} */
+ parent: Timeline;
+ duration: number;
+ /** @type {Boolean} */
+ backwards: boolean;
+ /** @type {Boolean} */
+ paused: boolean;
+ /** @type {Boolean} */
+ began: boolean;
+ /** @type {Boolean} */
+ completed: boolean;
+ /** @type {Callback<this>} */
+ onBegin: Callback<this>;
+ /** @type {Callback<this>} */
+ onBeforeUpdate: Callback<this>;
+ /** @type {Callback<this>} */
+ onUpdate: Callback<this>;
+ /** @type {Callback<this>} */
+ onLoop: Callback<this>;
+ /** @type {Callback<this>} */
+ onPause: Callback<this>;
+ /** @type {Callback<this>} */
+ onComplete: Callback<this>;
+ /** @type {Number} */
+ iterationDuration: number;
+ /** @type {Number} */
+ iterationCount: number;
+ /** @type {Boolean|ScrollObserver} */
+ _autoplay: boolean | ScrollObserver;
+ /** @type {Number} */
+ _offset: number;
+ /** @type {Number} */
+ _delay: number;
+ /** @type {Number} */
+ _loopDelay: number;
+ /** @type {Number} */
+ _iterationTime: number;
+ /** @type {Number} */
+ _currentIteration: number;
+ /** @type {Function} */
+ _resolve: Function;
+ /** @type {Boolean} */
+ _running: boolean;
+ /** @type {Number} */
+ _reversed: number;
+ /** @type {Number} */
+ _reverse: number;
+ /** @type {Number} */
+ _cancelled: number;
+ /** @type {Boolean} */
+ _alternate: boolean;
+ /** @type {Renderable} */
+ _prev: Renderable;
+ /** @type {Renderable} */
+ _next: Renderable;
+ set cancelled(cancelled: boolean);
+ get cancelled(): boolean;
+ set currentTime(time: number);
+ get currentTime(): number;
+ set iterationCurrentTime(time: number);
+ get iterationCurrentTime(): number;
+ set progress(progress: number);
+ get progress(): number;
+ set iterationProgress(progress: number);
+ get iterationProgress(): number;
+ set currentIteration(iterationCount: number);
+ get currentIteration(): number;
+ set reversed(reverse: boolean);
+ get reversed(): boolean;
+ /**
+ * @param {Number} internalRender
+ * @return {this}
+ */
+ reset(internalRender?: number): this;
+ /**
+ * @param {Number} internalRender
+ * @return {this}
+ */
+ init(internalRender?: number): this;
+ /** @return {this} */
+ resetTime(): this;
+ /** @return {this} */
+ pause(): this;
+ /** @return {this} */
+ resume(): this;
+ /** @return {this} */
+ restart(): this;
+ /**
+ * @param {Number} time
+ * @param {Boolean|Number} [muteCallbacks]
+ * @param {Boolean|Number} [internalRender]
+ * @return {this}
+ */
+ seek(time: number, muteCallbacks?: boolean | number, internalRender?: boolean | number): this;
+ /** @return {this} */
+ alternate(): this;
+ /** @return {this} */
+ play(): this;
+ /** @return {this} */
+ reverse(): this;
+ /** @return {this} */
+ cancel(): this;
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration: number): this;
+ /**
+ * Cancels the timer by seeking it back to 0 and reverting the attached scroller if necessary
+ * @return {this}
+ */
+ revert(): this;
+ /**
+ * Imediatly completes the timer, cancels it and triggers the onComplete callback
+ * @return {this}
+ */
+ complete(): this;
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback?: Callback<this>): Promise<any>;
+}
+export function createTimer(parameters?: TimerParams): Timer;
+import { Clock } from '../core/clock.js';
+import type { Timeline } from '../timeline/timeline.js';
+import type { Callback } from '../types/index.js';
+import type { ScrollObserver } from '../events/scroll.js';
+import type { Renderable } from '../types/index.js';
+import type { TimerParams } from '../types/index.js';
diff --git a/dist/modules/timer/timer.js b/dist/modules/timer/timer.js
new file mode 100644
index 00000000..13910d56
--- /dev/null
+++ b/dist/modules/timer/timer.js
@@ -0,0 +1,488 @@
+/**
+ * Anime.js - timer - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { minValue, noop, maxValue, compositionTypes, tickModes } from '../core/consts.js';
+import { isFnc, isUnd, now, clampInfinity, clamp, round, forEachChildren, addChild, normalizeTime, floor } from '../core/helpers.js';
+import { globals, scope } from '../core/globals.js';
+import { setValue } from '../core/values.js';
+import { tick } from '../core/render.js';
+import { removeTweenSliblings, composeTween, getTweenSiblings } from '../animation/composition.js';
+import { Clock } from '../core/clock.js';
+import { engine } from '../engine/engine.js';
+
+/**
+ * @import {
+ * Callback,
+ * TimerParams,
+ * Renderable,
+ * Tween,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * ScrollObserver,
+ * } from '../events/scroll.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
+
+/**
+ * @param {Timer} timer
+ * @return {Timer}
+ */
+const resetTimerProperties = timer => {
+ timer.paused = true;
+ timer.began = false;
+ timer.completed = false;
+ return timer;
+};
+
+/**
+ * @param {Timer} timer
+ * @return {Timer}
+ */
+const reviveTimer = timer => {
+ if (!timer._cancelled) return timer;
+ if (timer._hasChildren) {
+ forEachChildren(timer, reviveTimer);
+ } else {
+ forEachChildren(timer, (/** @type {Tween} tween*/tween) => {
+ if (tween._composition !== compositionTypes.none) {
+ composeTween(tween, getTweenSiblings(tween.target, tween.property));
+ }
+ });
+ }
+ timer._cancelled = 0;
+ return timer;
+};
+
+let timerId = 0;
+
+/**
+ * Base class used to create Timers, Animations and Timelines
+ */
+class Timer extends Clock {
+ /**
+ * @param {TimerParams} [parameters]
+ * @param {Timeline} [parent]
+ * @param {Number} [parentPosition]
+ */
+ constructor(parameters = {}, parent = null, parentPosition = 0) {
+
+ super(0);
+
+ const {
+ id,
+ delay,
+ duration,
+ reversed,
+ alternate,
+ loop,
+ loopDelay,
+ autoplay,
+ frameRate,
+ playbackRate,
+ onComplete,
+ onLoop,
+ onPause,
+ onBegin,
+ onBeforeUpdate,
+ onUpdate,
+ } = parameters;
+
+ if (scope.current) scope.current.register(this);
+
+ const timerInitTime = parent ? 0 : engine._elapsedTime;
+ const timerDefaults = parent ? parent.defaults : globals.defaults;
+ const timerDelay = /** @type {Number} */(isFnc(delay) || isUnd(delay) ? timerDefaults.delay : +delay);
+ const timerDuration = isFnc(duration) || isUnd(duration) ? Infinity : +duration;
+ const timerLoop = setValue(loop, timerDefaults.loop);
+ const timerLoopDelay = setValue(loopDelay, timerDefaults.loopDelay);
+ const timerIterationCount = timerLoop === true ||
+ timerLoop === Infinity ||
+ /** @type {Number} */(timerLoop) < 0 ? Infinity :
+ /** @type {Number} */(timerLoop) + 1;
+
+
+ let offsetPosition = 0;
+
+ if (parent) {
+ offsetPosition = parentPosition;
+ } else {
+ // Make sure to tick the engine once if not currently running to get up to date engine._elapsedTime
+ // to avoid big gaps with the following offsetPosition calculation
+ if (!engine.reqId) engine.requestTick(now());
+ // Make sure to scale the offset position with globals.timeScale to properly handle seconds unit
+ offsetPosition = (engine._elapsedTime - engine._startTime) * globals.timeScale;
+ }
+
+ // Timer's parameters
+ this.id = !isUnd(id) ? id : ++timerId;
+ /** @type {Timeline} */
+ this.parent = parent;
+ // Total duration of the timer
+ this.duration = clampInfinity(((timerDuration + timerLoopDelay) * timerIterationCount) - timerLoopDelay) || minValue;
+ /** @type {Boolean} */
+ this.backwards = false;
+ /** @type {Boolean} */
+ this.paused = true;
+ /** @type {Boolean} */
+ this.began = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Callback<this>} */
+ this.onBegin = onBegin || timerDefaults.onBegin;
+ /** @type {Callback<this>} */
+ this.onBeforeUpdate = onBeforeUpdate || timerDefaults.onBeforeUpdate;
+ /** @type {Callback<this>} */
+ this.onUpdate = onUpdate || timerDefaults.onUpdate;
+ /** @type {Callback<this>} */
+ this.onLoop = onLoop || timerDefaults.onLoop;
+ /** @type {Callback<this>} */
+ this.onPause = onPause || timerDefaults.onPause;
+ /** @type {Callback<this>} */
+ this.onComplete = onComplete || timerDefaults.onComplete;
+ /** @type {Number} */
+ this.iterationDuration = timerDuration; // Duration of one loop
+ /** @type {Number} */
+ this.iterationCount = timerIterationCount; // Number of loops
+ /** @type {Boolean|ScrollObserver} */
+ this._autoplay = parent ? false : setValue(autoplay, timerDefaults.autoplay);
+ /** @type {Number} */
+ this._offset = offsetPosition;
+ /** @type {Number} */
+ this._delay = timerDelay;
+ /** @type {Number} */
+ this._loopDelay = timerLoopDelay;
+ /** @type {Number} */
+ this._iterationTime = 0;
+ /** @type {Number} */
+ this._currentIteration = 0; // Current loop index
+ /** @type {Function} */
+ this._resolve = noop; // Used by .then()
+ /** @type {Boolean} */
+ this._running = false;
+ /** @type {Number} */
+ this._reversed = +setValue(reversed, timerDefaults.reversed);
+ /** @type {Number} */
+ this._reverse = this._reversed;
+ /** @type {Number} */
+ this._cancelled = 0;
+ /** @type {Boolean} */
+ this._alternate = setValue(alternate, timerDefaults.alternate);
+ /** @type {Renderable} */
+ this._prev = null;
+ /** @type {Renderable} */
+ this._next = null;
+
+ // Clock's parameters
+ /** @type {Number} */
+ this._elapsedTime = timerInitTime;
+ /** @type {Number} */
+ this._startTime = timerInitTime;
+ /** @type {Number} */
+ this._lastTime = timerInitTime;
+ /** @type {Number} */
+ this._fps = setValue(frameRate, timerDefaults.frameRate);
+ /** @type {Number} */
+ this._speed = setValue(playbackRate, timerDefaults.playbackRate);
+ }
+
+ get cancelled() {
+ return !!this._cancelled;
+ }
+
+ set cancelled(cancelled) {
+ cancelled ? this.cancel() : this.reset(1).play();
+ }
+
+ get currentTime() {
+ return clamp(round(this._currentTime, globals.precision), -this._delay, this.duration);
+ }
+
+ set currentTime(time) {
+ const paused = this.paused;
+ // Pausing the timer is necessary to avoid time jumps on a running instance
+ this.pause().seek(+time);
+ if (!paused) this.resume();
+ }
+
+ get iterationCurrentTime() {
+ return round(this._iterationTime, globals.precision);
+ }
+
+ set iterationCurrentTime(time) {
+ this.currentTime = (this.iterationDuration * this._currentIteration) + time;
+ }
+
+ get progress() {
+ return clamp(round(this._currentTime / this.duration, 10), 0, 1);
+ }
+
+ set progress(progress) {
+ this.currentTime = this.duration * progress;
+ }
+
+ get iterationProgress() {
+ return clamp(round(this._iterationTime / this.iterationDuration, 10), 0, 1);
+ }
+
+ set iterationProgress(progress) {
+ const iterationDuration = this.iterationDuration;
+ this.currentTime = (iterationDuration * this._currentIteration) + (iterationDuration * progress);
+ }
+
+ get currentIteration() {
+ return this._currentIteration;
+ }
+
+ set currentIteration(iterationCount) {
+ this.currentTime = (this.iterationDuration * clamp(+iterationCount, 0, this.iterationCount - 1));
+ }
+
+ get reversed() {
+ return !!this._reversed;
+ }
+
+ set reversed(reverse) {
+ reverse ? this.reverse() : this.play();
+ }
+
+ get speed() {
+ return super.speed;
+ }
+
+ set speed(playbackRate) {
+ super.speed = playbackRate;
+ this.resetTime();
+ }
+
+ /**
+ * @param {Number} internalRender
+ * @return {this}
+ */
+ reset(internalRender = 0) {
+ // If cancelled, revive the timer before rendering in order to have propertly composed tweens siblings
+ reviveTimer(this);
+ if (this._reversed && !this._reverse) this.reversed = false;
+ // Rendering before updating the completed flag to prevent skips and to make sure the properties are not overridden
+ // Setting the iterationTime at the end to force the rendering to happend backwards, otherwise calling .reset() on Timelines might not render children in the right order
+ // NOTE: This is only required for Timelines and might be better to move to the Timeline class?
+ this._iterationTime = this.iterationDuration;
+ // Set tickMode to tickModes.FORCE to force rendering
+ tick(this, 0, 1, internalRender, tickModes.FORCE);
+ // Reset timer properties after revive / render to make sure the props are not updated again
+ resetTimerProperties(this);
+ // Also reset children properties
+ if (this._hasChildren) {
+ forEachChildren(this, resetTimerProperties);
+ }
+ return this;
+ }
+
+ /**
+ * @param {Number} internalRender
+ * @return {this}
+ */
+ init(internalRender = 0) {
+ this.fps = this._fps;
+ this.speed = this._speed;
+ // Manually calling .init() on timelines should render all children intial state
+ // Forces all children to render once then render to 0 when reseted
+ if (!internalRender && this._hasChildren) {
+ tick(this, this.duration, 1, internalRender, tickModes.FORCE);
+ }
+ this.reset(internalRender);
+ // Make sure to set autoplay to false to child timers so it doesn't attempt to autoplay / link
+ const autoplay = this._autoplay;
+ if (autoplay === true) {
+ this.resume();
+ } else if (autoplay && !isUnd(/** @type {ScrollObserver} */(autoplay).linked)) {
+ /** @type {ScrollObserver} */(autoplay).link(this);
+ }
+ return this;
+ }
+
+ /** @return {this} */
+ resetTime() {
+ const timeScale = 1 / (this._speed * engine._speed);
+ // TODO: See if we can safely use engine._elapsedTime here
+ // if (!engine.reqId) engine.requestTick(now())
+ // this._startTime = engine._elapsedTime - (this._currentTime + this._delay) * timeScale;
+ this._startTime = now() - (this._currentTime + this._delay) * timeScale;
+ return this;
+ }
+
+ /** @return {this} */
+ pause() {
+ if (this.paused) return this;
+ this.paused = true;
+ this.onPause(this);
+ return this;
+ }
+
+ /** @return {this} */
+ resume() {
+ if (!this.paused) return this;
+ this.paused = false;
+ // We can safely imediatly render a timer that has no duration and no children
+ if (this.duration <= minValue && !this._hasChildren) {
+ tick(this, minValue, 0, 0, tickModes.FORCE);
+ } else {
+ if (!this._running) {
+ addChild(engine, this);
+ engine._hasChildren = true;
+ this._running = true;
+ }
+ this.resetTime();
+ // Forces the timer to advance by at least one frame when the next tick occurs
+ this._startTime -= 12;
+ engine.wake();
+ }
+ return this;
+ }
+
+ /** @return {this} */
+ restart() {
+ return this.reset(0).resume();
+ }
+
+ /**
+ * @param {Number} time
+ * @param {Boolean|Number} [muteCallbacks]
+ * @param {Boolean|Number} [internalRender]
+ * @return {this}
+ */
+ seek(time, muteCallbacks = 0, internalRender = 0) {
+ // Recompose the tween siblings in case the timer has been cancelled
+ reviveTimer(this);
+ // If you seek a completed animation, otherwise the next play will starts at 0
+ this.completed = false;
+ const isPaused = this.paused;
+ this.paused = true;
+ // timer, time, muteCallbacks, internalRender, tickMode
+ tick(this, time + this._delay, ~~muteCallbacks, ~~internalRender, tickModes.AUTO);
+ return isPaused ? this : this.resume();
+ }
+
+ /** @return {this} */
+ alternate() {
+ const reversed = this._reversed;
+ const count = this.iterationCount;
+ const duration = this.iterationDuration;
+ // Calculate the maximum iterations possible given the iteration duration
+ const iterations = count === Infinity ? floor(maxValue / duration) : count;
+ this._reversed = +(this._alternate && !(iterations % 2) ? reversed : !reversed);
+ if (count === Infinity) {
+ // Handle infinite loops to loop on themself
+ this.iterationProgress = this._reversed ? 1 - this.iterationProgress : this.iterationProgress;
+ } else {
+ this.seek((duration * iterations) - this._currentTime);
+ }
+ this.resetTime();
+ return this;
+ }
+
+ /** @return {this} */
+ play() {
+ if (this._reversed) this.alternate();
+ return this.resume();
+ }
+
+ /** @return {this} */
+ reverse() {
+ if (!this._reversed) this.alternate();
+ return this.resume();
+ }
+
+ // TODO: Move all the animation / tweens / children related code to Animation / Timeline
+
+ /** @return {this} */
+ cancel() {
+ if (this._hasChildren) {
+ forEachChildren(this, (/** @type {Renderable} */child) => child.cancel(), true);
+ } else {
+ forEachChildren(this, removeTweenSliblings);
+ }
+ this._cancelled = 1;
+ // Pausing the timer removes it from the engine
+ return this.pause();
+ }
+
+ /**
+ * @param {Number} newDuration
+ * @return {this}
+ */
+ stretch(newDuration) {
+ const currentDuration = this.duration;
+ const normlizedDuration = normalizeTime(newDuration);
+ if (currentDuration === normlizedDuration) return this;
+ const timeScale = newDuration / currentDuration;
+ const isSetter = newDuration <= minValue;
+ this.duration = isSetter ? minValue : normlizedDuration;
+ this.iterationDuration = isSetter ? minValue : normalizeTime(this.iterationDuration * timeScale);
+ this._offset *= timeScale;
+ this._delay *= timeScale;
+ this._loopDelay *= timeScale;
+ return this;
+ }
+
+ /**
+ * Cancels the timer by seeking it back to 0 and reverting the attached scroller if necessary
+ * @return {this}
+ */
+ revert() {
+ tick(this, 0, 1, 0, tickModes.AUTO);
+ const ap = /** @type {ScrollObserver} */(this._autoplay);
+ if (ap && ap.linked && ap.linked === this) ap.revert();
+ return this.cancel();
+ }
+
+ /**
+ * Imediatly completes the timer, cancels it and triggers the onComplete callback
+ * @return {this}
+ */
+ complete() {
+ return this.seek(this.duration).cancel();
+ }
+
+ /**
+ * @param {Callback<this>} [callback]
+ * @return {Promise}
+ */
+ then(callback = noop) {
+ const then = this.then;
+ const onResolve = () => {
+ // this.then = null prevents infinite recursion if returned by an async function
+ // https://github.com/juliangarnierorg/anime-beta/issues/26
+ this.then = null;
+ callback(this);
+ this.then = then;
+ this._resolve = noop;
+ };
+ return new Promise(r => {
+ this._resolve = () => r(onResolve());
+ // Make sure to resolve imediatly if the timer has already completed
+ if (this.completed) this._resolve();
+ return this;
+ });
+ }
+
+}
+
+/**
+ * @param {TimerParams} [parameters]
+ * @return {Timer}
+ */
+const createTimer = parameters => new Timer(parameters, null, 0).init();
+
+export { Timer, createTimer };
diff --git a/dist/modules/types/index.d.ts b/dist/modules/types/index.d.ts
new file mode 100644
index 00000000..9e4fbeac
--- /dev/null
+++ b/dist/modules/types/index.d.ts
@@ -0,0 +1,387 @@
+export type DefaultsParams = {
+ id?: number | string;
+ keyframes?: PercentageKeyframes | DurationKeyframes;
+ playbackEase?: EasingParam;
+ playbackRate?: number;
+ frameRate?: number;
+ loop?: number | boolean;
+ reversed?: boolean;
+ alternate?: boolean;
+ autoplay?: boolean | ScrollObserver;
+ duration?: number | FunctionValue;
+ delay?: number | FunctionValue;
+ loopDelay?: number;
+ ease?: EasingParam;
+ composition?: "none" | "replace" | "blend" | compositionTypes;
+ modifier?: (v: any) => any;
+ onBegin?: (tickable: Tickable) => void;
+ onBeforeUpdate?: (tickable: Tickable) => void;
+ onUpdate?: (tickable: Tickable) => void;
+ onLoop?: (tickable: Tickable) => void;
+ onPause?: (tickable: Tickable) => void;
+ onComplete?: (tickable: Tickable) => void;
+ onRender?: (renderable: Renderable) => void;
+};
+export type Renderable = JSAnimation | Timeline;
+export type Tickable = Timer | Renderable;
+export type CallbackArgument = Timer & JSAnimation & Timeline;
+export type Revertible = Animatable | Tickable | WAAPIAnimation | Draggable | ScrollObserver | TextSplitter | Scope;
+export type StaggerFunction<T> = (target?: Target, index?: number, length?: number, tl?: Timeline) => T;
+export type StaggerParams = {
+ start?: number | string;
+ from?: number | "first" | "center" | "last" | "random";
+ reversed?: boolean;
+ grid?: Array<number>;
+ axis?: ("x" | "y");
+ use?: string | ((target: Target, i: number, length: number) => number);
+ total?: number;
+ ease?: EasingParam;
+ modifier?: TweenModifier;
+};
+export type DOMTarget = HTMLElement | SVGElement;
+export type JSTarget = Record<string, any>;
+export type Target = DOMTarget | JSTarget;
+export type TargetSelector = Target | NodeList | string;
+export type DOMTargetSelector = DOMTarget | NodeList | string;
+export type DOMTargetsParam = Array<DOMTargetSelector> | DOMTargetSelector;
+export type DOMTargetsArray = Array<DOMTarget>;
+export type JSTargetsParam = Array<JSTarget> | JSTarget;
+export type JSTargetsArray = Array<JSTarget>;
+export type TargetsParam = Array<TargetSelector> | TargetSelector;
+export type TargetsArray = Array<Target>;
+export type EasingFunction = (time: number) => number;
+export type EaseStringParamNames = ("linear" | "linear(x1, x2 25%, x3)" | "in" | "out" | "inOut" | "inQuad" | "outQuad" | "inOutQuad" | "inCubic" | "outCubic" | "inOutCubic" | "inQuart" | "outQuart" | "inOutQuart" | "inQuint" | "outQuint" | "inOutQuint" | "inSine" | "outSine" | "inOutSine" | "inCirc" | "outCirc" | "inOutCirc" | "inExpo" | "outExpo" | "inOutExpo" | "inBounce" | "outBounce" | "inOutBounce" | "inBack" | "outBack" | "inOutBack" | "inElastic" | "outElastic" | "inOutElastic" | "irregular" | "cubicBezier" | "steps" | "in(p = 1.675)" | "out(p = 1.675)" | "inOut(p = 1.675)" | "inBack(overshoot = 1.70158)" | "outBack(overshoot = 1.70158)" | "inOutBack(overshoot = 1.70158)" | "inElastic(amplitude = 1, period = .3)" | "outElastic(amplitude = 1, period = .3)" | "inOutElastic(amplitude = 1, period = .3)" | "irregular(length = 10, randomness = 1)" | "cubicBezier(x1, y1, x2, y2)" | "steps(steps = 10)");
+export type PowerEasing = (power?: number | string) => EasingFunction;
+export type BackEasing = (overshoot?: number | string) => EasingFunction;
+export type ElasticEasing = (amplitude?: number | string, period?: number | string) => EasingFunction;
+export type EasingFunctionWithParams = PowerEasing | BackEasing | ElasticEasing;
+export type EasingParam = (string & {}) | EaseStringParamNames | EasingFunction | Spring;
+export type SpringParams = {
+ /**
+ * - Mass, default 1
+ */
+ mass?: number;
+ /**
+ * - Stiffness, default 100
+ */
+ stiffness?: number;
+ /**
+ * - Damping, default 10
+ */
+ damping?: number;
+ /**
+ * - Initial velocity, default 0
+ */
+ velocity?: number;
+};
+export type Callback<T> = (self: T, e?: PointerEvent) => any;
+export type TickableCallbacks<T extends unknown> = {
+ onBegin?: Callback<T>;
+ onBeforeUpdate?: Callback<T>;
+ onUpdate?: Callback<T>;
+ onLoop?: Callback<T>;
+ onPause?: Callback<T>;
+ onComplete?: Callback<T>;
+};
+export type RenderableCallbacks<T extends unknown> = {
+ onRender?: Callback<T>;
+};
+export type TimerOptions = {
+ id?: number | string;
+ duration?: TweenParamValue;
+ delay?: TweenParamValue;
+ loopDelay?: number;
+ reversed?: boolean;
+ alternate?: boolean;
+ loop?: boolean | number;
+ autoplay?: boolean | ScrollObserver;
+ frameRate?: number;
+ playbackRate?: number;
+};
+export type TimerParams = TimerOptions & TickableCallbacks<Timer>;
+export type FunctionValue = (target: Target, index: number, length: number) => number | string | TweenObjectValue | Array<number | string | TweenObjectValue>;
+export type TweenModifier = (value: number) => number | string;
+export type ColorArray = [number, number, number, number];
+export type Tween = {
+ id: number;
+ parent: JSAnimation;
+ property: string;
+ target: Target;
+ _value: string | number;
+ _func: Function | null;
+ _ease: EasingFunction;
+ _fromNumbers: Array<number>;
+ _toNumbers: Array<number>;
+ _strings: Array<string>;
+ _fromNumber: number;
+ _toNumber: number;
+ _numbers: Array<number>;
+ _number: number;
+ _unit: string;
+ _modifier: TweenModifier;
+ _currentTime: number;
+ _delay: number;
+ _updateDuration: number;
+ _startTime: number;
+ _changeDuration: number;
+ _absoluteStartTime: number;
+ _tweenType: tweenTypes;
+ _valueType: valueTypes;
+ _composition: number;
+ _isOverlapped: number;
+ _isOverridden: number;
+ _renderTransforms: number;
+ _prevRep: Tween;
+ _nextRep: Tween;
+ _prevAdd: Tween;
+ _nextAdd: Tween;
+ _prev: Tween;
+ _next: Tween;
+};
+export type TweenDecomposedValue = {
+ /**
+ * - Type
+ */
+ t: number;
+ /**
+ * - Single number value
+ */
+ n: number;
+ /**
+ * - Value unit
+ */
+ u: string;
+ /**
+ * - Value operator
+ */
+ o: string;
+ /**
+ * - Array of Numbers (in case of complex value type)
+ */
+ d: Array<number>;
+ /**
+ * - Strings (in case of complex value type)
+ */
+ s: Array<string>;
+};
+export type TweenPropertySiblings = {
+ _head: null | Tween;
+ _tail: null | Tween;
+};
+export type TweenLookups = Record<string, TweenPropertySiblings>;
+export type TweenReplaceLookups = WeakMap<Target, TweenLookups>;
+export type TweenAdditiveLookups = Map<Target, TweenLookups>;
+export type TweenParamValue = number | string | FunctionValue;
+export type TweenPropValue = TweenParamValue | [TweenParamValue, TweenParamValue];
+export type TweenComposition = (string & {}) | "none" | "replace" | "blend" | compositionTypes;
+export type TweenParamsOptions = {
+ duration?: TweenParamValue;
+ delay?: TweenParamValue;
+ ease?: EasingParam;
+ modifier?: TweenModifier;
+ composition?: TweenComposition;
+};
+export type TweenValues = {
+ from?: TweenParamValue;
+ to?: TweenPropValue;
+ fromTo?: TweenPropValue;
+};
+export type TweenKeyValue = TweenParamsOptions & TweenValues;
+export type ArraySyntaxValue = Array<TweenKeyValue | TweenPropValue>;
+export type TweenOptions = TweenParamValue | ArraySyntaxValue | TweenKeyValue;
+export type TweenObjectValue = Partial<{
+ to: TweenParamValue | Array<TweenParamValue>;
+ from: TweenParamValue | Array<TweenParamValue>;
+ fromTo: TweenParamValue | Array<TweenParamValue>;
+}>;
+export type PercentageKeyframeOptions = {
+ ease?: EasingParam;
+};
+export type PercentageKeyframeParams = Record<string, TweenParamValue>;
+export type PercentageKeyframes = Record<string, PercentageKeyframeParams & PercentageKeyframeOptions>;
+export type DurationKeyframes = Array<Record<string, TweenOptions | TweenModifier | boolean> & TweenParamsOptions>;
+export type AnimationOptions = {
+ keyframes?: PercentageKeyframes | DurationKeyframes;
+ playbackEase?: EasingParam;
+};
+export type AnimationParams = Record<string, TweenOptions | Callback<JSAnimation> | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & TickableCallbacks<JSAnimation> & RenderableCallbacks<JSAnimation>;
+/**
+ * Accepts:<br>
+ * - `Number` - Absolute position in milliseconds (e.g., `500` places element at exactly 500ms)<br>
+ * - `'+=Number'` - Addition: Position element X ms after the last element (e.g., `'+=100'`)<br>
+ * - `'-=Number'` - Subtraction: Position element X ms before the last element's end (e.g., `'-=100'`)<br>
+ * - `'*=Number'` - Multiplier: Position element at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br>
+ * - `'<'` - Previous end: Position element at the end position of the previous element<br>
+ * - `'<<'` - Previous start: Position element at the start position of the previous element<br>
+ * - `'<<+=Number'` - Combined: Position element relative to previous element's start (e.g., `'<<+=250'`)<br>
+ * - `'label'` - Label: Position element at a named label position (e.g., `'My Label'`)
+ */
+export type TimelinePosition = number | `+=${number}` | `-=${number}` | `*=${number}` | "<" | "<<" | `<<+=${number}` | `<<-=${number}` | string;
+/**
+ * Accepts:<br>
+ * - `Number` - Absolute position in milliseconds (e.g., `500` places animation at exactly 500ms)<br>
+ * - `'+=Number'` - Addition: Position animation X ms after the last animation (e.g., `'+=100'`)<br>
+ * - `'-=Number'` - Subtraction: Position animation X ms before the last animation's end (e.g., `'-=100'`)<br>
+ * - `'*=Number'` - Multiplier: Position animation at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br>
+ * - `'<'` - Previous end: Position animation at the end position of the previous animation<br>
+ * - `'<<'` - Previous start: Position animation at the start position of the previous animation<br>
+ * - `'<<+=Number'` - Combined: Position animation relative to previous animation's start (e.g., `'<<+=250'`)<br>
+ * - `'label'` - Label: Position animation at a named label position (e.g., `'My Label'`)<br>
+ * - `stagger(String|Nummber)` - Stagger multi-elements animation positions (e.g., 10, 20, 30...)
+ */
+export type TimelineAnimationPosition = TimelinePosition | StaggerFunction<number | string>;
+export type TimelineOptions = {
+ defaults?: DefaultsParams;
+ playbackEase?: EasingParam;
+};
+export type TimelineParams = TimerOptions & TimelineOptions & TickableCallbacks<Timeline> & RenderableCallbacks<Timeline>;
+export type WAAPITweenValue = string | number | Array<string> | Array<number>;
+export type WAAPIFunctionValue = (target: DOMTarget, index: number, length: number) => WAAPITweenValue;
+export type WAAPIKeyframeValue = WAAPITweenValue | WAAPIFunctionValue | Array<string | number | WAAPIFunctionValue>;
+export type WAAPICallback = (animation: WAAPIAnimation) => void;
+export type WAAPITweenOptions = {
+ to?: WAAPIKeyframeValue;
+ from?: WAAPIKeyframeValue;
+ duration?: number | WAAPIFunctionValue;
+ delay?: number | WAAPIFunctionValue;
+ ease?: EasingParam;
+ composition?: CompositeOperation;
+};
+export type WAAPIAnimationOptions = {
+ loop?: number | boolean;
+ Reversed?: boolean;
+ Alternate?: boolean;
+ autoplay?: boolean | ScrollObserver;
+ playbackRate?: number;
+ duration?: number | WAAPIFunctionValue;
+ delay?: number | WAAPIFunctionValue;
+ ease?: EasingParam;
+ composition?: CompositeOperation;
+ onComplete?: WAAPICallback;
+};
+export type WAAPIAnimationParams = Record<string, WAAPIKeyframeValue | WAAPIAnimationOptions | boolean | ScrollObserver | WAAPICallback | EasingParam | WAAPITweenOptions> & WAAPIAnimationOptions;
+export type AnimatablePropertySetter = (to: number | Array<number>, duration?: number, ease?: EasingParam) => AnimatableObject;
+export type AnimatablePropertyGetter = () => number | Array<number>;
+export type AnimatableProperty = AnimatablePropertySetter & AnimatablePropertyGetter;
+export type AnimatableObject = Animatable & Record<string, AnimatableProperty>;
+export type AnimatablePropertyParamsOptions = {
+ unit?: string;
+ duration?: TweenParamValue;
+ ease?: EasingParam;
+ modifier?: TweenModifier;
+ composition?: TweenComposition;
+};
+export type AnimatableParams = Record<string, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions;
+export type ReactRef = {
+ current?: HTMLElement | SVGElement | null;
+};
+export type AngularRef = {
+ nativeElement?: HTMLElement | SVGElement;
+};
+export type ScopeParams = {
+ root?: DOMTargetSelector | ReactRef | AngularRef;
+ defaults?: DefaultsParams;
+ mediaQueries?: Record<string, string>;
+};
+export type ScopedCallback<T> = (scope: Scope) => T;
+export type ScopeCleanupCallback = (scope?: Scope) => any;
+export type ScopeConstructorCallback = (scope?: Scope) => ScopeCleanupCallback | void;
+export type ScopeMethod = (...args: any[]) => ScopeCleanupCallback | void;
+export type ScrollThresholdValue = string | number;
+export type ScrollThresholdParam = {
+ target?: ScrollThresholdValue;
+ container?: ScrollThresholdValue;
+};
+export type ScrollObserverAxisCallback = (self: ScrollObserver) => "x" | "y";
+export type ScrollThresholdCallback = (self: ScrollObserver) => ScrollThresholdValue | ScrollThresholdParam;
+export type ScrollObserverParams = {
+ id?: number | string;
+ sync?: boolean | number | string | EasingParam;
+ container?: TargetsParam;
+ target?: TargetsParam;
+ axis?: "x" | "y" | ScrollObserverAxisCallback | ((observer: ScrollObserver) => "x" | "y" | ScrollObserverAxisCallback);
+ enter?: ScrollThresholdValue | ScrollThresholdParam | ScrollThresholdCallback | ((observer: ScrollObserver) => ScrollThresholdValue | ScrollThresholdParam | ScrollThresholdCallback);
+ leave?: ScrollThresholdValue | ScrollThresholdParam | ScrollThresholdCallback | ((observer: ScrollObserver) => ScrollThresholdValue | ScrollThresholdParam | ScrollThresholdCallback);
+ repeat?: boolean | ((observer: ScrollObserver) => boolean);
+ debug?: boolean;
+ onEnter?: Callback<ScrollObserver>;
+ onLeave?: Callback<ScrollObserver>;
+ onEnterForward?: Callback<ScrollObserver>;
+ onLeaveForward?: Callback<ScrollObserver>;
+ onEnterBackward?: Callback<ScrollObserver>;
+ onLeaveBackward?: Callback<ScrollObserver>;
+ onUpdate?: Callback<ScrollObserver>;
+ onSyncComplete?: Callback<ScrollObserver>;
+};
+export type DraggableAxisParam = {
+ mapTo?: string;
+ modifier?: TweenModifier;
+ composition?: TweenComposition;
+ snap?: number | Array<number> | ((draggable: Draggable) => number | Array<number>);
+};
+export type DraggableCursorParams = {
+ onHover?: string;
+ onGrab?: string;
+};
+export type DraggableParams = {
+ trigger?: DOMTargetSelector;
+ container?: DOMTargetSelector | Array<number> | ((draggable: Draggable) => DOMTargetSelector | Array<number>);
+ x?: boolean | DraggableAxisParam;
+ y?: boolean | DraggableAxisParam;
+ modifier?: TweenModifier;
+ snap?: number | Array<number> | ((draggable: Draggable) => number | Array<number>);
+ containerPadding?: number | Array<number> | ((draggable: Draggable) => number | Array<number>);
+ containerFriction?: number | ((draggable: Draggable) => number);
+ releaseContainerFriction?: number | ((draggable: Draggable) => number);
+ dragSpeed?: number | ((draggable: Draggable) => number);
+ scrollSpeed?: number | ((draggable: Draggable) => number);
+ scrollThreshold?: number | ((draggable: Draggable) => number);
+ minVelocity?: number | ((draggable: Draggable) => number);
+ maxVelocity?: number | ((draggable: Draggable) => number);
+ velocityMultiplier?: number | ((draggable: Draggable) => number);
+ releaseMass?: number;
+ releaseStiffness?: number;
+ releaseDamping?: number;
+ releaseEase?: EasingParam;
+ cursor?: boolean | DraggableCursorParams | ((draggable: Draggable) => boolean | DraggableCursorParams);
+ onGrab?: Callback<Draggable>;
+ onDrag?: Callback<Draggable>;
+ onRelease?: Callback<Draggable>;
+ onUpdate?: Callback<Draggable>;
+ onSettle?: Callback<Draggable>;
+ onSnap?: Callback<Draggable>;
+ onResize?: Callback<Draggable>;
+ onAfterResize?: Callback<Draggable>;
+};
+export type SplitTemplateParams = {
+ class?: false | string;
+ wrap?: boolean | "hidden" | "clip" | "visible" | "scroll" | "auto";
+ clone?: boolean | "top" | "right" | "bottom" | "left" | "center";
+};
+export type SplitValue = boolean | string;
+export type SplitFunctionValue = (value?: Node | HTMLElement) => any;
+export type TextSplitterParams = {
+ lines?: SplitValue | SplitTemplateParams | SplitFunctionValue;
+ words?: SplitValue | SplitTemplateParams | SplitFunctionValue;
+ chars?: SplitValue | SplitTemplateParams | SplitFunctionValue;
+ accessible?: boolean;
+ includeSpaces?: boolean;
+ debug?: boolean;
+};
+export type DrawableSVGGeometry = SVGGeometryElement & {
+ setAttribute(name: "draw", value: `${number} ${number}`): void;
+ draw: `${number} ${number}`;
+};
+import type { ScrollObserver } from '../events/scroll.js';
+import type { compositionTypes } from '../core/consts.js';
+import type { JSAnimation } from '../animation/animation.js';
+import type { Timeline } from '../timeline/timeline.js';
+import type { Timer } from '../timer/timer.js';
+import type { Animatable } from '../animatable/animatable.js';
+import type { WAAPIAnimation } from '../waapi/waapi.js';
+import type { Draggable } from '../draggable/draggable.js';
+import type { TextSplitter } from '../text/split.js';
+import type { Scope } from '../scope/scope.js';
+import type { Spring } from '../spring/spring.js';
+import type { tweenTypes } from '../core/consts.js';
+import type { valueTypes } from '../core/consts.js';
diff --git a/dist/modules/utils/chainable.cjs b/dist/modules/utils/chainable.cjs
new file mode 100644
index 00000000..43b51870
--- /dev/null
+++ b/dist/modules/utils/chainable.cjs
@@ -0,0 +1,190 @@
+/**
+ * Anime.js - utils - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var number = require('./number.cjs');
+
+// Chain-able utilities
+
+const numberUtils = number; // Needed to keep the import when bundling
+
+const chainables = {};
+
+/**
+ * @callback UtilityFunction
+ * @param {...*} args
+ * @return {Number|String}
+ *
+ * @param {UtilityFunction} fn
+ * @param {Number} [last=0]
+ * @return {function(...(Number|String)): function(Number|String): (Number|String)}
+ */
+const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args);
+
+/**
+ * @param {Function} fn
+ * @return {function(...(Number|String))}
+ */
+const chain = fn => {
+ return (...args) => {
+ const result = fn(...args);
+ return new Proxy(consts.noop, {
+ apply: (_, __, [v]) => result(v),
+ get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => {
+ const nextResult = chainables[prop](...nextArgs);
+ return (/**@type {Number|String} */v) => nextResult(result(v));
+ })
+ });
+ }
+};
+
+/**
+ * @param {UtilityFunction} fn
+ * @param {String} name
+ * @param {Number} [right]
+ * @return {function(...(Number|String)): UtilityFunction}
+ */
+const makeChainable = (name, fn, right = 0) => {
+ const chained = (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args);
+ if (!chainables[name]) chainables[name] = chained;
+ return chained;
+};
+
+/**
+ * @typedef {Object} ChainablesMap
+ * @property {ChainedClamp} clamp
+ * @property {ChainedRound} round
+ * @property {ChainedSnap} snap
+ * @property {ChainedWrap} wrap
+ * @property {ChainedLerp} lerp
+ * @property {ChainedDamp} damp
+ * @property {ChainedMapRange} mapRange
+ * @property {ChainedRoundPad} roundPad
+ * @property {ChainedPadStart} padStart
+ * @property {ChainedPadEnd} padEnd
+ * @property {ChainedDegToRad} degToRad
+ * @property {ChainedRadToDeg} radToDeg
+ */
+
+/**
+ * @callback ChainedUtilsResult
+ * @param {Number} value - The value to process through the chained operations
+ * @return {Number} The processed result
+ */
+
+/**
+ * @typedef {ChainablesMap & ChainedUtilsResult} ChainableUtil
+ */
+
+// Chainable
+
+/**
+ * @callback ChainedRoundPad
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+const roundPad = /** @type {typeof numberUtils.roundPad & ChainedRoundPad} */(makeChainable('roundPad', numberUtils.roundPad));
+
+/**
+ * @callback ChainedPadStart
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+const padStart = /** @type {typeof numberUtils.padStart & ChainedPadStart} */(makeChainable('padStart', numberUtils.padStart));
+
+/**
+ * @callback ChainedPadEnd
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+const padEnd = /** @type {typeof numberUtils.padEnd & ChainedPadEnd} */(makeChainable('padEnd', numberUtils.padEnd));
+
+/**
+ * @callback ChainedWrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+const wrap = /** @type {typeof numberUtils.wrap & ChainedWrap} */(makeChainable('wrap', numberUtils.wrap));
+
+/**
+ * @callback ChainedMapRange
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {ChainableUtil}
+ */
+const mapRange = /** @type {typeof numberUtils.mapRange & ChainedMapRange} */(makeChainable('mapRange', numberUtils.mapRange));
+
+/**
+ * @callback ChainedDegToRad
+ * @return {ChainableUtil}
+ */
+const degToRad = /** @type {typeof numberUtils.degToRad & ChainedDegToRad} */(makeChainable('degToRad', numberUtils.degToRad));
+
+/**
+ * @callback ChainedRadToDeg
+ * @return {ChainableUtil}
+ */
+const radToDeg = /** @type {typeof numberUtils.radToDeg & ChainedRadToDeg} */(makeChainable('radToDeg', numberUtils.radToDeg));
+
+/**
+ * @callback ChainedSnap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {ChainableUtil}
+ */
+const snap = /** @type {typeof numberUtils.snap & ChainedSnap} */(makeChainable('snap', numberUtils.snap));
+
+/**
+ * @callback ChainedClamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+const clamp = /** @type {typeof numberUtils.clamp & ChainedClamp} */(makeChainable('clamp', numberUtils.clamp));
+
+/**
+ * @callback ChainedRound
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+const round = /** @type {typeof numberUtils.round & ChainedRound} */(makeChainable('round', numberUtils.round));
+
+/**
+ * @callback ChainedLerp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @return {ChainableUtil}
+ */
+const lerp = /** @type {typeof numberUtils.lerp & ChainedLerp} */(makeChainable('lerp', numberUtils.lerp, 1));
+
+/**
+ * @callback ChainedDamp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @return {ChainableUtil}
+ */
+const damp = /** @type {typeof numberUtils.damp & ChainedDamp} */(makeChainable('damp', numberUtils.damp, 1));
+
+exports.clamp = clamp;
+exports.damp = damp;
+exports.degToRad = degToRad;
+exports.lerp = lerp;
+exports.mapRange = mapRange;
+exports.padEnd = padEnd;
+exports.padStart = padStart;
+exports.radToDeg = radToDeg;
+exports.round = round;
+exports.roundPad = roundPad;
+exports.snap = snap;
+exports.wrap = wrap;
diff --git a/dist/modules/utils/chainable.d.ts b/dist/modules/utils/chainable.d.ts
new file mode 100644
index 00000000..4d017799
--- /dev/null
+++ b/dist/modules/utils/chainable.d.ts
@@ -0,0 +1,135 @@
+/**
+ * @typedef {Object} ChainablesMap
+ * @property {ChainedClamp} clamp
+ * @property {ChainedRound} round
+ * @property {ChainedSnap} snap
+ * @property {ChainedWrap} wrap
+ * @property {ChainedLerp} lerp
+ * @property {ChainedDamp} damp
+ * @property {ChainedMapRange} mapRange
+ * @property {ChainedRoundPad} roundPad
+ * @property {ChainedPadStart} padStart
+ * @property {ChainedPadEnd} padEnd
+ * @property {ChainedDegToRad} degToRad
+ * @property {ChainedRadToDeg} radToDeg
+ */
+/**
+ * @callback ChainedUtilsResult
+ * @param {Number} value - The value to process through the chained operations
+ * @return {Number} The processed result
+ */
+/**
+ * @typedef {ChainablesMap & ChainedUtilsResult} ChainableUtil
+ */
+/**
+ * @callback ChainedRoundPad
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+export const roundPad: typeof numberUtils.roundPad & ChainedRoundPad;
+/**
+ * @callback ChainedPadStart
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+export const padStart: typeof numberUtils.padStart & ChainedPadStart;
+/**
+ * @callback ChainedPadEnd
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+export const padEnd: typeof numberUtils.padEnd & ChainedPadEnd;
+/**
+ * @callback ChainedWrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+export const wrap: typeof numberUtils.wrap & ChainedWrap;
+/**
+ * @callback ChainedMapRange
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {ChainableUtil}
+ */
+export const mapRange: typeof numberUtils.mapRange & ChainedMapRange;
+/**
+ * @callback ChainedDegToRad
+ * @return {ChainableUtil}
+ */
+export const degToRad: typeof numberUtils.degToRad & ChainedDegToRad;
+/**
+ * @callback ChainedRadToDeg
+ * @return {ChainableUtil}
+ */
+export const radToDeg: typeof numberUtils.radToDeg & ChainedRadToDeg;
+/**
+ * @callback ChainedSnap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {ChainableUtil}
+ */
+export const snap: typeof numberUtils.snap & ChainedSnap;
+/**
+ * @callback ChainedClamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+export const clamp: typeof numberUtils.clamp & ChainedClamp;
+/**
+ * @callback ChainedRound
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+export const round: typeof numberUtils.round & ChainedRound;
+/**
+ * @callback ChainedLerp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @return {ChainableUtil}
+ */
+export const lerp: typeof numberUtils.lerp & ChainedLerp;
+/**
+ * @callback ChainedDamp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @return {ChainableUtil}
+ */
+export const damp: typeof numberUtils.damp & ChainedDamp;
+export type UtilityFunction = (...args: any[]) => number | string;
+export type ChainablesMap = {
+ clamp: ChainedClamp;
+ round: ChainedRound;
+ snap: ChainedSnap;
+ wrap: ChainedWrap;
+ lerp: ChainedLerp;
+ damp: ChainedDamp;
+ mapRange: ChainedMapRange;
+ roundPad: ChainedRoundPad;
+ padStart: ChainedPadStart;
+ padEnd: ChainedPadEnd;
+ degToRad: ChainedDegToRad;
+ radToDeg: ChainedRadToDeg;
+};
+export type ChainedUtilsResult = (value: number) => number;
+export type ChainableUtil = ChainablesMap & ChainedUtilsResult;
+export type ChainedRoundPad = (decimalLength: number) => ChainableUtil;
+export type ChainedPadStart = (totalLength: number, padString: string) => ChainableUtil;
+export type ChainedPadEnd = (totalLength: number, padString: string) => ChainableUtil;
+export type ChainedWrap = (min: number, max: number) => ChainableUtil;
+export type ChainedMapRange = (inLow: number, inHigh: number, outLow: number, outHigh: number) => ChainableUtil;
+export type ChainedDegToRad = () => ChainableUtil;
+export type ChainedRadToDeg = () => ChainableUtil;
+export type ChainedSnap = (increment: number | Array<number>) => ChainableUtil;
+export type ChainedClamp = (min: number, max: number) => ChainableUtil;
+export type ChainedRound = (decimalLength: number) => ChainableUtil;
+export type ChainedLerp = (start: number, end: number) => ChainableUtil;
+export type ChainedDamp = (start: number, end: number, deltaTime: number) => ChainableUtil;
+declare const numberUtils: typeof numberImports;
+import * as numberImports from './number.js';
+export {};
diff --git a/dist/modules/utils/chainable.js b/dist/modules/utils/chainable.js
new file mode 100644
index 00000000..2034b9d9
--- /dev/null
+++ b/dist/modules/utils/chainable.js
@@ -0,0 +1,177 @@
+/**
+ * Anime.js - utils - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { noop } from '../core/consts.js';
+import * as number from './number.js';
+
+// Chain-able utilities
+
+const numberUtils = number; // Needed to keep the import when bundling
+
+const chainables = {};
+
+/**
+ * @callback UtilityFunction
+ * @param {...*} args
+ * @return {Number|String}
+ *
+ * @param {UtilityFunction} fn
+ * @param {Number} [last=0]
+ * @return {function(...(Number|String)): function(Number|String): (Number|String)}
+ */
+const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args);
+
+/**
+ * @param {Function} fn
+ * @return {function(...(Number|String))}
+ */
+const chain = fn => {
+ return (...args) => {
+ const result = fn(...args);
+ return new Proxy(noop, {
+ apply: (_, __, [v]) => result(v),
+ get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => {
+ const nextResult = chainables[prop](...nextArgs);
+ return (/**@type {Number|String} */v) => nextResult(result(v));
+ })
+ });
+ }
+};
+
+/**
+ * @param {UtilityFunction} fn
+ * @param {String} name
+ * @param {Number} [right]
+ * @return {function(...(Number|String)): UtilityFunction}
+ */
+const makeChainable = (name, fn, right = 0) => {
+ const chained = (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args);
+ if (!chainables[name]) chainables[name] = chained;
+ return chained;
+};
+
+/**
+ * @typedef {Object} ChainablesMap
+ * @property {ChainedClamp} clamp
+ * @property {ChainedRound} round
+ * @property {ChainedSnap} snap
+ * @property {ChainedWrap} wrap
+ * @property {ChainedLerp} lerp
+ * @property {ChainedDamp} damp
+ * @property {ChainedMapRange} mapRange
+ * @property {ChainedRoundPad} roundPad
+ * @property {ChainedPadStart} padStart
+ * @property {ChainedPadEnd} padEnd
+ * @property {ChainedDegToRad} degToRad
+ * @property {ChainedRadToDeg} radToDeg
+ */
+
+/**
+ * @callback ChainedUtilsResult
+ * @param {Number} value - The value to process through the chained operations
+ * @return {Number} The processed result
+ */
+
+/**
+ * @typedef {ChainablesMap & ChainedUtilsResult} ChainableUtil
+ */
+
+// Chainable
+
+/**
+ * @callback ChainedRoundPad
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+const roundPad = /** @type {typeof numberUtils.roundPad & ChainedRoundPad} */(makeChainable('roundPad', numberUtils.roundPad));
+
+/**
+ * @callback ChainedPadStart
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+const padStart = /** @type {typeof numberUtils.padStart & ChainedPadStart} */(makeChainable('padStart', numberUtils.padStart));
+
+/**
+ * @callback ChainedPadEnd
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+const padEnd = /** @type {typeof numberUtils.padEnd & ChainedPadEnd} */(makeChainable('padEnd', numberUtils.padEnd));
+
+/**
+ * @callback ChainedWrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+const wrap = /** @type {typeof numberUtils.wrap & ChainedWrap} */(makeChainable('wrap', numberUtils.wrap));
+
+/**
+ * @callback ChainedMapRange
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {ChainableUtil}
+ */
+const mapRange = /** @type {typeof numberUtils.mapRange & ChainedMapRange} */(makeChainable('mapRange', numberUtils.mapRange));
+
+/**
+ * @callback ChainedDegToRad
+ * @return {ChainableUtil}
+ */
+const degToRad = /** @type {typeof numberUtils.degToRad & ChainedDegToRad} */(makeChainable('degToRad', numberUtils.degToRad));
+
+/**
+ * @callback ChainedRadToDeg
+ * @return {ChainableUtil}
+ */
+const radToDeg = /** @type {typeof numberUtils.radToDeg & ChainedRadToDeg} */(makeChainable('radToDeg', numberUtils.radToDeg));
+
+/**
+ * @callback ChainedSnap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {ChainableUtil}
+ */
+const snap = /** @type {typeof numberUtils.snap & ChainedSnap} */(makeChainable('snap', numberUtils.snap));
+
+/**
+ * @callback ChainedClamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+const clamp = /** @type {typeof numberUtils.clamp & ChainedClamp} */(makeChainable('clamp', numberUtils.clamp));
+
+/**
+ * @callback ChainedRound
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+const round = /** @type {typeof numberUtils.round & ChainedRound} */(makeChainable('round', numberUtils.round));
+
+/**
+ * @callback ChainedLerp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @return {ChainableUtil}
+ */
+const lerp = /** @type {typeof numberUtils.lerp & ChainedLerp} */(makeChainable('lerp', numberUtils.lerp, 1));
+
+/**
+ * @callback ChainedDamp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @return {ChainableUtil}
+ */
+const damp = /** @type {typeof numberUtils.damp & ChainedDamp} */(makeChainable('damp', numberUtils.damp, 1));
+
+export { clamp, damp, degToRad, lerp, mapRange, padEnd, padStart, radToDeg, round, roundPad, snap, wrap };
diff --git a/dist/modules/utils/index.cjs b/dist/modules/utils/index.cjs
new file mode 100644
index 00000000..ddd50eac
--- /dev/null
+++ b/dist/modules/utils/index.cjs
@@ -0,0 +1,43 @@
+/**
+ * Anime.js - utils - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var chainable = require('./chainable.cjs');
+var random = require('./random.cjs');
+var time = require('./time.cjs');
+var target = require('./target.cjs');
+var stagger = require('./stagger.cjs');
+var styles = require('../core/styles.cjs');
+var targets = require('../core/targets.cjs');
+
+
+
+exports.clamp = chainable.clamp;
+exports.damp = chainable.damp;
+exports.degToRad = chainable.degToRad;
+exports.lerp = chainable.lerp;
+exports.mapRange = chainable.mapRange;
+exports.padEnd = chainable.padEnd;
+exports.padStart = chainable.padStart;
+exports.radToDeg = chainable.radToDeg;
+exports.round = chainable.round;
+exports.roundPad = chainable.roundPad;
+exports.snap = chainable.snap;
+exports.wrap = chainable.wrap;
+exports.createSeededRandom = random.createSeededRandom;
+exports.random = random.random;
+exports.randomPick = random.randomPick;
+exports.shuffle = random.shuffle;
+exports.keepTime = time.keepTime;
+exports.sync = time.sync;
+exports.get = target.get;
+exports.remove = target.remove;
+exports.set = target.set;
+exports.stagger = stagger.stagger;
+exports.cleanInlineStyles = styles.cleanInlineStyles;
+exports.$ = targets.registerTargets;
diff --git a/dist/modules/utils/index.d.ts b/dist/modules/utils/index.d.ts
new file mode 100644
index 00000000..32ed8b4f
--- /dev/null
+++ b/dist/modules/utils/index.d.ts
@@ -0,0 +1,5 @@
+export * from "./chainable.js";
+export * from "./random.js";
+export * from "./time.js";
+export * from "./target.js";
+export * from "./stagger.js";
diff --git a/dist/modules/utils/index.js b/dist/modules/utils/index.js
new file mode 100644
index 00000000..4a683950
--- /dev/null
+++ b/dist/modules/utils/index.js
@@ -0,0 +1,14 @@
+/**
+ * Anime.js - utils - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { clamp, damp, degToRad, lerp, mapRange, padEnd, padStart, radToDeg, round, roundPad, snap, wrap } from './chainable.js';
+export { createSeededRandom, random, randomPick, shuffle } from './random.js';
+export { keepTime, sync } from './time.js';
+export { get, remove, set } from './target.js';
+export { stagger } from './stagger.js';
+export { cleanInlineStyles } from '../core/styles.js';
+export { registerTargets as $ } from '../core/targets.js';
diff --git a/dist/modules/utils/number.cjs b/dist/modules/utils/number.cjs
new file mode 100644
index 00000000..bea494e7
--- /dev/null
+++ b/dist/modules/utils/number.cjs
@@ -0,0 +1,97 @@
+/**
+ * Anime.js - utils - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+
+/**
+ * Rounds a number to fixed decimal places
+ * @param {Number|String} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {String}
+ */
+const roundPad = (v, decimalLength) => (+v).toFixed(decimalLength);
+
+/**
+ * Pads the start of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {String}
+ */
+const padStart = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString);
+
+/**
+ * Pads the end of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {String}
+ */
+const padEnd = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString);
+
+/**
+ * Wraps a value within a range
+ * @param {Number} v - Value to wrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {Number}
+ */
+const wrap = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min;
+
+/**
+ * Maps a value from one range to another
+ * @param {Number} value - Input value
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {Number}
+ */
+const mapRange = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow);
+
+/**
+ * Converts degrees to radians
+ * @param {Number} degrees - Angle in degrees
+ * @return {Number}
+ */
+const degToRad = degrees => degrees * Math.PI / 180;
+
+/**
+ * Converts radians to degrees
+ * @param {Number} radians - Angle in radians
+ * @return {Number}
+ */
+const radToDeg = radians => radians * 180 / Math.PI;
+
+/**
+ * Frame rate independent damped lerp
+ * Based on: https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
+ */
+const damp = (start, end, deltaTime, factor) => {
+ return !factor ? start : factor === 1 ? end : helpers.lerp(start, end, 1 - Math.exp(-factor * deltaTime * .1));
+};
+
+exports.clamp = helpers.clamp;
+exports.lerp = helpers.lerp;
+exports.round = helpers.round;
+exports.snap = helpers.snap;
+exports.damp = damp;
+exports.degToRad = degToRad;
+exports.mapRange = mapRange;
+exports.padEnd = padEnd;
+exports.padStart = padStart;
+exports.radToDeg = radToDeg;
+exports.roundPad = roundPad;
+exports.wrap = wrap;
diff --git a/dist/modules/utils/number.d.ts b/dist/modules/utils/number.d.ts
new file mode 100644
index 00000000..f8460095
--- /dev/null
+++ b/dist/modules/utils/number.d.ts
@@ -0,0 +1,9 @@
+export function roundPad(v: number | string, decimalLength: number): string;
+export function padStart(v: number, totalLength: number, padString: string): string;
+export function padEnd(v: number, totalLength: number, padString: string): string;
+export function wrap(v: number, min: number, max: number): number;
+export function mapRange(value: number, inLow: number, inHigh: number, outLow: number, outHigh: number): number;
+export function degToRad(degrees: number): number;
+export function radToDeg(radians: number): number;
+export function damp(start: number, end: number, deltaTime: number, factor: number): number;
+export { snap, clamp, round, lerp } from "../core/helpers.js";
diff --git a/dist/modules/utils/number.js b/dist/modules/utils/number.js
new file mode 100644
index 00000000..30e8e7c4
--- /dev/null
+++ b/dist/modules/utils/number.js
@@ -0,0 +1,85 @@
+/**
+ * Anime.js - utils - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { lerp } from '../core/helpers.js';
+export { clamp, round, snap } from '../core/helpers.js';
+
+/**
+ * Rounds a number to fixed decimal places
+ * @param {Number|String} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {String}
+ */
+const roundPad = (v, decimalLength) => (+v).toFixed(decimalLength);
+
+/**
+ * Pads the start of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {String}
+ */
+const padStart = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString);
+
+/**
+ * Pads the end of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {String}
+ */
+const padEnd = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString);
+
+/**
+ * Wraps a value within a range
+ * @param {Number} v - Value to wrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {Number}
+ */
+const wrap = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min;
+
+/**
+ * Maps a value from one range to another
+ * @param {Number} value - Input value
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {Number}
+ */
+const mapRange = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow);
+
+/**
+ * Converts degrees to radians
+ * @param {Number} degrees - Angle in degrees
+ * @return {Number}
+ */
+const degToRad = degrees => degrees * Math.PI / 180;
+
+/**
+ * Converts radians to degrees
+ * @param {Number} radians - Angle in radians
+ * @return {Number}
+ */
+const radToDeg = radians => radians * 180 / Math.PI;
+
+/**
+ * Frame rate independent damped lerp
+ * Based on: https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
+ */
+const damp = (start, end, deltaTime, factor) => {
+ return !factor ? start : factor === 1 ? end : lerp(start, end, 1 - Math.exp(-factor * deltaTime * .1));
+};
+
+export { damp, degToRad, lerp, mapRange, padEnd, padStart, radToDeg, roundPad, wrap };
diff --git a/dist/modules/utils/random.cjs b/dist/modules/utils/random.cjs
new file mode 100644
index 00000000..0b7547d5
--- /dev/null
+++ b/dist/modules/utils/random.cjs
@@ -0,0 +1,77 @@
+/**
+ * Anime.js - utils - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+/**
+ * Generate a random number between optional min and max (inclusive) and decimal precision
+ *
+ * @callback RandomNumberGenerator
+ * @param {Number} [min=0] - The minimum value (inclusive)
+ * @param {Number} [max=1] - The maximum value (inclusive)
+ * @param {Number} [decimalLength=0] - Number of decimal places to round to
+ * @return {Number} A random number between min and max
+ */
+
+/**
+ * Generates a random number between min and max (inclusive) with optional decimal precision
+ *
+ * @type {RandomNumberGenerator}
+ */
+const random = (min = 0, max = 1, decimalLength = 0) => {
+ const m = 10 ** decimalLength;
+ return Math.floor((Math.random() * (max - min + (1 / m)) + min) * m) / m;
+};
+
+let _seed = 0;
+
+/**
+ * Creates a seeded pseudorandom number generator function
+ *
+ * @param {Number} [seed] - The seed value for the random number generator
+ * @param {Number} [seededMin=0] - The minimum default value (inclusive) of the returned function
+ * @param {Number} [seededMax=1] - The maximum default value (inclusive) of the returned function
+ * @param {Number} [seededDecimalLength=0] - Default number of decimal places to round to of the returned function
+ * @return {RandomNumberGenerator} A function to generate a random number between optional min and max (inclusive) and decimal precision
+ */
+const createSeededRandom = (seed, seededMin = 0, seededMax = 1, seededDecimalLength = 0) => {
+ let t = seed === undefined ? _seed++ : seed;
+ return (min = seededMin, max = seededMax, decimalLength = seededDecimalLength) => {
+ t += 0x6D2B79F5;
+ t = Math.imul(t ^ t >>> 15, t | 1);
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
+ const m = 10 ** decimalLength;
+ return Math.floor(((((t ^ t >>> 14) >>> 0) / 4294967296) * (max - min + (1 / m)) + min) * m) / m;
+ }
+};
+
+/**
+ * Picks a random element from an array or a string
+ *
+ * @template T
+ * @param {String|Array<T>} items - The array or string to pick from
+ * @return {String|T} A random element from the array or character from the string
+ */
+const randomPick = items => items[random(0, items.length - 1)];
+
+/**
+ * Shuffles an array in-place using the Fisher-Yates algorithm
+ * Adapted from https://bost.ocks.org/mike/shuffle/
+ *
+ * @param {Array} items - The array to shuffle (will be modified in-place)
+ * @return {Array} The same array reference, now shuffled
+ */
+const shuffle = items => {
+ let m = items.length, t, i;
+ while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; }
+ return items;
+};
+
+exports.createSeededRandom = createSeededRandom;
+exports.random = random;
+exports.randomPick = randomPick;
+exports.shuffle = shuffle;
diff --git a/dist/modules/utils/random.d.ts b/dist/modules/utils/random.d.ts
new file mode 100644
index 00000000..813a5844
--- /dev/null
+++ b/dist/modules/utils/random.d.ts
@@ -0,0 +1,22 @@
+/**
+ * Generate a random number between optional min and max (inclusive) and decimal precision
+ *
+ * @callback RandomNumberGenerator
+ * @param {Number} [min=0] - The minimum value (inclusive)
+ * @param {Number} [max=1] - The maximum value (inclusive)
+ * @param {Number} [decimalLength=0] - Number of decimal places to round to
+ * @return {Number} A random number between min and max
+ */
+/**
+ * Generates a random number between min and max (inclusive) with optional decimal precision
+ *
+ * @type {RandomNumberGenerator}
+ */
+export const random: RandomNumberGenerator;
+export function createSeededRandom(seed?: number, seededMin?: number, seededMax?: number, seededDecimalLength?: number): RandomNumberGenerator;
+export function randomPick<T>(items: string | Array<T>): string | T;
+export function shuffle(items: any[]): any[];
+/**
+ * Generate a random number between optional min and max (inclusive) and decimal precision
+ */
+export type RandomNumberGenerator = (min?: number, max?: number, decimalLength?: number) => number;
diff --git a/dist/modules/utils/random.js b/dist/modules/utils/random.js
new file mode 100644
index 00000000..dcff5069
--- /dev/null
+++ b/dist/modules/utils/random.js
@@ -0,0 +1,72 @@
+/**
+ * Anime.js - utils - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+/**
+ * Generate a random number between optional min and max (inclusive) and decimal precision
+ *
+ * @callback RandomNumberGenerator
+ * @param {Number} [min=0] - The minimum value (inclusive)
+ * @param {Number} [max=1] - The maximum value (inclusive)
+ * @param {Number} [decimalLength=0] - Number of decimal places to round to
+ * @return {Number} A random number between min and max
+ */
+
+/**
+ * Generates a random number between min and max (inclusive) with optional decimal precision
+ *
+ * @type {RandomNumberGenerator}
+ */
+const random = (min = 0, max = 1, decimalLength = 0) => {
+ const m = 10 ** decimalLength;
+ return Math.floor((Math.random() * (max - min + (1 / m)) + min) * m) / m;
+};
+
+let _seed = 0;
+
+/**
+ * Creates a seeded pseudorandom number generator function
+ *
+ * @param {Number} [seed] - The seed value for the random number generator
+ * @param {Number} [seededMin=0] - The minimum default value (inclusive) of the returned function
+ * @param {Number} [seededMax=1] - The maximum default value (inclusive) of the returned function
+ * @param {Number} [seededDecimalLength=0] - Default number of decimal places to round to of the returned function
+ * @return {RandomNumberGenerator} A function to generate a random number between optional min and max (inclusive) and decimal precision
+ */
+const createSeededRandom = (seed, seededMin = 0, seededMax = 1, seededDecimalLength = 0) => {
+ let t = seed === undefined ? _seed++ : seed;
+ return (min = seededMin, max = seededMax, decimalLength = seededDecimalLength) => {
+ t += 0x6D2B79F5;
+ t = Math.imul(t ^ t >>> 15, t | 1);
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
+ const m = 10 ** decimalLength;
+ return Math.floor(((((t ^ t >>> 14) >>> 0) / 4294967296) * (max - min + (1 / m)) + min) * m) / m;
+ }
+};
+
+/**
+ * Picks a random element from an array or a string
+ *
+ * @template T
+ * @param {String|Array<T>} items - The array or string to pick from
+ * @return {String|T} A random element from the array or character from the string
+ */
+const randomPick = items => items[random(0, items.length - 1)];
+
+/**
+ * Shuffles an array in-place using the Fisher-Yates algorithm
+ * Adapted from https://bost.ocks.org/mike/shuffle/
+ *
+ * @param {Array} items - The array to shuffle (will be modified in-place)
+ * @return {Array} The same array reference, now shuffled
+ */
+const shuffle = items => {
+ let m = items.length, t, i;
+ while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; }
+ return items;
+};
+
+export { createSeededRandom, random, randomPick, shuffle };
diff --git a/dist/modules/utils/stagger.cjs b/dist/modules/utils/stagger.cjs
new file mode 100644
index 00000000..d14f8a9d
--- /dev/null
+++ b/dist/modules/utils/stagger.cjs
@@ -0,0 +1,122 @@
+/**
+ * Anime.js - utils - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var eases = require('../easings/eases.cjs');
+var position = require('../timeline/position.cjs');
+var values = require('../core/values.cjs');
+var targets = require('../core/targets.cjs');
+var random = require('./random.cjs');
+
+/**
+ * @import {
+ * StaggerParams,
+ * StaggerFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
+
+/**
+ * @overload
+ * @param {Number} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+/**
+ * @overload
+ * @param {String} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+/**
+ * @overload
+ * @param {[Number, Number]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+/**
+ * @overload
+ * @param {[String, String]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+/**
+ * @param {Number|String|[Number, Number]|[String, String]} val The staggered value or range
+ * @param {StaggerParams} [params] The stagger parameters
+ * @return {StaggerFunction<Number|String>}
+ */
+const stagger = (val, params = {}) => {
+ let values$1 = [];
+ let maxValue = 0;
+ const from = params.from;
+ const reversed = params.reversed;
+ const ease = params.ease;
+ const hasEasing = !helpers.isUnd(ease);
+ const hasSpring = hasEasing && !helpers.isUnd(/** @type {Spring} */(ease).ease);
+ const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? eases.parseEase(ease) : null;
+ const grid = params.grid;
+ const axis = params.axis;
+ const customTotal = params.total;
+ const fromFirst = helpers.isUnd(from) || from === 0 || from === 'first';
+ const fromCenter = from === 'center';
+ const fromLast = from === 'last';
+ const fromRandom = from === 'random';
+ const isRange = helpers.isArr(val);
+ const useProp = params.use;
+ const val1 = isRange ? helpers.parseNumber(val[0]) : helpers.parseNumber(val);
+ const val2 = isRange ? helpers.parseNumber(val[1]) : 0;
+ const unitMatch = consts.unitsExecRgx.exec((isRange ? val[1] : val) + consts.emptyString);
+ const start = params.start || 0 + (isRange ? val1 : 0);
+ let fromIndex = fromFirst ? 0 : helpers.isNum(from) ? from : 0;
+ return (target, i, t, tl) => {
+ const [ registeredTarget ] = targets.registerTargets(target);
+ const total = helpers.isUnd(customTotal) ? t : customTotal;
+ const customIndex = !helpers.isUnd(useProp) ? helpers.isFnc(useProp) ? useProp(registeredTarget, i, total) : values.getOriginalAnimatableValue(registeredTarget, useProp) : false;
+ const staggerIndex = helpers.isNum(customIndex) || helpers.isStr(customIndex) && helpers.isNum(+customIndex) ? +customIndex : i;
+ if (fromCenter) fromIndex = (total - 1) / 2;
+ if (fromLast) fromIndex = total - 1;
+ if (!values$1.length) {
+ for (let index = 0; index < total; index++) {
+ if (!grid) {
+ values$1.push(helpers.abs(fromIndex - index));
+ } else {
+ const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2;
+ const fromY = !fromCenter ? helpers.floor(fromIndex / grid[0]) : (grid[1] - 1) / 2;
+ const toX = index % grid[0];
+ const toY = helpers.floor(index / grid[0]);
+ const distanceX = fromX - toX;
+ const distanceY = fromY - toY;
+ let value = helpers.sqrt(distanceX * distanceX + distanceY * distanceY);
+ if (axis === 'x') value = -distanceX;
+ if (axis === 'y') value = -distanceY;
+ values$1.push(value);
+ }
+ maxValue = helpers.max(...values$1);
+ }
+ if (staggerEase) values$1 = values$1.map(val => staggerEase(val / maxValue) * maxValue);
+ if (reversed) values$1 = values$1.map(val => axis ? (val < 0) ? val * -1 : -val : helpers.abs(maxValue - val));
+ if (fromRandom) values$1 = random.shuffle(values$1);
+ }
+ const spacing = isRange ? (val2 - val1) / maxValue : val1;
+ const offset = tl ? position.parseTimelinePosition(tl, helpers.isUnd(params.start) ? tl.iterationDuration : start) : /** @type {Number} */(start);
+ /** @type {String|Number} */
+ let output = offset + ((spacing * helpers.round(values$1[staggerIndex], 2)) || 0);
+ if (params.modifier) output = params.modifier(output);
+ if (unitMatch) output = `${output}${unitMatch[2]}`;
+ return output;
+ }
+};
+
+exports.stagger = stagger;
diff --git a/dist/modules/utils/stagger.d.ts b/dist/modules/utils/stagger.d.ts
new file mode 100644
index 00000000..68aa7ce7
--- /dev/null
+++ b/dist/modules/utils/stagger.d.ts
@@ -0,0 +1,30 @@
+/**
+ * @overload
+ * @param {Number} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+export function stagger(val: number, params?: StaggerParams): StaggerFunction<number>;
+/**
+ * @overload
+ * @param {String} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+export function stagger(val: string, params?: StaggerParams): StaggerFunction<string>;
+/**
+ * @overload
+ * @param {[Number, Number]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+export function stagger(val: [number, number], params?: StaggerParams): StaggerFunction<number>;
+/**
+ * @overload
+ * @param {[String, String]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+export function stagger(val: [string, string], params?: StaggerParams): StaggerFunction<string>;
+import type { StaggerParams } from '../types/index.js';
+import type { StaggerFunction } from '../types/index.js';
diff --git a/dist/modules/utils/stagger.js b/dist/modules/utils/stagger.js
new file mode 100644
index 00000000..55e982ba
--- /dev/null
+++ b/dist/modules/utils/stagger.js
@@ -0,0 +1,120 @@
+/**
+ * Anime.js - utils - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { unitsExecRgx, emptyString } from '../core/consts.js';
+import { isUnd, parseNumber, isFnc, abs, floor, sqrt, round, isArr, isNum, isStr, max } from '../core/helpers.js';
+import { parseEase } from '../easings/eases.js';
+import { parseTimelinePosition } from '../timeline/position.js';
+import { getOriginalAnimatableValue } from '../core/values.js';
+import { registerTargets } from '../core/targets.js';
+import { shuffle } from './random.js';
+
+/**
+ * @import {
+ * StaggerParams,
+ * StaggerFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
+
+/**
+ * @overload
+ * @param {Number} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+/**
+ * @overload
+ * @param {String} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+/**
+ * @overload
+ * @param {[Number, Number]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<Number>}
+ */
+/**
+ * @overload
+ * @param {[String, String]} val
+ * @param {StaggerParams} [params]
+ * @return {StaggerFunction<String>}
+ */
+/**
+ * @param {Number|String|[Number, Number]|[String, String]} val The staggered value or range
+ * @param {StaggerParams} [params] The stagger parameters
+ * @return {StaggerFunction<Number|String>}
+ */
+const stagger = (val, params = {}) => {
+ let values = [];
+ let maxValue = 0;
+ const from = params.from;
+ const reversed = params.reversed;
+ const ease = params.ease;
+ const hasEasing = !isUnd(ease);
+ const hasSpring = hasEasing && !isUnd(/** @type {Spring} */(ease).ease);
+ const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEase(ease) : null;
+ const grid = params.grid;
+ const axis = params.axis;
+ const customTotal = params.total;
+ const fromFirst = isUnd(from) || from === 0 || from === 'first';
+ const fromCenter = from === 'center';
+ const fromLast = from === 'last';
+ const fromRandom = from === 'random';
+ const isRange = isArr(val);
+ const useProp = params.use;
+ const val1 = isRange ? parseNumber(val[0]) : parseNumber(val);
+ const val2 = isRange ? parseNumber(val[1]) : 0;
+ const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString);
+ const start = params.start || 0 + (isRange ? val1 : 0);
+ let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0;
+ return (target, i, t, tl) => {
+ const [ registeredTarget ] = registerTargets(target);
+ const total = isUnd(customTotal) ? t : customTotal;
+ const customIndex = !isUnd(useProp) ? isFnc(useProp) ? useProp(registeredTarget, i, total) : getOriginalAnimatableValue(registeredTarget, useProp) : false;
+ const staggerIndex = isNum(customIndex) || isStr(customIndex) && isNum(+customIndex) ? +customIndex : i;
+ if (fromCenter) fromIndex = (total - 1) / 2;
+ if (fromLast) fromIndex = total - 1;
+ if (!values.length) {
+ for (let index = 0; index < total; index++) {
+ if (!grid) {
+ values.push(abs(fromIndex - index));
+ } else {
+ const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2;
+ const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2;
+ const toX = index % grid[0];
+ const toY = floor(index / grid[0]);
+ const distanceX = fromX - toX;
+ const distanceY = fromY - toY;
+ let value = sqrt(distanceX * distanceX + distanceY * distanceY);
+ if (axis === 'x') value = -distanceX;
+ if (axis === 'y') value = -distanceY;
+ values.push(value);
+ }
+ maxValue = max(...values);
+ }
+ if (staggerEase) values = values.map(val => staggerEase(val / maxValue) * maxValue);
+ if (reversed) values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val));
+ if (fromRandom) values = shuffle(values);
+ }
+ const spacing = isRange ? (val2 - val1) / maxValue : val1;
+ const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl.iterationDuration : start) : /** @type {Number} */(start);
+ /** @type {String|Number} */
+ let output = offset + ((spacing * round(values[staggerIndex], 2)) || 0);
+ if (params.modifier) output = params.modifier(output);
+ if (unitMatch) output = `${output}${unitMatch[2]}`;
+ return output;
+ }
+};
+
+export { stagger };
diff --git a/dist/modules/utils/target.cjs b/dist/modules/utils/target.cjs
new file mode 100644
index 00000000..2de66964
--- /dev/null
+++ b/dist/modules/utils/target.cjs
@@ -0,0 +1,130 @@
+/**
+ * Anime.js - utils - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var globals = require('../core/globals.cjs');
+var consts = require('../core/consts.cjs');
+var helpers = require('../core/helpers.cjs');
+var targets = require('../core/targets.cjs');
+var styles = require('../core/styles.cjs');
+var values = require('../core/values.cjs');
+var units = require('../core/units.cjs');
+var composition = require('../waapi/composition.cjs');
+var composition$1 = require('../animation/composition.cjs');
+var animation = require('../animation/animation.cjs');
+
+/**
+ * @import {
+ * Renderable,
+ * DOMTargetSelector,
+ * JSTargetsParam,
+ * DOMTargetsParam,
+ * TargetsParam,
+ * DOMTarget,
+ * AnimationParams,
+ * TargetsArray,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
+ * @param {String} propName
+ * @return {String}
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
+ * @param {String} propName
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+function get(targetSelector, propName, unit) {
+ const targets$1 = targets.registerTargets(targetSelector);
+ if (!targets$1.length) return;
+ const [ target ] = targets$1;
+ const tweenType = values.getTweenType(target, propName);
+ const normalizePropName = styles.sanitizePropertyName(propName, target, tweenType);
+ let originalValue = values.getOriginalAnimatableValue(target, normalizePropName);
+ if (helpers.isUnd(unit)) {
+ return originalValue;
+ } else {
+ values.decomposeRawValue(originalValue, values.decomposedOriginalValue);
+ if (values.decomposedOriginalValue.t === consts.valueTypes.NUMBER || values.decomposedOriginalValue.t === consts.valueTypes.UNIT) {
+ if (unit === false) {
+ return values.decomposedOriginalValue.n;
+ } else {
+ const convertedValue = units.convertValueUnit(/** @type {DOMTarget} */(target), values.decomposedOriginalValue, /** @type {String} */(unit), false);
+ return `${helpers.round(convertedValue.n, globals.globals.precision)}${convertedValue.u}`;
+ }
+ }
+ }
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @return {JSAnimation}
+ */
+const set = (targets, parameters) => {
+ if (helpers.isUnd(parameters)) return;
+ parameters.duration = consts.minValue;
+ // Do not overrides currently active tweens by default
+ parameters.composition = values.setValue(parameters.composition, consts.compositionTypes.none);
+ // Skip init() and force rendering by playing the animation
+ return new animation.JSAnimation(targets, parameters, null, 0, true).resume();
+};
+
+/**
+ * @param {TargetsParam} targets
+ * @param {Renderable|WAAPIAnimation} [renderable]
+ * @param {String} [propertyName]
+ * @return {TargetsArray}
+ */
+const remove = (targets$1, renderable, propertyName) => {
+ const targetsArray = targets.parseTargets(targets$1);
+ for (let i = 0, l = targetsArray.length; i < l; i++) {
+ composition.removeWAAPIAnimation(
+ /** @type {DOMTarget} */(targetsArray[i]),
+ propertyName,
+ renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable),
+ );
+ }
+ composition$1.removeTargetsFromRenderable(
+ targetsArray,
+ /** @type {Renderable} */(renderable),
+ propertyName
+ );
+ return targetsArray;
+};
+
+exports.$ = targets.registerTargets;
+exports.cleanInlineStyles = styles.cleanInlineStyles;
+exports.get = get;
+exports.remove = remove;
+exports.set = set;
diff --git a/dist/modules/utils/target.d.ts b/dist/modules/utils/target.d.ts
new file mode 100644
index 00000000..b5c105c3
--- /dev/null
+++ b/dist/modules/utils/target.d.ts
@@ -0,0 +1,126 @@
+/**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
+ * @param {String} propName
+ * @return {String}
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
+ * @param {String} propName
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+export function get(targetSelector: DOMTargetSelector, propName: string): string;
+/**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
+ * @param {String} propName
+ * @return {String}
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
+ * @param {String} propName
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+export function get(targetSelector: JSTargetsParam, propName: string): number | string;
+/**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
+ * @param {String} propName
+ * @return {String}
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
+ * @param {String} propName
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+export function get(targetSelector: DOMTargetsParam, propName: string, unit: string): string;
+/**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
+ * @param {String} propName
+ * @return {String}
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
+ * @param {String} propName
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+export function get(targetSelector: TargetsParam, propName: string, unit: boolean): number;
+export { registerTargets as $ };
+export function set(targets: TargetsParam, parameters: AnimationParams): JSAnimation;
+export function remove(targets: TargetsParam, renderable?: Renderable | WAAPIAnimation, propertyName?: string): TargetsArray;
+export { cleanInlineStyles } from "../core/styles.js";
+import type { DOMTargetSelector } from '../types/index.js';
+import type { JSTargetsParam } from '../types/index.js';
+import type { DOMTargetsParam } from '../types/index.js';
+import type { TargetsParam } from '../types/index.js';
+import { registerTargets } from '../core/targets.js';
+import type { AnimationParams } from '../types/index.js';
+import { JSAnimation } from '../animation/animation.js';
+import type { Renderable } from '../types/index.js';
+import type { WAAPIAnimation } from '../waapi/waapi.js';
+import type { TargetsArray } from '../types/index.js';
diff --git a/dist/modules/utils/target.js b/dist/modules/utils/target.js
new file mode 100644
index 00000000..d18b74b8
--- /dev/null
+++ b/dist/modules/utils/target.js
@@ -0,0 +1,125 @@
+/**
+ * Anime.js - utils - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { globals } from '../core/globals.js';
+import { valueTypes, minValue, compositionTypes } from '../core/consts.js';
+import { isUnd, round } from '../core/helpers.js';
+import { registerTargets, parseTargets } from '../core/targets.js';
+import { sanitizePropertyName } from '../core/styles.js';
+export { cleanInlineStyles } from '../core/styles.js';
+import { getTweenType, getOriginalAnimatableValue, decomposeRawValue, decomposedOriginalValue, setValue } from '../core/values.js';
+import { convertValueUnit } from '../core/units.js';
+import { removeWAAPIAnimation } from '../waapi/composition.js';
+import { removeTargetsFromRenderable } from '../animation/composition.js';
+import { JSAnimation } from '../animation/animation.js';
+
+/**
+ * @import {
+ * Renderable,
+ * DOMTargetSelector,
+ * JSTargetsParam,
+ * DOMTargetsParam,
+ * TargetsParam,
+ * DOMTarget,
+ * AnimationParams,
+ * TargetsArray,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
+ * @param {String} propName
+ * @return {String}
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
+ * @param {String} propName
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+function get(targetSelector, propName, unit) {
+ const targets = registerTargets(targetSelector);
+ if (!targets.length) return;
+ const [ target ] = targets;
+ const tweenType = getTweenType(target, propName);
+ const normalizePropName = sanitizePropertyName(propName, target, tweenType);
+ let originalValue = getOriginalAnimatableValue(target, normalizePropName);
+ if (isUnd(unit)) {
+ return originalValue;
+ } else {
+ decomposeRawValue(originalValue, decomposedOriginalValue);
+ if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) {
+ if (unit === false) {
+ return decomposedOriginalValue.n;
+ } else {
+ const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false);
+ return `${round(convertedValue.n, globals.precision)}${convertedValue.u}`;
+ }
+ }
+ }
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @return {JSAnimation}
+ */
+const set = (targets, parameters) => {
+ if (isUnd(parameters)) return;
+ parameters.duration = minValue;
+ // Do not overrides currently active tweens by default
+ parameters.composition = setValue(parameters.composition, compositionTypes.none);
+ // Skip init() and force rendering by playing the animation
+ return new JSAnimation(targets, parameters, null, 0, true).resume();
+};
+
+/**
+ * @param {TargetsParam} targets
+ * @param {Renderable|WAAPIAnimation} [renderable]
+ * @param {String} [propertyName]
+ * @return {TargetsArray}
+ */
+const remove = (targets, renderable, propertyName) => {
+ const targetsArray = parseTargets(targets);
+ for (let i = 0, l = targetsArray.length; i < l; i++) {
+ removeWAAPIAnimation(
+ /** @type {DOMTarget} */(targetsArray[i]),
+ propertyName,
+ renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable),
+ );
+ }
+ removeTargetsFromRenderable(
+ targetsArray,
+ /** @type {Renderable} */(renderable),
+ propertyName
+ );
+ return targetsArray;
+};
+
+export { registerTargets as $, get, remove, set };
diff --git a/dist/modules/utils/time.cjs b/dist/modules/utils/time.cjs
new file mode 100644
index 00000000..4317453a
--- /dev/null
+++ b/dist/modules/utils/time.cjs
@@ -0,0 +1,57 @@
+/**
+ * Anime.js - utils - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var consts = require('../core/consts.cjs');
+var globals = require('../core/globals.cjs');
+var helpers = require('../core/helpers.cjs');
+var timer = require('../timer/timer.cjs');
+
+/**
+ * @import {
+ * Callback,
+ * Tickable,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {Callback<Timer>} [callback]
+ * @return {Timer}
+ */
+const sync = (callback = consts.noop) => {
+ return new timer.Timer({ duration: 1 * globals.globals.timeScale, onComplete: callback }, null, 0).resume();
+};
+
+/**
+ * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor
+ * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)}
+ */
+const keepTime = constructor => {
+ /** @type {Tickable} */
+ let tracked;
+ return (...args) => {
+ let currentIteration, currentIterationProgress, reversed, alternate;
+ if (tracked) {
+ currentIteration = tracked.currentIteration;
+ currentIterationProgress = tracked.iterationProgress;
+ reversed = tracked.reversed;
+ alternate = tracked._alternate;
+ tracked.revert();
+ }
+ const cleanup = constructor(...args);
+ if (cleanup && !helpers.isFnc(cleanup) && cleanup.revert) tracked = cleanup;
+ if (!helpers.isUnd(currentIterationProgress)) {
+ /** @type {Tickable} */(tracked).currentIteration = currentIteration;
+ /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress;
+ }
+ return cleanup || consts.noop;
+ }
+};
+
+exports.keepTime = keepTime;
+exports.sync = sync;
diff --git a/dist/modules/utils/time.d.ts b/dist/modules/utils/time.d.ts
new file mode 100644
index 00000000..ee11bb12
--- /dev/null
+++ b/dist/modules/utils/time.d.ts
@@ -0,0 +1,5 @@
+export function sync(callback?: Callback<Timer>): Timer;
+export function keepTime(constructor: (...args: any[]) => Tickable | ((...args: any[]) => void)): (...args: any[]) => Tickable | ((...args: any[]) => void);
+import { Timer } from '../timer/timer.js';
+import type { Callback } from '../types/index.js';
+import type { Tickable } from '../types/index.js';
diff --git a/dist/modules/utils/time.js b/dist/modules/utils/time.js
new file mode 100644
index 00000000..bbe8c4ce
--- /dev/null
+++ b/dist/modules/utils/time.js
@@ -0,0 +1,54 @@
+/**
+ * Anime.js - utils - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { noop } from '../core/consts.js';
+import { globals } from '../core/globals.js';
+import { isFnc, isUnd } from '../core/helpers.js';
+import { Timer } from '../timer/timer.js';
+
+/**
+ * @import {
+ * Callback,
+ * Tickable,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {Callback<Timer>} [callback]
+ * @return {Timer}
+ */
+const sync = (callback = noop) => {
+ return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
+};
+
+/**
+ * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor
+ * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)}
+ */
+const keepTime = constructor => {
+ /** @type {Tickable} */
+ let tracked;
+ return (...args) => {
+ let currentIteration, currentIterationProgress, reversed, alternate;
+ if (tracked) {
+ currentIteration = tracked.currentIteration;
+ currentIterationProgress = tracked.iterationProgress;
+ reversed = tracked.reversed;
+ alternate = tracked._alternate;
+ tracked.revert();
+ }
+ const cleanup = constructor(...args);
+ if (cleanup && !isFnc(cleanup) && cleanup.revert) tracked = cleanup;
+ if (!isUnd(currentIterationProgress)) {
+ /** @type {Tickable} */(tracked).currentIteration = currentIteration;
+ /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress;
+ }
+ return cleanup || noop;
+ }
+};
+
+export { keepTime, sync };
diff --git a/dist/modules/waapi/composition.cjs b/dist/modules/waapi/composition.cjs
new file mode 100644
index 00000000..ea01842c
--- /dev/null
+++ b/dist/modules/waapi/composition.cjs
@@ -0,0 +1,89 @@
+/**
+ * Anime.js - waapi - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+
+/**
+ * @import {
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
+
+const WAAPIAnimationsLookups = {
+ _head: null,
+ _tail: null,
+};
+
+/**
+ * @param {DOMTarget} $el
+ * @param {String} [property]
+ * @param {WAAPIAnimation} [parent]
+ */
+const removeWAAPIAnimation = ($el, property, parent) => {
+ let nextLookup = WAAPIAnimationsLookups._head;
+ while (nextLookup) {
+ const next = nextLookup._next;
+ const matchTarget = nextLookup.$el === $el;
+ const matchProperty = !property || nextLookup.property === property;
+ const matchParent = !parent || nextLookup.parent === parent;
+ if (matchTarget && matchProperty && matchParent) {
+ const anim = nextLookup.animation;
+ try { anim.commitStyles(); } catch {} anim.cancel();
+ helpers.removeChild(WAAPIAnimationsLookups, nextLookup);
+ const lookupParent = nextLookup.parent;
+ if (lookupParent) {
+ lookupParent._completed++;
+ if (lookupParent.animations.length === lookupParent._completed) {
+ lookupParent.completed = true;
+ if (!lookupParent.muteCallbacks) {
+ lookupParent.paused = true;
+ lookupParent.onComplete(lookupParent);
+ lookupParent._resolve(lookupParent);
+ }
+ }
+ }
+ }
+ nextLookup = next;
+ }
+};
+
+/**
+ * @param {WAAPIAnimation} parent
+ * @param {DOMTarget} $el
+ * @param {String} property
+ * @param {PropertyIndexedKeyframes} keyframes
+ * @param {KeyframeAnimationOptions} params
+ * @retun {Animation}
+ */
+const addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
+ const animation = $el.animate(keyframes, params);
+ const animTotalDuration = params.delay + (+params.duration * params.iterations);
+ animation.playbackRate = parent._speed;
+ if (parent.paused) animation.pause();
+ if (parent.duration < animTotalDuration) {
+ parent.duration = animTotalDuration;
+ parent.controlAnimation = animation;
+ }
+ parent.animations.push(animation);
+ removeWAAPIAnimation($el, property);
+ helpers.addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null });
+ const handleRemove = () => { removeWAAPIAnimation($el, property, parent); };
+ animation.onremove = handleRemove;
+ animation.onfinish = handleRemove;
+ return animation;
+};
+
+exports.addWAAPIAnimation = addWAAPIAnimation;
+exports.removeWAAPIAnimation = removeWAAPIAnimation;
diff --git a/dist/modules/waapi/composition.d.ts b/dist/modules/waapi/composition.d.ts
new file mode 100644
index 00000000..93c35c80
--- /dev/null
+++ b/dist/modules/waapi/composition.d.ts
@@ -0,0 +1,4 @@
+export function removeWAAPIAnimation($el: DOMTarget, property?: string, parent?: WAAPIAnimation): void;
+export function addWAAPIAnimation(parent: WAAPIAnimation, $el: DOMTarget, property: string, keyframes: PropertyIndexedKeyframes, params: KeyframeAnimationOptions): Animation;
+import type { DOMTarget } from '../types/index.js';
+import type { WAAPIAnimation } from '../waapi/waapi.js';
diff --git a/dist/modules/waapi/composition.js b/dist/modules/waapi/composition.js
new file mode 100644
index 00000000..346078c0
--- /dev/null
+++ b/dist/modules/waapi/composition.js
@@ -0,0 +1,86 @@
+/**
+ * Anime.js - waapi - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { removeChild, addChild } from '../core/helpers.js';
+
+/**
+ * @import {
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
+
+const WAAPIAnimationsLookups = {
+ _head: null,
+ _tail: null,
+};
+
+/**
+ * @param {DOMTarget} $el
+ * @param {String} [property]
+ * @param {WAAPIAnimation} [parent]
+ */
+const removeWAAPIAnimation = ($el, property, parent) => {
+ let nextLookup = WAAPIAnimationsLookups._head;
+ while (nextLookup) {
+ const next = nextLookup._next;
+ const matchTarget = nextLookup.$el === $el;
+ const matchProperty = !property || nextLookup.property === property;
+ const matchParent = !parent || nextLookup.parent === parent;
+ if (matchTarget && matchProperty && matchParent) {
+ const anim = nextLookup.animation;
+ try { anim.commitStyles(); } catch {} anim.cancel();
+ removeChild(WAAPIAnimationsLookups, nextLookup);
+ const lookupParent = nextLookup.parent;
+ if (lookupParent) {
+ lookupParent._completed++;
+ if (lookupParent.animations.length === lookupParent._completed) {
+ lookupParent.completed = true;
+ if (!lookupParent.muteCallbacks) {
+ lookupParent.paused = true;
+ lookupParent.onComplete(lookupParent);
+ lookupParent._resolve(lookupParent);
+ }
+ }
+ }
+ }
+ nextLookup = next;
+ }
+};
+
+/**
+ * @param {WAAPIAnimation} parent
+ * @param {DOMTarget} $el
+ * @param {String} property
+ * @param {PropertyIndexedKeyframes} keyframes
+ * @param {KeyframeAnimationOptions} params
+ * @retun {Animation}
+ */
+const addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
+ const animation = $el.animate(keyframes, params);
+ const animTotalDuration = params.delay + (+params.duration * params.iterations);
+ animation.playbackRate = parent._speed;
+ if (parent.paused) animation.pause();
+ if (parent.duration < animTotalDuration) {
+ parent.duration = animTotalDuration;
+ parent.controlAnimation = animation;
+ }
+ parent.animations.push(animation);
+ removeWAAPIAnimation($el, property);
+ addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null });
+ const handleRemove = () => { removeWAAPIAnimation($el, property, parent); };
+ animation.onremove = handleRemove;
+ animation.onfinish = handleRemove;
+ return animation;
+};
+
+export { addWAAPIAnimation, removeWAAPIAnimation };
diff --git a/dist/modules/waapi/index.cjs b/dist/modules/waapi/index.cjs
new file mode 100644
index 00000000..ab51d7e9
--- /dev/null
+++ b/dist/modules/waapi/index.cjs
@@ -0,0 +1,15 @@
+/**
+ * Anime.js - waapi - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var waapi = require('./waapi.cjs');
+
+
+
+exports.WAAPIAnimation = waapi.WAAPIAnimation;
+exports.waapi = waapi.waapi;
diff --git a/dist/modules/waapi/index.d.ts b/dist/modules/waapi/index.d.ts
new file mode 100644
index 00000000..eb223bc0
--- /dev/null
+++ b/dist/modules/waapi/index.d.ts
@@ -0,0 +1 @@
+export * from "./waapi.js";
diff --git a/dist/modules/waapi/index.js b/dist/modules/waapi/index.js
new file mode 100644
index 00000000..eee5754d
--- /dev/null
+++ b/dist/modules/waapi/index.js
@@ -0,0 +1,8 @@
+/**
+ * Anime.js - waapi - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+export { WAAPIAnimation, waapi } from './waapi.js';
diff --git a/dist/modules/waapi/waapi.cjs b/dist/modules/waapi/waapi.cjs
new file mode 100644
index 00000000..86fff3dc
--- /dev/null
+++ b/dist/modules/waapi/waapi.cjs
@@ -0,0 +1,473 @@
+/**
+ * Anime.js - waapi - CJS
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+'use strict';
+
+var helpers = require('../core/helpers.cjs');
+var globals = require('../core/globals.cjs');
+var targets = require('../core/targets.cjs');
+var values = require('../core/values.cjs');
+var consts = require('../core/consts.cjs');
+var none = require('../easings/none.cjs');
+var parser = require('../easings/parser.cjs');
+var composition = require('./composition.cjs');
+
+/**
+ * @import {
+ * Callback,
+ * EasingFunction,
+ * EasingParam,
+ * DOMTarget,
+ * DOMTargetsParam,
+ * DOMTargetsArray,
+ * WAAPIAnimationParams,
+ * WAAPITweenOptions,
+ * WAAPIKeyframeValue,
+ * WAAPICallback,
+ * WAAPITweenValue
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
+
+/**
+ * @import {
+ * ScrollObserver,
+ * } from '../events/scroll.js'
+*/
+
+/**
+ * Converts an easing function into a valid CSS linear() timing function string
+ * @param {EasingFunction} fn
+ * @param {number} [samples=100]
+ * @returns {string} CSS linear() timing function
+ */
+const easingToLinear = (fn, samples = 100) => {
+ const points = [];
+ for (let i = 0; i <= samples; i++) points.push(fn(i / samples));
+ return `linear(${points.join(', ')})`;
+};
+
+const WAAPIEasesLookups = {
+ in: 'ease-in',
+ out: 'ease-out',
+ inOut: 'ease-in-out',
+};
+
+const WAAPIeases = /*#__PURE__*/(() => {
+ const list = {};
+ for (let type in parser.easeTypes) list[type] = (/** @type {String|Number} */p) => parser.easeTypes[type](parser.easeInPower(p));
+ return /** @type {Record<String, EasingFunction>} */(list);
+})();
+
+/**
+ * @param {EasingParam} ease
+ * @return {String}
+ */
+const parseWAAPIEasing = (ease) => {
+ let parsedEase = WAAPIEasesLookups[ease];
+ if (parsedEase) return parsedEase;
+ parsedEase = 'linear';
+ if (helpers.isStr(ease)) {
+ if (
+ helpers.stringStartsWith(ease, 'linear') ||
+ helpers.stringStartsWith(ease, 'cubic-') ||
+ helpers.stringStartsWith(ease, 'steps') ||
+ helpers.stringStartsWith(ease, 'ease')
+ ) {
+ parsedEase = ease;
+ } else if (helpers.stringStartsWith(ease, 'cubicB')) {
+ parsedEase = helpers.toLowerCase(ease);
+ } else {
+ const parsed = parser.parseEaseString(ease, WAAPIeases, WAAPIEasesLookups);
+ if (helpers.isFnc(parsed)) parsedEase = parsed === none.none ? 'linear' : easingToLinear(parsed);
+ }
+ WAAPIEasesLookups[ease] = parsedEase;
+ } else if (helpers.isFnc(ease)) {
+ const easing = easingToLinear(ease);
+ if (easing) parsedEase = easing;
+ } else if (/** @type {Spring} */(ease).ease) {
+ parsedEase = easingToLinear(/** @type {Spring} */(ease).ease);
+ }
+ return parsedEase;
+};
+
+const transformsShorthands = ['x', 'y', 'z'];
+const commonDefaultPXProperties = [
+ 'perspective',
+ 'width',
+ 'height',
+ 'margin',
+ 'padding',
+ 'top',
+ 'right',
+ 'bottom',
+ 'left',
+ 'borderWidth',
+ 'fontSize',
+ 'borderRadius',
+ ...transformsShorthands
+];
+
+const validIndividualTransforms = /*#__PURE__*/ (() => [...transformsShorthands, ...consts.validTransforms.filter(t => ['X', 'Y', 'Z'].some(axis => t.endsWith(axis)))])();
+
+let transformsPropertiesRegistered = null;
+
+/**
+ * @param {String} propName
+ * @param {WAAPIKeyframeValue} value
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ * @param {Number} targetsLength
+ * @return {String}
+ */
+const normalizeTweenValue = (propName, value, $el, i, targetsLength) => {
+ let v = values.getFunctionValue(/** @type {any} */(value), $el, i, targetsLength);
+ if (!helpers.isNum(v)) return v;
+ if (commonDefaultPXProperties.includes(propName) || helpers.stringStartsWith(propName, 'translate')) return `${v}px`;
+ if (helpers.stringStartsWith(propName, 'rotate') || helpers.stringStartsWith(propName, 'skew')) return `${v}deg`;
+ return `${v}`;
+};
+
+/**
+ * @param {DOMTarget} $el
+ * @param {String} propName
+ * @param {WAAPIKeyframeValue} from
+ * @param {WAAPIKeyframeValue} to
+ * @param {Number} i
+ * @param {Number} targetsLength
+ * @return {WAAPITweenValue}
+ */
+const parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => {
+ /** @type {WAAPITweenValue} */
+ let tweenValue = '0';
+ const computedTo = !helpers.isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName];
+ if (!helpers.isUnd(from)) {
+ const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength);
+ tweenValue = [computedFrom, computedTo];
+ } else {
+ tweenValue = helpers.isArr(to) ? to.map((/** @type {any} */v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo;
+ }
+ return tweenValue;
+};
+
+class WAAPIAnimation {
+/**
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
+ */
+ constructor(targets$1, params) {
+
+ if (globals.scope.current) globals.scope.current.register(this);
+
+ // Skip the registration and fallback to no animation in case CSS.registerProperty is not supported
+ if (helpers.isNil(transformsPropertiesRegistered)) {
+ if (consts.isBrowser && (helpers.isUnd(CSS) || !Object.hasOwnProperty.call(CSS, 'registerProperty'))) {
+ transformsPropertiesRegistered = false;
+ } else {
+ consts.validTransforms.forEach(t => {
+ const isSkew = helpers.stringStartsWith(t, 'skew');
+ const isScale = helpers.stringStartsWith(t, 'scale');
+ const isRotate = helpers.stringStartsWith(t, 'rotate');
+ const isTranslate = helpers.stringStartsWith(t, 'translate');
+ const isAngle = isRotate || isSkew;
+ const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*";
+ try {
+ CSS.registerProperty({
+ name: '--' + t,
+ syntax,
+ inherits: false,
+ initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0',
+ });
+ } catch {} });
+ transformsPropertiesRegistered = true;
+ }
+ }
+
+ const parsedTargets = targets.registerTargets(targets$1);
+ const targetsLength = parsedTargets.length;
+
+ if (!targetsLength) {
+ console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
+ }
+
+ const ease = values.setValue(params.ease, parseWAAPIEasing(globals.globals.defaults.ease));
+ const spring = /** @type {Spring} */(ease).ease && ease;
+ const autoplay = values.setValue(params.autoplay, globals.globals.defaults.autoplay);
+ const scroll = autoplay && /** @type {ScrollObserver} */(autoplay).link ? autoplay : false;
+ const alternate = params.alternate && /** @type {Boolean} */(params.alternate) === true;
+ const reversed = params.reversed && /** @type {Boolean} */(params.reversed) === true;
+ const loop = values.setValue(params.loop, globals.globals.defaults.loop);
+ const iterations = /** @type {Number} */((loop === true || loop === Infinity) ? Infinity : helpers.isNum(loop) ? loop + 1 : 1);
+ /** @type {PlaybackDirection} */
+ const direction = alternate ? reversed ? 'alternate-reverse' : 'alternate' : reversed ? 'reverse' : 'normal';
+ /** @type {FillMode} */
+ const fill = 'forwards';
+ /** @type {String} */
+ const easing = parseWAAPIEasing(ease);
+ const timeScale = (globals.globals.timeScale === 1 ? 1 : consts.K);
+
+ /** @type {DOMTargetsArray}] */
+ this.targets = parsedTargets;
+ /** @type {Array<globalThis.Animation>}] */
+ this.animations = [];
+ /** @type {globalThis.Animation}] */
+ this.controlAnimation = null;
+ /** @type {Callback<this>} */
+ this.onComplete = params.onComplete || consts.noop;
+ /** @type {Number} */
+ this.duration = 0;
+ /** @type {Boolean} */
+ this.muteCallbacks = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Boolean} */
+ this.paused = !autoplay || scroll !== false;
+ /** @type {Boolean} */
+ this.reversed = reversed;
+ /** @type {Boolean|ScrollObserver} */
+ this.autoplay = autoplay;
+ /** @type {Number} */
+ this._speed = values.setValue(params.playbackRate, globals.globals.defaults.playbackRate);
+ /** @type {Function} */
+ this._resolve = consts.noop; // Used by .then()
+ /** @type {Number} */
+ this._completed = 0;
+ /** @type {Array<Object>}] */
+ this._inlineStyles = parsedTargets.map($el => $el.getAttribute('style'));
+
+ parsedTargets.forEach(($el, i) => {
+
+ const cachedTransforms = $el[consts.transformsSymbol];
+
+ const hasIndividualTransforms = validIndividualTransforms.some(t => params.hasOwnProperty(t));
+
+ /** @type {Number} */
+ const duration = (spring ? /** @type {Spring} */(spring).duration : values.getFunctionValue(values.setValue(params.duration, globals.globals.defaults.duration), $el, i, targetsLength)) * timeScale;
+ /** @type {Number} */
+ const delay = values.getFunctionValue(values.setValue(params.delay, globals.globals.defaults.delay), $el, i, targetsLength) * timeScale;
+ /** @type {CompositeOperation} */
+ const composite = /** @type {CompositeOperation} */(values.setValue(params.composition, 'replace'));
+
+ for (let name in params) {
+ if (!helpers.isKey(name)) continue;
+ /** @type {PropertyIndexedKeyframes} */
+ const keyframes = {};
+ /** @type {KeyframeAnimationOptions} */
+ const tweenParams = { iterations, direction, fill, easing, duration, delay, composite };
+ const propertyValue = params[name];
+ const individualTransformProperty = hasIndividualTransforms ? consts.validTransforms.includes(name) ? name : consts.shortTransforms.get(name) : false;
+ let parsedPropertyValue;
+ if (helpers.isObj(propertyValue)) {
+ const tweenOptions = /** @type {WAAPITweenOptions} */(propertyValue);
+ const tweenOptionsEase = values.setValue(tweenOptions.ease, ease);
+ const tweenOptionsSpring = /** @type {Spring} */(tweenOptionsEase).ease && tweenOptionsEase;
+ const to = /** @type {WAAPITweenOptions} */(tweenOptions).to;
+ const from = /** @type {WAAPITweenOptions} */(tweenOptions).from;
+ /** @type {Number} */
+ tweenParams.duration = (tweenOptionsSpring ? /** @type {Spring} */(tweenOptionsSpring).duration : values.getFunctionValue(values.setValue(tweenOptions.duration, duration), $el, i, targetsLength)) * timeScale;
+ /** @type {Number} */
+ tweenParams.delay = values.getFunctionValue(values.setValue(tweenOptions.delay, delay), $el, i, targetsLength) * timeScale;
+ /** @type {CompositeOperation} */
+ tweenParams.composite = /** @type {CompositeOperation} */(values.setValue(tweenOptions.composition, composite));
+ /** @type {String} */
+ tweenParams.easing = parseWAAPIEasing(tweenOptionsEase);
+ parsedPropertyValue = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
+ if (individualTransformProperty) {
+ keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
+ cachedTransforms[individualTransformProperty] = parsedPropertyValue;
+ } else {
+ keyframes[name] = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
+ }
+ composition.addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
+ if (!helpers.isUnd(from)) {
+ if (!individualTransformProperty) {
+ $el.style[name] = keyframes[name][0];
+ } else {
+ const key = `--${individualTransformProperty}`;
+ $el.style.setProperty(key, keyframes[key][0]);
+ }
+ }
+ } else {
+ parsedPropertyValue = helpers.isArr(propertyValue) ?
+ propertyValue.map((/** @type {any} */v) => normalizeTweenValue(name, v, $el, i, targetsLength)) :
+ normalizeTweenValue(name, /** @type {any} */(propertyValue), $el, i, targetsLength);
+ if (individualTransformProperty) {
+ keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
+ cachedTransforms[individualTransformProperty] = parsedPropertyValue;
+ } else {
+ keyframes[name] = parsedPropertyValue;
+ }
+ composition.addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
+ }
+ }
+ if (hasIndividualTransforms) {
+ let transforms = consts.emptyString;
+ for (let t in cachedTransforms) {
+ transforms += `${consts.transformsFragmentStrings[t]}var(--${t})) `;
+ }
+ $el.style.transform = transforms;
+ }
+ });
+
+ if (scroll) {
+ /** @type {ScrollObserver} */(this.autoplay).link(this);
+ }
+ }
+
+ /**
+ * @callback forEachCallback
+ * @param {globalThis.Animation} animation
+ */
+
+ /**
+ * @param {forEachCallback|String} callback
+ * @return {this}
+ */
+ forEach(callback) {
+ const cb = helpers.isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback;
+ this.animations.forEach(cb);
+ return this;
+ }
+
+ get speed() {
+ return this._speed;
+ }
+
+ set speed(speed) {
+ this._speed = +speed;
+ this.forEach(anim => anim.playbackRate = speed);
+ }
+
+ get currentTime() {
+ const controlAnimation = this.controlAnimation;
+ const timeScale = globals.globals.timeScale;
+ return this.completed ? this.duration : controlAnimation ? +controlAnimation.currentTime * (timeScale === 1 ? 1 : timeScale) : 0;
+ }
+
+ set currentTime(time) {
+ const t = time * (globals.globals.timeScale === 1 ? 1 : consts.K);
+ this.forEach(anim => {
+ // Make sure the animation playState is not 'paused' in order to properly trigger an onfinish callback.
+ // The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported.
+ // https://developer.mozilla.org/en-US/docs/Web/API/Animation/finish_event
+ if (t >= this.duration) anim.play();
+ anim.currentTime = t;
+ });
+ }
+
+ get progress() {
+ return this.currentTime / this.duration;
+ }
+
+ set progress(progress) {
+ this.forEach(anim => anim.currentTime = progress * this.duration || 0);
+ }
+
+ resume() {
+ if (!this.paused) return this;
+ this.paused = false;
+ // TODO: Store the current time, and seek back to the last position
+ return this.forEach('play');
+ }
+
+ pause() {
+ if (this.paused) return this;
+ this.paused = true;
+ return this.forEach('pause');
+ }
+
+ alternate() {
+ this.reversed = !this.reversed;
+ this.forEach('reverse');
+ if (this.paused) this.forEach('pause');
+ return this;
+ }
+
+ play() {
+ if (this.reversed) this.alternate();
+ return this.resume();
+ }
+
+ reverse() {
+ if (!this.reversed) this.alternate();
+ return this.resume();
+ }
+
+ /**
+ * @param {Number} time
+ * @param {Boolean} muteCallbacks
+ */
+ seek(time, muteCallbacks = false) {
+ if (muteCallbacks) this.muteCallbacks = true;
+ if (time < this.duration) this.completed = false;
+ this.currentTime = time;
+ this.muteCallbacks = false;
+ if (this.paused) this.pause();
+ return this;
+ }
+
+ restart() {
+ this.completed = false;
+ return this.seek(0, true).resume();
+ }
+
+ commitStyles() {
+ return this.forEach('commitStyles');
+ }
+
+ complete() {
+ return this.seek(this.duration);
+ }
+
+ cancel() {
+ this.forEach('cancel');
+ return this.pause();
+ }
+
+ revert() {
+ this.cancel();
+ this.targets.forEach(($el, i) => $el.setAttribute('style', this._inlineStyles[i]) );
+ return this;
+ }
+
+ /**
+ * @param {WAAPICallback} [callback]
+ * @return {Promise}
+ */
+ then(callback = consts.noop) {
+ const then = this.then;
+ const onResolve = () => {
+ this.then = null;
+ callback(this);
+ this.then = then;
+ this._resolve = consts.noop;
+ };
+ return new Promise(r => {
+ this._resolve = () => r(onResolve());
+ if (this.completed) this._resolve();
+ return this;
+ });
+ }
+}
+
+const waapi = {
+/**
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
+ * @return {WAAPIAnimation}
+ */
+ animate: (targets, params) => new WAAPIAnimation(targets, params),
+ convertEase: easingToLinear
+};
+
+exports.WAAPIAnimation = WAAPIAnimation;
+exports.waapi = waapi;
diff --git a/dist/modules/waapi/waapi.d.ts b/dist/modules/waapi/waapi.d.ts
new file mode 100644
index 00000000..23ca5efc
--- /dev/null
+++ b/dist/modules/waapi/waapi.d.ts
@@ -0,0 +1,114 @@
+export class WAAPIAnimation {
+ /**
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
+ */
+ constructor(targets: DOMTargetsParam, params: WAAPIAnimationParams);
+ /** @type {DOMTargetsArray}] */
+ targets: DOMTargetsArray;
+ /** @type {Array<globalThis.Animation>}] */
+ animations: Array<globalThis.Animation>;
+ /** @type {globalThis.Animation}] */
+ controlAnimation: globalThis.Animation;
+ /** @type {Callback<this>} */
+ onComplete: Callback<this>;
+ /** @type {Number} */
+ duration: number;
+ /** @type {Boolean} */
+ muteCallbacks: boolean;
+ /** @type {Boolean} */
+ completed: boolean;
+ /** @type {Boolean} */
+ paused: boolean;
+ /** @type {Boolean} */
+ reversed: boolean;
+ /** @type {Boolean|ScrollObserver} */
+ autoplay: boolean | ScrollObserver;
+ /** @type {Number} */
+ _speed: number;
+ /** @type {Function} */
+ _resolve: Function;
+ /** @type {Number} */
+ _completed: number;
+ /** @type {Array<Object>}] */
+ _inlineStyles: Array<any>;
+ /**
+ * @callback forEachCallback
+ * @param {globalThis.Animation} animation
+ */
+ /**
+ * @param {forEachCallback|String} callback
+ * @return {this}
+ */
+ forEach(callback: ((animation: globalThis.Animation) => any) | string): this;
+ set speed(speed: number);
+ get speed(): number;
+ set currentTime(time: number);
+ get currentTime(): number;
+ set progress(progress: number);
+ get progress(): number;
+ resume(): this;
+ pause(): this;
+ alternate(): this;
+ play(): this;
+ reverse(): this;
+ /**
+ * @param {Number} time
+ * @param {Boolean} muteCallbacks
+ */
+ seek(time: number, muteCallbacks?: boolean): this;
+ restart(): this;
+ commitStyles(): this;
+ complete(): this;
+ cancel(): this;
+ revert(): this;
+ /**
+ * @param {WAAPICallback} [callback]
+ * @return {Promise}
+ */
+ then(callback?: WAAPICallback): Promise<any>;
+}
+export namespace waapi {
+ export function animate(targets: DOMTargetsParam, params: WAAPIAnimationParams): WAAPIAnimation;
+ export { easingToLinear as convertEase };
+}
+import type { DOMTargetsArray } from '../types/index.js';
+import type { Callback } from '../types/index.js';
+import type { ScrollObserver } from '../events/scroll.js';
+import type { WAAPICallback } from '../types/index.js';
+import type { DOMTargetsParam } from '../types/index.js';
+import type { WAAPIAnimationParams } from '../types/index.js';
+/**
+ * @import {
+ * Callback,
+ * EasingFunction,
+ * EasingParam,
+ * DOMTarget,
+ * DOMTargetsParam,
+ * DOMTargetsArray,
+ * WAAPIAnimationParams,
+ * WAAPITweenOptions,
+ * WAAPIKeyframeValue,
+ * WAAPICallback,
+ * WAAPITweenValue
+ * } from '../types/index.js'
+*/
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
+/**
+ * @import {
+ * ScrollObserver,
+ * } from '../events/scroll.js'
+*/
+/**
+ * Converts an easing function into a valid CSS linear() timing function string
+ * @param {EasingFunction} fn
+ * @param {number} [samples=100]
+ * @returns {string} CSS linear() timing function
+ */
+declare function easingToLinear(fn: EasingFunction, samples?: number): string;
+import type { EasingFunction } from '../types/index.js';
+export {};
diff --git a/dist/modules/waapi/waapi.js b/dist/modules/waapi/waapi.js
new file mode 100644
index 00000000..a42a617e
--- /dev/null
+++ b/dist/modules/waapi/waapi.js
@@ -0,0 +1,470 @@
+/**
+ * Anime.js - waapi - ESM
+ * @version v4.2.0
+ * @license MIT
+ * @copyright 2025 - Julian Garnier
+ */
+
+import { isNil, isUnd, stringStartsWith, isKey, isObj, isArr, isStr, toLowerCase, isFnc, isNum } from '../core/helpers.js';
+import { scope, globals } from '../core/globals.js';
+import { registerTargets } from '../core/targets.js';
+import { setValue, getFunctionValue } from '../core/values.js';
+import { isBrowser, validTransforms, noop, transformsSymbol, shortTransforms, transformsFragmentStrings, emptyString, K } from '../core/consts.js';
+import { none } from '../easings/none.js';
+import { parseEaseString, easeTypes, easeInPower } from '../easings/parser.js';
+import { addWAAPIAnimation } from './composition.js';
+
+/**
+ * @import {
+ * Callback,
+ * EasingFunction,
+ * EasingParam,
+ * DOMTarget,
+ * DOMTargetsParam,
+ * DOMTargetsArray,
+ * WAAPIAnimationParams,
+ * WAAPITweenOptions,
+ * WAAPIKeyframeValue,
+ * WAAPICallback,
+ * WAAPITweenValue
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
+
+/**
+ * @import {
+ * ScrollObserver,
+ * } from '../events/scroll.js'
+*/
+
+/**
+ * Converts an easing function into a valid CSS linear() timing function string
+ * @param {EasingFunction} fn
+ * @param {number} [samples=100]
+ * @returns {string} CSS linear() timing function
+ */
+const easingToLinear = (fn, samples = 100) => {
+ const points = [];
+ for (let i = 0; i <= samples; i++) points.push(fn(i / samples));
+ return `linear(${points.join(', ')})`;
+};
+
+const WAAPIEasesLookups = {
+ in: 'ease-in',
+ out: 'ease-out',
+ inOut: 'ease-in-out',
+};
+
+const WAAPIeases = /*#__PURE__*/(() => {
+ const list = {};
+ for (let type in easeTypes) list[type] = (/** @type {String|Number} */p) => easeTypes[type](easeInPower(p));
+ return /** @type {Record<String, EasingFunction>} */(list);
+})();
+
+/**
+ * @param {EasingParam} ease
+ * @return {String}
+ */
+const parseWAAPIEasing = (ease) => {
+ let parsedEase = WAAPIEasesLookups[ease];
+ if (parsedEase) return parsedEase;
+ parsedEase = 'linear';
+ if (isStr(ease)) {
+ if (
+ stringStartsWith(ease, 'linear') ||
+ stringStartsWith(ease, 'cubic-') ||
+ stringStartsWith(ease, 'steps') ||
+ stringStartsWith(ease, 'ease')
+ ) {
+ parsedEase = ease;
+ } else if (stringStartsWith(ease, 'cubicB')) {
+ parsedEase = toLowerCase(ease);
+ } else {
+ const parsed = parseEaseString(ease, WAAPIeases, WAAPIEasesLookups);
+ if (isFnc(parsed)) parsedEase = parsed === none ? 'linear' : easingToLinear(parsed);
+ }
+ WAAPIEasesLookups[ease] = parsedEase;
+ } else if (isFnc(ease)) {
+ const easing = easingToLinear(ease);
+ if (easing) parsedEase = easing;
+ } else if (/** @type {Spring} */(ease).ease) {
+ parsedEase = easingToLinear(/** @type {Spring} */(ease).ease);
+ }
+ return parsedEase;
+};
+
+const transformsShorthands = ['x', 'y', 'z'];
+const commonDefaultPXProperties = [
+ 'perspective',
+ 'width',
+ 'height',
+ 'margin',
+ 'padding',
+ 'top',
+ 'right',
+ 'bottom',
+ 'left',
+ 'borderWidth',
+ 'fontSize',
+ 'borderRadius',
+ ...transformsShorthands
+];
+
+const validIndividualTransforms = /*#__PURE__*/ (() => [...transformsShorthands, ...validTransforms.filter(t => ['X', 'Y', 'Z'].some(axis => t.endsWith(axis)))])();
+
+let transformsPropertiesRegistered = null;
+
+/**
+ * @param {String} propName
+ * @param {WAAPIKeyframeValue} value
+ * @param {DOMTarget} $el
+ * @param {Number} i
+ * @param {Number} targetsLength
+ * @return {String}
+ */
+const normalizeTweenValue = (propName, value, $el, i, targetsLength) => {
+ let v = getFunctionValue(/** @type {any} */(value), $el, i, targetsLength);
+ if (!isNum(v)) return v;
+ if (commonDefaultPXProperties.includes(propName) || stringStartsWith(propName, 'translate')) return `${v}px`;
+ if (stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew')) return `${v}deg`;
+ return `${v}`;
+};
+
+/**
+ * @param {DOMTarget} $el
+ * @param {String} propName
+ * @param {WAAPIKeyframeValue} from
+ * @param {WAAPIKeyframeValue} to
+ * @param {Number} i
+ * @param {Number} targetsLength
+ * @return {WAAPITweenValue}
+ */
+const parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => {
+ /** @type {WAAPITweenValue} */
+ let tweenValue = '0';
+ const computedTo = !isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName];
+ if (!isUnd(from)) {
+ const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength);
+ tweenValue = [computedFrom, computedTo];
+ } else {
+ tweenValue = isArr(to) ? to.map((/** @type {any} */v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo;
+ }
+ return tweenValue;
+};
+
+class WAAPIAnimation {
+/**
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
+ */
+ constructor(targets, params) {
+
+ if (scope.current) scope.current.register(this);
+
+ // Skip the registration and fallback to no animation in case CSS.registerProperty is not supported
+ if (isNil(transformsPropertiesRegistered)) {
+ if (isBrowser && (isUnd(CSS) || !Object.hasOwnProperty.call(CSS, 'registerProperty'))) {
+ transformsPropertiesRegistered = false;
+ } else {
+ validTransforms.forEach(t => {
+ const isSkew = stringStartsWith(t, 'skew');
+ const isScale = stringStartsWith(t, 'scale');
+ const isRotate = stringStartsWith(t, 'rotate');
+ const isTranslate = stringStartsWith(t, 'translate');
+ const isAngle = isRotate || isSkew;
+ const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*";
+ try {
+ CSS.registerProperty({
+ name: '--' + t,
+ syntax,
+ inherits: false,
+ initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0',
+ });
+ } catch {} });
+ transformsPropertiesRegistered = true;
+ }
+ }
+
+ const parsedTargets = registerTargets(targets);
+ const targetsLength = parsedTargets.length;
+
+ if (!targetsLength) {
+ console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
+ }
+
+ const ease = setValue(params.ease, parseWAAPIEasing(globals.defaults.ease));
+ const spring = /** @type {Spring} */(ease).ease && ease;
+ const autoplay = setValue(params.autoplay, globals.defaults.autoplay);
+ const scroll = autoplay && /** @type {ScrollObserver} */(autoplay).link ? autoplay : false;
+ const alternate = params.alternate && /** @type {Boolean} */(params.alternate) === true;
+ const reversed = params.reversed && /** @type {Boolean} */(params.reversed) === true;
+ const loop = setValue(params.loop, globals.defaults.loop);
+ const iterations = /** @type {Number} */((loop === true || loop === Infinity) ? Infinity : isNum(loop) ? loop + 1 : 1);
+ /** @type {PlaybackDirection} */
+ const direction = alternate ? reversed ? 'alternate-reverse' : 'alternate' : reversed ? 'reverse' : 'normal';
+ /** @type {FillMode} */
+ const fill = 'forwards';
+ /** @type {String} */
+ const easing = parseWAAPIEasing(ease);
+ const timeScale = (globals.timeScale === 1 ? 1 : K);
+
+ /** @type {DOMTargetsArray}] */
+ this.targets = parsedTargets;
+ /** @type {Array<globalThis.Animation>}] */
+ this.animations = [];
+ /** @type {globalThis.Animation}] */
+ this.controlAnimation = null;
+ /** @type {Callback<this>} */
+ this.onComplete = params.onComplete || noop;
+ /** @type {Number} */
+ this.duration = 0;
+ /** @type {Boolean} */
+ this.muteCallbacks = false;
+ /** @type {Boolean} */
+ this.completed = false;
+ /** @type {Boolean} */
+ this.paused = !autoplay || scroll !== false;
+ /** @type {Boolean} */
+ this.reversed = reversed;
+ /** @type {Boolean|ScrollObserver} */
+ this.autoplay = autoplay;
+ /** @type {Number} */
+ this._speed = setValue(params.playbackRate, globals.defaults.playbackRate);
+ /** @type {Function} */
+ this._resolve = noop; // Used by .then()
+ /** @type {Number} */
+ this._completed = 0;
+ /** @type {Array<Object>}] */
+ this._inlineStyles = parsedTargets.map($el => $el.getAttribute('style'));
+
+ parsedTargets.forEach(($el, i) => {
+
+ const cachedTransforms = $el[transformsSymbol];
+
+ const hasIndividualTransforms = validIndividualTransforms.some(t => params.hasOwnProperty(t));
+
+ /** @type {Number} */
+ const duration = (spring ? /** @type {Spring} */(spring).duration : getFunctionValue(setValue(params.duration, globals.defaults.duration), $el, i, targetsLength)) * timeScale;
+ /** @type {Number} */
+ const delay = getFunctionValue(setValue(params.delay, globals.defaults.delay), $el, i, targetsLength) * timeScale;
+ /** @type {CompositeOperation} */
+ const composite = /** @type {CompositeOperation} */(setValue(params.composition, 'replace'));
+
+ for (let name in params) {
+ if (!isKey(name)) continue;
+ /** @type {PropertyIndexedKeyframes} */
+ const keyframes = {};
+ /** @type {KeyframeAnimationOptions} */
+ const tweenParams = { iterations, direction, fill, easing, duration, delay, composite };
+ const propertyValue = params[name];
+ const individualTransformProperty = hasIndividualTransforms ? validTransforms.includes(name) ? name : shortTransforms.get(name) : false;
+ let parsedPropertyValue;
+ if (isObj(propertyValue)) {
+ const tweenOptions = /** @type {WAAPITweenOptions} */(propertyValue);
+ const tweenOptionsEase = setValue(tweenOptions.ease, ease);
+ const tweenOptionsSpring = /** @type {Spring} */(tweenOptionsEase).ease && tweenOptionsEase;
+ const to = /** @type {WAAPITweenOptions} */(tweenOptions).to;
+ const from = /** @type {WAAPITweenOptions} */(tweenOptions).from;
+ /** @type {Number} */
+ tweenParams.duration = (tweenOptionsSpring ? /** @type {Spring} */(tweenOptionsSpring).duration : getFunctionValue(setValue(tweenOptions.duration, duration), $el, i, targetsLength)) * timeScale;
+ /** @type {Number} */
+ tweenParams.delay = getFunctionValue(setValue(tweenOptions.delay, delay), $el, i, targetsLength) * timeScale;
+ /** @type {CompositeOperation} */
+ tweenParams.composite = /** @type {CompositeOperation} */(setValue(tweenOptions.composition, composite));
+ /** @type {String} */
+ tweenParams.easing = parseWAAPIEasing(tweenOptionsEase);
+ parsedPropertyValue = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
+ if (individualTransformProperty) {
+ keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
+ cachedTransforms[individualTransformProperty] = parsedPropertyValue;
+ } else {
+ keyframes[name] = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
+ }
+ addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
+ if (!isUnd(from)) {
+ if (!individualTransformProperty) {
+ $el.style[name] = keyframes[name][0];
+ } else {
+ const key = `--${individualTransformProperty}`;
+ $el.style.setProperty(key, keyframes[key][0]);
+ }
+ }
+ } else {
+ parsedPropertyValue = isArr(propertyValue) ?
+ propertyValue.map((/** @type {any} */v) => normalizeTweenValue(name, v, $el, i, targetsLength)) :
+ normalizeTweenValue(name, /** @type {any} */(propertyValue), $el, i, targetsLength);
+ if (individualTransformProperty) {
+ keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
+ cachedTransforms[individualTransformProperty] = parsedPropertyValue;
+ } else {
+ keyframes[name] = parsedPropertyValue;
+ }
+ addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
+ }
+ }
+ if (hasIndividualTransforms) {
+ let transforms = emptyString;
+ for (let t in cachedTransforms) {
+ transforms += `${transformsFragmentStrings[t]}var(--${t})) `;
+ }
+ $el.style.transform = transforms;
+ }
+ });
+
+ if (scroll) {
+ /** @type {ScrollObserver} */(this.autoplay).link(this);
+ }
+ }
+
+ /**
+ * @callback forEachCallback
+ * @param {globalThis.Animation} animation
+ */
+
+ /**
+ * @param {forEachCallback|String} callback
+ * @return {this}
+ */
+ forEach(callback) {
+ const cb = isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback;
+ this.animations.forEach(cb);
+ return this;
+ }
+
+ get speed() {
+ return this._speed;
+ }
+
+ set speed(speed) {
+ this._speed = +speed;
+ this.forEach(anim => anim.playbackRate = speed);
+ }
+
+ get currentTime() {
+ const controlAnimation = this.controlAnimation;
+ const timeScale = globals.timeScale;
+ return this.completed ? this.duration : controlAnimation ? +controlAnimation.currentTime * (timeScale === 1 ? 1 : timeScale) : 0;
+ }
+
+ set currentTime(time) {
+ const t = time * (globals.timeScale === 1 ? 1 : K);
+ this.forEach(anim => {
+ // Make sure the animation playState is not 'paused' in order to properly trigger an onfinish callback.
+ // The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported.
+ // https://developer.mozilla.org/en-US/docs/Web/API/Animation/finish_event
+ if (t >= this.duration) anim.play();
+ anim.currentTime = t;
+ });
+ }
+
+ get progress() {
+ return this.currentTime / this.duration;
+ }
+
+ set progress(progress) {
+ this.forEach(anim => anim.currentTime = progress * this.duration || 0);
+ }
+
+ resume() {
+ if (!this.paused) return this;
+ this.paused = false;
+ // TODO: Store the current time, and seek back to the last position
+ return this.forEach('play');
+ }
+
+ pause() {
+ if (this.paused) return this;
+ this.paused = true;
+ return this.forEach('pause');
+ }
+
+ alternate() {
+ this.reversed = !this.reversed;
+ this.forEach('reverse');
+ if (this.paused) this.forEach('pause');
+ return this;
+ }
+
+ play() {
+ if (this.reversed) this.alternate();
+ return this.resume();
+ }
+
+ reverse() {
+ if (!this.reversed) this.alternate();
+ return this.resume();
+ }
+
+ /**
+ * @param {Number} time
+ * @param {Boolean} muteCallbacks
+ */
+ seek(time, muteCallbacks = false) {
+ if (muteCallbacks) this.muteCallbacks = true;
+ if (time < this.duration) this.completed = false;
+ this.currentTime = time;
+ this.muteCallbacks = false;
+ if (this.paused) this.pause();
+ return this;
+ }
+
+ restart() {
+ this.completed = false;
+ return this.seek(0, true).resume();
+ }
+
+ commitStyles() {
+ return this.forEach('commitStyles');
+ }
+
+ complete() {
+ return this.seek(this.duration);
+ }
+
+ cancel() {
+ this.forEach('cancel');
+ return this.pause();
+ }
+
+ revert() {
+ this.cancel();
+ this.targets.forEach(($el, i) => $el.setAttribute('style', this._inlineStyles[i]) );
+ return this;
+ }
+
+ /**
+ * @param {WAAPICallback} [callback]
+ * @return {Promise}
+ */
+ then(callback = noop) {
+ const then = this.then;
+ const onResolve = () => {
+ this.then = null;
+ callback(this);
+ this.then = then;
+ this._resolve = noop;
+ };
+ return new Promise(r => {
+ this._resolve = () => r(onResolve());
+ if (this.completed) this._resolve();
+ return this;
+ });
+ }
+}
+
+const waapi = {
+/**
+ * @param {DOMTargetsParam} targets
+ * @param {WAAPIAnimationParams} params
+ * @return {WAAPIAnimation}
+ */
+ animate: (targets, params) => new WAAPIAnimation(targets, params),
+ convertEase: easingToLinear
+};
+
+export { WAAPIAnimation, waapi };
diff --git a/examples/additive-creature/index.js b/examples/additive-creature/index.js
index 4aede9a2..1343c018 100644
--- a/examples/additive-creature/index.js
+++ b/examples/additive-creature/index.js
@@ -1,4 +1,4 @@
-import { animate, createTimeline, createTimer, stagger, utils } from '../../lib/anime.esm.js';
+import { animate, createTimeline, createTimer, stagger, utils } from '../../dist/modules/index.js';
const creatureEl = document.querySelector('#creature');
const viewport = { w: window.innerWidth * .5, h: window.innerHeight * .5 };
diff --git a/examples/additive-fireflies/index.js b/examples/additive-fireflies/index.js
index 63f095a1..8c286e21 100644
--- a/examples/additive-fireflies/index.js
+++ b/examples/additive-fireflies/index.js
@@ -1,4 +1,4 @@
-import { animate, createTimer, utils } from '../../lib/anime.esm.js';
+import { animate, createTimer, utils } from '../../dist/modules/index.js';
const $animationWrapper = document.querySelector('#animation-wrapper');
const $circle = document.querySelector('#circle');
diff --git a/examples/advanced-grid-staggering/index.js b/examples/advanced-grid-staggering/index.js
index 184ea4cf..5848ffbc 100644
--- a/examples/advanced-grid-staggering/index.js
+++ b/examples/advanced-grid-staggering/index.js
@@ -1,4 +1,4 @@
-import { createTimeline, utils, stagger } from '../../lib/anime.esm.js';
+import { createTimeline, utils, stagger } from '../../dist/modules/index.js';
const staggerVisualizerEl = document.querySelector('.stagger-visualizer');
const fragment = document.createDocumentFragment();
diff --git a/examples/animatable-follow-cursor/index.js b/examples/animatable-follow-cursor/index.js
index 26734ec7..6f8b7489 100644
--- a/examples/animatable-follow-cursor/index.js
+++ b/examples/animatable-follow-cursor/index.js
@@ -2,7 +2,7 @@ import {
createAnimatable,
utils,
stagger,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
// Setup
diff --git a/examples/animejs-v4-logo-animation/index.js b/examples/animejs-v4-logo-animation/index.js
index 1df4d3b0..3c4e5cfb 100644
--- a/examples/animejs-v4-logo-animation/index.js
+++ b/examples/animejs-v4-logo-animation/index.js
@@ -1,4 +1,4 @@
-import { createTimeline, stagger, svg, utils, eases } from '../../lib/anime.esm.js';
+import { createTimeline, stagger, svg, utils, eases } from '../../dist/modules/index.js';
const [ $dot1 ] = utils.$('#dot-1');
const onions = [];
diff --git a/examples/canvas-2d/index.js b/examples/canvas-2d/index.js
index a6ae8662..a4cb2c8f 100644
--- a/examples/canvas-2d/index.js
+++ b/examples/canvas-2d/index.js
@@ -1,4 +1,4 @@
-import { animate, createTimer, utils } from '../../lib/anime.esm.js';
+import { animate, createTimer, utils } from '../../dist/modules/index.js';
const canvasEl = document.querySelector('canvas');
const ctx = canvasEl.getContext('2d', { alpha: false });
diff --git a/examples/clock-playback-controls/index.js b/examples/clock-playback-controls/index.js
index 11f78ee5..88b4c1c4 100644
--- a/examples/clock-playback-controls/index.js
+++ b/examples/clock-playback-controls/index.js
@@ -1,4 +1,4 @@
-import { animate, createTimeline, utils } from '../../lib/anime.esm.js';
+import { animate, createTimeline, utils } from '../../dist/modules/index.js';
const [ $digitalClock ] = utils.$('#digital');
diff --git a/examples/draggable-infinite-auto-carousel/index.js b/examples/draggable-infinite-auto-carousel/index.js
index 1e84ee8f..4e19bbc8 100644
--- a/examples/draggable-infinite-auto-carousel/index.js
+++ b/examples/draggable-infinite-auto-carousel/index.js
@@ -4,7 +4,7 @@ import {
createDraggable,
createAnimatable,
utils,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
const [ $carousel ] = /** @type {Array<HTMLElement>} */(utils.$('.carousel'));
$carousel.innerHTML += $carousel.innerHTML; // Clone the children for creating the illusion of infinity
diff --git a/examples/draggable-mouse-scroll-snap-carousel/index.js b/examples/draggable-mouse-scroll-snap-carousel/index.js
index 9cc3ce79..1216cceb 100644
--- a/examples/draggable-mouse-scroll-snap-carousel/index.js
+++ b/examples/draggable-mouse-scroll-snap-carousel/index.js
@@ -2,7 +2,7 @@ import {
createTimer,
createDraggable,
utils,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
const carousel = {
totalWidth: 0,
diff --git a/examples/draggable-playground/index.js b/examples/draggable-playground/index.js
index 1040f898..69c31513 100644
--- a/examples/draggable-playground/index.js
+++ b/examples/draggable-playground/index.js
@@ -9,7 +9,7 @@ import {
createSpring,
createTimeline,
engine,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
engine.timeUnit = 'ms';
// engine.timeUnit = 's';
diff --git a/examples/easings-visualizer/index.js b/examples/easings-visualizer/index.js
index 81e8fc3e..846509bb 100644
--- a/examples/easings-visualizer/index.js
+++ b/examples/easings-visualizer/index.js
@@ -1,4 +1,4 @@
-import { animate, createTimeline, eases, createSpring, utils, stagger } from '../../lib/anime.esm.js';
+import { animate, createTimeline, eases, createSpring, utils, stagger } from '../../dist/modules/index.js';
function bindInputsToObject(name, obj, onChange = () => {}) {
const $bindedInputs = document.querySelectorAll(`[data-${ name }]`);
diff --git a/examples/irregular-playback-typewriter/index.js b/examples/irregular-playback-typewriter/index.js
index a7f6d312..3ac39978 100644
--- a/examples/irregular-playback-typewriter/index.js
+++ b/examples/irregular-playback-typewriter/index.js
@@ -4,7 +4,7 @@ import {
utils,
stagger,
eases,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
const $spans = utils.$('span');
const $cursor = utils.$('.cursor');
diff --git a/examples/layered-css-transforms/index.js b/examples/layered-css-transforms/index.js
index e67bdafe..4cc16538 100644
--- a/examples/layered-css-transforms/index.js
+++ b/examples/layered-css-transforms/index.js
@@ -1,4 +1,4 @@
-import { createTimeline, utils, createSpring } from '../../lib/anime.esm.js';
+import { createTimeline, utils, createSpring } from '../../dist/modules/index.js';
const shapeEls = document.querySelectorAll('.shape');
const triangleEl = document.querySelector('.layered-animations polygon');
diff --git a/examples/onscroll-responsive-scope/index.js b/examples/onscroll-responsive-scope/index.js
index 88139fe3..9ede8840 100644
--- a/examples/onscroll-responsive-scope/index.js
+++ b/examples/onscroll-responsive-scope/index.js
@@ -3,7 +3,7 @@ import {
onScroll,
stagger,
createScope,
-} from '../../src/anime.js';
+} from '../../dist/modules/index.js';
createScope({
mediaQueries: { landscape: '(orientation: landscape)' },
diff --git a/examples/onscroll-sticky/index.js b/examples/onscroll-sticky/index.js
index 187090b7..66d3a5f4 100644
--- a/examples/onscroll-sticky/index.js
+++ b/examples/onscroll-sticky/index.js
@@ -4,7 +4,7 @@ import {
onScroll,
createTimeline,
animate,
-} from '../../src/anime.js';
+} from '../../dist/modules/index.js';
utils.set('.card', {
rotate: () => utils.random(-1, 1, 2),
diff --git a/examples/svg-graph/index.js b/examples/svg-graph/index.js
index 396b4a36..fd1ee4a9 100644
--- a/examples/svg-graph/index.js
+++ b/examples/svg-graph/index.js
@@ -4,7 +4,7 @@ import {
createTimeline,
stagger,
utils,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
const line = svg.createDrawable('line');
diff --git a/examples/svg-line-drawing/index.js b/examples/svg-line-drawing/index.js
index d5c52f21..48e4e899 100644
--- a/examples/svg-line-drawing/index.js
+++ b/examples/svg-line-drawing/index.js
@@ -3,7 +3,7 @@ import {
createTimeline,
stagger,
utils,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
function generateLines(numberOfLines) {
const svgWidth = 1100;
diff --git a/examples/text/hover-effects/index.js b/examples/text/hover-effects/index.js
index 8c1e89fa..c38a2b72 100644
--- a/examples/text/hover-effects/index.js
+++ b/examples/text/hover-effects/index.js
@@ -4,9 +4,9 @@ import {
createSpring,
createTimeline,
stagger,
- text,
+ splitText,
utils,
-} from '../../../lib/anime.esm.js';
+} from '../../../dist/modules/index.js';
createScope({
root: '#horizontal-split',
@@ -18,7 +18,7 @@ createScope({
const { root, methods } = scope;
- text.split('h2', {
+ splitText('h2', {
chars: {
class: 'char',
clone: 'left',
@@ -48,7 +48,7 @@ createScope({
const { root } = scope;
const params = {
- split: text.split('h2', { chars: true }),
+ split: splitText('h2', { chars: true }),
strength: 0,
};
@@ -80,7 +80,7 @@ createScope({
const { root, methods } = scope;
- text.split('h2', {
+ splitText('h2', {
chars: {
class: 'char',
clone: 'top',
@@ -117,7 +117,7 @@ createScope({
}).add((scope) => {
const { root, methods } = scope;
- const { chars } = text.split('h2', { chars: true });
+ const { chars } = splitText('h2', { chars: true });
utils.set(chars, { opacity: .25 });
@@ -138,7 +138,7 @@ createScope({
const { root, methods } = scope;
- text.split('h2', {
+ splitText('h2', {
words: `<span class="word-3d word-{i}">
<em class="face face-top">{value}</em>
<em class="face-front">{value}</em>
@@ -172,7 +172,7 @@ createScope({
}).add((scope) => {
const { root, methods } = scope;
- const { chars } = text.split('h2', { chars: true });
+ const { chars } = splitText('h2', { chars: true });
scope.add('onEnter', () => {
createTimeline().add(chars, {
diff --git a/examples/text/split-effects/index.js b/examples/text/split-effects/index.js
index 4277aaf2..8ae0f738 100644
--- a/examples/text/split-effects/index.js
+++ b/examples/text/split-effects/index.js
@@ -2,9 +2,9 @@ import {
animate,
createTimeline,
stagger,
- text,
+ splitText,
utils,
-} from '../../../lib/anime.esm.js';
+} from '../../../dist/modules/index.js';
const coords = [];
const [ $revert ] = utils.$('#revert');
@@ -22,7 +22,7 @@ const splitAndAnimate = () => {
$revert.disabled = false;
$split.disabled = true;
- split = text.split('p', {
+ split = splitText('p', {
lines: true,
});
diff --git a/examples/text/split-playground/index.html b/examples/text/split-playground/index.html
index e922dc59..85f9e954 100644
--- a/examples/text/split-playground/index.html
+++ b/examples/text/split-playground/index.html
@@ -137,7 +137,7 @@
<article>
<h1>An all-in-one text splitter function to easily split, wrap, and clone text<br></h1>
<p>
- Anime.js <code>text.split()</code> utility function is an easy to use, fully-featured, lightweight and performant modern text splitter for JavaScript.<br>
+ Anime.js <code>splitText()</code> utility function is an easy to use, fully-featured, lightweight and performant modern text splitter for JavaScript.<br>
It does all the following in only <strong>7KB</strong>:
</p>
<ul>
diff --git a/examples/text/split-playground/index.js b/examples/text/split-playground/index.js
index d86ad744..77297d03 100644
--- a/examples/text/split-playground/index.js
+++ b/examples/text/split-playground/index.js
@@ -3,10 +3,10 @@ import {
createTimeline,
createScope,
stagger,
- text,
+ splitText,
utils,
Scope,
-} from '../../../lib/anime.esm.js';
+} from '../../../dist/modules/index.js';
let split;
@@ -71,7 +71,7 @@ function updateSplitConfig() {
if (split) split.revert();
- split = text.split('article', { ...config.split })
+ split = splitText('article', { ...config.split })
.addEffect(self => config.animation.lines && self.lines.length && animateSplit(self.lines, 'lines'))
.addEffect(self => config.animation.words && self.words.length && animateSplit(self.words, 'words'))
.addEffect(self => config.animation.chars && self.chars.length && animateSplit(self.chars, 'chars'))
diff --git a/examples/timeline-50K-stars/index.js b/examples/timeline-50K-stars/index.js
index 9ce8f873..57bd741f 100644
--- a/examples/timeline-50K-stars/index.js
+++ b/examples/timeline-50K-stars/index.js
@@ -1,4 +1,4 @@
-import { animate, createTimeline, utils } from '../../lib/anime.esm.js';
+import { animate, createTimeline, utils } from '../../dist/modules/index.js';
const [$animation] = utils.$('#animation');
const [$button] = utils.$('.star-button');
diff --git a/examples/timeline-refresh-starlings/index.js b/examples/timeline-refresh-starlings/index.js
index 4b01b211..f94cb28c 100644
--- a/examples/timeline-refresh-starlings/index.js
+++ b/examples/timeline-refresh-starlings/index.js
@@ -2,7 +2,7 @@ import {
createTimeline,
stagger,
utils,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
const { random, cos, sin, sqrt, PI } = Math;
const count = 2500;
diff --git a/examples/timeline-seamless-loop/index.js b/examples/timeline-seamless-loop/index.js
index b3dad1be..bd0f8510 100644
--- a/examples/timeline-seamless-loop/index.js
+++ b/examples/timeline-seamless-loop/index.js
@@ -1,4 +1,4 @@
-import { createTimeline, utils, stagger } from '../../lib/anime.esm.js';
+import { createTimeline, utils, stagger } from '../../dist/modules/index.js';
const wrapperEl = document.querySelector('#test-wrapper');
const numberOfEls = 500;
diff --git a/examples/timeline-stress-test/index.js b/examples/timeline-stress-test/index.js
index f197f681..5e27ffa9 100644
--- a/examples/timeline-stress-test/index.js
+++ b/examples/timeline-stress-test/index.js
@@ -2,7 +2,7 @@ import {
createTimeline,
stagger,
utils,
-} from '../../lib/anime.esm.js';
+} from '../../dist/modules/index.js';
const count = 2024;
const duration = 10000;
diff --git a/lib/anime.cjs b/lib/anime.cjs
deleted file mode 100644
index 957ed5f4..00000000
--- a/lib/anime.cjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * anime.js - CJS
- * @version v4.1.3
- * @author Julian Garnier
- * @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
- */
-"use strict";const isBrowser=typeof window!=="undefined";const win=isBrowser?window:null;const doc=isBrowser?document:null;const tweenTypes={OBJECT:0,ATTRIBUTE:1,CSS:2,TRANSFORM:3,CSS_VAR:4};const valueTypes={NUMBER:0,UNIT:1,COLOR:2,COMPLEX:3};const tickModes={NONE:0,AUTO:1,FORCE:2};const compositionTypes={replace:0,none:1,blend:2};const isRegisteredTargetSymbol=Symbol();const isDomSymbol=Symbol();const isSvgSymbol=Symbol();const transformsSymbol=Symbol();const morphPointsSymbol=Symbol();const proxyTargetSymbol=Symbol();const minValue=1e-11;const maxValue=1e12;const K=1e3;const maxFps=120;const emptyString="";const shortTransforms=(()=>{const map=new Map;map.set("x","translateX");map.set("y","translateY");map.set("z","translateZ");return map})();const validTransforms=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"];const transformsFragmentStrings=validTransforms.reduce(((a,v)=>({...a,[v]:v+"("})),{});const noop=()=>{};const hexTestRgx=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;const rgbExecRgx=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;const rgbaExecRgx=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;const hslExecRgx=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;const hslaExecRgx=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;const digitWithExponentRgx=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;const unitsExecRgx=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;const lowerCaseRgx=/([a-z])([A-Z])/g;const transformsExecRgx=/(\w+)(\([^)]+\)+)/g;const relativeValuesExecRgx=/(\*=|\+=|-=)/;const defaults={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:maxFps,loop:0,reversed:false,alternate:false,autoplay:true,duration:K,delay:0,loopDelay:0,ease:"out(2)",composition:compositionTypes.replace,modifier:v=>v,onBegin:noop,onBeforeUpdate:noop,onUpdate:noop,onLoop:noop,onPause:noop,onComplete:noop,onRender:noop};const scope={current:null,root:doc};const globals={defaults:defaults,precision:4,timeScale:1,tickThreshold:200};const globalVersions={version:"4.1.3",engine:null};if(isBrowser){if(!win.AnimeJS)win.AnimeJS=[];win.AnimeJS.push(globalVersions)}const toLowerCase=str=>str.replace(lowerCaseRgx,"$1-$2").toLowerCase();const stringStartsWith=(str,sub)=>str.indexOf(sub)===0;const now=Date.now;const isArr=Array.isArray;const isObj=a=>a&&a.constructor===Object;const isNum=a=>typeof a==="number"&&!isNaN(a);const isStr=a=>typeof a==="string";const isFnc=a=>typeof a==="function";const isUnd=a=>typeof a==="undefined";const isNil=a=>isUnd(a)||a===null;const isSvg=a=>isBrowser&&a instanceof SVGElement;const isHex=a=>hexTestRgx.test(a);const isRgb=a=>stringStartsWith(a,"rgb");const isHsl=a=>stringStartsWith(a,"hsl");const isCol=a=>isHex(a)||isRgb(a)||isHsl(a);const isKey=a=>!globals.defaults.hasOwnProperty(a);const parseNumber=str=>isStr(str)?parseFloat(str):str;const pow=Math.pow;const sqrt=Math.sqrt;const sin=Math.sin;const cos=Math.cos;const abs=Math.abs;const exp=Math.exp;const ceil=Math.ceil;const floor=Math.floor;const asin=Math.asin;const max=Math.max;const atan2=Math.atan2;const PI=Math.PI;const _round=Math.round;const clamp=(v,min,max)=>v<min?min:v>max?max:v;const powCache={};const round=(v,decimalLength)=>{if(decimalLength<0)return v;if(!decimalLength)return _round(v);let p=powCache[decimalLength];if(!p)p=powCache[decimalLength]=10**decimalLength;return _round(v*p)/p};const snap=(v,increment)=>isArr(increment)?increment.reduce(((closest,cv)=>abs(cv-v)<abs(closest-v)?cv:closest)):increment?_round(v/increment)*increment:v;const interpolate=(start,end,progress)=>start+(end-start)*progress;const random=(min,max,decimalLength)=>{const m=10**(decimalLength||0);return floor((Math.random()*(max-min+1/m)+min)*m)/m};const shuffle=items=>{let m=items.length,t,i;while(m){i=random(0,--m);t=items[m];items[m]=items[i];items[i]=t}return items};const clampInfinity=v=>v===Infinity?maxValue:v===-Infinity?-1e12:v;const normalizeTime=v=>v<=minValue?minValue:clampInfinity(round(v,11));const cloneArray=a=>isArr(a)?[...a]:a;const mergeObjects=(o1,o2)=>{const merged={...o1};for(let p in o2){const o1p=o1[p];merged[p]=isUnd(o1p)?o2[p]:o1p}return merged};const forEachChildren=(parent,callback,reverse,prevProp="_prev",nextProp="_next")=>{let next=parent._head;let adjustedNextProp=nextProp;if(reverse){next=parent._tail;adjustedNextProp=prevProp}while(next){const currentNext=next[adjustedNextProp];callback(next);next=currentNext}};const removeChild=(parent,child,prevProp="_prev",nextProp="_next")=>{const prev=child[prevProp];const next=child[nextProp];prev?prev[nextProp]=next:parent._head=next;next?next[prevProp]=prev:parent._tail=prev;child[prevProp]=null;child[nextProp]=null};const addChild=(parent,child,sortMethod,prevProp="_prev",nextProp="_next")=>{let prev=parent._tail;while(prev&&sortMethod&&sortMethod(prev,child))prev=prev[prevProp];const next=prev?prev[nextProp]:parent._head;prev?prev[nextProp]=child:parent._head=child;next?next[prevProp]=child:parent._tail=child;child[prevProp]=prev;child[nextProp]=next};const createRefreshable=constructor=>{let tracked;return(...args)=>{let currentIteration,currentIterationProgress,reversed,alternate;if(tracked){currentIteration=tracked.currentIteration;currentIterationProgress=tracked.iterationProgress;reversed=tracked.reversed;alternate=tracked._alternate;tracked.revert()}const cleanup=constructor(...args);if(cleanup&&!isFnc(cleanup)&&cleanup.revert)tracked=cleanup;if(!isUnd(currentIterationProgress)){tracked.currentIteration=currentIteration;tracked.iterationProgress=(alternate?!(currentIteration%2)?reversed:!reversed:reversed)?1-currentIterationProgress:currentIterationProgress}return cleanup||noop}};class Clock{constructor(initTime=0){this.deltaTime=0;this._currentTime=initTime;this._elapsedTime=initTime;this._startTime=initTime;this._lastTime=initTime;this._scheduledTime=0;this._frameDuration=round(K/maxFps,0);this._fps=maxFps;this._speed=1;this._hasChildren=false;this._head=null;this._tail=null}get fps(){return this._fps}set fps(frameRate){const previousFrameDuration=this._frameDuration;const fr=+frameRate;const fps=fr<minValue?minValue:fr;const frameDuration=round(K/fps,0);this._fps=fps;this._frameDuration=frameDuration;this._scheduledTime+=frameDuration-previousFrameDuration}get speed(){return this._speed}set speed(playbackRate){const pbr=+playbackRate;this._speed=pbr<minValue?minValue:pbr}requestTick(time){const scheduledTime=this._scheduledTime;const elapsedTime=this._elapsedTime;this._elapsedTime+=time-elapsedTime;if(elapsedTime<scheduledTime)return tickModes.NONE;const frameDuration=this._frameDuration;const frameDelta=elapsedTime-scheduledTime;this._scheduledTime+=frameDelta<frameDuration?frameDuration:frameDelta;return tickModes.AUTO}computeDeltaTime(time){const delta=time-this._lastTime;this.deltaTime=delta;this._lastTime=time;return delta}}const render=(tickable,time,muteCallbacks,internalRender,tickMode)=>{const parent=tickable.parent;const duration=tickable.duration;const completed=tickable.completed;const iterationDuration=tickable.iterationDuration;const iterationCount=tickable.iterationCount;const _currentIteration=tickable._currentIteration;const _loopDelay=tickable._loopDelay;const _reversed=tickable._reversed;const _alternate=tickable._alternate;const _hasChildren=tickable._hasChildren;const tickableDelay=tickable._delay;const tickablePrevAbsoluteTime=tickable._currentTime;const tickableEndTime=tickableDelay+iterationDuration;const tickableAbsoluteTime=time-tickableDelay;const tickablePrevTime=clamp(tickablePrevAbsoluteTime,-tickableDelay,duration);const tickableCurrentTime=clamp(tickableAbsoluteTime,-tickableDelay,duration);const deltaTime=tickableAbsoluteTime-tickablePrevAbsoluteTime;const isCurrentTimeAboveZero=tickableCurrentTime>0;const isCurrentTimeEqualOrAboveDuration=tickableCurrentTime>=duration;const isSetter=duration<=minValue;const forcedTick=tickMode===tickModes.FORCE;let isOdd=0;let iterationElapsedTime=tickableAbsoluteTime;let hasRendered=0;if(iterationCount>1){const currentIteration=~~(tickableCurrentTime/(iterationDuration+(isCurrentTimeEqualOrAboveDuration?0:_loopDelay)));tickable._currentIteration=clamp(currentIteration,0,iterationCount);if(isCurrentTimeEqualOrAboveDuration)tickable._currentIteration--;isOdd=tickable._currentIteration%2;iterationElapsedTime=tickableCurrentTime%(iterationDuration+_loopDelay)||0}const isReversed=_reversed^(_alternate&&isOdd);const _ease=tickable._ease;let iterationTime=isCurrentTimeEqualOrAboveDuration?isReversed?0:duration:isReversed?iterationDuration-iterationElapsedTime:iterationElapsedTime;if(_ease)iterationTime=iterationDuration*_ease(iterationTime/iterationDuration)||0;const isRunningBackwards=(parent?parent.backwards:tickableAbsoluteTime<tickablePrevAbsoluteTime)?!isReversed:!!isReversed;tickable._currentTime=tickableAbsoluteTime;tickable._iterationTime=iterationTime;tickable.backwards=isRunningBackwards;if(isCurrentTimeAboveZero&&!tickable.began){tickable.began=true;if(!muteCallbacks&&!(parent&&(isRunningBackwards||!parent.began))){tickable.onBegin(tickable)}}else if(tickableAbsoluteTime<=0){tickable.began=false}if(!muteCallbacks&&!_hasChildren&&isCurrentTimeAboveZero&&tickable._currentIteration!==_currentIteration){tickable.onLoop(tickable)}if(forcedTick||tickMode===tickModes.AUTO&&(time>=tickableDelay&&time<=tickableEndTime||time<=tickableDelay&&tickablePrevTime>tickableDelay||time>=tickableEndTime&&tickablePrevTime!==duration)||iterationTime>=tickableEndTime&&tickablePrevTime!==duration||iterationTime<=tickableDelay&&tickablePrevTime>0||time<=tickablePrevTime&&tickablePrevTime===duration&&completed||isCurrentTimeEqualOrAboveDuration&&!completed&&isSetter){if(isCurrentTimeAboveZero){tickable.computeDeltaTime(tickablePrevTime);if(!muteCallbacks)tickable.onBeforeUpdate(tickable)}if(!_hasChildren){const forcedRender=forcedTick||(isRunningBackwards?deltaTime*-1:deltaTime)>=globals.tickThreshold;const absoluteTime=tickable._offset+(parent?parent._offset:0)+tickableDelay+iterationTime;let tween=tickable._head;let tweenTarget;let tweenStyle;let tweenTargetTransforms;let tweenTargetTransformsProperties;let tweenTransformsNeedUpdate=0;while(tween){const tweenComposition=tween._composition;const tweenCurrentTime=tween._currentTime;const tweenChangeDuration=tween._changeDuration;const tweenAbsEndTime=tween._absoluteStartTime+tween._changeDuration;const tweenNextRep=tween._nextRep;const tweenPrevRep=tween._prevRep;const tweenHasComposition=tweenComposition!==compositionTypes.none;if((forcedRender||(tweenCurrentTime!==tweenChangeDuration||absoluteTime<=tweenAbsEndTime+(tweenNextRep?tweenNextRep._delay:0))&&(tweenCurrentTime!==0||absoluteTime>=tween._absoluteStartTime))&&(!tweenHasComposition||!tween._isOverridden&&(!tween._isOverlapped||absoluteTime<=tweenAbsEndTime)&&(!tweenNextRep||(tweenNextRep._isOverridden||absoluteTime<=tweenNextRep._absoluteStartTime))&&(!tweenPrevRep||(tweenPrevRep._isOverridden||absoluteTime>=tweenPrevRep._absoluteStartTime+tweenPrevRep._changeDuration+tween._delay)))){const tweenNewTime=tween._currentTime=clamp(iterationTime-tween._startTime,0,tweenChangeDuration);const tweenProgress=tween._ease(tweenNewTime/tween._updateDuration);const tweenModifier=tween._modifier;const tweenValueType=tween._valueType;const tweenType=tween._tweenType;const tweenIsObject=tweenType===tweenTypes.OBJECT;const tweenIsNumber=tweenValueType===valueTypes.NUMBER;const tweenPrecision=tweenIsNumber&&tweenIsObject||tweenProgress===0||tweenProgress===1?-1:globals.precision;let value;let number;if(tweenIsNumber){value=number=tweenModifier(round(interpolate(tween._fromNumber,tween._toNumber,tweenProgress),tweenPrecision))}else if(tweenValueType===valueTypes.UNIT){number=tweenModifier(round(interpolate(tween._fromNumber,tween._toNumber,tweenProgress),tweenPrecision));value=`${number}${tween._unit}`}else if(tweenValueType===valueTypes.COLOR){const fn=tween._fromNumbers;const tn=tween._toNumbers;const r=round(clamp(tweenModifier(interpolate(fn[0],tn[0],tweenProgress)),0,255),0);const g=round(clamp(tweenModifier(interpolate(fn[1],tn[1],tweenProgress)),0,255),0);const b=round(clamp(tweenModifier(interpolate(fn[2],tn[2],tweenProgress)),0,255),0);const a=clamp(tweenModifier(round(interpolate(fn[3],tn[3],tweenProgress),tweenPrecision)),0,1);value=`rgba(${r},${g},${b},${a})`;if(tweenHasComposition){const ns=tween._numbers;ns[0]=r;ns[1]=g;ns[2]=b;ns[3]=a}}else if(tweenValueType===valueTypes.COMPLEX){value=tween._strings[0];for(let j=0,l=tween._toNumbers.length;j<l;j++){const n=tweenModifier(round(interpolate(tween._fromNumbers[j],tween._toNumbers[j],tweenProgress),tweenPrecision));const s=tween._strings[j+1];value+=`${s?n+s:n}`;if(tweenHasComposition){tween._numbers[j]=n}}}if(tweenHasComposition){tween._number=number}if(!internalRender&&tweenComposition!==compositionTypes.blend){const tweenProperty=tween.property;tweenTarget=tween.target;if(tweenIsObject){tweenTarget[tweenProperty]=value}else if(tweenType===tweenTypes.ATTRIBUTE){tweenTarget.setAttribute(tweenProperty,value)}else{tweenStyle=tweenTarget.style;if(tweenType===tweenTypes.TRANSFORM){if(tweenTarget!==tweenTargetTransforms){tweenTargetTransforms=tweenTarget;tweenTargetTransformsProperties=tweenTarget[transformsSymbol]}tweenTargetTransformsProperties[tweenProperty]=value;tweenTransformsNeedUpdate=1}else if(tweenType===tweenTypes.CSS){tweenStyle[tweenProperty]=value}else if(tweenType===tweenTypes.CSS_VAR){tweenStyle.setProperty(tweenProperty,value)}}if(isCurrentTimeAboveZero)hasRendered=1}else{tween._value=value}}if(tweenTransformsNeedUpdate&&tween._renderTransforms){let str=emptyString;for(let key in tweenTargetTransformsProperties){str+=`${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `}tweenStyle.transform=str;tweenTransformsNeedUpdate=0}tween=tween._next}if(!muteCallbacks&&hasRendered){tickable.onRender(tickable)}}if(!muteCallbacks&&isCurrentTimeAboveZero){tickable.onUpdate(tickable)}}if(parent&&isSetter){if(!muteCallbacks&&(parent.began&&!isRunningBackwards&&tickableAbsoluteTime>=duration&&!completed||isRunningBackwards&&tickableAbsoluteTime<=minValue&&completed)){tickable.onComplete(tickable);tickable.completed=!isRunningBackwards}}else if(isCurrentTimeAboveZero&&isCurrentTimeEqualOrAboveDuration){if(iterationCount===Infinity){tickable._startTime+=tickable.duration}else if(tickable._currentIteration>=iterationCount-1){tickable.paused=true;if(!completed&&!_hasChildren){tickable.completed=true;if(!muteCallbacks&&!(parent&&(isRunningBackwards||!parent.began))){tickable.onComplete(tickable);tickable._resolve(tickable)}}}}else{tickable.completed=false}return hasRendered};const tick=(tickable,time,muteCallbacks,internalRender,tickMode)=>{const _currentIteration=tickable._currentIteration;render(tickable,time,muteCallbacks,internalRender,tickMode);if(tickable._hasChildren){const tl=tickable;const tlIsRunningBackwards=tl.backwards;const tlChildrenTime=internalRender?time:tl._iterationTime;const tlCildrenTickTime=now();let tlChildrenHasRendered=0;let tlChildrenHaveCompleted=true;if(!internalRender&&tl._currentIteration!==_currentIteration){const tlIterationDuration=tl.iterationDuration;forEachChildren(tl,(child=>{if(!tlIsRunningBackwards){if(!child.completed&&!child.backwards&&child._currentTime<child.iterationDuration){render(child,tlIterationDuration,muteCallbacks,1,tickModes.FORCE)}child.began=false;child.completed=false}else{const childDuration=child.duration;const childStartTime=child._offset+child._delay;const childEndTime=childStartTime+childDuration;if(!muteCallbacks&&childDuration<=minValue&&(!childStartTime||childEndTime===tlIterationDuration)){child.onComplete(child)}}}));if(!muteCallbacks)tl.onLoop(tl)}forEachChildren(tl,(child=>{const childTime=round((tlChildrenTime-child._offset)*child._speed,12);const childTickMode=child._fps<tl._fps?child.requestTick(tlCildrenTickTime):tickMode;tlChildrenHasRendered+=render(child,childTime,muteCallbacks,internalRender,childTickMode);if(!child.completed&&tlChildrenHaveCompleted)tlChildrenHaveCompleted=false}),tlIsRunningBackwards);if(!muteCallbacks&&tlChildrenHasRendered)tl.onRender(tl);if((tlChildrenHaveCompleted||tlIsRunningBackwards)&&tl._currentTime>=tl.duration){tl.paused=true;if(!tl.completed){tl.completed=true;if(!muteCallbacks){tl.onComplete(tl);tl._resolve(tl)}}}}};const additive={animation:null,update:noop};const addAdditiveAnimation=lookups=>{let animation=additive.animation;if(!animation){animation={duration:minValue,computeDeltaTime:noop,_offset:0,_delay:0,_head:null,_tail:null};additive.animation=animation;additive.update=()=>{lookups.forEach((propertyAnimation=>{for(let propertyName in propertyAnimation){const tweens=propertyAnimation[propertyName];const lookupTween=tweens._head;if(lookupTween){const valueType=lookupTween._valueType;const additiveValues=valueType===valueTypes.COMPLEX||valueType===valueTypes.COLOR?cloneArray(lookupTween._fromNumbers):null;let additiveValue=lookupTween._fromNumber;let tween=tweens._tail;while(tween&&tween!==lookupTween){if(additiveValues){for(let i=0,l=tween._numbers.length;i<l;i++)additiveValues[i]+=tween._numbers[i]}else{additiveValue+=tween._number}tween=tween._prevAdd}lookupTween._toNumber=additiveValue;lookupTween._toNumbers=additiveValues}}}));render(animation,1,1,0,tickModes.FORCE)}}return animation};const engineTickMethod=(()=>isBrowser?requestAnimationFrame:setImmediate)();const engineCancelMethod=(()=>isBrowser?cancelAnimationFrame:clearImmediate)();class Engine extends Clock{constructor(initTime){super(initTime);this.useDefaultMainLoop=true;this.pauseOnDocumentHidden=true;this.defaults=defaults;this.paused=true;this.reqId=0}update(){const time=this._currentTime=now();if(this.requestTick(time)){this.computeDeltaTime(time);const engineSpeed=this._speed;const engineFps=this._fps;let activeTickable=this._head;while(activeTickable){const nextTickable=activeTickable._next;if(!activeTickable.paused){tick(activeTickable,(time-activeTickable._startTime)*activeTickable._speed*engineSpeed,0,0,activeTickable._fps<engineFps?activeTickable.requestTick(time):tickModes.AUTO)}else{removeChild(this,activeTickable);this._hasChildren=!!this._tail;activeTickable._running=false;if(activeTickable.completed&&!activeTickable._cancelled){activeTickable.cancel()}}activeTickable=nextTickable}additive.update()}}wake(){if(this.useDefaultMainLoop&&!this.reqId){this.requestTick(now());this.reqId=engineTickMethod(tickEngine)}return this}pause(){if(!this.reqId)return;this.paused=true;return killEngine()}resume(){if(!this.paused)return;this.paused=false;forEachChildren(this,(child=>child.resetTime()));return this.wake()}get speed(){return this._speed*(globals.timeScale===1?1:K)}set speed(playbackRate){this._speed=playbackRate*globals.timeScale;forEachChildren(this,(child=>child.speed=child._speed))}get timeUnit(){return globals.timeScale===1?"ms":"s"}set timeUnit(unit){const secondsScale=.001;const isSecond=unit==="s";const newScale=isSecond?secondsScale:1;if(globals.timeScale!==newScale){globals.timeScale=newScale;globals.tickThreshold=200*newScale;const scaleFactor=isSecond?secondsScale:K;this.defaults.duration*=scaleFactor;this._speed*=scaleFactor}}get precision(){return globals.precision}set precision(precision){globals.precision=precision}}const engine=(()=>{const engine=new Engine(now());if(isBrowser){globalVersions.engine=engine;doc.addEventListener("visibilitychange",(()=>{if(!engine.pauseOnDocumentHidden)return;doc.hidden?engine.pause():engine.resume()}))}return engine})();const tickEngine=()=>{if(engine._head){engine.reqId=engineTickMethod(tickEngine);engine.update()}else{engine.reqId=0}};const killEngine=()=>{engineCancelMethod(engine.reqId);engine.reqId=0;return engine};const parseInlineTransforms=(target,propName,animationInlineStyles)=>{const inlineTransforms=target.style.transform;let inlinedStylesPropertyValue;if(inlineTransforms){const cachedTransforms=target[transformsSymbol];let t;while(t=transformsExecRgx.exec(inlineTransforms)){const inlinePropertyName=t[1];const inlinePropertyValue=t[2].slice(1,-1);cachedTransforms[inlinePropertyName]=inlinePropertyValue;if(inlinePropertyName===propName){inlinedStylesPropertyValue=inlinePropertyValue;if(animationInlineStyles){animationInlineStyles[propName]=inlinePropertyValue}}}}return inlineTransforms&&!isUnd(inlinedStylesPropertyValue)?inlinedStylesPropertyValue:stringStartsWith(propName,"scale")?"1":stringStartsWith(propName,"rotate")||stringStartsWith(propName,"skew")?"0deg":"0px"};function getNodeList(v){const n=isStr(v)?scope.root.querySelectorAll(v):v;if(n instanceof NodeList||n instanceof HTMLCollection)return n}function parseTargets(targets){if(isNil(targets))return[];if(!isBrowser)return isArr(targets)&&targets.flat(Infinity)||[targets];if(isArr(targets)){const flattened=targets.flat(Infinity);const parsed=[];for(let i=0,l=flattened.length;i<l;i++){const item=flattened[i];if(!isNil(item)){const nodeList=getNodeList(item);if(nodeList){for(let j=0,jl=nodeList.length;j<jl;j++){const subItem=nodeList[j];if(!isNil(subItem)){let isDuplicate=false;for(let k=0,kl=parsed.length;k<kl;k++){if(parsed[k]===subItem){isDuplicate=true;break}}if(!isDuplicate){parsed.push(subItem)}}}}else{let isDuplicate=false;for(let j=0,jl=parsed.length;j<jl;j++){if(parsed[j]===item){isDuplicate=true;break}}if(!isDuplicate){parsed.push(item)}}}}return parsed}const nodeList=getNodeList(targets);if(nodeList)return Array.from(nodeList);return[targets]}function registerTargets(targets){const parsedTargetsArray=parseTargets(targets);const parsedTargetsLength=parsedTargetsArray.length;if(parsedTargetsLength){for(let i=0;i<parsedTargetsLength;i++){const target=parsedTargetsArray[i];if(!target[isRegisteredTargetSymbol]){target[isRegisteredTargetSymbol]=true;const isSvgType=isSvg(target);const isDom=target.nodeType||isSvgType;if(isDom){target[isDomSymbol]=true;target[isSvgSymbol]=isSvgType;target[transformsSymbol]={}}}}}return parsedTargetsArray}const getPath=path=>{const parsedTargets=parseTargets(path);const $parsedSvg=parsedTargets[0];if(!$parsedSvg||!isSvg($parsedSvg))return;return $parsedSvg};const morphTo=(path2,precision=.33)=>$path1=>{const $path2=getPath(path2);if(!$path2)return;const isPath=$path1.tagName==="path";const separator=isPath?" ":",";const previousPoints=$path1[morphPointsSymbol];if(previousPoints)$path1.setAttribute(isPath?"d":"points",previousPoints);let v1="",v2="";if(!precision){v1=$path1.getAttribute(isPath?"d":"points");v2=$path2.getAttribute(isPath?"d":"points")}else{const length1=$path1.getTotalLength();const length2=$path2.getTotalLength();const maxPoints=Math.max(Math.ceil(length1*precision),Math.ceil(length2*precision));for(let i=0;i<maxPoints;i++){const t=i/(maxPoints-1);const pointOnPath1=$path1.getPointAtLength(length1*t);const pointOnPath2=$path2.getPointAtLength(length2*t);const prefix=isPath?i===0?"M":"L":"";v1+=prefix+round(pointOnPath1.x,3)+separator+pointOnPath1.y+" ";v2+=prefix+round(pointOnPath2.x,3)+separator+pointOnPath2.y+" "}}$path1[morphPointsSymbol]=v2;return[v1,v2]};const getScaleFactor=$el=>{let scaleFactor=1;if($el&&$el.getCTM){const ctm=$el.getCTM();if(ctm){const scaleX=sqrt(ctm.a*ctm.a+ctm.b*ctm.b);const scaleY=sqrt(ctm.c*ctm.c+ctm.d*ctm.d);scaleFactor=(scaleX+scaleY)/2}}return scaleFactor};const createDrawableProxy=($el,start,end)=>{const pathLength=K;const computedStyles=getComputedStyle($el);const strokeLineCap=computedStyles.strokeLinecap;const $scalled=computedStyles.vectorEffect==="non-scaling-stroke"?$el:null;let currentCap=strokeLineCap;const proxy=new Proxy($el,{get(target,property){const value=target[property];if(property===proxyTargetSymbol)return target;if(property==="setAttribute"){return(...args)=>{if(args[0]==="draw"){const value=args[1];const values=value.split(" ");const v1=+values[0];const v2=+values[1];const scaleFactor=getScaleFactor($scalled);const os=v1*-1e3*scaleFactor;const d1=v2*pathLength*scaleFactor+os;const d2=pathLength*scaleFactor+(v1===0&&v2===1||v1===1&&v2===0?0:10*scaleFactor)-d1;if(strokeLineCap!=="butt"){const newCap=v1===v2?"butt":strokeLineCap;if(currentCap!==newCap){target.style.strokeLinecap=`${newCap}`;currentCap=newCap}}target.setAttribute("stroke-dashoffset",`${os}`);target.setAttribute("stroke-dasharray",`${d1} ${d2}`)}return Reflect.apply(value,target,args)}}if(isFnc(value)){return(...args)=>Reflect.apply(value,target,args)}else{return value}}});if($el.getAttribute("pathLength")!==`${pathLength}`){$el.setAttribute("pathLength",`${pathLength}`);proxy.setAttribute("draw",`${start} ${end}`)}return proxy};const createDrawable=(selector,start=0,end=0)=>{const els=parseTargets(selector);return els.map(($el=>createDrawableProxy($el,start,end)))};const getPathPoint=($path,progress,lookup=0)=>$path.getPointAtLength(progress+lookup>=1?progress+lookup:0);const getPathProgess=($path,pathProperty)=>$el=>{const totalLength=+$path.getTotalLength();const inSvg=$el[isSvgSymbol];const ctm=$path.getCTM();return{from:0,to:totalLength,modifier:progress=>{if(pathProperty==="a"){const p0=getPathPoint($path,progress,-1);const p1=getPathPoint($path,progress,1);return atan2(p1.y-p0.y,p1.x-p0.x)*180/PI}else{const p=getPathPoint($path,progress,0);return pathProperty==="x"?inSvg||!ctm?p.x:p.x*ctm.a+p.y*ctm.c+ctm.e:inSvg||!ctm?p.y:p.x*ctm.b+p.y*ctm.d+ctm.f}}}};const createMotionPath=path=>{const $path=getPath(path);if(!$path)return;return{translateX:getPathProgess($path,"x"),translateY:getPathProgess($path,"y"),rotate:getPathProgess($path,"a")}};const cssReservedProperties=["opacity","rotate","overflow","color"];const isValidSVGAttribute=(el,propertyName)=>{if(cssReservedProperties.includes(propertyName))return false;if(el.getAttribute(propertyName)||propertyName in el){if(propertyName==="scale"){const elParentNode=el.parentNode;return elParentNode&&elParentNode.tagName==="filter"}return true}};const svg={morphTo:morphTo,createMotionPath:createMotionPath,createDrawable:createDrawable};const rgbToRgba=rgbValue=>{const rgba=rgbExecRgx.exec(rgbValue)||rgbaExecRgx.exec(rgbValue);const a=!isUnd(rgba[4])?+rgba[4]:1;return[+rgba[1],+rgba[2],+rgba[3],a]};const hexToRgba=hexValue=>{const hexLength=hexValue.length;const isShort=hexLength===4||hexLength===5;return[+("0x"+hexValue[1]+hexValue[isShort?1:2]),+("0x"+hexValue[isShort?2:3]+hexValue[isShort?2:4]),+("0x"+hexValue[isShort?3:5]+hexValue[isShort?3:6]),hexLength===5||hexLength===9?+(+("0x"+hexValue[isShort?4:7]+hexValue[isShort?4:8])/255).toFixed(3):1]};const hue2rgb=(p,q,t)=>{if(t<0)t+=1;if(t>1)t-=1;return t<1/6?p+(q-p)*6*t:t<1/2?q:t<2/3?p+(q-p)*(2/3-t)*6:p};const hslToRgba=hslValue=>{const hsla=hslExecRgx.exec(hslValue)||hslaExecRgx.exec(hslValue);const h=+hsla[1]/360;const s=+hsla[2]/100;const l=+hsla[3]/100;const a=!isUnd(hsla[4])?+hsla[4]:1;let r,g,b;if(s===0){r=g=b=l}else{const q=l<.5?l*(1+s):l+s-l*s;const p=2*l-q;r=round(hue2rgb(p,q,h+1/3)*255,0);g=round(hue2rgb(p,q,h)*255,0);b=round(hue2rgb(p,q,h-1/3)*255,0)}return[r,g,b,a]};const convertColorStringValuesToRgbaArray=colorString=>isRgb(colorString)?rgbToRgba(colorString):isHex(colorString)?hexToRgba(colorString):isHsl(colorString)?hslToRgba(colorString):[0,0,0,1];const setValue=(targetValue,defaultValue)=>isUnd(targetValue)?defaultValue:targetValue;const getFunctionValue=(value,target,index,total,store)=>{if(isFnc(value)){const func=()=>{const computed=value(target,index,total);return!isNaN(+computed)?+computed:computed||0};if(store){store.func=func}return func()}else{return value}};const getTweenType=(target,prop)=>!target[isDomSymbol]?tweenTypes.OBJECT:target[isSvgSymbol]&&isValidSVGAttribute(target,prop)?tweenTypes.ATTRIBUTE:validTransforms.includes(prop)||shortTransforms.get(prop)?tweenTypes.TRANSFORM:stringStartsWith(prop,"--")?tweenTypes.CSS_VAR:prop in target.style?tweenTypes.CSS:prop in target?tweenTypes.OBJECT:tweenTypes.ATTRIBUTE;const getCSSValue=(target,propName,animationInlineStyles)=>{const inlineStyles=target.style[propName];if(inlineStyles&&animationInlineStyles){animationInlineStyles[propName]=inlineStyles}const value=inlineStyles||getComputedStyle(target[proxyTargetSymbol]||target).getPropertyValue(propName);return value==="auto"?"0":value};const getOriginalAnimatableValue=(target,propName,tweenType,animationInlineStyles)=>{const type=!isUnd(tweenType)?tweenType:getTweenType(target,propName);return type===tweenTypes.OBJECT?target[propName]||0:type===tweenTypes.ATTRIBUTE?target.getAttribute(propName):type===tweenTypes.TRANSFORM?parseInlineTransforms(target,propName,animationInlineStyles):type===tweenTypes.CSS_VAR?getCSSValue(target,propName,animationInlineStyles).trimStart():getCSSValue(target,propName,animationInlineStyles)};const getRelativeValue=(x,y,operator)=>operator==="-"?x-y:operator==="+"?x+y:x*y;const createDecomposedValueTargetObject=()=>({t:valueTypes.NUMBER,n:0,u:null,o:null,d:null,s:null});const decomposeRawValue=(rawValue,targetObject)=>{targetObject.t=valueTypes.NUMBER;targetObject.n=0;targetObject.u=null;targetObject.o=null;targetObject.d=null;targetObject.s=null;if(!rawValue)return targetObject;const num=+rawValue;if(!isNaN(num)){targetObject.n=num;return targetObject}else{let str=rawValue;if(str[1]==="="){targetObject.o=str[0];str=str.slice(2)}const unitMatch=str.includes(" ")?false:unitsExecRgx.exec(str);if(unitMatch){targetObject.t=valueTypes.UNIT;targetObject.n=+unitMatch[1];targetObject.u=unitMatch[2];return targetObject}else if(targetObject.o){targetObject.n=+str;return targetObject}else if(isCol(str)){targetObject.t=valueTypes.COLOR;targetObject.d=convertColorStringValuesToRgbaArray(str);return targetObject}else{const matchedNumbers=str.match(digitWithExponentRgx);targetObject.t=valueTypes.COMPLEX;targetObject.d=matchedNumbers?matchedNumbers.map(Number):[];targetObject.s=str.split(digitWithExponentRgx)||[];return targetObject}}};const decomposeTweenValue=(tween,targetObject)=>{targetObject.t=tween._valueType;targetObject.n=tween._toNumber;targetObject.u=tween._unit;targetObject.o=null;targetObject.d=cloneArray(tween._toNumbers);targetObject.s=cloneArray(tween._strings);return targetObject};const decomposedOriginalValue=createDecomposedValueTargetObject();const lookups={_rep:new WeakMap,_add:new Map};const getTweenSiblings=(target,property,lookup="_rep")=>{const lookupMap=lookups[lookup];let targetLookup=lookupMap.get(target);if(!targetLookup){targetLookup={};lookupMap.set(target,targetLookup)}return targetLookup[property]?targetLookup[property]:targetLookup[property]={_head:null,_tail:null}};const addTweenSortMethod=(p,c)=>p._isOverridden||p._absoluteStartTime>c._absoluteStartTime;const overrideTween=tween=>{tween._isOverlapped=1;tween._isOverridden=1;tween._changeDuration=minValue;tween._currentTime=minValue};const composeTween=(tween,siblings)=>{const tweenCompositionType=tween._composition;if(tweenCompositionType===compositionTypes.replace){const tweenAbsStartTime=tween._absoluteStartTime;addChild(siblings,tween,addTweenSortMethod,"_prevRep","_nextRep");const prevSibling=tween._prevRep;if(prevSibling){const prevParent=prevSibling.parent;const prevAbsEndTime=prevSibling._absoluteStartTime+prevSibling._changeDuration;if(tween.parent.id!==prevParent.id&&prevParent.iterationCount>1&&prevAbsEndTime+(prevParent.duration-prevParent.iterationDuration)>tweenAbsStartTime){overrideTween(prevSibling);let prevPrevSibling=prevSibling._prevRep;while(prevPrevSibling&&prevPrevSibling.parent.id===prevParent.id){overrideTween(prevPrevSibling);prevPrevSibling=prevPrevSibling._prevRep}}const absoluteUpdateStartTime=tweenAbsStartTime-tween._delay;if(prevAbsEndTime>absoluteUpdateStartTime){const prevChangeStartTime=prevSibling._startTime;const prevTLOffset=prevAbsEndTime-(prevChangeStartTime+prevSibling._updateDuration);const updatedPrevChangeDuration=round(absoluteUpdateStartTime-prevTLOffset-prevChangeStartTime,12);prevSibling._changeDuration=updatedPrevChangeDuration;prevSibling._currentTime=updatedPrevChangeDuration;prevSibling._isOverlapped=1;if(updatedPrevChangeDuration<minValue){overrideTween(prevSibling)}}let pausePrevParentAnimation=true;forEachChildren(prevParent,(t=>{if(!t._isOverlapped)pausePrevParentAnimation=false}));if(pausePrevParentAnimation){const prevParentTL=prevParent.parent;if(prevParentTL){let pausePrevParentTL=true;forEachChildren(prevParentTL,(a=>{if(a!==prevParent){forEachChildren(a,(t=>{if(!t._isOverlapped)pausePrevParentTL=false}))}}));if(pausePrevParentTL){prevParentTL.cancel()}}else{prevParent.cancel()}}}}else if(tweenCompositionType===compositionTypes.blend){const additiveTweenSiblings=getTweenSiblings(tween.target,tween.property,"_add");const additiveAnimation=addAdditiveAnimation(lookups._add);let lookupTween=additiveTweenSiblings._head;if(!lookupTween){lookupTween={...tween};lookupTween._composition=compositionTypes.replace;lookupTween._updateDuration=minValue;lookupTween._startTime=0;lookupTween._numbers=cloneArray(tween._fromNumbers);lookupTween._number=0;lookupTween._next=null;lookupTween._prev=null;addChild(additiveTweenSiblings,lookupTween);addChild(additiveAnimation,lookupTween)}const toNumber=tween._toNumber;tween._fromNumber=lookupTween._fromNumber-toNumber;tween._toNumber=0;tween._numbers=cloneArray(tween._fromNumbers);tween._number=0;lookupTween._fromNumber=toNumber;if(tween._toNumbers){const toNumbers=cloneArray(tween._toNumbers);if(toNumbers){toNumbers.forEach(((value,i)=>{tween._fromNumbers[i]=lookupTween._fromNumbers[i]-value;tween._toNumbers[i]=0}))}lookupTween._fromNumbers=toNumbers}addChild(additiveTweenSiblings,tween,null,"_prevAdd","_nextAdd")}return tween};const removeTweenSliblings=tween=>{const tweenComposition=tween._composition;if(tweenComposition!==compositionTypes.none){const tweenTarget=tween.target;const tweenProperty=tween.property;const replaceTweensLookup=lookups._rep;const replaceTargetProps=replaceTweensLookup.get(tweenTarget);const tweenReplaceSiblings=replaceTargetProps[tweenProperty];removeChild(tweenReplaceSiblings,tween,"_prevRep","_nextRep");if(tweenComposition===compositionTypes.blend){const addTweensLookup=lookups._add;const addTargetProps=addTweensLookup.get(tweenTarget);if(!addTargetProps)return;const additiveTweenSiblings=addTargetProps[tweenProperty];const additiveAnimation=additive.animation;removeChild(additiveTweenSiblings,tween,"_prevAdd","_nextAdd");const lookupTween=additiveTweenSiblings._head;if(lookupTween&&lookupTween===additiveTweenSiblings._tail){removeChild(additiveTweenSiblings,lookupTween,"_prevAdd","_nextAdd");removeChild(additiveAnimation,lookupTween);let shouldClean=true;for(let prop in addTargetProps){if(addTargetProps[prop]._head){shouldClean=false;break}}if(shouldClean){addTweensLookup.delete(tweenTarget)}}}}return tween};const resetTimerProperties=timer=>{timer.paused=true;timer.began=false;timer.completed=false;return timer};const reviveTimer=timer=>{if(!timer._cancelled)return timer;if(timer._hasChildren){forEachChildren(timer,reviveTimer)}else{forEachChildren(timer,(tween=>{if(tween._composition!==compositionTypes.none){composeTween(tween,getTweenSiblings(tween.target,tween.property))}}))}timer._cancelled=0;return timer};let timerId=0;class Timer extends Clock{constructor(parameters={},parent=null,parentPosition=0){super(0);const{id:id,delay:delay,duration:duration,reversed:reversed,alternate:alternate,loop:loop,loopDelay:loopDelay,autoplay:autoplay,frameRate:frameRate,playbackRate:playbackRate,onComplete:onComplete,onLoop:onLoop,onPause:onPause,onBegin:onBegin,onBeforeUpdate:onBeforeUpdate,onUpdate:onUpdate}=parameters;if(scope.current)scope.current.register(this);const timerInitTime=parent?0:engine._elapsedTime;const timerDefaults=parent?parent.defaults:globals.defaults;const timerDelay=isFnc(delay)||isUnd(delay)?timerDefaults.delay:+delay;const timerDuration=isFnc(duration)||isUnd(duration)?Infinity:+duration;const timerLoop=setValue(loop,timerDefaults.loop);const timerLoopDelay=setValue(loopDelay,timerDefaults.loopDelay);const timerIterationCount=timerLoop===true||timerLoop===Infinity||timerLoop<0?Infinity:timerLoop+1;let offsetPosition=0;if(parent){offsetPosition=parentPosition}else{if(!engine.reqId)engine.requestTick(now());offsetPosition=(engine._elapsedTime-engine._startTime)*globals.timeScale}this.id=!isUnd(id)?id:++timerId;this.parent=parent;this.duration=clampInfinity((timerDuration+timerLoopDelay)*timerIterationCount-timerLoopDelay)||minValue;this.backwards=false;this.paused=true;this.began=false;this.completed=false;this.onBegin=onBegin||timerDefaults.onBegin;this.onBeforeUpdate=onBeforeUpdate||timerDefaults.onBeforeUpdate;this.onUpdate=onUpdate||timerDefaults.onUpdate;this.onLoop=onLoop||timerDefaults.onLoop;this.onPause=onPause||timerDefaults.onPause;this.onComplete=onComplete||timerDefaults.onComplete;this.iterationDuration=timerDuration;this.iterationCount=timerIterationCount;this._autoplay=parent?false:setValue(autoplay,timerDefaults.autoplay);this._offset=offsetPosition;this._delay=timerDelay;this._loopDelay=timerLoopDelay;this._iterationTime=0;this._currentIteration=0;this._resolve=noop;this._running=false;this._reversed=+setValue(reversed,timerDefaults.reversed);this._reverse=this._reversed;this._cancelled=0;this._alternate=setValue(alternate,timerDefaults.alternate);this._prev=null;this._next=null;this._elapsedTime=timerInitTime;this._startTime=timerInitTime;this._lastTime=timerInitTime;this._fps=setValue(frameRate,timerDefaults.frameRate);this._speed=setValue(playbackRate,timerDefaults.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(cancelled){cancelled?this.cancel():this.reset(1).play()}get currentTime(){return clamp(round(this._currentTime,globals.precision),-this._delay,this.duration)}set currentTime(time){const paused=this.paused;this.pause().seek(+time);if(!paused)this.resume()}get iterationCurrentTime(){return round(this._iterationTime,globals.precision)}set iterationCurrentTime(time){this.currentTime=this.iterationDuration*this._currentIteration+time}get progress(){return clamp(round(this._currentTime/this.duration,10),0,1)}set progress(progress){this.currentTime=this.duration*progress}get iterationProgress(){return clamp(round(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(progress){const iterationDuration=this.iterationDuration;this.currentTime=iterationDuration*this._currentIteration+iterationDuration*progress}get currentIteration(){return this._currentIteration}set currentIteration(iterationCount){this.currentTime=this.iterationDuration*clamp(+iterationCount,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(reverse){reverse?this.reverse():this.play()}get speed(){return super.speed}set speed(playbackRate){super.speed=playbackRate;this.resetTime()}reset(internalRender=0){reviveTimer(this);if(this._reversed&&!this._reverse)this.reversed=false;this._iterationTime=this.iterationDuration;tick(this,0,1,internalRender,tickModes.FORCE);resetTimerProperties(this);if(this._hasChildren){forEachChildren(this,resetTimerProperties)}return this}init(internalRender=0){this.fps=this._fps;this.speed=this._speed;if(!internalRender&&this._hasChildren){tick(this,this.duration,1,internalRender,tickModes.FORCE)}this.reset(internalRender);const autoplay=this._autoplay;if(autoplay===true){this.resume()}else if(autoplay&&!isUnd(autoplay.linked)){autoplay.link(this)}return this}resetTime(){const timeScale=1/(this._speed*engine._speed);this._startTime=now()-(this._currentTime+this._delay)*timeScale;return this}pause(){if(this.paused)return this;this.paused=true;this.onPause(this);return this}resume(){if(!this.paused)return this;this.paused=false;if(this.duration<=minValue&&!this._hasChildren){tick(this,minValue,0,0,tickModes.FORCE)}else{if(!this._running){addChild(engine,this);engine._hasChildren=true;this._running=true}this.resetTime();this._startTime-=12;engine.wake()}return this}restart(){return this.reset(0).resume()}seek(time,muteCallbacks=0,internalRender=0){reviveTimer(this);this.completed=false;const isPaused=this.paused;this.paused=true;tick(this,time+this._delay,~~muteCallbacks,~~internalRender,tickModes.AUTO);return isPaused?this:this.resume()}alternate(){const reversed=this._reversed;const count=this.iterationCount;const duration=this.iterationDuration;const iterations=count===Infinity?floor(maxValue/duration):count;this._reversed=+(this._alternate&&!(iterations%2)?reversed:!reversed);if(count===Infinity){this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress}else{this.seek(duration*iterations-this._currentTime)}this.resetTime();return this}play(){if(this._reversed)this.alternate();return this.resume()}reverse(){if(!this._reversed)this.alternate();return this.resume()}cancel(){if(this._hasChildren){forEachChildren(this,(child=>child.cancel()),true)}else{forEachChildren(this,removeTweenSliblings)}this._cancelled=1;return this.pause()}stretch(newDuration){const currentDuration=this.duration;const normlizedDuration=normalizeTime(newDuration);if(currentDuration===normlizedDuration)return this;const timeScale=newDuration/currentDuration;const isSetter=newDuration<=minValue;this.duration=isSetter?minValue:normlizedDuration;this.iterationDuration=isSetter?minValue:normalizeTime(this.iterationDuration*timeScale);this._offset*=timeScale;this._delay*=timeScale;this._loopDelay*=timeScale;return this}revert(){tick(this,0,1,0,tickModes.AUTO);const ap=this._autoplay;if(ap&&ap.linked&&ap.linked===this)ap.revert();return this.cancel()}complete(){return this.seek(this.duration).cancel()}then(callback=noop){const then=this.then;const onResolve=()=>{this.then=null;callback(this);this.then=then;this._resolve=noop};return new Promise((r=>{this._resolve=()=>r(onResolve());if(this.completed)this._resolve();return this}))}}const createTimer=parameters=>new Timer(parameters,null,0).init();const none=t=>t;const calcBezier=(aT,aA1,aA2)=>(((1-3*aA2+3*aA1)*aT+(3*aA2-6*aA1))*aT+3*aA1)*aT;const binarySubdivide=(aX,mX1,mX2)=>{let aA=0,aB=1,currentX,currentT,i=0;do{currentT=aA+(aB-aA)/2;currentX=calcBezier(currentT,mX1,mX2)-aX;if(currentX>0){aB=currentT}else{aA=currentT}}while(abs(currentX)>1e-7&&++i<100);return currentT};const cubicBezier=(mX1=.5,mY1=0,mX2=.5,mY2=1)=>mX1===mY1&&mX2===mY2?none:t=>t===0||t===1?t:calcBezier(binarySubdivide(t,mX1,mX2),mY1,mY2);const steps=(steps=10,fromStart)=>{const roundMethod=fromStart?ceil:floor;return t=>roundMethod(clamp(t,0,1)*steps)*(1/steps)};const linear=(...args)=>{const argsLength=args.length;if(!argsLength)return none;const totalPoints=argsLength-1;const firstArg=args[0];const lastArg=args[totalPoints];const xPoints=[0];const yPoints=[parseNumber(firstArg)];for(let i=1;i<totalPoints;i++){const arg=args[i];const splitValue=isStr(arg)?arg.trim().split(" "):[arg];const value=splitValue[0];const percent=splitValue[1];xPoints.push(!isUnd(percent)?parseNumber(percent)/100:i/totalPoints);yPoints.push(parseNumber(value))}yPoints.push(parseNumber(lastArg));xPoints.push(1);return function easeLinear(t){for(let i=1,l=xPoints.length;i<l;i++){const currentX=xPoints[i];if(t<=currentX){const prevX=xPoints[i-1];const prevY=yPoints[i-1];return prevY+(yPoints[i]-prevY)*(t-prevX)/(currentX-prevX)}}return yPoints[yPoints.length-1]}};const irregular=(length=10,randomness=1)=>{const values=[0];const total=length-1;for(let i=1;i<total;i++){const previousValue=values[i-1];const spacing=i/total;const segmentEnd=(i+1)/total;const randomVariation=spacing+(segmentEnd-spacing)*Math.random();const randomValue=spacing*(1-randomness)+randomVariation*randomness;values.push(clamp(randomValue,previousValue,1))}values.push(1);return linear(...values)};const halfPI=PI/2;const doublePI=PI*2;const easeInPower=(p=1.68)=>t=>pow(t,+p);const easeInFunctions={[emptyString]:easeInPower,Quad:easeInPower(2),Cubic:easeInPower(3),Quart:easeInPower(4),Quint:easeInPower(5),Sine:t=>1-cos(t*halfPI),Circ:t=>1-sqrt(1-t*t),Expo:t=>t?pow(2,10*t-10):0,Bounce:t=>{let pow2,b=4;while(t<((pow2=pow(2,--b))-1)/11);return 1/pow(4,3-b)-7.5625*pow((pow2*3-2)/22-t,2)},Back:(overshoot=1.70158)=>t=>(+overshoot+1)*t*t*t-+overshoot*t*t,Elastic:(amplitude=1,period=.3)=>{const a=clamp(+amplitude,1,10);const p=clamp(+period,minValue,2);const s=p/doublePI*asin(1/a);const e=doublePI/p;return t=>t===0||t===1?t:-a*pow(2,-10*(1-t))*sin((1-t-s)*e)}};const easeTypes={in:easeIn=>t=>easeIn(t),out:easeIn=>t=>1-easeIn(1-t),inOut:easeIn=>t=>t<.5?easeIn(t*2)/2:1-easeIn(t*-2+2)/2,outIn:easeIn=>t=>t<.5?(1-easeIn(1-t*2))/2:(easeIn(t*2-1)+1)/2};const parseEaseString=(string,easesFunctions,easesLookups)=>{if(easesLookups[string])return easesLookups[string];if(string.indexOf("(")<=-1){const hasParams=easeTypes[string]||string.includes("Back")||string.includes("Elastic");const parsedFn=hasParams?easesFunctions[string]():easesFunctions[string];return parsedFn?easesLookups[string]=parsedFn:none}else{const split=string.slice(0,-1).split("(");const parsedFn=easesFunctions[split[0]];return parsedFn?easesLookups[string]=parsedFn(...split[1].split(",")):none}};const eases=(()=>{const list={linear:linear,irregular:irregular,steps:steps,cubicBezier:cubicBezier};for(let type in easeTypes){for(let name in easeInFunctions){const easeIn=easeInFunctions[name];const easeType=easeTypes[type];list[type+name]=name===emptyString||name==="Back"||name==="Elastic"?(a,b)=>easeType(easeIn(a,b)):easeType(easeIn)}}return list})();const JSEasesLookups={linear:none};const parseEasings=ease=>isFnc(ease)?ease:isStr(ease)?parseEaseString(ease,eases,JSEasesLookups):none;const propertyNamesCache={};const sanitizePropertyName=(propertyName,target,tweenType)=>{if(tweenType===tweenTypes.TRANSFORM){const t=shortTransforms.get(propertyName);return t?t:propertyName}else if(tweenType===tweenTypes.CSS||tweenType===tweenTypes.ATTRIBUTE&&(isSvg(target)&&propertyName in target.style)){const cachedPropertyName=propertyNamesCache[propertyName];if(cachedPropertyName){return cachedPropertyName}else{const lowerCaseName=propertyName?toLowerCase(propertyName):propertyName;propertyNamesCache[propertyName]=lowerCaseName;return lowerCaseName}}else{return propertyName}};const angleUnitsMap={deg:1,rad:180/PI,turn:360};const convertedValuesCache={};const convertValueUnit=(el,decomposedValue,unit,force=false)=>{const currentUnit=decomposedValue.u;const currentNumber=decomposedValue.n;if(decomposedValue.t===valueTypes.UNIT&&currentUnit===unit){return decomposedValue}const cachedKey=currentNumber+currentUnit+unit;const cached=convertedValuesCache[cachedKey];if(!isUnd(cached)&&!force){decomposedValue.n=cached}else{let convertedValue;if(currentUnit in angleUnitsMap){convertedValue=currentNumber*angleUnitsMap[currentUnit]/angleUnitsMap[unit]}else{const baseline=100;const tempEl=el.cloneNode();const parentNode=el.parentNode;const parentEl=parentNode&&parentNode!==doc?parentNode:doc.body;parentEl.appendChild(tempEl);const elStyle=tempEl.style;elStyle.width=baseline+currentUnit;const currentUnitWidth=tempEl.offsetWidth||baseline;elStyle.width=baseline+unit;const newUnitWidth=tempEl.offsetWidth||baseline;const factor=currentUnitWidth/newUnitWidth;parentEl.removeChild(tempEl);convertedValue=factor*currentNumber}decomposedValue.n=convertedValue;convertedValuesCache[cachedKey]=convertedValue}decomposedValue.t===valueTypes.UNIT;decomposedValue.u=unit;return decomposedValue};const cleanInlineStyles=renderable=>{if(renderable._hasChildren){forEachChildren(renderable,cleanInlineStyles,true)}else{const animation=renderable;animation.pause();forEachChildren(animation,(tween=>{const tweenProperty=tween.property;const tweenTarget=tween.target;if(tweenTarget[isDomSymbol]){const targetStyle=tweenTarget.style;const originalInlinedValue=animation._inlineStyles[tweenProperty];if(tween._tweenType===tweenTypes.TRANSFORM){const cachedTransforms=tweenTarget[transformsSymbol];if(isUnd(originalInlinedValue)||originalInlinedValue===emptyString){delete cachedTransforms[tweenProperty]}else{cachedTransforms[tweenProperty]=originalInlinedValue}if(tween._renderTransforms){if(!Object.keys(cachedTransforms).length){targetStyle.removeProperty("transform")}else{let str=emptyString;for(let key in cachedTransforms){str+=transformsFragmentStrings[key]+cachedTransforms[key]+") "}targetStyle.transform=str}}}else{if(isUnd(originalInlinedValue)||originalInlinedValue===emptyString){targetStyle.removeProperty(tweenProperty)}else{targetStyle[tweenProperty]=originalInlinedValue}}if(animation._tail===tween){animation.targets.forEach((t=>{if(t.getAttribute&&t.getAttribute("style")===emptyString){t.removeAttribute("style")}}))}}}))}return renderable};const fromTargetObject=createDecomposedValueTargetObject();const toTargetObject=createDecomposedValueTargetObject();const toFunctionStore={func:null};const keyframesTargetArray=[null];const fastSetValuesArray=[null,null];const keyObjectTarget={to:null};let tweenId=0;let keyframes;let key;const generateKeyframes=(keyframes,parameters)=>{const properties={};if(isArr(keyframes)){const propertyNames=[].concat(...keyframes.map((key=>Object.keys(key)))).filter(isKey);for(let i=0,l=propertyNames.length;i<l;i++){const propName=propertyNames[i];const propArray=keyframes.map((key=>{const newKey={};for(let p in key){const keyValue=key[p];if(isKey(p)){if(p===propName){newKey.to=keyValue}}else{newKey[p]=keyValue}}return newKey}));properties[propName]=propArray}}else{const totalDuration=setValue(parameters.duration,globals.defaults.duration);const keys=Object.keys(keyframes).map((key=>({o:parseFloat(key)/100,p:keyframes[key]}))).sort(((a,b)=>a.o-b.o));keys.forEach((key=>{const offset=key.o;const prop=key.p;for(let name in prop){if(isKey(name)){let propArray=properties[name];if(!propArray)propArray=properties[name]=[];const duration=offset*totalDuration;let length=propArray.length;let prevKey=propArray[length-1];const keyObj={to:prop[name]};let durProgress=0;for(let i=0;i<length;i++){durProgress+=propArray[i].duration}if(length===1){keyObj.from=prevKey.to}if(prop.ease){keyObj.ease=prop.ease}keyObj.duration=duration-(length?durProgress:0);propArray.push(keyObj)}}return key}));for(let name in properties){const propArray=properties[name];let prevEase;for(let i=0,l=propArray.length;i<l;i++){const prop=propArray[i];const currentEase=prop.ease;prop.ease=prevEase?prevEase:undefined;prevEase=currentEase}if(!propArray[0].duration){propArray.shift()}}}return properties};class JSAnimation extends Timer{constructor(targets,parameters,parent,parentPosition,fastSet=false,index=0,length=0){super(parameters,parent,parentPosition);const parsedTargets=registerTargets(targets);const targetsLength=parsedTargets.length;const kfParams=parameters.keyframes;const params=kfParams?mergeObjects(generateKeyframes(kfParams,parameters),parameters):parameters;const{delay:delay,duration:duration,ease:ease,playbackEase:playbackEase,modifier:modifier,composition:composition,onRender:onRender}=params;const animDefaults=parent?parent.defaults:globals.defaults;const animaPlaybackEase=setValue(playbackEase,animDefaults.playbackEase);const animEase=animaPlaybackEase?parseEasings(animaPlaybackEase):null;const hasSpring=!isUnd(ease)&&!isUnd(ease.ease);const tEasing=hasSpring?ease.ease:setValue(ease,animEase?"linear":animDefaults.ease);const tDuration=hasSpring?ease.duration:setValue(duration,animDefaults.duration);const tDelay=setValue(delay,animDefaults.delay);const tModifier=modifier||animDefaults.modifier;const tComposition=isUnd(composition)&&targetsLength>=K?compositionTypes.none:!isUnd(composition)?composition:animDefaults.composition;const animInlineStyles={};const absoluteOffsetTime=this._offset+(parent?parent._offset:0);let iterationDuration=NaN;let iterationDelay=NaN;let animationAnimationLength=0;let shouldTriggerRender=0;for(let targetIndex=0;targetIndex<targetsLength;targetIndex++){const target=parsedTargets[targetIndex];const ti=index||targetIndex;const tl=length||targetsLength;let lastTransformGroupIndex=NaN;let lastTransformGroupLength=NaN;for(let p in params){if(isKey(p)){const tweenType=getTweenType(target,p);const propName=sanitizePropertyName(p,target,tweenType);let propValue=params[p];const isPropValueArray=isArr(propValue);if(fastSet&&!isPropValueArray){fastSetValuesArray[0]=propValue;fastSetValuesArray[1]=propValue;propValue=fastSetValuesArray}if(isPropValueArray){const arrayLength=propValue.length;const isNotObjectValue=!isObj(propValue[0]);if(arrayLength===2&&isNotObjectValue){keyObjectTarget.to=propValue;keyframesTargetArray[0]=keyObjectTarget;keyframes=keyframesTargetArray}else if(arrayLength>2&&isNotObjectValue){keyframes=[];propValue.forEach(((v,i)=>{if(!i){fastSetValuesArray[0]=v}else if(i===1){fastSetValuesArray[1]=v;keyframes.push(fastSetValuesArray)}else{keyframes.push(v)}}))}else{keyframes=propValue}}else{keyframesTargetArray[0]=propValue;keyframes=keyframesTargetArray}let siblings=null;let prevTween=null;let firstTweenChangeStartTime=NaN;let lastTweenChangeEndTime=0;let tweenIndex=0;for(let l=keyframes.length;tweenIndex<l;tweenIndex++){const keyframe=keyframes[tweenIndex];if(isObj(keyframe)){key=keyframe}else{keyObjectTarget.to=keyframe;key=keyObjectTarget}toFunctionStore.func=null;const computedToValue=getFunctionValue(key.to,target,ti,tl,toFunctionStore);let tweenToValue;if(isObj(computedToValue)&&!isUnd(computedToValue.to)){key=computedToValue;tweenToValue=computedToValue.to}else{tweenToValue=computedToValue}const tweenFromValue=getFunctionValue(key.from,target,ti,tl);const keyEasing=key.ease;const hasSpring=!isUnd(keyEasing)&&!isUnd(keyEasing.ease);const tweenEasing=hasSpring?keyEasing.ease:keyEasing||tEasing;const tweenDuration=hasSpring?keyEasing.duration:getFunctionValue(setValue(key.duration,l>1?getFunctionValue(tDuration,target,ti,tl)/l:tDuration),target,ti,tl);const tweenDelay=getFunctionValue(setValue(key.delay,!tweenIndex?tDelay:0),target,ti,tl);const computedComposition=getFunctionValue(setValue(key.composition,tComposition),target,ti,tl);const tweenComposition=isNum(computedComposition)?computedComposition:compositionTypes[computedComposition];const tweenModifier=key.modifier||tModifier;const hasFromvalue=!isUnd(tweenFromValue);const hasToValue=!isUnd(tweenToValue);const isFromToArray=isArr(tweenToValue);const isFromToValue=isFromToArray||hasFromvalue&&hasToValue;const tweenStartTime=prevTween?lastTweenChangeEndTime+tweenDelay:tweenDelay;const absoluteStartTime=round(absoluteOffsetTime+tweenStartTime,12);if(!shouldTriggerRender&&(hasFromvalue||isFromToArray))shouldTriggerRender=1;let prevSibling=prevTween;if(tweenComposition!==compositionTypes.none){if(!siblings)siblings=getTweenSiblings(target,propName);let nextSibling=siblings._head;while(nextSibling&&!nextSibling._isOverridden&&nextSibling._absoluteStartTime<=absoluteStartTime){prevSibling=nextSibling;nextSibling=nextSibling._nextRep;if(nextSibling&&nextSibling._absoluteStartTime>=absoluteStartTime){while(nextSibling){overrideTween(nextSibling);nextSibling=nextSibling._nextRep}}}}if(isFromToValue){decomposeRawValue(isFromToArray?getFunctionValue(tweenToValue[0],target,ti,tl):tweenFromValue,fromTargetObject);decomposeRawValue(isFromToArray?getFunctionValue(tweenToValue[1],target,ti,tl,toFunctionStore):tweenToValue,toTargetObject);if(fromTargetObject.t===valueTypes.NUMBER){if(prevSibling){if(prevSibling._valueType===valueTypes.UNIT){fromTargetObject.t=valueTypes.UNIT;fromTargetObject.u=prevSibling._unit}}else{decomposeRawValue(getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),decomposedOriginalValue);if(decomposedOriginalValue.t===valueTypes.UNIT){fromTargetObject.t=valueTypes.UNIT;fromTargetObject.u=decomposedOriginalValue.u}}}}else{if(hasToValue){decomposeRawValue(tweenToValue,toTargetObject)}else{if(prevTween){decomposeTweenValue(prevTween,toTargetObject)}else{decomposeRawValue(parent&&prevSibling&&prevSibling.parent.parent===parent?prevSibling._value:getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),toTargetObject)}}if(hasFromvalue){decomposeRawValue(tweenFromValue,fromTargetObject)}else{if(prevTween){decomposeTweenValue(prevTween,fromTargetObject)}else{decomposeRawValue(parent&&prevSibling&&prevSibling.parent.parent===parent?prevSibling._value:getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),fromTargetObject)}}}if(fromTargetObject.o){fromTargetObject.n=getRelativeValue(!prevSibling?decomposeRawValue(getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),decomposedOriginalValue).n:prevSibling._toNumber,fromTargetObject.n,fromTargetObject.o)}if(toTargetObject.o){toTargetObject.n=getRelativeValue(fromTargetObject.n,toTargetObject.n,toTargetObject.o)}if(fromTargetObject.t!==toTargetObject.t){if(fromTargetObject.t===valueTypes.COMPLEX||toTargetObject.t===valueTypes.COMPLEX){const complexValue=fromTargetObject.t===valueTypes.COMPLEX?fromTargetObject:toTargetObject;const notComplexValue=fromTargetObject.t===valueTypes.COMPLEX?toTargetObject:fromTargetObject;notComplexValue.t=valueTypes.COMPLEX;notComplexValue.s=cloneArray(complexValue.s);notComplexValue.d=complexValue.d.map((()=>notComplexValue.n))}else if(fromTargetObject.t===valueTypes.UNIT||toTargetObject.t===valueTypes.UNIT){const unitValue=fromTargetObject.t===valueTypes.UNIT?fromTargetObject:toTargetObject;const notUnitValue=fromTargetObject.t===valueTypes.UNIT?toTargetObject:fromTargetObject;notUnitValue.t=valueTypes.UNIT;notUnitValue.u=unitValue.u}else if(fromTargetObject.t===valueTypes.COLOR||toTargetObject.t===valueTypes.COLOR){const colorValue=fromTargetObject.t===valueTypes.COLOR?fromTargetObject:toTargetObject;const notColorValue=fromTargetObject.t===valueTypes.COLOR?toTargetObject:fromTargetObject;notColorValue.t=valueTypes.COLOR;notColorValue.s=colorValue.s;notColorValue.d=[0,0,0,1]}}if(fromTargetObject.u!==toTargetObject.u){let valueToConvert=toTargetObject.u?fromTargetObject:toTargetObject;valueToConvert=convertValueUnit(target,valueToConvert,toTargetObject.u?toTargetObject.u:fromTargetObject.u,false)}if(toTargetObject.d&&fromTargetObject.d&&toTargetObject.d.length!==fromTargetObject.d.length){const longestValue=fromTargetObject.d.length>toTargetObject.d.length?fromTargetObject:toTargetObject;const shortestValue=longestValue===fromTargetObject?toTargetObject:fromTargetObject;shortestValue.d=longestValue.d.map(((_,i)=>isUnd(shortestValue.d[i])?0:shortestValue.d[i]));shortestValue.s=cloneArray(longestValue.s)}const tweenUpdateDuration=round(+tweenDuration||minValue,12);const tween={parent:this,id:tweenId++,property:propName,target:target,_value:null,_func:toFunctionStore.func,_ease:parseEasings(tweenEasing),_fromNumbers:cloneArray(fromTargetObject.d),_toNumbers:cloneArray(toTargetObject.d),_strings:cloneArray(toTargetObject.s),_fromNumber:fromTargetObject.n,_toNumber:toTargetObject.n,_numbers:cloneArray(fromTargetObject.d),_number:fromTargetObject.n,_unit:toTargetObject.u,_modifier:tweenModifier,_currentTime:0,_startTime:tweenStartTime,_delay:+tweenDelay,_updateDuration:tweenUpdateDuration,_changeDuration:tweenUpdateDuration,_absoluteStartTime:absoluteStartTime,_tweenType:tweenType,_valueType:toTargetObject.t,_composition:tweenComposition,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};if(tweenComposition!==compositionTypes.none){composeTween(tween,siblings)}if(isNaN(firstTweenChangeStartTime)){firstTweenChangeStartTime=tween._startTime}lastTweenChangeEndTime=round(tweenStartTime+tweenUpdateDuration,12);prevTween=tween;animationAnimationLength++;addChild(this,tween)}if(isNaN(iterationDelay)||firstTweenChangeStartTime<iterationDelay){iterationDelay=firstTweenChangeStartTime}if(isNaN(iterationDuration)||lastTweenChangeEndTime>iterationDuration){iterationDuration=lastTweenChangeEndTime}if(tweenType===tweenTypes.TRANSFORM){lastTransformGroupIndex=animationAnimationLength-tweenIndex;lastTransformGroupLength=animationAnimationLength}}}if(!isNaN(lastTransformGroupIndex)){let i=0;forEachChildren(this,(tween=>{if(i>=lastTransformGroupIndex&&i<lastTransformGroupLength){tween._renderTransforms=1;if(tween._composition===compositionTypes.blend){forEachChildren(additive.animation,(additiveTween=>{if(additiveTween.id===tween.id){additiveTween._renderTransforms=1}}))}}i++}))}}if(!targetsLength){console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`)}if(iterationDelay){forEachChildren(this,(tween=>{if(!(tween._startTime-tween._delay)){tween._delay-=iterationDelay}tween._startTime-=iterationDelay}));iterationDuration-=iterationDelay}else{iterationDelay=0}if(!iterationDuration){iterationDuration=minValue;this.iterationCount=0}this.targets=parsedTargets;this.duration=iterationDuration===minValue?minValue:clampInfinity((iterationDuration+this._loopDelay)*this.iterationCount-this._loopDelay)||minValue;this.onRender=onRender||animDefaults.onRender;this._ease=animEase;this._delay=iterationDelay;this.iterationDuration=iterationDuration;this._inlineStyles=animInlineStyles;if(!this._autoplay&&shouldTriggerRender)this.onRender(this)}stretch(newDuration){const currentDuration=this.duration;if(currentDuration===normalizeTime(newDuration))return this;const timeScale=newDuration/currentDuration;forEachChildren(this,(tween=>{tween._updateDuration=normalizeTime(tween._updateDuration*timeScale);tween._changeDuration=normalizeTime(tween._changeDuration*timeScale);tween._currentTime*=timeScale;tween._startTime*=timeScale;tween._absoluteStartTime*=timeScale}));return super.stretch(newDuration)}refresh(){forEachChildren(this,(tween=>{const tweenFunc=tween._func;if(tweenFunc){const ogValue=getOriginalAnimatableValue(tween.target,tween.property,tween._tweenType);decomposeRawValue(ogValue,decomposedOriginalValue);decomposeRawValue(tweenFunc(),toTargetObject);tween._fromNumbers=cloneArray(decomposedOriginalValue.d);tween._fromNumber=decomposedOriginalValue.n;tween._toNumbers=cloneArray(toTargetObject.d);tween._strings=cloneArray(toTargetObject.s);tween._toNumber=toTargetObject.o?getRelativeValue(decomposedOriginalValue.n,toTargetObject.n,toTargetObject.o):toTargetObject.n}}));return this}revert(){super.revert();return cleanInlineStyles(this)}then(callback){return super.then(callback)}}const animate=(targets,parameters)=>new JSAnimation(targets,parameters,null,0,false).init();const easingToLinear=(fn,samples=100)=>{const points=[];for(let i=0;i<=samples;i++)points.push(fn(i/samples));return`linear(${points.join(", ")})`};const WAAPIEasesLookups={in:"ease-in",out:"ease-out",inOut:"ease-in-out"};const WAAPIeases=(()=>{const list={};for(let type in easeTypes)list[type]=p=>easeTypes[type](easeInPower(p));return list})();const parseWAAPIEasing=ease=>{let parsedEase=WAAPIEasesLookups[ease];if(parsedEase)return parsedEase;parsedEase="linear";if(isStr(ease)){if(stringStartsWith(ease,"linear")||stringStartsWith(ease,"cubic-")||stringStartsWith(ease,"steps")||stringStartsWith(ease,"ease")){parsedEase=ease}else if(stringStartsWith(ease,"cubicB")){parsedEase=toLowerCase(ease)}else{const parsed=parseEaseString(ease,WAAPIeases,WAAPIEasesLookups);if(isFnc(parsed))parsedEase=parsed===none?"linear":easingToLinear(parsed)}WAAPIEasesLookups[ease]=parsedEase}else if(isFnc(ease)){const easing=easingToLinear(ease);if(easing)parsedEase=easing}else if(ease.ease){parsedEase=easingToLinear(ease.ease)}return parsedEase};const transformsShorthands=["x","y","z"];const commonDefaultPXProperties=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",...transformsShorthands];const validIndividualTransforms=(()=>[...transformsShorthands,...validTransforms.filter((t=>["X","Y","Z"].some((axis=>t.endsWith(axis)))))])();let transformsPropertiesRegistered=null;const WAAPIAnimationsLookups={_head:null,_tail:null};const removeWAAPIAnimation=($el,property,parent)=>{let nextLookup=WAAPIAnimationsLookups._head;while(nextLookup){const next=nextLookup._next;const matchTarget=nextLookup.$el===$el;const matchProperty=!property||nextLookup.property===property;const matchParent=!parent||nextLookup.parent===parent;if(matchTarget&&matchProperty&&matchParent){const anim=nextLookup.animation;try{anim.commitStyles()}catch{}anim.cancel();removeChild(WAAPIAnimationsLookups,nextLookup);const lookupParent=nextLookup.parent;if(lookupParent){lookupParent._completed++;if(lookupParent.animations.length===lookupParent._completed){lookupParent.completed=true;if(!lookupParent.muteCallbacks){lookupParent.paused=true;lookupParent.onComplete(lookupParent);lookupParent._resolve(lookupParent)}}}}nextLookup=next}};const addWAAPIAnimation=(parent,$el,property,keyframes,params)=>{const animation=$el.animate(keyframes,params);const animTotalDuration=params.delay+ +params.duration*params.iterations;animation.playbackRate=parent._speed;if(parent.paused)animation.pause();if(parent.duration<animTotalDuration){parent.duration=animTotalDuration;parent.controlAnimation=animation}parent.animations.push(animation);removeWAAPIAnimation($el,property);addChild(WAAPIAnimationsLookups,{parent:parent,animation:animation,$el:$el,property:property,_next:null,_prev:null});const handleRemove=()=>{removeWAAPIAnimation($el,property,parent)};animation.onremove=handleRemove;animation.onfinish=handleRemove;return animation};const normalizeTweenValue=(propName,value,$el,i,targetsLength)=>{let v=getFunctionValue(value,$el,i,targetsLength);if(!isNum(v))return v;if(commonDefaultPXProperties.includes(propName)||stringStartsWith(propName,"translate"))return`${v}px`;if(stringStartsWith(propName,"rotate")||stringStartsWith(propName,"skew"))return`${v}deg`;return`${v}`};const parseIndividualTweenValue=($el,propName,from,to,i,targetsLength)=>{let tweenValue="0";const computedTo=!isUnd(to)?normalizeTweenValue(propName,to,$el,i,targetsLength):getComputedStyle($el)[propName];if(!isUnd(from)){const computedFrom=normalizeTweenValue(propName,from,$el,i,targetsLength);tweenValue=[computedFrom,computedTo]}else{tweenValue=isArr(to)?to.map((v=>normalizeTweenValue(propName,v,$el,i,targetsLength))):computedTo}return tweenValue};class WAAPIAnimation{constructor(targets,params){if(scope.current)scope.current.register(this);if(isNil(transformsPropertiesRegistered)){if(isBrowser&&(isUnd(CSS)||!Object.hasOwnProperty.call(CSS,"registerProperty"))){transformsPropertiesRegistered=false}else{validTransforms.forEach((t=>{const isSkew=stringStartsWith(t,"skew");const isScale=stringStartsWith(t,"scale");const isRotate=stringStartsWith(t,"rotate");const isTranslate=stringStartsWith(t,"translate");const isAngle=isRotate||isSkew;const syntax=isAngle?"<angle>":isScale?"<number>":isTranslate?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:syntax,inherits:false,initialValue:isTranslate?"0px":isAngle?"0deg":isScale?"1":"0"})}catch{}}));transformsPropertiesRegistered=true}}const parsedTargets=registerTargets(targets);const targetsLength=parsedTargets.length;if(!targetsLength){console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`)}const ease=setValue(params.ease,parseWAAPIEasing(globals.defaults.ease));const spring=ease.ease&&ease;const autoplay=setValue(params.autoplay,globals.defaults.autoplay);const scroll=autoplay&&autoplay.link?autoplay:false;const alternate=params.alternate&&params.alternate===true;const reversed=params.reversed&&params.reversed===true;const loop=setValue(params.loop,globals.defaults.loop);const iterations=loop===true||loop===Infinity?Infinity:isNum(loop)?loop+1:1;const direction=alternate?reversed?"alternate-reverse":"alternate":reversed?"reverse":"normal";const fill="forwards";const easing=parseWAAPIEasing(ease);const timeScale=globals.timeScale===1?1:K;this.targets=parsedTargets;this.animations=[];this.controlAnimation=null;this.onComplete=params.onComplete||noop;this.duration=0;this.muteCallbacks=false;this.completed=false;this.paused=!autoplay||scroll!==false;this.reversed=reversed;this.autoplay=autoplay;this._speed=setValue(params.playbackRate,globals.defaults.playbackRate);this._resolve=noop;this._completed=0;this._inlineStyles=parsedTargets.map(($el=>$el.getAttribute("style")));parsedTargets.forEach((($el,i)=>{const cachedTransforms=$el[transformsSymbol];const hasIndividualTransforms=validIndividualTransforms.some((t=>params.hasOwnProperty(t)));const duration=(spring?spring.duration:getFunctionValue(setValue(params.duration,globals.defaults.duration),$el,i,targetsLength))*timeScale;const delay=getFunctionValue(setValue(params.delay,globals.defaults.delay),$el,i,targetsLength)*timeScale;const composite=setValue(params.composition,"replace");for(let name in params){if(!isKey(name))continue;const keyframes={};const tweenParams={iterations:iterations,direction:direction,fill:fill,easing:easing,duration:duration,delay:delay,composite:composite};const propertyValue=params[name];const individualTransformProperty=hasIndividualTransforms?validTransforms.includes(name)?name:shortTransforms.get(name):false;let parsedPropertyValue;if(isObj(propertyValue)){const tweenOptions=propertyValue;const tweenOptionsEase=setValue(tweenOptions.ease,ease);const tweenOptionsSpring=tweenOptionsEase.ease&&tweenOptionsEase;const to=tweenOptions.to;const from=tweenOptions.from;tweenParams.duration=(tweenOptionsSpring?tweenOptionsSpring.duration:getFunctionValue(setValue(tweenOptions.duration,duration),$el,i,targetsLength))*timeScale;tweenParams.delay=getFunctionValue(setValue(tweenOptions.delay,delay),$el,i,targetsLength)*timeScale;tweenParams.composite=setValue(tweenOptions.composition,composite);tweenParams.easing=parseWAAPIEasing(tweenOptionsEase);parsedPropertyValue=parseIndividualTweenValue($el,name,from,to,i,targetsLength);if(individualTransformProperty){keyframes[`--${individualTransformProperty}`]=parsedPropertyValue;cachedTransforms[individualTransformProperty]=parsedPropertyValue}else{keyframes[name]=parseIndividualTweenValue($el,name,from,to,i,targetsLength)}addWAAPIAnimation(this,$el,name,keyframes,tweenParams);if(!isUnd(from)){if(!individualTransformProperty){$el.style[name]=keyframes[name][0]}else{const key=`--${individualTransformProperty}`;$el.style.setProperty(key,keyframes[key][0])}}}else{parsedPropertyValue=isArr(propertyValue)?propertyValue.map((v=>normalizeTweenValue(name,v,$el,i,targetsLength))):normalizeTweenValue(name,propertyValue,$el,i,targetsLength);if(individualTransformProperty){keyframes[`--${individualTransformProperty}`]=parsedPropertyValue;cachedTransforms[individualTransformProperty]=parsedPropertyValue}else{keyframes[name]=parsedPropertyValue}addWAAPIAnimation(this,$el,name,keyframes,tweenParams)}}if(hasIndividualTransforms){let transforms=emptyString;for(let t in cachedTransforms){transforms+=`${transformsFragmentStrings[t]}var(--${t})) `}$el.style.transform=transforms}}));if(scroll){this.autoplay.link(this)}}forEach(callback){const cb=isStr(callback)?a=>a[callback]():callback;this.animations.forEach(cb);return this}get speed(){return this._speed}set speed(speed){this._speed=+speed;this.forEach((anim=>anim.playbackRate=speed))}get currentTime(){const controlAnimation=this.controlAnimation;const timeScale=globals.timeScale;return this.completed?this.duration:controlAnimation?+controlAnimation.currentTime*(timeScale===1?1:timeScale):0}set currentTime(time){const t=time*(globals.timeScale===1?1:K);this.forEach((anim=>{if(t>=this.duration)anim.play();anim.currentTime=t}))}get progress(){return this.currentTime/this.duration}set progress(progress){this.forEach((anim=>anim.currentTime=progress*this.duration||0))}resume(){if(!this.paused)return this;this.paused=false;return this.forEach("play")}pause(){if(this.paused)return this;this.paused=true;return this.forEach("pause")}alternate(){this.reversed=!this.reversed;this.forEach("reverse");if(this.paused)this.forEach("pause");return this}play(){if(this.reversed)this.alternate();return this.resume()}reverse(){if(!this.reversed)this.alternate();return this.resume()}seek(time,muteCallbacks=false){if(muteCallbacks)this.muteCallbacks=true;if(time<this.duration)this.completed=false;this.currentTime=time;this.muteCallbacks=false;if(this.paused)this.pause();return this}restart(){this.completed=false;return this.seek(0,true).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){this.forEach("cancel");return this.pause()}revert(){this.cancel();this.targets.forEach((($el,i)=>$el.setAttribute("style",this._inlineStyles[i])));return this}then(callback=noop){const then=this.then;const onResolve=()=>{this.then=null;callback(this);this.then=then;this._resolve=noop};return new Promise((r=>{this._resolve=()=>r(onResolve());if(this.completed)this._resolve();return this}))}}const waapi={animate:(targets,params)=>new WAAPIAnimation(targets,params),convertEase:easingToLinear};const sync=(callback=noop)=>new Timer({duration:1*globals.timeScale,onComplete:callback},null,0).resume();function getTargetValue(targetSelector,propName,unit){const targets=registerTargets(targetSelector);if(!targets.length)return;const[target]=targets;const tweenType=getTweenType(target,propName);const normalizePropName=sanitizePropertyName(propName,target,tweenType);let originalValue=getOriginalAnimatableValue(target,normalizePropName);if(isUnd(unit)){return originalValue}else{decomposeRawValue(originalValue,decomposedOriginalValue);if(decomposedOriginalValue.t===valueTypes.NUMBER||decomposedOriginalValue.t===valueTypes.UNIT){if(unit===false){return decomposedOriginalValue.n}else{const convertedValue=convertValueUnit(target,decomposedOriginalValue,unit,false);return`${round(convertedValue.n,globals.precision)}${convertedValue.u}`}}}}const setTargetValues=(targets,parameters)=>{if(isUnd(parameters))return;parameters.duration=minValue;parameters.composition=setValue(parameters.composition,compositionTypes.none);return new JSAnimation(targets,parameters,null,0,true).resume()};const removeTargetsFromAnimation=(targetsArray,animation,propertyName)=>{let tweensMatchesTargets=false;forEachChildren(animation,(tween=>{const tweenTarget=tween.target;if(targetsArray.includes(tweenTarget)){const tweenName=tween.property;const tweenType=tween._tweenType;const normalizePropName=sanitizePropertyName(propertyName,tweenTarget,tweenType);if(!normalizePropName||normalizePropName&&normalizePropName===tweenName){if(tween.parent._tail===tween&&tween._tweenType===tweenTypes.TRANSFORM&&tween._prev&&tween._prev._tweenType===tweenTypes.TRANSFORM){tween._prev._renderTransforms=1}removeChild(animation,tween);removeTweenSliblings(tween);tweensMatchesTargets=true}}}),true);return tweensMatchesTargets};const remove=(targets,renderable,propertyName)=>{const targetsArray=parseTargets(targets);const parent=renderable?renderable:engine;const waapiAnimation=renderable&&renderable.controlAnimation&&renderable;for(let i=0,l=targetsArray.length;i<l;i++){const $el=targetsArray[i];removeWAAPIAnimation($el,propertyName,waapiAnimation)}let removeMatches;if(parent._hasChildren){let iterationDuration=0;forEachChildren(parent,(child=>{if(!child._hasChildren){removeMatches=removeTargetsFromAnimation(targetsArray,child,propertyName);if(removeMatches&&!child._head){child.cancel();removeChild(parent,child)}else{const childTLOffset=child._offset+child._delay;const childDur=childTLOffset+child.duration;if(childDur>iterationDuration){iterationDuration=childDur}}}if(child._head){remove(targets,child,propertyName)}else{child._hasChildren=false}}),true);if(!isUnd(parent.iterationDuration)){parent.iterationDuration=iterationDuration}}else{removeMatches=removeTargetsFromAnimation(targetsArray,parent,propertyName)}if(removeMatches&&!parent._head){parent._hasChildren=false;if(parent.cancel)parent.cancel()}return targetsArray};const keepTime=createRefreshable;const randomPick=items=>items[random(0,items.length-1)];const roundPad=(v,decimalLength)=>(+v).toFixed(decimalLength);const padStart=(v,totalLength,padString)=>`${v}`.padStart(totalLength,padString);const padEnd=(v,totalLength,padString)=>`${v}`.padEnd(totalLength,padString);const wrap=(v,min,max)=>((v-min)%(max-min)+(max-min))%(max-min)+min;const mapRange=(value,inLow,inHigh,outLow,outHigh)=>outLow+(value-inLow)/(inHigh-inLow)*(outHigh-outLow);const degToRad=degrees=>degrees*PI/180;const radToDeg=radians=>radians*180/PI;const lerp=(start,end,amount,renderable)=>{let dt=K/globals.defaults.frameRate;if(renderable!==false){const ticker=renderable||engine._hasChildren&&engine;if(ticker&&ticker.deltaTime){dt=ticker.deltaTime}}const t=1-Math.exp(-amount*dt*.1);return!amount?start:amount===1?end:(1-t)*start+t*end};const curry=(fn,last=0)=>(...args)=>last?v=>fn(...args,v):v=>fn(v,...args);const chain=fn=>(...args)=>{const result=fn(...args);return new Proxy(noop,{apply:(_,__,[v])=>result(v),get:(_,prop)=>chain(((...nextArgs)=>{const nextResult=utils[prop](...nextArgs);return v=>nextResult(result(v))}))})};const makeChainable=(fn,right=0)=>(...args)=>(args.length<fn.length?chain(curry(fn,right)):fn)(...args);const utils={$:registerTargets,get:getTargetValue,set:setTargetValues,remove:remove,cleanInlineStyles:cleanInlineStyles,random:random,randomPick:randomPick,shuffle:shuffle,lerp:lerp,sync:sync,keepTime:keepTime,clamp:makeChainable(clamp),round:makeChainable(round),snap:makeChainable(snap),wrap:makeChainable(wrap),interpolate:makeChainable(interpolate,1),mapRange:makeChainable(mapRange),roundPad:makeChainable(roundPad),padStart:makeChainable(padStart),padEnd:makeChainable(padEnd),degToRad:makeChainable(degToRad),radToDeg:makeChainable(radToDeg)};const getPrevChildOffset=(timeline,timePosition)=>{if(stringStartsWith(timePosition,"<")){const goToPrevAnimationOffset=timePosition[1]==="<";const prevAnimation=timeline._tail;const prevOffset=prevAnimation?prevAnimation._offset+prevAnimation._delay:0;return goToPrevAnimationOffset?prevOffset:prevOffset+prevAnimation.duration}};const parseTimelinePosition=(timeline,timePosition)=>{let tlDuration=timeline.iterationDuration;if(tlDuration===minValue)tlDuration=0;if(isUnd(timePosition))return tlDuration;if(isNum(+timePosition))return+timePosition;const timePosStr=timePosition;const tlLabels=timeline?timeline.labels:null;const hasLabels=!isNil(tlLabels);const prevOffset=getPrevChildOffset(timeline,timePosStr);const hasSibling=!isUnd(prevOffset);const matchedRelativeOperator=relativeValuesExecRgx.exec(timePosStr);if(matchedRelativeOperator){const fullOperator=matchedRelativeOperator[0];const split=timePosStr.split(fullOperator);const labelOffset=hasLabels&&split[0]?tlLabels[split[0]]:tlDuration;const parsedOffset=hasSibling?prevOffset:hasLabels?labelOffset:tlDuration;const parsedNumericalOffset=+split[1];return getRelativeValue(parsedOffset,parsedNumericalOffset,fullOperator[0])}else{return hasSibling?prevOffset:hasLabels?!isUnd(tlLabels[timePosStr])?tlLabels[timePosStr]:tlDuration:tlDuration}};function getTimelineTotalDuration(tl){return clampInfinity((tl.iterationDuration+tl._loopDelay)*tl.iterationCount-tl._loopDelay)||minValue}function addTlChild(childParams,tl,timePosition,targets,index,length){const isSetter=isNum(childParams.duration)&&childParams.duration<=minValue;const adjustedPosition=isSetter?timePosition-minValue:timePosition;tick(tl,adjustedPosition,1,1,tickModes.AUTO);const tlChild=targets?new JSAnimation(targets,childParams,tl,adjustedPosition,false,index,length):new Timer(childParams,tl,adjustedPosition);tlChild.init(1);addChild(tl,tlChild);forEachChildren(tl,(child=>{const childTLOffset=child._offset+child._delay;const childDur=childTLOffset+child.duration;if(childDur>tl.iterationDuration)tl.iterationDuration=childDur}));tl.duration=getTimelineTotalDuration(tl);return tl}class Timeline extends Timer{constructor(parameters={}){super(parameters,null,0);this.duration=0;this.labels={};const defaultsParams=parameters.defaults;const globalDefaults=globals.defaults;this.defaults=defaultsParams?mergeObjects(defaultsParams,globalDefaults):globalDefaults;this.onRender=parameters.onRender||globalDefaults.onRender;const tlPlaybackEase=setValue(parameters.playbackEase,globalDefaults.playbackEase);this._ease=tlPlaybackEase?parseEasings(tlPlaybackEase):null;this.iterationDuration=0}add(a1,a2,a3){const isAnim=isObj(a2);const isTimer=isObj(a1);if(isAnim||isTimer){this._hasChildren=true;if(isAnim){const childParams=a2;if(isFnc(a3)){const staggeredPosition=a3;const parsedTargetsArray=parseTargets(a1);const tlDuration=this.duration;const tlIterationDuration=this.iterationDuration;const id=childParams.id;let i=0;const parsedLength=parsedTargetsArray.length;parsedTargetsArray.forEach((target=>{const staggeredChildParams={...childParams};this.duration=tlDuration;this.iterationDuration=tlIterationDuration;if(!isUnd(id))staggeredChildParams.id=id+"-"+i;addTlChild(staggeredChildParams,this,parseTimelinePosition(this,staggeredPosition(target,i,parsedLength,this)),target,i,parsedLength);i++}))}else{addTlChild(childParams,this,parseTimelinePosition(this,a3),a1)}}else{addTlChild(a1,this,parseTimelinePosition(this,a2))}return this.init(1)}}sync(synced,position){if(isUnd(synced)||synced&&isUnd(synced.pause))return this;synced.pause();const duration=+(synced.effect?synced.effect.getTiming().duration:synced.duration);return this.add(synced,{currentTime:[0,duration],duration:duration,ease:"linear"},position)}set(targets,parameters,position){if(isUnd(parameters))return this;parameters.duration=minValue;parameters.composition=compositionTypes.replace;return this.add(targets,parameters,position)}call(callback,position){if(isUnd(callback)||callback&&!isFnc(callback))return this;return this.add({duration:0,onComplete:()=>callback(this)},position)}label(labelName,position){if(isUnd(labelName)||labelName&&!isStr(labelName))return this;this.labels[labelName]=parseTimelinePosition(this,position);return this}remove(targets,propertyName){remove(targets,this,propertyName);return this}stretch(newDuration){const currentDuration=this.duration;if(currentDuration===normalizeTime(newDuration))return this;const timeScale=newDuration/currentDuration;const labels=this.labels;forEachChildren(this,(child=>child.stretch(child.duration*timeScale)));for(let labelName in labels)labels[labelName]*=timeScale;return super.stretch(newDuration)}refresh(){forEachChildren(this,(child=>{if(child.refresh)child.refresh()}));return this}revert(){super.revert();forEachChildren(this,(child=>child.revert),true);return cleanInlineStyles(this)}then(callback){return super.then(callback)}}const createTimeline=parameters=>new Timeline(parameters).init();class Animatable{constructor(targets,parameters){if(scope.current)scope.current.register(this);const beginHandler=()=>{if(this.callbacks.completed)this.callbacks.reset();this.callbacks.play()};const pauseHandler=()=>{if(this.callbacks.completed)return;let paused=true;for(let name in this.animations){const anim=this.animations[name];if(!anim.paused&&paused){paused=false;break}}if(paused){this.callbacks.complete()}};const globalParams={onBegin:beginHandler,onComplete:pauseHandler,onPause:pauseHandler};const callbacksAnimationParams={v:1,autoplay:false};const properties={};this.targets=[];this.animations={};this.callbacks=null;if(isUnd(targets)||isUnd(parameters))return;for(let propName in parameters){const paramValue=parameters[propName];if(isKey(propName)){properties[propName]=paramValue}else if(stringStartsWith(propName,"on")){callbacksAnimationParams[propName]=paramValue}else{globalParams[propName]=paramValue}}this.callbacks=new JSAnimation({v:0},callbacksAnimationParams);for(let propName in properties){const propValue=properties[propName];const isObjValue=isObj(propValue);let propParams={};let to="+=0";if(isObjValue){const unit=propValue.unit;if(isStr(unit))to+=unit}else{propParams.duration=propValue}propParams[propName]=isObjValue?mergeObjects({to:to},propValue):to;const animParams=mergeObjects(globalParams,propParams);animParams.composition=compositionTypes.replace;animParams.autoplay=false;const animation=this.animations[propName]=new JSAnimation(targets,animParams,null,0,false).init();if(!this.targets.length)this.targets.push(...animation.targets);this[propName]=(to,duration,ease)=>{const tween=animation._head;if(isUnd(to)&&tween){const numbers=tween._numbers;if(numbers&&numbers.length){return numbers}else{return tween._modifier(tween._number)}}else{forEachChildren(animation,(tween=>{if(isArr(to)){for(let i=0,l=to.length;i<l;i++){if(!isUnd(tween._numbers[i])){tween._fromNumbers[i]=tween._modifier(tween._numbers[i]);tween._toNumbers[i]=to[i]}}}else{tween._fromNumber=tween._modifier(tween._number);tween._toNumber=to}if(!isUnd(ease))tween._ease=parseEasings(ease);tween._currentTime=0}));if(!isUnd(duration))animation.stretch(duration);animation.reset(1).resume();return this}}}}revert(){for(let propName in this.animations){this[propName]=noop;this.animations[propName].revert()}this.animations={};this.targets.length=0;if(this.callbacks)this.callbacks.revert();return this}}const createAnimatable=(targets,parameters)=>new Animatable(targets,parameters);const maxSpringParamValue=K*10;class Spring{constructor(parameters={}){this.timeStep=.02;this.restThreshold=5e-4;this.restDuration=200;this.maxDuration=6e4;this.maxRestSteps=this.restDuration/this.timeStep/K;this.maxIterations=this.maxDuration/this.timeStep/K;this.m=clamp(setValue(parameters.mass,1),0,maxSpringParamValue);this.s=clamp(setValue(parameters.stiffness,100),1,maxSpringParamValue);this.d=clamp(setValue(parameters.damping,10),.1,maxSpringParamValue);this.v=clamp(setValue(parameters.velocity,0),-1e4,maxSpringParamValue);this.w0=0;this.zeta=0;this.wd=0;this.b=0;this.solverDuration=0;this.duration=0;this.compute();this.ease=t=>t===0||t===1?t:this.solve(t*this.solverDuration)}solve(time){const{zeta:zeta,w0:w0,wd:wd,b:b}=this;let t=time;if(zeta<1){t=exp(-t*zeta*w0)*(1*cos(wd*t)+b*sin(wd*t))}else{t=(1+b*t)*exp(-t*w0)}return 1-t}compute(){const{maxRestSteps:maxRestSteps,maxIterations:maxIterations,restThreshold:restThreshold,timeStep:timeStep,m:m,d:d,s:s,v:v}=this;const w0=this.w0=clamp(sqrt(s/m),minValue,K);const zeta=this.zeta=d/(2*sqrt(s*m));const wd=this.wd=zeta<1?w0*sqrt(1-zeta*zeta):0;this.b=zeta<1?(zeta*w0+-v)/wd:-v+w0;let solverTime=0;let restSteps=0;let iterations=0;while(restSteps<maxRestSteps&&iterations<maxIterations){if(abs(1-this.solve(solverTime))<restThreshold){restSteps++}else{restSteps=0}this.solverDuration=solverTime;solverTime+=timeStep;iterations++}this.duration=round(this.solverDuration*K,0)*globals.timeScale}get mass(){return this.m}set mass(v){this.m=clamp(setValue(v,1),0,maxSpringParamValue);this.compute()}get stiffness(){return this.s}set stiffness(v){this.s=clamp(setValue(v,100),1,maxSpringParamValue);this.compute()}get damping(){return this.d}set damping(v){this.d=clamp(setValue(v,10),.1,maxSpringParamValue);this.compute()}get velocity(){return this.v}set velocity(v){this.v=clamp(setValue(v,0),-1e4,maxSpringParamValue);this.compute()}}const createSpring=parameters=>new Spring(parameters);const preventDefault=e=>{if(e.cancelable)e.preventDefault()};class DOMProxy{constructor(el){this.el=el;this.zIndex=0;this.parentElement=null;this.classList={add:noop,remove:noop}}get x(){return this.el.x||0}set x(v){this.el.x=v}get y(){return this.el.y||0}set y(v){this.el.y=v}get width(){return this.el.width||0}set width(v){this.el.width=v}get height(){return this.el.height||0}set height(v){this.el.height=v}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class Transforms{constructor($el){this.$el=$el;this.inlineTransforms=[];this.point=new DOMPoint;this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(x,y){this.point.x=x;this.point.y=y;return this.point.matrixTransform(this.inversedMatrix)}traverseUp(cb){let $el=this.$el.parentElement,i=0;while($el&&$el!==doc){cb($el,i);$el=$el.parentElement;i++}}getMatrix(){const matrix=new DOMMatrix;this.traverseUp(($el=>{const transformValue=getComputedStyle($el).transform;if(transformValue){const elMatrix=new DOMMatrix(transformValue);matrix.preMultiplySelf(elMatrix)}}));return matrix}remove(){this.traverseUp((($el,i)=>{this.inlineTransforms[i]=$el.style.transform;$el.style.transform="none"}))}revert(){this.traverseUp((($el,i)=>{const ct=this.inlineTransforms[i];if(ct===""){$el.style.removeProperty("transform")}else{$el.style.transform=ct}}))}}const parseDraggableFunctionParameter=(value,draggable)=>value&&isFnc(value)?value(draggable):value;let zIndex=0;class Draggable{constructor(target,parameters={}){if(!target)return;if(scope.current)scope.current.register(this);const paramX=parameters.x;const paramY=parameters.y;const trigger=parameters.trigger;const modifier=parameters.modifier;const ease=parameters.releaseEase;const customEase=ease&&parseEasings(ease);const hasSpring=!isUnd(ease)&&!isUnd(ease.ease);const xProp=isObj(paramX)&&!isUnd(paramX.mapTo)?paramX.mapTo:"translateX";const yProp=isObj(paramY)&&!isUnd(paramY.mapTo)?paramY.mapTo:"translateY";const container=parseDraggableFunctionParameter(parameters.container,this);this.containerArray=isArr(container)?container:null;this.$container=container&&!this.containerArray?parseTargets(container)[0]:doc.body;this.useWin=this.$container===doc.body;this.$scrollContainer=this.useWin?win:this.$container;this.$target=isObj(target)?new DOMProxy(target):parseTargets(target)[0];this.$trigger=parseTargets(trigger?trigger:target)[0];this.fixed=getTargetValue(this.$target,"position")==="fixed";this.isFinePointer=true;this.containerPadding=[0,0,0,0];this.containerFriction=0;this.releaseContainerFriction=0;this.snapX=0;this.snapY=0;this.scrollSpeed=0;this.scrollThreshold=0;this.dragSpeed=0;this.maxVelocity=0;this.minVelocity=0;this.velocityMultiplier=0;this.cursor=false;this.releaseXSpring=hasSpring?ease:createSpring({mass:setValue(parameters.releaseMass,1),stiffness:setValue(parameters.releaseStiffness,80),damping:setValue(parameters.releaseDamping,20)});this.releaseYSpring=hasSpring?ease:createSpring({mass:setValue(parameters.releaseMass,1),stiffness:setValue(parameters.releaseStiffness,80),damping:setValue(parameters.releaseDamping,20)});this.releaseEase=customEase||eases.outQuint;this.hasReleaseSpring=hasSpring;this.onGrab=parameters.onGrab||noop;this.onDrag=parameters.onDrag||noop;this.onRelease=parameters.onRelease||noop;this.onUpdate=parameters.onUpdate||noop;this.onSettle=parameters.onSettle||noop;this.onSnap=parameters.onSnap||noop;this.onResize=parameters.onResize||noop;this.onAfterResize=parameters.onAfterResize||noop;this.disabled=[0,0];const animatableParams={};if(modifier)animatableParams.modifier=modifier;if(isUnd(paramX)||paramX===true){animatableParams[xProp]=0}else if(isObj(paramX)){const paramXObject=paramX;const animatableXParams={};if(paramXObject.modifier)animatableXParams.modifier=paramXObject.modifier;if(paramXObject.composition)animatableXParams.composition=paramXObject.composition;animatableParams[xProp]=animatableXParams}else if(paramX===false){animatableParams[xProp]=0;this.disabled[0]=1}if(isUnd(paramY)||paramY===true){animatableParams[yProp]=0}else if(isObj(paramY)){const paramYObject=paramY;const animatableYParams={};if(paramYObject.modifier)animatableYParams.modifier=paramYObject.modifier;if(paramYObject.composition)animatableYParams.composition=paramYObject.composition;animatableParams[yProp]=animatableYParams}else if(paramY===false){animatableParams[yProp]=0;this.disabled[1]=1}this.animate=new Animatable(this.$target,animatableParams);this.xProp=xProp;this.yProp=yProp;this.destX=0;this.destY=0;this.deltaX=0;this.deltaY=0;this.scroll={x:0,y:0};this.coords=[this.x,this.y,0,0];this.snapped=[0,0];this.pointer=[0,0,0,0,0,0,0,0];this.scrollView=[0,0];this.dragArea=[0,0,0,0];this.containerBounds=[-1e12,maxValue,maxValue,-1e12];this.scrollBounds=[0,0,0,0];this.targetBounds=[0,0,0,0];this.window=[0,0];this.velocityStack=[0,0,0];this.velocityStackIndex=0;this.velocityTime=now();this.velocity=0;this.angle=0;this.cursorStyles=null;this.triggerStyles=null;this.bodyStyles=null;this.targetStyles=null;this.touchActionStyles=null;this.transforms=new Transforms(this.$target);this.overshootCoords={x:0,y:0};this.overshootTicker=new Timer({autoplay:false,onUpdate:()=>{this.updated=true;this.manual=true;if(!this.disabled[0])this.animate[this.xProp](this.overshootCoords.x,1);if(!this.disabled[1])this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=false;if(!this.disabled[0])this.animate[this.xProp](this.overshootCoords.x,0);if(!this.disabled[1])this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init();this.updateTicker=new Timer({autoplay:false,onUpdate:()=>this.update()},null,0).init();this.contained=!isUnd(container);this.manual=false;this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.enabled=false;this.initialized=false;this.activeProp=this.disabled[1]?xProp:yProp;this.animate.callbacks.onRender=()=>{const hasUpdated=this.updated;const hasMoved=this.grabbed&&hasUpdated;const hasReleased=!hasMoved&&this.released;const x=this.x;const y=this.y;const dx=x-this.coords[2];const dy=y-this.coords[3];this.deltaX=dx;this.deltaY=dy;this.coords[2]=x;this.coords[3]=y;if(hasUpdated&&(dx||dy)){this.onUpdate(this)}if(!hasReleased){this.updated=false}else{this.computeVelocity(dx,dy);this.angle=atan2(dy,dx)}};this.animate.callbacks.onComplete=()=>{if(!this.grabbed&&this.released){this.released=false}if(!this.manual){this.deltaX=0;this.deltaY=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.onSettle(this)}};this.resizeTicker=new Timer({autoplay:false,duration:150*globals.timeScale,onComplete:()=>{this.onResize(this);this.refresh();this.onAfterResize(this)}}).init();this.parameters=parameters;this.resizeObserver=new ResizeObserver((()=>{if(this.initialized){this.resizeTicker.restart()}else{this.initialized=true}}));this.enable();this.refresh();this.resizeObserver.observe(this.$container);if(!isObj(target))this.resizeObserver.observe(this.$target)}computeVelocity(dx,dy){const prevTime=this.velocityTime;const curTime=now();const elapsed=curTime-prevTime;if(elapsed<17)return this.velocity;this.velocityTime=curTime;const velocityStack=this.velocityStack;const vMul=this.velocityMultiplier;const minV=this.minVelocity;const maxV=this.maxVelocity;const vi=this.velocityStackIndex;velocityStack[vi]=round(clamp(sqrt(dx*dx+dy*dy)/elapsed*vMul,minV,maxV),5);const velocity=max(velocityStack[0],velocityStack[1],velocityStack[2]);this.velocity=velocity;this.velocityStackIndex=(vi+1)%3;return velocity}setX(x,muteUpdateCallback=false){if(this.disabled[0])return;const v=round(x,5);this.overshootTicker.pause();this.manual=true;this.updated=!muteUpdateCallback;this.destX=v;this.snapped[0]=snap(v,this.snapX);this.animate[this.xProp](v,0);this.manual=false;return this}setY(y,muteUpdateCallback=false){if(this.disabled[1])return;const v=round(y,5);this.overshootTicker.pause();this.manual=true;this.updated=!muteUpdateCallback;this.destY=v;this.snapped[1]=snap(v,this.snapY);this.animate[this.yProp](v,0);this.manual=false;return this}get x(){return round(this.animate[this.xProp](),globals.precision)}set x(x){this.setX(x,false)}get y(){return round(this.animate[this.yProp](),globals.precision)}set y(y){this.setY(y,false)}get progressX(){return mapRange(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(x){this.setX(mapRange(x,0,1,this.containerBounds[3],this.containerBounds[1]),false)}get progressY(){return mapRange(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(y){this.setY(mapRange(y,0,1,this.containerBounds[0],this.containerBounds[2]),false)}updateScrollCoords(){const sx=round(this.useWin?win.scrollX:this.$container.scrollLeft,0);const sy=round(this.useWin?win.scrollY:this.$container.scrollTop,0);const[cpt,cpr,cpb,cpl]=this.containerPadding;const threshold=this.scrollThreshold;this.scroll.x=sx;this.scroll.y=sy;this.scrollBounds[0]=sy-this.targetBounds[0]+cpt-threshold;this.scrollBounds[1]=sx-this.targetBounds[1]-cpr+threshold;this.scrollBounds[2]=sy-this.targetBounds[2]-cpb+threshold;this.scrollBounds[3]=sx-this.targetBounds[3]+cpl-threshold}updateBoundingValues(){const $container=this.$container;if(!$container)return;const cx=this.x;const cy=this.y;const cx2=this.coords[2];const cy2=this.coords[3];this.coords[2]=0;this.coords[3]=0;this.setX(0,true);this.setY(0,true);this.transforms.remove();const iw=this.window[0]=win.innerWidth;const ih=this.window[1]=win.innerHeight;const uw=this.useWin;const sw=$container.scrollWidth;const sh=$container.scrollHeight;const fx=this.fixed;const transformContainerRect=$container.getBoundingClientRect();const[cpt,cpr,cpb,cpl]=this.containerPadding;this.dragArea[0]=uw?0:transformContainerRect.left;this.dragArea[1]=uw?0:transformContainerRect.top;this.scrollView[0]=uw?clamp(sw,iw,sw):sw;this.scrollView[1]=uw?clamp(sh,ih,sh):sh;this.updateScrollCoords();const{width:width,height:height,left:left,top:top,right:right,bottom:bottom}=$container.getBoundingClientRect();this.dragArea[2]=round(uw?clamp(width,iw,iw):width,0);this.dragArea[3]=round(uw?clamp(height,ih,ih):height,0);const containerOverflow=getTargetValue($container,"overflow");const visibleOverflow=containerOverflow==="visible";const hiddenOverflow=containerOverflow==="hidden";this.canScroll=fx?false:this.contained&&($container===doc.body&&visibleOverflow||!hiddenOverflow&&!visibleOverflow)&&(sw>this.dragArea[2]+cpl-cpr||sh>this.dragArea[3]+cpt-cpb)&&(!this.containerArray||this.containerArray&&!isArr(this.containerArray));if(this.contained){const sx=this.scroll.x;const sy=this.scroll.y;const canScroll=this.canScroll;const targetRect=this.$target.getBoundingClientRect();const hiddenLeft=canScroll?uw?0:$container.scrollLeft:0;const hiddenTop=canScroll?uw?0:$container.scrollTop:0;const hiddenRight=canScroll?this.scrollView[0]-hiddenLeft-width:0;const hiddenBottom=canScroll?this.scrollView[1]-hiddenTop-height:0;this.targetBounds[0]=round(targetRect.top+sy-(uw?0:top),0);this.targetBounds[1]=round(targetRect.right+sx-(uw?iw:right),0);this.targetBounds[2]=round(targetRect.bottom+sy-(uw?ih:bottom),0);this.targetBounds[3]=round(targetRect.left+sx-(uw?0:left),0);if(this.containerArray){this.containerBounds[0]=this.containerArray[0]+cpt;this.containerBounds[1]=this.containerArray[1]-cpr;this.containerBounds[2]=this.containerArray[2]-cpb;this.containerBounds[3]=this.containerArray[3]+cpl}else{this.containerBounds[0]=-round(targetRect.top-(fx?clamp(top,0,ih):top)+hiddenTop-cpt,0);this.containerBounds[1]=-round(targetRect.right-(fx?clamp(right,0,iw):right)-hiddenRight+cpr,0);this.containerBounds[2]=-round(targetRect.bottom-(fx?clamp(bottom,0,ih):bottom)-hiddenBottom+cpb,0);this.containerBounds[3]=-round(targetRect.left-(fx?clamp(left,0,iw):left)+hiddenLeft-cpl,0)}}this.transforms.revert();this.coords[2]=cx2;this.coords[3]=cy2;this.setX(cx,true);this.setY(cy,true)}isOutOfBounds(bounds,x,y){if(!this.contained)return 0;const[bt,br,bb,bl]=bounds;const[dx,dy]=this.disabled;const obx=!dx&&x<bl||!dx&&x>br;const oby=!dy&&y<bt||!dy&&y>bb;return obx&&!oby?1:!obx&&oby?2:obx&&oby?3:0}refresh(){const params=this.parameters;const paramX=params.x;const paramY=params.y;const container=parseDraggableFunctionParameter(params.container,this);const cp=parseDraggableFunctionParameter(params.containerPadding,this)||0;const containerPadding=isArr(cp)?cp:[cp,cp,cp,cp];const cx=this.x;const cy=this.y;const parsedCursorStyles=parseDraggableFunctionParameter(params.cursor,this);const cursorStyles={onHover:"grab",onGrab:"grabbing"};if(parsedCursorStyles){const{onHover:onHover,onGrab:onGrab}=parsedCursorStyles;if(onHover)cursorStyles.onHover=onHover;if(onGrab)cursorStyles.onGrab=onGrab}this.containerArray=isArr(container)?container:null;this.$container=container&&!this.containerArray?parseTargets(container)[0]:doc.body;this.useWin=this.$container===doc.body;this.$scrollContainer=this.useWin?win:this.$container;this.isFinePointer=matchMedia("(pointer:fine)").matches;this.containerPadding=setValue(containerPadding,[0,0,0,0]);this.containerFriction=clamp(setValue(parseDraggableFunctionParameter(params.containerFriction,this),.8),0,1);this.releaseContainerFriction=clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction,this),this.containerFriction),0,1);this.snapX=parseDraggableFunctionParameter(isObj(paramX)&&!isUnd(paramX.snap)?paramX.snap:params.snap,this);this.snapY=parseDraggableFunctionParameter(isObj(paramY)&&!isUnd(paramY.snap)?paramY.snap:params.snap,this);this.scrollSpeed=setValue(parseDraggableFunctionParameter(params.scrollSpeed,this),1.5);this.scrollThreshold=setValue(parseDraggableFunctionParameter(params.scrollThreshold,this),20);this.dragSpeed=setValue(parseDraggableFunctionParameter(params.dragSpeed,this),1);this.minVelocity=setValue(parseDraggableFunctionParameter(params.minVelocity,this),0);this.maxVelocity=setValue(parseDraggableFunctionParameter(params.maxVelocity,this),50);this.velocityMultiplier=setValue(parseDraggableFunctionParameter(params.velocityMultiplier,this),1);this.cursor=parsedCursorStyles===false?false:cursorStyles;this.updateBoundingValues();const[bt,br,bb,bl]=this.containerBounds;this.setX(clamp(cx,bl,br),true);this.setY(clamp(cy,bt,bb),true)}update(){this.updateScrollCoords();if(this.canScroll){const[cpt,cpr,cpb,cpl]=this.containerPadding;const[sw,sh]=this.scrollView;const daw=this.dragArea[2];const dah=this.dragArea[3];const csx=this.scroll.x;const csy=this.scroll.y;const nsw=this.$container.scrollWidth;const nsh=this.$container.scrollHeight;const csw=this.useWin?clamp(nsw,this.window[0],nsw):nsw;const csh=this.useWin?clamp(nsh,this.window[1],nsh):nsh;const swd=sw-csw;const shd=sh-csh;if(this.dragged&&swd>0){this.coords[0]-=swd;this.scrollView[0]=csw}if(this.dragged&&shd>0){this.coords[1]-=shd;this.scrollView[1]=csh}const s=this.scrollSpeed*10;const threshold=this.scrollThreshold;const[x,y]=this.coords;const[st,sr,sb,sl]=this.scrollBounds;const t=round(clamp((y-st+cpt)/threshold,-1,0)*s,0);const r=round(clamp((x-sr-cpr)/threshold,0,1)*s,0);const b=round(clamp((y-sb-cpb)/threshold,0,1)*s,0);const l=round(clamp((x-sl+cpl)/threshold,-1,0)*s,0);if(t||b||l||r){const[nx,ny]=this.disabled;let scrollX=csx;let scrollY=csy;if(!nx){scrollX=round(clamp(csx+(l||r),0,sw-daw),0);this.coords[0]-=csx-scrollX}if(!ny){scrollY=round(clamp(csy+(t||b),0,sh-dah),0);this.coords[1]-=csy-scrollY}if(this.useWin){this.$scrollContainer.scrollBy(-(csx-scrollX),-(csy-scrollY))}else{this.$scrollContainer.scrollTo(scrollX,scrollY)}}}const[ct,cr,cb,cl]=this.containerBounds;const[px1,py1,px2,py2,px3,py3]=this.pointer;this.coords[0]+=(px1-px3)*this.dragSpeed;this.coords[1]+=(py1-py3)*this.dragSpeed;this.pointer[4]=px1;this.pointer[5]=py1;const[cx,cy]=this.coords;const[sx,sy]=this.snapped;const cf=(1-this.containerFriction)*this.dragSpeed;this.setX(cx>cr?cr+(cx-cr)*cf:cx<cl?cl+(cx-cl)*cf:cx,false);this.setY(cy>cb?cb+(cy-cb)*cf:cy<ct?ct+(cy-ct)*cf:cy,false);this.computeVelocity(px1-px3,py1-py3);this.angle=atan2(py1-py2,px1-px2);const[nsx,nsy]=this.snapped;if(nsx!==sx&&this.snapX||nsy!==sy&&this.snapY){this.onSnap(this)}}stop(){this.updateTicker.pause();this.overshootTicker.pause();for(let prop in this.animate.animations)this.animate.animations[prop].pause();remove(this,null,"x");remove(this,null,"y");remove(this,null,"progressX");remove(this,null,"progressY");remove(this.scroll);remove(this.overshootCoords);return this}scrollInView(duration,gap=0,ease=eases.inOutQuad){this.updateScrollCoords();const x=this.destX;const y=this.destY;const scroll=this.scroll;const scrollBounds=this.scrollBounds;const canScroll=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(scrollBounds,x,y)){const[st,sr,sb,sl]=scrollBounds;const t=round(clamp(y-st,-1e12,0),0);const r=round(clamp(x-sr,0,maxValue),0);const b=round(clamp(y-sb,0,maxValue),0);const l=round(clamp(x-sl,-1e12,0),0);new JSAnimation(scroll,{x:round(scroll.x+(l?l-gap:r?r+gap:0),0),y:round(scroll.y+(t?t-gap:b?b+gap:0),0),duration:isUnd(duration)?350*globals.timeScale:duration,ease:ease,onUpdate:()=>{this.canScroll=false;this.$scrollContainer.scrollTo(scroll.x,scroll.y)}}).init().then((()=>{this.canScroll=canScroll}))}return this}handleHover(){if(this.isFinePointer&&this.cursor&&!this.cursorStyles){this.cursorStyles=setTargetValues(this.$trigger,{cursor:this.cursor.onHover})}}animateInView(duration,gap=0,ease=eases.inOutQuad){this.stop();this.updateBoundingValues();const x=this.x;const y=this.y;const[cpt,cpr,cpb,cpl]=this.containerPadding;const bt=this.scroll.y-this.targetBounds[0]+cpt+gap;const br=this.scroll.x-this.targetBounds[1]-cpr-gap;const bb=this.scroll.y-this.targetBounds[2]-cpb-gap;const bl=this.scroll.x-this.targetBounds[3]+cpl+gap;const ob=this.isOutOfBounds([bt,br,bb,bl],x,y);if(ob){const[disabledX,disabledY]=this.disabled;const destX=clamp(snap(x,this.snapX),bl,br);const destY=clamp(snap(y,this.snapY),bt,bb);const dur=isUnd(duration)?350*globals.timeScale:duration;if(!disabledX&&(ob===1||ob===3))this.animate[this.xProp](destX,dur,ease);if(!disabledY&&(ob===2||ob===3))this.animate[this.yProp](destY,dur,ease)}return this}handleDown(e){const $eTarget=e.target;if(this.grabbed||$eTarget.type==="range")return;e.stopPropagation();this.grabbed=true;this.released=false;this.stop();this.updateBoundingValues();const touches=e.changedTouches;const eventX=touches?touches[0].clientX:e.clientX;const eventY=touches?touches[0].clientY:e.clientY;const{x:x,y:y}=this.transforms.normalizePoint(eventX,eventY);const[ct,cr,cb,cl]=this.containerBounds;const cf=(1-this.containerFriction)*this.dragSpeed;const cx=this.x;const cy=this.y;this.coords[0]=this.coords[2]=!cf?cx:cx>cr?cr+(cx-cr)/cf:cx<cl?cl+(cx-cl)/cf:cx;this.coords[1]=this.coords[3]=!cf?cy:cy>cb?cb+(cy-cb)/cf:cy<ct?ct+(cy-ct)/cf:cy;this.pointer[0]=x;this.pointer[1]=y;this.pointer[2]=x;this.pointer[3]=y;this.pointer[4]=x;this.pointer[5]=y;this.pointer[6]=x;this.pointer[7]=y;this.deltaX=0;this.deltaY=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.angle=0;if(this.targetStyles){this.targetStyles.revert();this.targetStyles=null}const z=getTargetValue(this.$target,"zIndex",false);zIndex=(z>zIndex?z:zIndex)+1;this.targetStyles=setTargetValues(this.$target,{zIndex:zIndex});if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.cursorStyles){this.cursorStyles.revert();this.cursorStyles=null}if(this.isFinePointer&&this.cursor){this.bodyStyles=setTargetValues(doc.body,{cursor:this.cursor.onGrab})}this.scrollInView(100,0,eases.out(3));this.onGrab(this);doc.addEventListener("touchmove",this);doc.addEventListener("touchend",this);doc.addEventListener("touchcancel",this);doc.addEventListener("mousemove",this);doc.addEventListener("mouseup",this);doc.addEventListener("selectstart",this)}handleMove(e){if(!this.grabbed)return;const touches=e.changedTouches;const eventX=touches?touches[0].clientX:e.clientX;const eventY=touches?touches[0].clientY:e.clientY;const{x:x,y:y}=this.transforms.normalizePoint(eventX,eventY);const movedX=x-this.pointer[6];const movedY=y-this.pointer[7];let $parent=e.target;let isAtTop=false;let isAtBottom=false;let canTouchScroll=false;while(touches&&$parent&&$parent!==this.$trigger){const overflowY=getTargetValue($parent,"overflow-y");if(overflowY!=="hidden"&&overflowY!=="visible"){const{scrollTop:scrollTop,scrollHeight:scrollHeight,clientHeight:clientHeight}=$parent;if(scrollHeight>clientHeight){canTouchScroll=true;isAtTop=scrollTop<=3;isAtBottom=scrollTop>=scrollHeight-clientHeight-3;break}}$parent=$parent.parentNode}if(canTouchScroll&&(!isAtTop&&!isAtBottom||isAtTop&&movedY<0||isAtBottom&&movedY>0)){this.pointer[0]=x;this.pointer[1]=y;this.pointer[2]=x;this.pointer[3]=y;this.pointer[4]=x;this.pointer[5]=y;this.pointer[6]=x;this.pointer[7]=y}else{preventDefault(e);if(!this.triggerStyles)this.triggerStyles=setTargetValues(this.$trigger,{pointerEvents:"none"});this.$trigger.addEventListener("touchstart",preventDefault,{passive:false});this.$trigger.addEventListener("touchmove",preventDefault,{passive:false});this.$trigger.addEventListener("touchend",preventDefault);if(!this.disabled[0]&&abs(movedX)>3||!this.disabled[1]&&abs(movedY)>3){this.updateTicker.resume();this.pointer[2]=this.pointer[0];this.pointer[3]=this.pointer[1];this.pointer[0]=x;this.pointer[1]=y;this.dragged=true;this.released=false;this.onDrag(this)}}}handleUp(){if(!this.grabbed)return;this.updateTicker.pause();if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.bodyStyles){this.bodyStyles.revert();this.bodyStyles=null}const[disabledX,disabledY]=this.disabled;const[px1,py1,px2,py2,px3,py3]=this.pointer;const[ct,cr,cb,cl]=this.containerBounds;const[sx,sy]=this.snapped;const springX=this.releaseXSpring;const springY=this.releaseYSpring;const releaseEase=this.releaseEase;const hasReleaseSpring=this.hasReleaseSpring;const overshootCoords=this.overshootCoords;const cx=this.x;const cy=this.y;const pv=this.computeVelocity(px1-px3,py1-py3);const pa=this.angle=atan2(py1-py2,px1-px2);const ds=pv*150;const cf=(1-this.releaseContainerFriction)*this.dragSpeed;const nx=cx+cos(pa)*ds;const ny=cy+sin(pa)*ds;const bx=nx>cr?cr+(nx-cr)*cf:nx<cl?cl+(nx-cl)*cf:nx;const by=ny>cb?cb+(ny-cb)*cf:ny<ct?ct+(ny-ct)*cf:ny;const dx=this.destX=clamp(round(snap(bx,this.snapX),5),cl,cr);const dy=this.destY=clamp(round(snap(by,this.snapY),5),ct,cb);const ob=this.isOutOfBounds(this.containerBounds,nx,ny);let durationX=0;let durationY=0;let easeX=releaseEase;let easeY=releaseEase;let longestReleaseDuration=0;overshootCoords.x=cx;overshootCoords.y=cy;if(!disabledX){const directionX=dx===cr?cx>cr?-1:1:cx<cl?-1:1;const distanceX=round(cx-dx,0);springX.velocity=disabledY&&hasReleaseSpring?distanceX?ds*directionX/abs(distanceX):0:pv;const{ease:ease,duration:duration,restDuration:restDuration}=springX;durationX=cx===dx?0:hasReleaseSpring?duration:duration-restDuration*globals.timeScale;if(hasReleaseSpring)easeX=ease;if(durationX>longestReleaseDuration)longestReleaseDuration=durationX}if(!disabledY){const directionY=dy===cb?cy>cb?-1:1:cy<ct?-1:1;const distanceY=round(cy-dy,0);springY.velocity=disabledX&&hasReleaseSpring?distanceY?ds*directionY/abs(distanceY):0:pv;const{ease:ease,duration:duration,restDuration:restDuration}=springY;durationY=cy===dy?0:hasReleaseSpring?duration:duration-restDuration*globals.timeScale;if(hasReleaseSpring)easeY=ease;if(durationY>longestReleaseDuration)longestReleaseDuration=durationY}if(!hasReleaseSpring&&ob&&cf&&(durationX||durationY)){const composition=compositionTypes.blend;new JSAnimation(overshootCoords,{x:{to:bx,duration:durationX*.65},y:{to:by,duration:durationY*.65},ease:releaseEase,composition:composition}).init();new JSAnimation(overshootCoords,{x:{to:dx,duration:durationX},y:{to:dy,duration:durationY},ease:releaseEase,composition:composition}).init();this.overshootTicker.stretch(max(durationX,durationY)).restart()}else{if(!disabledX)this.animate[this.xProp](dx,durationX,easeX);if(!disabledY)this.animate[this.yProp](dy,durationY,easeY)}this.scrollInView(longestReleaseDuration,this.scrollThreshold,releaseEase);let hasSnapped=false;if(dx!==sx){this.snapped[0]=dx;if(this.snapX)hasSnapped=true}if(dy!==sy&&this.snapY){this.snapped[1]=dy;if(this.snapY)hasSnapped=true}if(hasSnapped)this.onSnap(this);this.grabbed=false;this.dragged=false;this.updated=true;this.released=true;this.onRelease(this);this.$trigger.removeEventListener("touchstart",preventDefault);this.$trigger.removeEventListener("touchmove",preventDefault);this.$trigger.removeEventListener("touchend",preventDefault);doc.removeEventListener("touchmove",this);doc.removeEventListener("touchend",this);doc.removeEventListener("touchcancel",this);doc.removeEventListener("mousemove",this);doc.removeEventListener("mouseup",this);doc.removeEventListener("selectstart",this)}reset(){this.stop();this.resizeTicker.pause();this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.setX(0,true);this.setY(0,true);this.coords[0]=0;this.coords[1]=0;this.pointer[0]=0;this.pointer[1]=0;this.pointer[2]=0;this.pointer[3]=0;this.pointer[4]=0;this.pointer[5]=0;this.pointer[6]=0;this.pointer[7]=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.angle=0;return this}enable(){if(!this.enabled){this.enabled=true;this.$target.classList.remove("is-disabled");this.touchActionStyles=setTargetValues(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"});this.$trigger.addEventListener("touchstart",this,{passive:true});this.$trigger.addEventListener("mousedown",this,{passive:true});this.$trigger.addEventListener("mouseenter",this)}return this}disable(){this.enabled=false;this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.touchActionStyles.revert();if(this.cursorStyles){this.cursorStyles.revert();this.cursorStyles=null}if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.bodyStyles){this.bodyStyles.revert();this.bodyStyles=null}if(this.targetStyles){this.targetStyles.revert();this.targetStyles=null}this.$target.classList.add("is-disabled");this.$trigger.removeEventListener("touchstart",this);this.$trigger.removeEventListener("mousedown",this);this.$trigger.removeEventListener("mouseenter",this);doc.removeEventListener("touchmove",this);doc.removeEventListener("touchend",this);doc.removeEventListener("touchcancel",this);doc.removeEventListener("mousemove",this);doc.removeEventListener("mouseup",this);doc.removeEventListener("selectstart",this);return this}revert(){this.reset();this.disable();this.$target.classList.remove("is-disabled");this.updateTicker.revert();this.overshootTicker.revert();this.resizeTicker.revert();this.animate.revert();this.resizeObserver.disconnect();return this}handleEvent(e){switch(e.type){case"mousedown":this.handleDown(e);break;case"touchstart":this.handleDown(e);break;case"mousemove":this.handleMove(e);break;case"touchmove":this.handleMove(e);break;case"mouseup":this.handleUp();break;case"touchend":this.handleUp();break;case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":preventDefault(e);break}}}const createDraggable=(target,parameters)=>new Draggable(target,parameters);class Scope{constructor(parameters={}){if(scope.current)scope.current.register(this);const rootParam=parameters.root;let root=doc;if(rootParam){root=rootParam.current||rootParam.nativeElement||parseTargets(rootParam)[0]||doc}const scopeDefaults=parameters.defaults;const globalDefault=globals.defaults;const mediaQueries=parameters.mediaQueries;this.defaults=scopeDefaults?mergeObjects(scopeDefaults,globalDefault):globalDefault;this.root=root;this.constructors=[];this.revertConstructors=[];this.revertibles=[];this.constructorsOnce=[];this.revertConstructorsOnce=[];this.revertiblesOnce=[];this.once=false;this.onceIndex=0;this.methods={};this.matches={};this.mediaQueryLists={};this.data={};if(mediaQueries){for(let mq in mediaQueries){const _mq=win.matchMedia(mediaQueries[mq]);this.mediaQueryLists[mq]=_mq;_mq.addEventListener("change",this)}}}register(revertible){const store=this.once?this.revertiblesOnce:this.revertibles;store.push(revertible)}execute(cb){let activeScope=scope.current;let activeRoot=scope.root;let activeDefaults=globals.defaults;scope.current=this;scope.root=this.root;globals.defaults=this.defaults;const mqs=this.mediaQueryLists;for(let mq in mqs)this.matches[mq]=mqs[mq].matches;const returned=cb(this);scope.current=activeScope;scope.root=activeRoot;globals.defaults=activeDefaults;return returned}refresh(){this.onceIndex=0;this.execute((()=>{let i=this.revertibles.length;let y=this.revertConstructors.length;while(i--)this.revertibles[i].revert();while(y--)this.revertConstructors[y](this);this.revertibles.length=0;this.revertConstructors.length=0;this.constructors.forEach((constructor=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructors.push(revertConstructor)}}))}));return this}add(a1,a2){this.once=false;if(isFnc(a1)){const constructor=a1;this.constructors.push(constructor);this.execute((()=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructors.push(revertConstructor)}}))}else{this.methods[a1]=(...args)=>this.execute((()=>a2(...args)))}return this}addOnce(scopeConstructorCallback){this.once=true;if(isFnc(scopeConstructorCallback)){const currentIndex=this.onceIndex++;const tracked=this.constructorsOnce[currentIndex];if(tracked)return this;const constructor=scopeConstructorCallback;this.constructorsOnce[currentIndex]=constructor;this.execute((()=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructorsOnce.push(revertConstructor)}}))}return this}keepTime(cb){this.once=true;const currentIndex=this.onceIndex++;const tracked=this.constructorsOnce[currentIndex];if(isFnc(tracked))return tracked(this);const constructor=createRefreshable(cb);this.constructorsOnce[currentIndex]=constructor;let trackedTickable;this.execute((()=>{trackedTickable=constructor(this)}));return trackedTickable}handleEvent(e){switch(e.type){case"change":this.refresh();break}}revert(){const revertibles=this.revertibles;const revertConstructors=this.revertConstructors;const revertiblesOnce=this.revertiblesOnce;const revertConstructorsOnce=this.revertConstructorsOnce;const mqs=this.mediaQueryLists;let i=revertibles.length;let j=revertConstructors.length;let k=revertiblesOnce.length;let l=revertConstructorsOnce.length;while(i--)revertibles[i].revert();while(j--)revertConstructors[j](this);while(k--)revertiblesOnce[k].revert();while(l--)revertConstructorsOnce[l](this);for(let mq in mqs)mqs[mq].removeEventListener("change",this);revertibles.length=0;revertConstructors.length=0;this.constructors.length=0;revertiblesOnce.length=0;revertConstructorsOnce.length=0;this.constructorsOnce.length=0;this.onceIndex=0;this.matches={};this.methods={};this.mediaQueryLists={};this.data={}}}const createScope=params=>new Scope(params);const getMaxViewHeight=()=>{const $el=doc.createElement("div");doc.body.appendChild($el);$el.style.height="100lvh";const height=$el.offsetHeight;doc.body.removeChild($el);return height};const parseScrollObserverFunctionParameter=(value,scroller)=>value&&isFnc(value)?value(scroller):value;const scrollContainers=new Map;class ScrollContainer{constructor($el){this.element=$el;this.useWin=this.element===doc.body;this.winWidth=0;this.winHeight=0;this.width=0;this.height=0;this.left=0;this.top=0;this.zIndex=0;this.scrollX=0;this.scrollY=0;this.prevScrollX=0;this.prevScrollY=0;this.scrollWidth=0;this.scrollHeight=0;this.velocity=0;this.backwardX=false;this.backwardY=false;this.scrollTicker=new Timer({autoplay:false,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const backwards=this.backwardX||this.backwardY;forEachChildren(this,(child=>child.handleScroll()),backwards)},onComplete:()=>this.dataTimer.pause()}).init();this.dataTimer=new Timer({autoplay:false,frameRate:30,onUpdate:self=>{const dt=self.deltaTime;const px=this.prevScrollX;const py=this.prevScrollY;const nx=this.scrollX;const ny=this.scrollY;const dx=px-nx;const dy=py-ny;this.prevScrollX=nx;this.prevScrollY=ny;if(dx)this.backwardX=px>nx;if(dy)this.backwardY=py>ny;this.velocity=round(dt>0?Math.sqrt(dx*dx+dy*dy)/dt:0,5)}}).init();this.resizeTicker=new Timer({autoplay:false,duration:250*globals.timeScale,onComplete:()=>{this.updateWindowBounds();this.refreshScrollObservers();this.handleScroll()}}).init();this.wakeTicker=new Timer({autoplay:false,duration:500*globals.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init();this._head=null;this._tail=null;this.updateScrollCoords();this.updateWindowBounds();this.updateBounds();this.refreshScrollObservers();this.handleScroll();this.resizeObserver=new ResizeObserver((()=>this.resizeTicker.restart()));this.resizeObserver.observe(this.element);(this.useWin?win:this.element).addEventListener("scroll",this,false)}updateScrollCoords(){const useWin=this.useWin;const $el=this.element;this.scrollX=round(useWin?win.scrollX:$el.scrollLeft,0);this.scrollY=round(useWin?win.scrollY:$el.scrollTop,0)}updateWindowBounds(){this.winWidth=win.innerWidth;this.winHeight=getMaxViewHeight()}updateBounds(){const style=getComputedStyle(this.element);const $el=this.element;this.scrollWidth=$el.scrollWidth+parseFloat(style.marginLeft)+parseFloat(style.marginRight);this.scrollHeight=$el.scrollHeight+parseFloat(style.marginTop)+parseFloat(style.marginBottom);this.updateWindowBounds();let width,height;if(this.useWin){width=this.winWidth;height=this.winHeight}else{const elRect=$el.getBoundingClientRect();width=$el.clientWidth;height=$el.clientHeight;this.top=elRect.top;this.left=elRect.left}this.width=width;this.height=height}refreshScrollObservers(){forEachChildren(this,(child=>{if(child._debug){child.removeDebug()}}));this.updateBounds();forEachChildren(this,(child=>{child.refresh();if(child._debug){child.debug()}}))}refresh(){this.updateWindowBounds();this.updateBounds();this.refreshScrollObservers();this.handleScroll()}handleScroll(){this.updateScrollCoords();this.wakeTicker.restart()}handleEvent(e){switch(e.type){case"scroll":this.handleScroll();break}}revert(){this.scrollTicker.cancel();this.dataTimer.cancel();this.resizeTicker.cancel();this.wakeTicker.cancel();this.resizeObserver.disconnect();(this.useWin?win:this.element).removeEventListener("scroll",this);scrollContainers.delete(this.element)}}const registerAndGetScrollContainer=target=>{const $el=target?parseTargets(target)[0]||doc.body:doc.body;let scrollContainer=scrollContainers.get($el);if(!scrollContainer){scrollContainer=new ScrollContainer($el);scrollContainers.set($el,scrollContainer)}return scrollContainer};const convertValueToPx=($el,v,size,under,over)=>{const clampMin=v==="min";const clampMax=v==="max";const value=v==="top"||v==="left"||v==="start"||clampMin?0:v==="bottom"||v==="right"||v==="end"||clampMax?"100%":v==="center"?"50%":v;const{n:n,u:u}=decomposeRawValue(value,decomposedOriginalValue);let px=n;if(u==="%"){px=n/100*size}else if(u){px=convertValueUnit($el,decomposedOriginalValue,"px",true).n}if(clampMax&&under<0)px+=under;if(clampMin&&over>0)px+=over;return px};const parseBoundValue=($el,v,size,under,over)=>{let value;if(isStr(v)){const matchedOperator=relativeValuesExecRgx.exec(v);if(matchedOperator){const splitter=matchedOperator[0];const operator=splitter[0];const splitted=v.split(splitter);const clampMin=splitted[0]==="min";const clampMax=splitted[0]==="max";const valueAPx=convertValueToPx($el,splitted[0],size,under,over);const valueBPx=convertValueToPx($el,splitted[1],size,under,over);if(clampMin){const min=getRelativeValue(convertValueToPx($el,"min",size),valueBPx,operator);value=min<valueAPx?valueAPx:min}else if(clampMax){const max=getRelativeValue(convertValueToPx($el,"max",size),valueBPx,operator);value=max>valueAPx?valueAPx:max}else{value=getRelativeValue(valueAPx,valueBPx,operator)}}else{value=convertValueToPx($el,v,size,under,over)}}else{value=v}return round(value,0)};const getAnimationDomTarget=linked=>{let $linkedTarget;const linkedTargets=linked.targets;for(let i=0,l=linkedTargets.length;i<l;i++){const target=linkedTargets[i];if(target[isDomSymbol]){$linkedTarget=target;break}}return $linkedTarget};let scrollerIndex=0;const debugColors$1=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class ScrollObserver{constructor(parameters={}){if(scope.current)scope.current.register(this);const syncMode=setValue(parameters.sync,"play pause");const ease=syncMode?parseEasings(syncMode):null;const isLinear=syncMode&&(syncMode==="linear"||syncMode===none);const isEase=syncMode&&!(ease===none&&!isLinear);const isSmooth=syncMode&&(isNum(syncMode)||syncMode===true||isLinear);const isMethods=syncMode&&(isStr(syncMode)&&!isEase&&!isSmooth);const syncMethods=isMethods?syncMode.split(" ").map((m=>()=>{const linked=this.linked;return linked&&linked[m]?linked[m]():null})):null;const biDirSync=isMethods&&syncMethods.length>2;this.index=scrollerIndex++;this.id=!isUnd(parameters.id)?parameters.id:this.index;this.container=registerAndGetScrollContainer(parameters.container);this.target=null;this.linked=null;this.repeat=null;this.horizontal=null;this.enter=null;this.leave=null;this.sync=isEase||isSmooth||!!syncMethods;this.syncEase=isEase?ease:null;this.syncSmooth=isSmooth?syncMode===true||isLinear?1:syncMode:null;this.onSyncEnter=syncMethods&&!biDirSync&&syncMethods[0]?syncMethods[0]:noop;this.onSyncLeave=syncMethods&&!biDirSync&&syncMethods[1]?syncMethods[1]:noop;this.onSyncEnterForward=syncMethods&&biDirSync&&syncMethods[0]?syncMethods[0]:noop;this.onSyncLeaveForward=syncMethods&&biDirSync&&syncMethods[1]?syncMethods[1]:noop;this.onSyncEnterBackward=syncMethods&&biDirSync&&syncMethods[2]?syncMethods[2]:noop;this.onSyncLeaveBackward=syncMethods&&biDirSync&&syncMethods[3]?syncMethods[3]:noop;this.onEnter=parameters.onEnter||noop;this.onLeave=parameters.onLeave||noop;this.onEnterForward=parameters.onEnterForward||noop;this.onLeaveForward=parameters.onLeaveForward||noop;this.onEnterBackward=parameters.onEnterBackward||noop;this.onLeaveBackward=parameters.onLeaveBackward||noop;this.onUpdate=parameters.onUpdate||noop;this.onSyncComplete=parameters.onSyncComplete||noop;this.reverted=false;this.completed=false;this.began=false;this.isInView=false;this.forceEnter=false;this.hasEntered=false;this.offset=0;this.offsetStart=0;this.offsetEnd=0;this.distance=0;this.prevProgress=0;this.thresholds=["start","end","end","start"];this.coords=[0,0,0,0];this.debugStyles=null;this.$debug=null;this._params=parameters;this._debug=setValue(parameters.debug,false);this._next=null;this._prev=null;addChild(this.container,this);sync((()=>{if(this.reverted)return;if(!this.target){const target=parseTargets(parameters.target)[0];this.target=target||doc.body;this.refresh()}if(this._debug)this.debug()}))}link(linked){if(linked){linked.pause();this.linked=linked;if(!this._params.target){let $linkedTarget;if(!isUnd(linked.targets)){$linkedTarget=getAnimationDomTarget(linked)}else{forEachChildren(linked,(child=>{if(child.targets&&!$linkedTarget){$linkedTarget=getAnimationDomTarget(child)}}))}this.target=$linkedTarget||doc.body;this.refresh()}}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const p=(this.scroll-this.offsetStart)/this.distance;return p===Infinity||isNaN(p)?0:round(clamp(p,0,1),6)}refresh(){this.reverted=false;const params=this._params;this.repeat=setValue(parseScrollObserverFunctionParameter(params.repeat,this),true);this.horizontal=setValue(parseScrollObserverFunctionParameter(params.axis,this),"y")==="x";this.enter=setValue(parseScrollObserverFunctionParameter(params.enter,this),"end start");this.leave=setValue(parseScrollObserverFunctionParameter(params.leave,this),"start end");this.updateBounds();this.handleScroll();return this}removeDebug(){if(this.$debug){this.$debug.parentNode.removeChild(this.$debug);this.$debug=null}if(this.debugStyles){this.debugStyles.revert();this.$debug=null}return this}debug(){this.removeDebug();const container=this.container;const isHori=this.horizontal;const $existingDebug=container.element.querySelector(":scope > .animejs-onscroll-debug");const $debug=doc.createElement("div");const $thresholds=doc.createElement("div");const $triggers=doc.createElement("div");const color=debugColors$1[this.index%debugColors$1.length];const useWin=container.useWin;const containerWidth=useWin?container.winWidth:container.width;const containerHeight=useWin?container.winHeight:container.height;const scrollWidth=container.scrollWidth;const scrollHeight=container.scrollHeight;const size=this.container.width>360?320:260;const offLeft=isHori?0:10;const offTop=isHori?10:0;const half=isHori?24:size/2;const labelHeight=isHori?half:15;const labelWidth=isHori?60:half;const labelSize=isHori?labelWidth:labelHeight;const repeat=isHori?"repeat-x":"repeat-y";const gradientOffset=v=>isHori?"0px "+v+"px":v+"px"+" 2px";const lineCSS=c=>`linear-gradient(${isHori?90:0}deg, ${c} 2px, transparent 1px)`;const baseCSS=(p,l,t,w,h)=>`position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`;$debug.style.cssText=`${baseCSS("absolute",offLeft,offTop,isHori?scrollWidth:size,isHori?size:scrollHeight)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${isHori?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `;$thresholds.style.cssText=`${baseCSS("sticky",0,0,isHori?containerWidth:half,isHori?half:containerHeight)}`;if(!$existingDebug){$thresholds.style.cssText+=`background:\n ${lineCSS("#FFFF")}${gradientOffset(half-10)} / ${isHori?"100px 100px":"100px 100px"} ${repeat},\n ${lineCSS("#FFF8")}${gradientOffset(half-10)} / ${isHori?"10px 10px":"10px 10px"} ${repeat};\n `}$triggers.style.cssText=`${baseCSS("relative",0,0,isHori?scrollWidth:half,isHori?half:scrollHeight)}`;if(!$existingDebug){$triggers.style.cssText+=`background:\n ${lineCSS("#FFFF")}${gradientOffset(0)} / ${isHori?"100px 10px":"10px 100px"} ${repeat},\n ${lineCSS("#FFF8")}${gradientOffset(0)} / ${isHori?"10px 0px":"0px 10px"} ${repeat};\n `}const labels=[" enter: "," leave: "];this.coords.forEach(((v,i)=>{const isView=i>1;const value=(isView?0:this.offset)+v;const isTail=i%2;const isFirst=value<labelSize;const isOver=value>(isView?isHori?containerWidth:containerHeight:isHori?scrollWidth:scrollHeight)-labelSize;const isFlip=(isView?isTail&&!isFirst:!isTail&&!isFirst)||isOver;const $label=doc.createElement("div");const $text=doc.createElement("div");const dirProp=isHori?isFlip?"right":"left":isFlip?"bottom":"top";const flipOffset=isFlip?(isHori?labelWidth:labelHeight)+(!isView?isHori?-1:-2:isHori?-1:isOver?0:-2):!isView?isHori?1:0:isHori?1:0;$text.innerHTML=`${this.id}${labels[isTail]}${this.thresholds[i]}`;$label.style.cssText=`${baseCSS("absolute",0,0,labelWidth,labelHeight)}\n display: flex;\n flex-direction: ${isHori?"column":"row"};\n justify-content: flex-${isView?"start":"end"};\n align-items: flex-${isFlip?"end":"start"};\n border-${dirProp}: 2px ${isTail?"solid":"solid"} ${color};\n `;$text.style.cssText=`\n overflow: hidden;\n max-width: ${size/2-10}px;\n height: ${labelHeight};\n margin-${isHori?isFlip?"right":"left":isFlip?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${isHori&&isFlip||!isHori&&!isView?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${isTail?color:"rgba(0,0,0,.75)"};\n background-color: ${isTail?"rgba(0,0,0,.65)":color};\n border: 2px solid ${isTail?color:"transparent"};\n border-${isHori?isFlip?"top-left":"top-right":isFlip?"top-left":"bottom-left"}-radius: 5px;\n border-${isHori?isFlip?"bottom-left":"bottom-right":isFlip?"top-right":"bottom-right"}-radius: 5px;\n `;$label.appendChild($text);let position=value-flipOffset+(isHori?1:0);$label.style[isHori?"left":"top"]=`${position}px`;(isView?$thresholds:$triggers).appendChild($label)}));$debug.appendChild($thresholds);$debug.appendChild($triggers);container.element.appendChild($debug);if(!$existingDebug)$debug.classList.add("animejs-onscroll-debug");this.$debug=$debug;const containerPosition=getTargetValue(container.element,"position");if(containerPosition==="static"){this.debugStyles=setTargetValues(container.element,{position:"relative "})}}updateBounds(){if(this._debug){this.removeDebug()}let stickys;const $target=this.target;const container=this.container;const isHori=this.horizontal;const linked=this.linked;let linkedTime;let $el=$target;if(linked){linkedTime=linked.currentTime;linked.seek(0,true)}$el.parentElement;while($el&&$el!==container.element&&$el!==doc.body){const isSticky=getTargetValue($el,"position")==="sticky"?setTargetValues($el,{position:"static"}):false;$el=$el.parentElement;if(isSticky){if(!stickys)stickys=[];stickys.push(isSticky)}}const rect=$target.getBoundingClientRect();const offset=isHori?rect.left+container.scrollX-container.left:rect.top+container.scrollY-container.top;const targetSize=isHori?rect.width:rect.height;const containerSize=isHori?container.width:container.height;const scrollSize=isHori?container.scrollWidth:container.scrollHeight;const maxScroll=scrollSize-containerSize;const enter=this.enter;const leave=this.leave;let enterTarget="start";let leaveTarget="end";let enterContainer="end";let leaveContainer="start";if(isStr(enter)){const splitted=enter.split(" ");enterContainer=splitted[0];enterTarget=splitted.length>1?splitted[1]:enterTarget}else if(isObj(enter)){const e=enter;if(!isUnd(e.container))enterContainer=e.container;if(!isUnd(e.target))enterTarget=e.target}else if(isNum(enter)){enterContainer=enter}if(isStr(leave)){const splitted=leave.split(" ");leaveContainer=splitted[0];leaveTarget=splitted.length>1?splitted[1]:leaveTarget}else if(isObj(leave)){const t=leave;if(!isUnd(t.container))leaveContainer=t.container;if(!isUnd(t.target))leaveTarget=t.target}else if(isNum(leave)){leaveContainer=leave}const parsedEnterTarget=parseBoundValue($target,enterTarget,targetSize);const parsedLeaveTarget=parseBoundValue($target,leaveTarget,targetSize);const under=parsedEnterTarget+offset-containerSize;const over=parsedLeaveTarget+offset-maxScroll;const parsedEnterContainer=parseBoundValue($target,enterContainer,containerSize,under,over);const parsedLeaveContainer=parseBoundValue($target,leaveContainer,containerSize,under,over);const offsetStart=parsedEnterTarget+offset-parsedEnterContainer;const offsetEnd=parsedLeaveTarget+offset-parsedLeaveContainer;const scrollDelta=offsetEnd-offsetStart;this.offset=offset;this.offsetStart=offsetStart;this.offsetEnd=offsetEnd;this.distance=scrollDelta<=0?0:scrollDelta;this.thresholds=[enterTarget,leaveTarget,enterContainer,leaveContainer];this.coords=[parsedEnterTarget,parsedLeaveTarget,parsedEnterContainer,parsedLeaveContainer];if(stickys){stickys.forEach((sticky=>sticky.revert()))}if(linked){linked.seek(linkedTime,true)}if(this._debug){this.debug()}}handleScroll(){const linked=this.linked;const sync=this.sync;const syncEase=this.syncEase;const syncSmooth=this.syncSmooth;const shouldSeek=linked&&(syncEase||syncSmooth);const isHori=this.horizontal;const container=this.container;const scroll=this.scroll;const isBefore=scroll<=this.offsetStart;const isAfter=scroll>=this.offsetEnd;const isInView=!isBefore&&!isAfter;const isOnTheEdge=scroll===this.offsetStart||scroll===this.offsetEnd;const forceEnter=!this.hasEntered&&isOnTheEdge;const $debug=this._debug&&this.$debug;let hasUpdated=false;let syncCompleted=false;let p=this.progress;if(isBefore&&this.began){this.began=false}if(p>0&&!this.began){this.began=true}if(shouldSeek){const lp=linked.progress;if(syncSmooth&&isNum(syncSmooth)){if(syncSmooth<1){const step=1e-4;const snap=lp<p&&p===1?step:lp>p&&!p?-1e-4:0;p=round(lerp(lp,p,interpolate(.01,.2,syncSmooth),false)+snap,6)}}else if(syncEase){p=syncEase(p)}hasUpdated=p!==this.prevProgress;syncCompleted=lp===1;if(hasUpdated&&!syncCompleted&&(syncSmooth&&lp)){container.wakeTicker.restart()}}if($debug){const sticky=isHori?container.scrollY:container.scrollX;$debug.style[isHori?"top":"left"]=sticky+10+"px"}if(isInView&&!this.isInView||forceEnter&&!this.forceEnter&&!this.hasEntered){if(isInView)this.isInView=true;if(!this.forceEnter||!this.hasEntered){if($debug&&isInView)$debug.style.zIndex=`${this.container.zIndex++}`;this.onSyncEnter(this);this.onEnter(this);if(this.backward){this.onSyncEnterBackward(this);this.onEnterBackward(this)}else{this.onSyncEnterForward(this);this.onEnterForward(this)}this.hasEntered=true;if(forceEnter)this.forceEnter=true}else if(isInView){this.forceEnter=false}}if(isInView||!isInView&&this.isInView){hasUpdated=true}if(hasUpdated){if(shouldSeek)linked.seek(linked.duration*p);this.onUpdate(this)}if(!isInView&&this.isInView){this.isInView=false;this.onSyncLeave(this);this.onLeave(this);if(this.backward){this.onSyncLeaveBackward(this);this.onLeaveBackward(this)}else{this.onSyncLeaveForward(this);this.onLeaveForward(this)}if(sync&&!syncSmooth){syncCompleted=true}}if(p>=1&&this.began&&!this.completed&&(sync&&syncCompleted||!sync)){if(sync){this.onSyncComplete(this)}this.completed=true;if(!this.repeat&&!linked||!this.repeat&&linked&&linked.completed){this.revert()}}if(p<1&&this.completed){this.completed=false}this.prevProgress=p}revert(){if(this.reverted)return;const container=this.container;removeChild(container,this);if(!container._head){container.revert()}if(this._debug){this.removeDebug()}this.reverted=true;return this}}const onScroll=(parameters={})=>new ScrollObserver(parameters);const segmenter=typeof Intl!=="undefined"&&Intl.Segmenter;const valueRgx=/\{value\}/g;const indexRgx=/\{i\}/g;const whiteSpaceGroupRgx=/(\s+)/;const whiteSpaceRgx=/^\s+$/;const lineType="line";const wordType="word";const charType="char";const dataLine=`data-line`;let wordSegmenter=null;let graphemeSegmenter=null;let $splitTemplate=null;const isSegmentWordLike=seg=>seg.isWordLike||seg.segment===" "||isNum(+seg.segment);const setAriaHidden=$el=>$el.setAttribute("aria-hidden","true");const getAllTopLevelElements=($el,type)=>[...$el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`)];const debugColors={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"};const filterEmptyElements=$el=>{if(!$el.childElementCount&&!$el.textContent.trim()){const $parent=$el.parentElement;$el.remove();if($parent)filterEmptyElements($parent)}};const filterLineElements=($el,lineIndex,bin)=>{const dataLineAttr=$el.getAttribute(dataLine);if(dataLineAttr!==null&&+dataLineAttr!==lineIndex||$el.tagName==="BR")bin.add($el);let i=$el.childElementCount;while(i--)filterLineElements($el.children[i],lineIndex,bin);return bin};const generateTemplate=(type,params={})=>{let template=``;const classString=isStr(params.class)?` class="${params.class}"`:"";const cloneType=setValue(params.clone,false);const wrapType=setValue(params.wrap,false);const overflow=wrapType?wrapType===true?"clip":wrapType:cloneType?"clip":false;if(wrapType)template+=`<span${overflow?` style="overflow:${overflow};"`:""}>`;template+=`<span${classString}${cloneType?` style="position:relative;"`:""} data-${type}="{i}">`;if(cloneType){const left=cloneType==="left"?"-100%":cloneType==="right"?"100%":"0";const top=cloneType==="top"?"-100%":cloneType==="bottom"?"100%":"0";template+=`<span>{value}</span>`;template+=`<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`}else{template+=`{value}`}template+=`</span>`;if(wrapType)template+=`</span>`;return template};const processHTMLTemplate=(htmlTemplate,store,node,$parentFragment,type,debug,lineIndex,wordIndex,charIndex)=>{const isLine=type===lineType;const isChar=type===charType;const className=`_${type}_`;const template=isFnc(htmlTemplate)?htmlTemplate(node):htmlTemplate;const displayStyle=isLine?"block":"inline-block";$splitTemplate.innerHTML=template.replace(valueRgx,`<i class="${className}"></i>`).replace(indexRgx,`${isChar?charIndex:isLine?lineIndex:wordIndex}`);const $content=$splitTemplate.content;const $highestParent=$content.firstElementChild;const $split=$content.querySelector(`[data-${type}]`)||$highestParent;const $replacables=$content.querySelectorAll(`i.${className}`);const replacablesLength=$replacables.length;if(replacablesLength){$highestParent.style.display=displayStyle;$split.style.display=displayStyle;$split.setAttribute(dataLine,`${lineIndex}`);if(!isLine){$split.setAttribute("data-word",`${wordIndex}`);if(isChar)$split.setAttribute("data-char",`${charIndex}`)}let i=replacablesLength;while(i--){const $replace=$replacables[i];const $closestParent=$replace.parentElement;$closestParent.style.display=displayStyle;if(isLine){$closestParent.innerHTML=node.innerHTML}else{$closestParent.replaceChild(node.cloneNode(true),$replace)}}store.push($split);$parentFragment.appendChild($content)}else{console.warn(`The expression "{value}" is missing from the provided template.`)}if(debug)$highestParent.style.outline=`1px dotted ${debugColors[type]}`;return $highestParent};class TextSplitter{constructor(target,parameters={}){if(!wordSegmenter)wordSegmenter=segmenter?new segmenter([],{granularity:wordType}):{segment:text=>{const segments=[];const words=text.split(whiteSpaceGroupRgx);for(let i=0,l=words.length;i<l;i++){const segment=words[i];segments.push({segment:segment,isWordLike:!whiteSpaceRgx.test(segment)})}return segments}};if(!graphemeSegmenter)graphemeSegmenter=segmenter?new segmenter([],{granularity:"grapheme"}):{segment:text=>[...text].map((char=>({segment:char})))};if(!$splitTemplate&&isBrowser)$splitTemplate=doc.createElement("template");if(scope.current)scope.current.register(this);const{words:words,chars:chars,lines:lines,accessible:accessible,includeSpaces:includeSpaces,debug:debug}=parameters;const $target=(target=isArr(target)?target[0]:target)&&target.nodeType?target:(getNodeList(target)||[])[0];const lineParams=lines===true?{}:lines;const wordParams=words===true||isUnd(words)?{}:words;const charParams=chars===true?{}:chars;this.debug=setValue(debug,false);this.includeSpaces=setValue(includeSpaces,false);this.accessible=setValue(accessible,true);this.linesOnly=lineParams&&(!wordParams&&!charParams);this.lineTemplate=isObj(lineParams)?generateTemplate(lineType,lineParams):lineParams;this.wordTemplate=isObj(wordParams)||this.linesOnly?generateTemplate(wordType,wordParams):wordParams;this.charTemplate=isObj(charParams)?generateTemplate(charType,charParams):charParams;this.$target=$target;this.html=$target&&$target.innerHTML;this.lines=[];this.words=[];this.chars=[];this.effects=[];this.effectsCleanups=[];this.cache=null;this.ready=false;this.width=0;this.resizeTimeout=null;const handleSplit=()=>this.html&&(lineParams||wordParams||charParams)&&this.split();this.resizeObserver=new ResizeObserver((()=>{clearTimeout(this.resizeTimeout);this.resizeTimeout=setTimeout((()=>{const currentWidth=$target.offsetWidth;if(currentWidth===this.width)return;this.width=currentWidth;handleSplit()}),150)}));if(this.lineTemplate&&!this.ready){doc.fonts.ready.then(handleSplit)}else{handleSplit()}$target?this.resizeObserver.observe($target):console.warn("No Text Splitter target found.")}addEffect(effect){if(!isFnc(effect))return console.warn("Effect must return a function.");const refreshableEffect=createRefreshable(effect);this.effects.push(refreshableEffect);if(this.ready)this.effectsCleanups[this.effects.length-1]=refreshableEffect(this);return this}revert(){clearTimeout(this.resizeTimeout);this.lines.length=this.words.length=this.chars.length=0;this.resizeObserver.disconnect();this.effectsCleanups.forEach((cleanup=>isFnc(cleanup)?cleanup(this):cleanup.revert&&cleanup.revert()));this.$target.innerHTML=this.html;return this}splitNode(node){const wordTemplate=this.wordTemplate;const charTemplate=this.charTemplate;const includeSpaces=this.includeSpaces;const debug=this.debug;const nodeType=node.nodeType;if(nodeType===3){const nodeText=node.nodeValue;if(nodeText.trim()){const tempWords=[];const words=this.words;const chars=this.chars;const wordSegments=wordSegmenter.segment(nodeText);const $wordsFragment=doc.createDocumentFragment();let prevSeg=null;for(const wordSegment of wordSegments){const segment=wordSegment.segment;const isWordLike=isSegmentWordLike(wordSegment);if(!prevSeg||isWordLike&&(prevSeg&&isSegmentWordLike(prevSeg))){tempWords.push(segment)}else{const lastWordIndex=tempWords.length-1;const lastWord=tempWords[lastWordIndex];if(!lastWord.includes(" ")&&!segment.includes(" ")){tempWords[lastWordIndex]+=segment}else{tempWords.push(segment)}}prevSeg=wordSegment}for(let i=0,l=tempWords.length;i<l;i++){const word=tempWords[i];if(!word.trim()){if(i&&includeSpaces)continue;$wordsFragment.appendChild(doc.createTextNode(word))}else{const nextWord=tempWords[i+1];const hasWordFollowingSpace=includeSpaces&&nextWord&&!nextWord.trim();const wordToProcess=word;const charSegments=charTemplate?graphemeSegmenter.segment(wordToProcess):null;const $charsFragment=charTemplate?doc.createDocumentFragment():doc.createTextNode(hasWordFollowingSpace?word+" ":word);if(charTemplate){const charSegmentsArray=[...charSegments];for(let j=0,jl=charSegmentsArray.length;j<jl;j++){const charSegment=charSegmentsArray[j];const isLastChar=j===jl-1;const charText=isLastChar&&hasWordFollowingSpace?charSegment.segment+" ":charSegment.segment;const $charNode=doc.createTextNode(charText);processHTMLTemplate(charTemplate,chars,$charNode,$charsFragment,charType,debug,-1,words.length,chars.length)}}if(wordTemplate){processHTMLTemplate(wordTemplate,words,$charsFragment,$wordsFragment,wordType,debug,-1,words.length,chars.length)}else if(charTemplate){$wordsFragment.appendChild($charsFragment)}else{$wordsFragment.appendChild(doc.createTextNode(word))}if(hasWordFollowingSpace)i++}}node.parentNode.replaceChild($wordsFragment,node)}}else if(nodeType===1){const childNodes=[...node.childNodes];for(let i=0,l=childNodes.length;i<l;i++)this.splitNode(childNodes[i])}}split(clearCache=false){const $el=this.$target;const isCached=!!this.cache&&!clearCache;const lineTemplate=this.lineTemplate;const wordTemplate=this.wordTemplate;const charTemplate=this.charTemplate;const fontsReady=doc.fonts.status!=="loading";const canSplitLines=lineTemplate&&fontsReady;this.ready=!lineTemplate||fontsReady;if(canSplitLines||clearCache){this.effectsCleanups.forEach((cleanup=>isFnc(cleanup)&&cleanup(this)))}if(!isCached){if(clearCache){$el.innerHTML=this.html;this.words.length=this.chars.length=0}this.splitNode($el);this.cache=$el.innerHTML}if(canSplitLines){if(isCached)$el.innerHTML=this.cache;this.lines.length=0;if(wordTemplate)this.words=getAllTopLevelElements($el,wordType)}if(charTemplate&&(canSplitLines||wordTemplate)){this.chars=getAllTopLevelElements($el,charType)}const elementsArray=this.words.length?this.words:this.chars;let y,linesCount=0;for(let i=0,l=elementsArray.length;i<l;i++){const $el=elementsArray[i];const{top:top,height:height}=$el.getBoundingClientRect();if(y&&top-y>height*.5)linesCount++;$el.setAttribute(dataLine,`${linesCount}`);const nested=$el.querySelectorAll(`[${dataLine}]`);let c=nested.length;while(c--)nested[c].setAttribute(dataLine,`${linesCount}`);y=top}if(canSplitLines){const linesFragment=doc.createDocumentFragment();const parents=new Set;const clones=[];for(let lineIndex=0;lineIndex<linesCount+1;lineIndex++){const $clone=$el.cloneNode(true);filterLineElements($clone,lineIndex,new Set).forEach(($el=>{const $parent=$el.parentElement;if($parent)parents.add($parent);$el.remove()}));clones.push($clone)}parents.forEach(filterEmptyElements);for(let cloneIndex=0,clonesLength=clones.length;cloneIndex<clonesLength;cloneIndex++){processHTMLTemplate(lineTemplate,this.lines,clones[cloneIndex],linesFragment,lineType,this.debug,cloneIndex)}$el.innerHTML="";$el.appendChild(linesFragment);if(wordTemplate)this.words=getAllTopLevelElements($el,wordType);if(charTemplate)this.chars=getAllTopLevelElements($el,charType)}if(this.linesOnly){const words=this.words;let w=words.length;while(w--){const $word=words[w];$word.replaceWith($word.textContent)}words.length=0}if(this.accessible&&(canSplitLines||!isCached)){const $accessible=doc.createElement("span");$accessible.style.cssText=`position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;$accessible.innerHTML=this.html;$el.insertBefore($accessible,$el.firstChild);this.lines.forEach(setAriaHidden);this.words.forEach(setAriaHidden);this.chars.forEach(setAriaHidden)}this.width=$el.offsetWidth;if(canSplitLines||clearCache){this.effects.forEach(((effect,i)=>this.effectsCleanups[i]=effect(this)))}return this}refresh(){this.split(true)}}const split=(target,parameters)=>new TextSplitter(target,parameters);const text={split:split};const stagger=(val,params={})=>{let values=[];let maxValue=0;const from=params.from;const reversed=params.reversed;const ease=params.ease;const hasEasing=!isUnd(ease);const hasSpring=hasEasing&&!isUnd(ease.ease);const staggerEase=hasSpring?ease.ease:hasEasing?parseEasings(ease):null;const grid=params.grid;const axis=params.axis;const customTotal=params.total;const fromFirst=isUnd(from)||from===0||from==="first";const fromCenter=from==="center";const fromLast=from==="last";const fromRandom=from==="random";const isRange=isArr(val);const useProp=params.use;const val1=isRange?parseNumber(val[0]):parseNumber(val);const val2=isRange?parseNumber(val[1]):0;const unitMatch=unitsExecRgx.exec((isRange?val[1]:val)+emptyString);const start=params.start||0+(isRange?val1:0);let fromIndex=fromFirst?0:isNum(from)?from:0;return(target,i,t,tl)=>{const[registeredTarget]=registerTargets(target);const total=isUnd(customTotal)?t:customTotal;const customIndex=!isUnd(useProp)?isFnc(useProp)?useProp(registeredTarget,i,total):getOriginalAnimatableValue(registeredTarget,useProp):false;const staggerIndex=isNum(customIndex)||isStr(customIndex)&&isNum(+customIndex)?+customIndex:i;if(fromCenter)fromIndex=(total-1)/2;if(fromLast)fromIndex=total-1;if(!values.length){for(let index=0;index<total;index++){if(!grid){values.push(abs(fromIndex-index))}else{const fromX=!fromCenter?fromIndex%grid[0]:(grid[0]-1)/2;const fromY=!fromCenter?floor(fromIndex/grid[0]):(grid[1]-1)/2;const toX=index%grid[0];const toY=floor(index/grid[0]);const distanceX=fromX-toX;const distanceY=fromY-toY;let value=sqrt(distanceX*distanceX+distanceY*distanceY);if(axis==="x")value=-distanceX;if(axis==="y")value=-distanceY;values.push(value)}maxValue=max(...values)}if(staggerEase)values=values.map((val=>staggerEase(val/maxValue)*maxValue));if(reversed)values=values.map((val=>axis?val<0?val*-1:-val:abs(maxValue-val)));if(fromRandom)values=shuffle(values)}const spacing=isRange?(val2-val1)/maxValue:val1;const offset=tl?parseTimelinePosition(tl,isUnd(params.start)?tl.iterationDuration:start):start;let output=offset+(spacing*round(values[staggerIndex],2)||0);if(params.modifier)output=params.modifier(output);if(unitMatch)output=`${output}${unitMatch[2]}`;return output}};exports.Animatable=Animatable;exports.Draggable=Draggable;exports.JSAnimation=JSAnimation;exports.Scope=Scope;exports.ScrollObserver=ScrollObserver;exports.Spring=Spring;exports.TextSplitter=TextSplitter;exports.Timeline=Timeline;exports.Timer=Timer;exports.WAAPIAnimation=WAAPIAnimation;exports.animate=animate;exports.createAnimatable=createAnimatable;exports.createDraggable=createDraggable;exports.createScope=createScope;exports.createSpring=createSpring;exports.createTimeline=createTimeline;exports.createTimer=createTimer;exports.eases=eases;exports.engine=engine;exports.onScroll=onScroll;exports.scrollContainers=scrollContainers;exports.stagger=stagger;exports.svg=svg;exports.text=text;exports.utils=utils;exports.waapi=waapi;
diff --git a/lib/anime.esm.min.js b/lib/anime.esm.min.js
deleted file mode 100644
index 3986ab51..00000000
--- a/lib/anime.esm.min.js
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * anime.js - ESM
- * @version v4.1.3
- * @author Julian Garnier
- * @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
- */
-const t="undefined"!=typeof window,e=t?window:null,s=t?document:null,i={replace:0,none:1,blend:2},r=Symbol(),n=Symbol(),o=Symbol(),h=Symbol(),a=Symbol(),l=Symbol(),c=1e-11,d=1e12,u=1e3,p="",m=(()=>{const t=new Map;return t.set("x","translateX"),t.set("y","translateY"),t.set("z","translateZ"),t})(),f=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],g=f.reduce(((t,e)=>({...t,[e]:e+"("})),{}),y=()=>{},_=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i,v=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i,b=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,T=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i,w=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,x=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi,S=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i,k=/([a-z])([A-Z])/g,$=/(\w+)(\([^)]+\)+)/g,E=/(\*=|\+=|-=)/,C={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:120,loop:0,reversed:!1,alternate:!1,autoplay:!0,duration:u,delay:0,loopDelay:0,ease:"out(2)",composition:i.replace,modifier:t=>t,onBegin:y,onBeforeUpdate:y,onUpdate:y,onLoop:y,onPause:y,onComplete:y,onRender:y},B={current:null,root:s},L={defaults:C,precision:4,timeScale:1,tickThreshold:200},D={version:"4.1.3",engine:null};t&&(e.AnimeJS||(e.AnimeJS=[]),e.AnimeJS.push(D));const N=t=>t.replace(k,"$1-$2").toLowerCase(),A=(t,e)=>0===t.indexOf(e),F=Date.now,O=Array.isArray,P=t=>t&&t.constructor===Object,R=t=>"number"==typeof t&&!isNaN(t),M=t=>"string"==typeof t,I=t=>"function"==typeof t,z=t=>void 0===t,Y=t=>z(t)||null===t,X=e=>t&&e instanceof SVGElement,W=t=>_.test(t),V=t=>A(t,"rgb"),H=t=>A(t,"hsl"),U=t=>!L.defaults.hasOwnProperty(t),q=t=>M(t)?parseFloat(t):t,Q=Math.pow,j=Math.sqrt,G=Math.sin,Z=Math.cos,J=Math.abs,K=Math.exp,tt=Math.ceil,et=Math.floor,st=Math.asin,it=Math.max,rt=Math.atan2,nt=Math.PI,ot=Math.round,ht=(t,e,s)=>t<e?e:t>s?s:t,at={},lt=(t,e)=>{if(e<0)return t;if(!e)return ot(t);let s=at[e];return s||(s=at[e]=10**e),ot(t*s)/s},ct=(t,e)=>O(e)?e.reduce(((e,s)=>J(s-t)<J(e-t)?s:e)):e?ot(t/e)*e:t,dt=(t,e,s)=>t+(e-t)*s,ut=(t,e,s)=>{const i=10**(s||0);return et((Math.random()*(e-t+1/i)+t)*i)/i},pt=t=>{let e,s,i=t.length;for(;i;)s=ut(0,--i),e=t[i],t[i]=t[s],t[s]=e;return t},mt=t=>t===1/0?d:t===-1/0?-1e12:t,ft=t=>t<=c?c:mt(lt(t,11)),gt=t=>O(t)?[...t]:t,yt=(t,e)=>{const s={...t};for(let i in e){const r=t[i];s[i]=z(r)?e[i]:r}return s},_t=(t,e,s,i="_prev",r="_next")=>{let n=t._head,o=r;for(s&&(n=t._tail,o=i);n;){const t=n[o];e(n),n=t}},vt=(t,e,s="_prev",i="_next")=>{const r=e[s],n=e[i];r?r[i]=n:t._head=n,n?n[s]=r:t._tail=r,e[s]=null,e[i]=null},bt=(t,e,s,i="_prev",r="_next")=>{let n=t._tail;for(;n&&s&&s(n,e);)n=n[i];const o=n?n[r]:t._head;n?n[r]=e:t._head=e,o?o[i]=e:t._tail=e,e[i]=n,e[r]=o},Tt=t=>{let e;return(...s)=>{let i,r,n,o;e&&(i=e.currentIteration,r=e.iterationProgress,n=e.reversed,o=e._alternate,e.revert());const h=t(...s);return h&&!I(h)&&h.revert&&(e=h),z(r)||(e.currentIteration=i,e.iterationProgress=(o&&i%2?!n:n)?1-r:r),h||y}};class wt{constructor(t=0){this.deltaTime=0,this._currentTime=t,this._elapsedTime=t,this._startTime=t,this._lastTime=t,this._scheduledTime=0,this._frameDuration=lt(u/120,0),this._fps=120,this._speed=1,this._hasChildren=!1,this._head=null,this._tail=null}get fps(){return this._fps}set fps(t){const e=this._frameDuration,s=+t,i=s<c?c:s,r=lt(u/i,0);this._fps=i,this._frameDuration=r,this._scheduledTime+=r-e}get speed(){return this._speed}set speed(t){const e=+t;this._speed=e<c?c:e}requestTick(t){const e=this._scheduledTime,s=this._elapsedTime;if(this._elapsedTime+=t-s,s<e)return 0;const i=this._frameDuration,r=s-e;return this._scheduledTime+=r<i?i:r,1}computeDeltaTime(t){const e=t-this._lastTime;return this.deltaTime=e,this._lastTime=t,e}}const xt=(t,e,s,r,n)=>{const o=t.parent,a=t.duration,l=t.completed,d=t.iterationDuration,u=t.iterationCount,m=t._currentIteration,f=t._loopDelay,y=t._reversed,_=t._alternate,v=t._hasChildren,b=t._delay,T=t._currentTime,w=b+d,x=e-b,S=ht(T,-b,a),k=ht(x,-b,a),$=x-T,E=k>0,C=k>=a,B=a<=c,D=2===n;let N=0,A=x,F=0;if(u>1){const e=~~(k/(d+(C?0:f)));t._currentIteration=ht(e,0,u),C&&t._currentIteration--,N=t._currentIteration%2,A=k%(d+f)||0}const O=y^(_&&N),P=t._ease;let R=C?O?0:a:O?d-A:A;P&&(R=d*P(R/d)||0);const M=(o?o.backwards:x<T)?!O:!!O;if(t._currentTime=x,t._iterationTime=R,t.backwards=M,E&&!t.began?(t.began=!0,s||o&&(M||!o.began)||t.onBegin(t)):x<=0&&(t.began=!1),s||v||!E||t._currentIteration===m||t.onLoop(t),D||1===n&&(e>=b&&e<=w||e<=b&&S>b||e>=w&&S!==a)||R>=w&&S!==a||R<=b&&S>0||e<=S&&S===a&&l||C&&!l&&B){if(E&&(t.computeDeltaTime(S),s||t.onBeforeUpdate(t)),!v){const e=D||(M?-1*$:$)>=L.tickThreshold,n=t._offset+(o?o._offset:0)+b+R;let a,l,c,d,u=t._head,m=0;for(;u;){const t=u._composition,s=u._currentTime,o=u._changeDuration,f=u._absoluteStartTime+u._changeDuration,y=u._nextRep,_=u._prevRep,v=t!==i.none;if((e||(s!==o||n<=f+(y?y._delay:0))&&(0!==s||n>=u._absoluteStartTime))&&(!v||!u._isOverridden&&(!u._isOverlapped||n<=f)&&(!y||y._isOverridden||n<=y._absoluteStartTime)&&(!_||_._isOverridden||n>=_._absoluteStartTime+_._changeDuration+u._delay))){const e=u._currentTime=ht(R-u._startTime,0,o),s=u._ease(e/u._updateDuration),n=u._modifier,p=u._valueType,f=u._tweenType,g=0===f,y=0===p,_=y&&g||0===s||1===s?-1:L.precision;let b,T;if(y)b=T=n(lt(dt(u._fromNumber,u._toNumber,s),_));else if(1===p)T=n(lt(dt(u._fromNumber,u._toNumber,s),_)),b=`${T}${u._unit}`;else if(2===p){const t=u._fromNumbers,e=u._toNumbers,i=lt(ht(n(dt(t[0],e[0],s)),0,255),0),r=lt(ht(n(dt(t[1],e[1],s)),0,255),0),o=lt(ht(n(dt(t[2],e[2],s)),0,255),0),h=ht(n(lt(dt(t[3],e[3],s),_)),0,1);if(b=`rgba(${i},${r},${o},${h})`,v){const t=u._numbers;t[0]=i,t[1]=r,t[2]=o,t[3]=h}}else if(3===p){b=u._strings[0];for(let t=0,e=u._toNumbers.length;t<e;t++){const e=n(lt(dt(u._fromNumbers[t],u._toNumbers[t],s),_)),i=u._strings[t+1];b+=`${i?e+i:e}`,v&&(u._numbers[t]=e)}}if(v&&(u._number=T),r||t===i.blend)u._value=b;else{const t=u.property;a=u.target,g?a[t]=b:1===f?a.setAttribute(t,b):(l=a.style,3===f?(a!==c&&(c=a,d=a[h]),d[t]=b,m=1):2===f?l[t]=b:4===f&&l.setProperty(t,b)),E&&(F=1)}}if(m&&u._renderTransforms){let t=p;for(let e in d)t+=`${g[e]}${d[e]}) `;l.transform=t,m=0}u=u._next}!s&&F&&t.onRender(t)}!s&&E&&t.onUpdate(t)}return o&&B?!s&&(o.began&&!M&&x>=a&&!l||M&&x<=c&&l)&&(t.onComplete(t),t.completed=!M):E&&C?u===1/0?t._startTime+=t.duration:t._currentIteration>=u-1&&(t.paused=!0,l||v||(t.completed=!0,s||o&&(M||!o.began)||(t.onComplete(t),t._resolve(t)))):t.completed=!1,F},St=(t,e,s,i,r)=>{const n=t._currentIteration;if(xt(t,e,s,i,r),t._hasChildren){const o=t,h=o.backwards,a=i?e:o._iterationTime,l=F();let d=0,u=!0;if(!i&&o._currentIteration!==n){const t=o.iterationDuration;_t(o,(e=>{if(h){const i=e.duration,r=e._offset+e._delay;s||!(i<=c)||r&&r+i!==t||e.onComplete(e)}else!e.completed&&!e.backwards&&e._currentTime<e.iterationDuration&&xt(e,t,s,1,2),e.began=!1,e.completed=!1})),s||o.onLoop(o)}_t(o,(t=>{const e=lt((a-t._offset)*t._speed,12),n=t._fps<o._fps?t.requestTick(l):r;d+=xt(t,e,s,i,n),!t.completed&&u&&(u=!1)}),h),!s&&d&&o.onRender(o),(u||h)&&o._currentTime>=o.duration&&(o.paused=!0,o.completed||(o.completed=!0,s||(o.onComplete(o),o._resolve(o))))}},kt={animation:null,update:y},$t=(()=>t?requestAnimationFrame:setImmediate)(),Et=(()=>t?cancelAnimationFrame:clearImmediate)();class Ct extends wt{constructor(t){super(t),this.useDefaultMainLoop=!0,this.pauseOnDocumentHidden=!0,this.defaults=C,this.paused=!0,this.reqId=0}update(){const t=this._currentTime=F();if(this.requestTick(t)){this.computeDeltaTime(t);const e=this._speed,s=this._fps;let i=this._head;for(;i;){const r=i._next;i.paused?(vt(this,i),this._hasChildren=!!this._tail,i._running=!1,i.completed&&!i._cancelled&&i.cancel()):St(i,(t-i._startTime)*i._speed*e,0,0,i._fps<s?i.requestTick(t):1),i=r}kt.update()}}wake(){return this.useDefaultMainLoop&&!this.reqId&&(this.requestTick(F()),this.reqId=$t(Lt)),this}pause(){if(this.reqId)return this.paused=!0,Dt()}resume(){if(this.paused)return this.paused=!1,_t(this,(t=>t.resetTime())),this.wake()}get speed(){return this._speed*(1===L.timeScale?1:u)}set speed(t){this._speed=t*L.timeScale,_t(this,(t=>t.speed=t._speed))}get timeUnit(){return 1===L.timeScale?"ms":"s"}set timeUnit(t){const e="s"===t,s=e?.001:1;if(L.timeScale!==s){L.timeScale=s,L.tickThreshold=200*s;const t=e?.001:u;this.defaults.duration*=t,this._speed*=t}}get precision(){return L.precision}set precision(t){L.precision=t}}const Bt=(()=>{const e=new Ct(F());return t&&(D.engine=e,s.addEventListener("visibilitychange",(()=>{e.pauseOnDocumentHidden&&(s.hidden?e.pause():e.resume())}))),e})(),Lt=()=>{Bt._head?(Bt.reqId=$t(Lt),Bt.update()):Bt.reqId=0},Dt=()=>(Et(Bt.reqId),Bt.reqId=0,Bt);function Nt(t){const e=M(t)?B.root.querySelectorAll(t):t;if(e instanceof NodeList||e instanceof HTMLCollection)return e}function At(e){if(Y(e))return[];if(!t)return O(e)&&e.flat(1/0)||[e];if(O(e)){const t=e.flat(1/0),s=[];for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!Y(i)){const t=Nt(i);if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!Y(i)){let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}else{let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}}return s}const s=Nt(e);return s?Array.from(s):[e]}function Ft(t){const e=At(t),s=e.length;if(s)for(let t=0;t<s;t++){const s=e[t];if(!s[r]){s[r]=!0;const t=X(s);(s.nodeType||t)&&(s[n]=!0,s[o]=t,s[h]={})}}return e}const Ot=t=>{const e=At(t)[0];if(e&&X(e))return e},Pt=(t,e,s=0)=>t.getPointAtLength(e+s>=1?e+s:0),Rt=(t,e)=>s=>{const i=+t.getTotalLength(),r=s[o],n=t.getCTM();return{from:0,to:i,modifier:s=>{if("a"===e){const e=Pt(t,s,-1),i=Pt(t,s,1);return 180*rt(i.y-e.y,i.x-e.x)/nt}{const i=Pt(t,s,0);return"x"===e?r||!n?i.x:i.x*n.a+i.y*n.c+n.e:r||!n?i.y:i.x*n.b+i.y*n.d+n.f}}}},Mt=["opacity","rotate","overflow","color"],It={morphTo:(t,e=.33)=>s=>{const i=Ot(t);if(!i)return;const r="path"===s.tagName,n=r?" ":",",o=s[a];o&&s.setAttribute(r?"d":"points",o);let h="",l="";if(e){const t=s.getTotalLength(),o=i.getTotalLength(),a=Math.max(Math.ceil(t*e),Math.ceil(o*e));for(let e=0;e<a;e++){const c=e/(a-1),d=s.getPointAtLength(t*c),u=i.getPointAtLength(o*c),p=r?0===e?"M":"L":"";h+=p+lt(d.x,3)+n+d.y+" ",l+=p+lt(u.x,3)+n+u.y+" "}}else h=s.getAttribute(r?"d":"points"),l=i.getAttribute(r?"d":"points");return s[a]=l,[h,l]},createMotionPath:t=>{const e=Ot(t);if(e)return{translateX:Rt(e,"x"),translateY:Rt(e,"y"),rotate:Rt(e,"a")}},createDrawable:(t,e=0,s=0)=>At(t).map((t=>((t,e,s)=>{const i=u,r=getComputedStyle(t),n=r.strokeLinecap,o="non-scaling-stroke"===r.vectorEffect?t:null;let h=n;const a=new Proxy(t,{get(t,e){const s=t[e];return e===l?t:"setAttribute"===e?(...e)=>{if("draw"===e[0]){const s=e[1].split(" "),r=+s[0],a=+s[1],l=(t=>{let e=1;if(t&&t.getCTM){const s=t.getCTM();s&&(e=(j(s.a*s.a+s.b*s.b)+j(s.c*s.c+s.d*s.d))/2)}return e})(o),c=-1e3*r*l,d=a*i*l+c,u=i*l+(0===r&&1===a||1===r&&0===a?0:10*l)-d;if("butt"!==n){const e=r===a?"butt":n;h!==e&&(t.style.strokeLinecap=`${e}`,h=e)}t.setAttribute("stroke-dashoffset",`${c}`),t.setAttribute("stroke-dasharray",`${d} ${u}`)}return Reflect.apply(s,t,e)}:I(s)?(...e)=>Reflect.apply(s,t,e):s}});return"1000"!==t.getAttribute("pathLength")&&(t.setAttribute("pathLength","1000"),a.setAttribute("draw",`${e} ${s}`)),a})(t,e,s)))},zt=(t,e,s)=>(s<0&&(s+=1),s>1&&(s-=1),s<1/6?t+6*(e-t)*s:s<.5?e:s<2/3?t+(e-t)*(2/3-s)*6:t),Yt=(t,e)=>z(t)?e:t,Xt=(t,e,s,i,r)=>{if(I(t)){const n=()=>{const r=t(e,s,i);return isNaN(+r)?r||0:+r};return r&&(r.func=n),n()}return t},Wt=(t,e)=>t[n]?t[o]&&((t,e)=>{if(Mt.includes(e))return!1;if(t.getAttribute(e)||e in t){if("scale"===e){const e=t.parentNode;return e&&"filter"===e.tagName}return!0}})(t,e)?1:f.includes(e)||m.get(e)?3:A(e,"--")?4:e in t.style?2:e in t?0:1:0,Vt=(t,e,s)=>{const i=t.style[e];i&&s&&(s[e]=i);const r=i||getComputedStyle(t[l]||t).getPropertyValue(e);return"auto"===r?"0":r},Ht=(t,e,s,i)=>{const r=z(s)?Wt(t,e):s;return 0===r?t[e]||0:1===r?t.getAttribute(e):3===r?((t,e,s)=>{const i=t.style.transform;let r;if(i){const n=t[h];let o;for(;o=$.exec(i);){const t=o[1],i=o[2].slice(1,-1);n[t]=i,t===e&&(r=i,s&&(s[e]=i))}}return i&&!z(r)?r:A(e,"scale")?"1":A(e,"rotate")||A(e,"skew")?"0deg":"0px"})(t,e,i):4===r?Vt(t,e,i).trimStart():Vt(t,e,i)},Ut=(t,e,s)=>"-"===s?t-e:"+"===s?t+e:t*e,qt=(t,e)=>{if(e.t=0,e.n=0,e.u=null,e.o=null,e.d=null,e.s=null,!t)return e;const s=+t;if(isNaN(s)){let s=t;"="===s[1]&&(e.o=s[0],s=s.slice(2));const n=!s.includes(" ")&&S.exec(s);if(n)return e.t=1,e.n=+n[1],e.u=n[2],e;if(e.o)return e.n=+s,e;if(W(r=s)||V(r)||H(r))return e.t=2,e.d=V(i=s)?(t=>{const e=v.exec(t)||b.exec(t),s=z(e[4])?1:+e[4];return[+e[1],+e[2],+e[3],s]})(i):W(i)?(t=>{const e=t.length,s=4===e||5===e;return[+("0x"+t[1]+t[s?1:2]),+("0x"+t[s?2:3]+t[s?2:4]),+("0x"+t[s?3:5]+t[s?3:6]),5===e||9===e?+(+("0x"+t[s?4:7]+t[s?4:8])/255).toFixed(3):1]})(i):H(i)?(t=>{const e=T.exec(t)||w.exec(t),s=+e[1]/360,i=+e[2]/100,r=+e[3]/100,n=z(e[4])?1:+e[4];let o,h,a;if(0===i)o=h=a=r;else{const t=r<.5?r*(1+i):r+i-r*i,e=2*r-t;o=lt(255*zt(e,t,s+1/3),0),h=lt(255*zt(e,t,s),0),a=lt(255*zt(e,t,s-1/3),0)}return[o,h,a,n]})(i):[0,0,0,1],e;{const t=s.match(x);return e.t=3,e.d=t?t.map(Number):[],e.s=s.split(x)||[],e}}var i,r;return e.n=s,e},Qt=(t,e)=>(e.t=t._valueType,e.n=t._toNumber,e.u=t._unit,e.o=null,e.d=gt(t._toNumbers),e.s=gt(t._strings),e),jt={t:0,n:0,u:null,o:null,d:null,s:null},Gt={_rep:new WeakMap,_add:new Map},Zt=(t,e,s="_rep")=>{const i=Gt[s];let r=i.get(t);return r||(r={},i.set(t,r)),r[e]?r[e]:r[e]={_head:null,_tail:null}},Jt=(t,e)=>t._isOverridden||t._absoluteStartTime>e._absoluteStartTime,Kt=t=>{t._isOverlapped=1,t._isOverridden=1,t._changeDuration=c,t._currentTime=c},te=(t,e)=>{const s=t._composition;if(s===i.replace){const s=t._absoluteStartTime;bt(e,t,Jt,"_prevRep","_nextRep");const i=t._prevRep;if(i){const e=i.parent,r=i._absoluteStartTime+i._changeDuration;if(t.parent.id!==e.id&&e.iterationCount>1&&r+(e.duration-e.iterationDuration)>s){Kt(i);let t=i._prevRep;for(;t&&t.parent.id===e.id;)Kt(t),t=t._prevRep}const n=s-t._delay;if(r>n){const t=i._startTime,e=r-(t+i._updateDuration),s=lt(n-e-t,12);i._changeDuration=s,i._currentTime=s,i._isOverlapped=1,s<c&&Kt(i)}let o=!0;if(_t(e,(t=>{t._isOverlapped||(o=!1)})),o){const t=e.parent;if(t){let s=!0;_t(t,(t=>{t!==e&&_t(t,(t=>{t._isOverlapped||(s=!1)}))})),s&&t.cancel()}else e.cancel()}}}else if(s===i.blend){const e=Zt(t.target,t.property,"_add"),s=(t=>{let e=kt.animation;return e||(e={duration:c,computeDeltaTime:y,_offset:0,_delay:0,_head:null,_tail:null},kt.animation=e,kt.update=()=>{t.forEach((t=>{for(let e in t){const s=t[e],i=s._head;if(i){const t=i._valueType,e=3===t||2===t?gt(i._fromNumbers):null;let r=i._fromNumber,n=s._tail;for(;n&&n!==i;){if(e)for(let t=0,s=n._numbers.length;t<s;t++)e[t]+=n._numbers[t];else r+=n._number;n=n._prevAdd}i._toNumber=r,i._toNumbers=e}}})),xt(e,1,1,0,2)}),e})(Gt._add);let r=e._head;r||(r={...t},r._composition=i.replace,r._updateDuration=c,r._startTime=0,r._numbers=gt(t._fromNumbers),r._number=0,r._next=null,r._prev=null,bt(e,r),bt(s,r));const n=t._toNumber;if(t._fromNumber=r._fromNumber-n,t._toNumber=0,t._numbers=gt(t._fromNumbers),t._number=0,r._fromNumber=n,t._toNumbers){const e=gt(t._toNumbers);e&&e.forEach(((e,s)=>{t._fromNumbers[s]=r._fromNumbers[s]-e,t._toNumbers[s]=0})),r._fromNumbers=e}bt(e,t,null,"_prevAdd","_nextAdd")}return t},ee=t=>{const e=t._composition;if(e!==i.none){const s=t.target,r=t.property,n=Gt._rep.get(s)[r];if(vt(n,t,"_prevRep","_nextRep"),e===i.blend){const e=Gt._add,i=e.get(s);if(!i)return;const n=i[r],o=kt.animation;vt(n,t,"_prevAdd","_nextAdd");const h=n._head;if(h&&h===n._tail){vt(n,h,"_prevAdd","_nextAdd"),vt(o,h);let t=!0;for(let e in i)if(i[e]._head){t=!1;break}t&&e.delete(s)}}}return t},se=t=>(t.paused=!0,t.began=!1,t.completed=!1,t),ie=t=>t._cancelled?(t._hasChildren?_t(t,ie):_t(t,(t=>{t._composition!==i.none&&te(t,Zt(t.target,t.property))})),t._cancelled=0,t):t;let re=0;class ne extends wt{constructor(t={},e=null,s=0){super(0);const{id:i,delay:r,duration:n,reversed:o,alternate:h,loop:a,loopDelay:l,autoplay:d,frameRate:u,playbackRate:p,onComplete:m,onLoop:f,onPause:g,onBegin:_,onBeforeUpdate:v,onUpdate:b}=t;B.current&&B.current.register(this);const T=e?0:Bt._elapsedTime,w=e?e.defaults:L.defaults,x=I(r)||z(r)?w.delay:+r,S=I(n)||z(n)?1/0:+n,k=Yt(a,w.loop),$=Yt(l,w.loopDelay),E=!0===k||k===1/0||k<0?1/0:k+1;let C=0;e?C=s:(Bt.reqId||Bt.requestTick(F()),C=(Bt._elapsedTime-Bt._startTime)*L.timeScale),this.id=z(i)?++re:i,this.parent=e,this.duration=mt((S+$)*E-$)||c,this.backwards=!1,this.paused=!0,this.began=!1,this.completed=!1,this.onBegin=_||w.onBegin,this.onBeforeUpdate=v||w.onBeforeUpdate,this.onUpdate=b||w.onUpdate,this.onLoop=f||w.onLoop,this.onPause=g||w.onPause,this.onComplete=m||w.onComplete,this.iterationDuration=S,this.iterationCount=E,this._autoplay=!e&&Yt(d,w.autoplay),this._offset=C,this._delay=x,this._loopDelay=$,this._iterationTime=0,this._currentIteration=0,this._resolve=y,this._running=!1,this._reversed=+Yt(o,w.reversed),this._reverse=this._reversed,this._cancelled=0,this._alternate=Yt(h,w.alternate),this._prev=null,this._next=null,this._elapsedTime=T,this._startTime=T,this._lastTime=T,this._fps=Yt(u,w.frameRate),this._speed=Yt(p,w.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(t){t?this.cancel():this.reset(1).play()}get currentTime(){return ht(lt(this._currentTime,L.precision),-this._delay,this.duration)}set currentTime(t){const e=this.paused;this.pause().seek(+t),e||this.resume()}get iterationCurrentTime(){return lt(this._iterationTime,L.precision)}set iterationCurrentTime(t){this.currentTime=this.iterationDuration*this._currentIteration+t}get progress(){return ht(lt(this._currentTime/this.duration,10),0,1)}set progress(t){this.currentTime=this.duration*t}get iterationProgress(){return ht(lt(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(t){const e=this.iterationDuration;this.currentTime=e*this._currentIteration+e*t}get currentIteration(){return this._currentIteration}set currentIteration(t){this.currentTime=this.iterationDuration*ht(+t,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(t){t?this.reverse():this.play()}get speed(){return super.speed}set speed(t){super.speed=t,this.resetTime()}reset(t=0){return ie(this),this._reversed&&!this._reverse&&(this.reversed=!1),this._iterationTime=this.iterationDuration,St(this,0,1,t,2),se(this),this._hasChildren&&_t(this,se),this}init(t=0){this.fps=this._fps,this.speed=this._speed,!t&&this._hasChildren&&St(this,this.duration,1,t,2),this.reset(t);const e=this._autoplay;return!0===e?this.resume():e&&!z(e.linked)&&e.link(this),this}resetTime(){const t=1/(this._speed*Bt._speed);return this._startTime=F()-(this._currentTime+this._delay)*t,this}pause(){return this.paused||(this.paused=!0,this.onPause(this)),this}resume(){return this.paused?(this.paused=!1,this.duration<=c&&!this._hasChildren?St(this,c,0,0,2):(this._running||(bt(Bt,this),Bt._hasChildren=!0,this._running=!0),this.resetTime(),this._startTime-=12,Bt.wake()),this):this}restart(){return this.reset(0).resume()}seek(t,e=0,s=0){ie(this),this.completed=!1;const i=this.paused;return this.paused=!0,St(this,t+this._delay,~~e,~~s,1),i?this:this.resume()}alternate(){const t=this._reversed,e=this.iterationCount,s=this.iterationDuration,i=e===1/0?et(d/s):e;return this._reversed=+(!this._alternate||i%2?!t:t),e===1/0?this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress:this.seek(s*i-this._currentTime),this.resetTime(),this}play(){return this._reversed&&this.alternate(),this.resume()}reverse(){return this._reversed||this.alternate(),this.resume()}cancel(){return this._hasChildren?_t(this,(t=>t.cancel()),!0):_t(this,ee),this._cancelled=1,this.pause()}stretch(t){const e=this.duration,s=ft(t);if(e===s)return this;const i=t/e,r=t<=c;return this.duration=r?c:s,this.iterationDuration=r?c:ft(this.iterationDuration*i),this._offset*=i,this._delay*=i,this._loopDelay*=i,this}revert(){St(this,0,1,0,1);const t=this._autoplay;return t&&t.linked&&t.linked===this&&t.revert(),this.cancel()}complete(){return this.seek(this.duration).cancel()}then(t=y){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=y};return new Promise((t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this)))}}const oe=t=>new ne(t,null,0).init(),he=t=>t,ae=(t,e,s)=>(((1-3*s+3*e)*t+(3*s-6*e))*t+3*e)*t,le=(t=.5,e=0,s=.5,i=1)=>t===e&&s===i?he:r=>0===r||1===r?r:ae(((t,e,s)=>{let i,r,n=0,o=1,h=0;do{r=n+(o-n)/2,i=ae(r,e,s)-t,i>0?o=r:n=r}while(J(i)>1e-7&&++h<100);return r})(r,t,s),e,i),ce=(t=10,e)=>{const s=e?tt:et;return e=>s(ht(e,0,1)*t)*(1/t)},de=(...t)=>{const e=t.length;if(!e)return he;const s=e-1,i=t[0],r=t[s],n=[0],o=[q(i)];for(let e=1;e<s;e++){const i=t[e],r=M(i)?i.trim().split(" "):[i],h=r[0],a=r[1];n.push(z(a)?e/s:q(a)/100),o.push(q(h))}return o.push(q(r)),n.push(1),function(t){for(let e=1,s=n.length;e<s;e++){const s=n[e];if(t<=s){const i=n[e-1],r=o[e-1];return r+(o[e]-r)*(t-i)/(s-i)}}return o[o.length-1]}},ue=(t=10,e=1)=>{const s=[0],i=t-1;for(let t=1;t<i;t++){const r=s[t-1],n=t/i,o=n*(1-e)+(n+((t+1)/i-n)*Math.random())*e;s.push(ht(o,r,1))}return s.push(1),de(...s)},pe=nt/2,me=2*nt,fe=(t=1.68)=>e=>Q(e,+t),ge={[p]:fe,Quad:fe(2),Cubic:fe(3),Quart:fe(4),Quint:fe(5),Sine:t=>1-Z(t*pe),Circ:t=>1-j(1-t*t),Expo:t=>t?Q(2,10*t-10):0,Bounce:t=>{let e,s=4;for(;t<((e=Q(2,--s))-1)/11;);return 1/Q(4,3-s)-7.5625*Q((3*e-2)/22-t,2)},Back:(t=1.70158)=>e=>(+t+1)*e*e*e-+t*e*e,Elastic:(t=1,e=.3)=>{const s=ht(+t,1,10),i=ht(+e,c,2),r=i/me*st(1/s),n=me/i;return t=>0===t||1===t?t:-s*Q(2,-10*(1-t))*G((1-t-r)*n)}},ye={in:t=>e=>t(e),out:t=>e=>1-t(1-e),inOut:t=>e=>e<.5?t(2*e)/2:1-t(-2*e+2)/2,outIn:t=>e=>e<.5?(1-t(1-2*e))/2:(t(2*e-1)+1)/2},_e=(t,e,s)=>{if(s[t])return s[t];if(t.indexOf("(")<=-1){const i=ye[t]||t.includes("Back")||t.includes("Elastic")?e[t]():e[t];return i?s[t]=i:he}{const i=t.slice(0,-1).split("("),r=e[i[0]];return r?s[t]=r(...i[1].split(",")):he}},ve=(()=>{const t={linear:de,irregular:ue,steps:ce,cubicBezier:le};for(let e in ye)for(let s in ge){const i=ge[s],r=ye[e];t[e+s]=s===p||"Back"===s||"Elastic"===s?(t,e)=>r(i(t,e)):r(i)}return t})(),be={linear:he},Te=t=>I(t)?t:M(t)?_e(t,ve,be):he,we={},xe=(t,e,s)=>{if(3===s)return m.get(t)||t;if(2===s||1===s&&X(e)&&t in e.style){const e=we[t];if(e)return e;{const e=t?N(t):t;return we[t]=e,e}}return t},Se={deg:1,rad:180/nt,turn:360},ke={},$e=(t,e,i,r=!1)=>{const n=e.u,o=e.n;if(1===e.t&&n===i)return e;const h=o+n+i,a=ke[h];if(z(a)||r){let r;if(n in Se)r=o*Se[n]/Se[i];else{const e=100,h=t.cloneNode(),a=t.parentNode,l=a&&a!==s?a:s.body;l.appendChild(h);const c=h.style;c.width=e+n;const d=h.offsetWidth||e;c.width=e+i;const u=d/(h.offsetWidth||e);l.removeChild(h),r=u*o}e.n=r,ke[h]=r}else e.n=a;return e.t,e.u=i,e},Ee=t=>{if(t._hasChildren)_t(t,Ee,!0);else{const e=t;e.pause(),_t(e,(t=>{const s=t.property,i=t.target;if(i[n]){const r=i.style,n=e._inlineStyles[s];if(3===t._tweenType){const e=i[h];if(z(n)||n===p?delete e[s]:e[s]=n,t._renderTransforms)if(Object.keys(e).length){let t=p;for(let s in e)t+=g[s]+e[s]+") ";r.transform=t}else r.removeProperty("transform")}else z(n)||n===p?r.removeProperty(s):r[s]=n;e._tail===t&&e.targets.forEach((t=>{t.getAttribute&&t.getAttribute("style")===p&&t.removeAttribute("style")}))}}))}return t},Ce={t:0,n:0,u:null,o:null,d:null,s:null},Be={t:0,n:0,u:null,o:null,d:null,s:null},Le={func:null},De=[null],Ne=[null,null],Ae={to:null};let Fe,Oe,Pe=0;class Re extends ne{constructor(t,e,s,r,n=!1,o=0,h=0){super(e,s,r);const a=Ft(t),l=a.length,d=e.keyframes,p=d?yt(((t,e)=>{const s={};if(O(t)){const e=[].concat(...t.map((t=>Object.keys(t)))).filter(U);for(let i=0,r=e.length;i<r;i++){const r=e[i],n=t.map((t=>{const e={};for(let s in t){const i=t[s];U(s)?s===r&&(e.to=i):e[s]=i}return e}));s[r]=n}}else{const i=Yt(e.duration,L.defaults.duration),r=Object.keys(t).map((e=>({o:parseFloat(e)/100,p:t[e]}))).sort(((t,e)=>t.o-e.o));r.forEach((t=>{const e=t.o,r=t.p;for(let t in r)if(U(t)){let n=s[t];n||(n=s[t]=[]);const o=e*i;let h=n.length,a=n[h-1];const l={to:r[t]};let c=0;for(let t=0;t<h;t++)c+=n[t].duration;1===h&&(l.from=a.to),r.ease&&(l.ease=r.ease),l.duration=o-(h?c:0),n.push(l)}return t}));for(let t in s){const e=s[t];let i;for(let t=0,s=e.length;t<s;t++){const s=e[t],r=s.ease;s.ease=i||void 0,i=r}e[0].duration||e.shift()}}return s})(d,e),e):e,{delay:m,duration:f,ease:g,playbackEase:y,modifier:_,composition:v,onRender:b}=p,T=s?s.defaults:L.defaults,w=Yt(y,T.playbackEase),x=w?Te(w):null,S=!z(g)&&!z(g.ease),k=S?g.ease:Yt(g,x?"linear":T.ease),$=S?g.duration:Yt(f,T.duration),E=Yt(m,T.delay),C=_||T.modifier,B=z(v)&&l>=u?i.none:z(v)?T.composition:v,D={},N=this._offset+(s?s._offset:0);let A=NaN,F=NaN,M=0,I=0;for(let t=0;t<l;t++){const e=a[t],r=o||t,d=h||l;let u=NaN,m=NaN;for(let t in p)if(U(t)){const o=Wt(e,t),h=xe(t,e,o);let a=p[t];const l=O(a);if(n&&!l&&(Ne[0]=a,Ne[1]=a,a=Ne),l){const t=a.length,e=!P(a[0]);2===t&&e?(Ae.to=a,De[0]=Ae,Fe=De):t>2&&e?(Fe=[],a.forEach(((t,e)=>{e?1===e?(Ne[1]=t,Fe.push(Ne)):Fe.push(t):Ne[0]=t}))):Fe=a}else De[0]=a,Fe=De;let f=null,g=null,y=NaN,_=0,v=0;for(let t=Fe.length;v<t;v++){const n=Fe[v];P(n)?Oe=n:(Ae.to=n,Oe=Ae),Le.func=null;const a=Xt(Oe.to,e,r,d,Le);let l;P(a)&&!z(a.to)?(Oe=a,l=a.to):l=a;const u=Xt(Oe.from,e,r,d),p=Oe.ease,m=!z(p)&&!z(p.ease),b=m?p.ease:p||k,T=m?p.duration:Xt(Yt(Oe.duration,t>1?Xt($,e,r,d)/t:$),e,r,d),w=Xt(Yt(Oe.delay,v?0:E),e,r,d),x=Xt(Yt(Oe.composition,B),e,r,d),S=R(x)?x:i[x],L=Oe.modifier||C,A=!z(u),F=!z(l),Y=O(l),X=Y||A&&F,W=g?_+w:w,V=lt(N+W,12);I||!A&&!Y||(I=1);let H=g;if(S!==i.none){f||(f=Zt(e,h));let t=f._head;for(;t&&!t._isOverridden&&t._absoluteStartTime<=V;)if(H=t,t=t._nextRep,t&&t._absoluteStartTime>=V)for(;t;)Kt(t),t=t._nextRep}if(X?(qt(Y?Xt(l[0],e,r,d):u,Ce),qt(Y?Xt(l[1],e,r,d,Le):l,Be),0===Ce.t&&(H?1===H._valueType&&(Ce.t=1,Ce.u=H._unit):(qt(Ht(e,h,o,D),jt),1===jt.t&&(Ce.t=1,Ce.u=jt.u)))):(F?qt(l,Be):g?Qt(g,Be):qt(s&&H&&H.parent.parent===s?H._value:Ht(e,h,o,D),Be),A?qt(u,Ce):g?Qt(g,Ce):qt(s&&H&&H.parent.parent===s?H._value:Ht(e,h,o,D),Ce)),Ce.o&&(Ce.n=Ut(H?H._toNumber:qt(Ht(e,h,o,D),jt).n,Ce.n,Ce.o)),Be.o&&(Be.n=Ut(Ce.n,Be.n,Be.o)),Ce.t!==Be.t)if(3===Ce.t||3===Be.t){const t=3===Ce.t?Ce:Be,e=3===Ce.t?Be:Ce;e.t=3,e.s=gt(t.s),e.d=t.d.map((()=>e.n))}else if(1===Ce.t||1===Be.t){const t=1===Ce.t?Ce:Be,e=1===Ce.t?Be:Ce;e.t=1,e.u=t.u}else if(2===Ce.t||2===Be.t){const t=2===Ce.t?Ce:Be,e=2===Ce.t?Be:Ce;e.t=2,e.s=t.s,e.d=[0,0,0,1]}if(Ce.u!==Be.u){let t=Be.u?Ce:Be;t=$e(e,t,Be.u?Be.u:Ce.u,!1)}if(Be.d&&Ce.d&&Be.d.length!==Ce.d.length){const t=Ce.d.length>Be.d.length?Ce:Be,e=t===Ce?Be:Ce;e.d=t.d.map(((t,s)=>z(e.d[s])?0:e.d[s])),e.s=gt(t.s)}const U=lt(+T||c,12),q={parent:this,id:Pe++,property:h,target:e,_value:null,_func:Le.func,_ease:Te(b),_fromNumbers:gt(Ce.d),_toNumbers:gt(Be.d),_strings:gt(Be.s),_fromNumber:Ce.n,_toNumber:Be.n,_numbers:gt(Ce.d),_number:Ce.n,_unit:Be.u,_modifier:L,_currentTime:0,_startTime:W,_delay:+w,_updateDuration:U,_changeDuration:U,_absoluteStartTime:V,_tweenType:o,_valueType:Be.t,_composition:S,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};S!==i.none&&te(q,f),isNaN(y)&&(y=q._startTime),_=lt(W+U,12),g=q,M++,bt(this,q)}(isNaN(F)||y<F)&&(F=y),(isNaN(A)||_>A)&&(A=_),3===o&&(u=M-v,m=M)}if(!isNaN(u)){let t=0;_t(this,(e=>{t>=u&&t<m&&(e._renderTransforms=1,e._composition===i.blend&&_t(kt.animation,(t=>{t.id===e.id&&(t._renderTransforms=1)}))),t++}))}}l||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation."),F?(_t(this,(t=>{t._startTime-t._delay||(t._delay-=F),t._startTime-=F})),A-=F):F=0,A||(A=c,this.iterationCount=0),this.targets=a,this.duration=A===c?c:mt((A+this._loopDelay)*this.iterationCount-this._loopDelay)||c,this.onRender=b||T.onRender,this._ease=x,this._delay=F,this.iterationDuration=A,this._inlineStyles=D,!this._autoplay&&I&&this.onRender(this)}stretch(t){const e=this.duration;if(e===ft(t))return this;const s=t/e;return _t(this,(t=>{t._updateDuration=ft(t._updateDuration*s),t._changeDuration=ft(t._changeDuration*s),t._currentTime*=s,t._startTime*=s,t._absoluteStartTime*=s})),super.stretch(t)}refresh(){return _t(this,(t=>{const e=t._func;if(e){const s=Ht(t.target,t.property,t._tweenType);qt(s,jt),qt(e(),Be),t._fromNumbers=gt(jt.d),t._fromNumber=jt.n,t._toNumbers=gt(Be.d),t._strings=gt(Be.s),t._toNumber=Be.o?Ut(jt.n,Be.n,Be.o):Be.n}})),this}revert(){return super.revert(),Ee(this)}then(t){return super.then(t)}}const Me=(t,e)=>new Re(t,e,null,0,!1).init(),Ie=(t,e=100)=>{const s=[];for(let i=0;i<=e;i++)s.push(t(i/e));return`linear(${s.join(", ")})`},ze={in:"ease-in",out:"ease-out",inOut:"ease-in-out"},Ye=(()=>{const t={};for(let e in ye)t[e]=t=>ye[e](fe(t));return t})(),Xe=t=>{let e=ze[t];if(e)return e;if(e="linear",M(t)){if(A(t,"linear")||A(t,"cubic-")||A(t,"steps")||A(t,"ease"))e=t;else if(A(t,"cubicB"))e=N(t);else{const s=_e(t,Ye,ze);I(s)&&(e=s===he?"linear":Ie(s))}ze[t]=e}else if(I(t)){const s=Ie(t);s&&(e=s)}else t.ease&&(e=Ie(t.ease));return e},We=["x","y","z"],Ve=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",...We],He=(()=>[...We,...f.filter((t=>["X","Y","Z"].some((e=>t.endsWith(e)))))])();let Ue=null;const qe={_head:null,_tail:null},Qe=(t,e,s)=>{let i=qe._head;for(;i;){const r=i._next,n=i.$el===t,o=!e||i.property===e,h=!s||i.parent===s;if(n&&o&&h){const t=i.animation;try{t.commitStyles()}catch{}t.cancel(),vt(qe,i);const e=i.parent;e&&(e._completed++,e.animations.length===e._completed&&(e.completed=!0,e.muteCallbacks||(e.paused=!0,e.onComplete(e),e._resolve(e))))}i=r}},je=(t,e,s,i,r)=>{const n=e.animate(i,r),o=r.delay+ +r.duration*r.iterations;n.playbackRate=t._speed,t.paused&&n.pause(),t.duration<o&&(t.duration=o,t.controlAnimation=n),t.animations.push(n),Qe(e,s),bt(qe,{parent:t,animation:n,$el:e,property:s,_next:null,_prev:null});const h=()=>{Qe(e,s,t)};return n.onremove=h,n.onfinish=h,n},Ge=(t,e,s,i,r)=>{let n=Xt(e,s,i,r);return R(n)?Ve.includes(t)||A(t,"translate")?`${n}px`:A(t,"rotate")||A(t,"skew")?`${n}deg`:`${n}`:n},Ze=(t,e,s,i,r,n)=>{let o="0";const h=z(i)?getComputedStyle(t)[e]:Ge(e,i,t,r,n);return o=z(s)?O(i)?i.map((s=>Ge(e,s,t,r,n))):h:[Ge(e,s,t,r,n),h],o};class Je{constructor(e,s){B.current&&B.current.register(this),Y(Ue)&&(!t||!z(CSS)&&Object.hasOwnProperty.call(CSS,"registerProperty")?(f.forEach((t=>{const e=A(t,"skew"),s=A(t,"scale"),i=A(t,"rotate"),r=A(t,"translate"),n=i||e,o=n?"<angle>":s?"<number>":r?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:o,inherits:!1,initialValue:r?"0px":n?"0deg":s?"1":"0"})}catch{}})),Ue=!0):Ue=!1);const i=Ft(e),r=i.length;r||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation.");const n=Yt(s.ease,Xe(L.defaults.ease)),o=n.ease&&n,a=Yt(s.autoplay,L.defaults.autoplay),l=!(!a||!a.link)&&a,c=s.alternate&&!0===s.alternate,d=s.reversed&&!0===s.reversed,_=Yt(s.loop,L.defaults.loop),v=!0===_||_===1/0?1/0:R(_)?_+1:1,b=c?d?"alternate-reverse":"alternate":d?"reverse":"normal",T=Xe(n),w=1===L.timeScale?1:u;this.targets=i,this.animations=[],this.controlAnimation=null,this.onComplete=s.onComplete||y,this.duration=0,this.muteCallbacks=!1,this.completed=!1,this.paused=!a||!1!==l,this.reversed=d,this.autoplay=a,this._speed=Yt(s.playbackRate,L.defaults.playbackRate),this._resolve=y,this._completed=0,this._inlineStyles=i.map((t=>t.getAttribute("style"))),i.forEach(((t,e)=>{const i=t[h],a=He.some((t=>s.hasOwnProperty(t))),l=(o?o.duration:Xt(Yt(s.duration,L.defaults.duration),t,e,r))*w,c=Xt(Yt(s.delay,L.defaults.delay),t,e,r)*w,d=Yt(s.composition,"replace");for(let o in s){if(!U(o))continue;const h={},u={iterations:v,direction:b,fill:"forwards",easing:T,duration:l,delay:c,composite:d},p=s[o],g=!!a&&(f.includes(o)?o:m.get(o));let y;if(P(p)){const s=p,a=Yt(s.ease,n),m=a.ease&&a,f=s.to,_=s.from;if(u.duration=(m?m.duration:Xt(Yt(s.duration,l),t,e,r))*w,u.delay=Xt(Yt(s.delay,c),t,e,r)*w,u.composite=Yt(s.composition,d),u.easing=Xe(a),y=Ze(t,o,_,f,e,r),g?(h[`--${g}`]=y,i[g]=y):h[o]=Ze(t,o,_,f,e,r),je(this,t,o,h,u),!z(_))if(g){const e=`--${g}`;t.style.setProperty(e,h[e][0])}else t.style[o]=h[o][0]}else y=O(p)?p.map((s=>Ge(o,s,t,e,r))):Ge(o,p,t,e,r),g?(h[`--${g}`]=y,i[g]=y):h[o]=y,je(this,t,o,h,u)}if(a){let e=p;for(let t in i)e+=`${g[t]}var(--${t})) `;t.style.transform=e}})),l&&this.autoplay.link(this)}forEach(t){const e=M(t)?e=>e[t]():t;return this.animations.forEach(e),this}get speed(){return this._speed}set speed(t){this._speed=+t,this.forEach((e=>e.playbackRate=t))}get currentTime(){const t=this.controlAnimation,e=L.timeScale;return this.completed?this.duration:t?+t.currentTime*(1===e?1:e):0}set currentTime(t){const e=t*(1===L.timeScale?1:u);this.forEach((t=>{e>=this.duration&&t.play(),t.currentTime=e}))}get progress(){return this.currentTime/this.duration}set progress(t){this.forEach((e=>e.currentTime=t*this.duration||0))}resume(){return this.paused?(this.paused=!1,this.forEach("play")):this}pause(){return this.paused?this:(this.paused=!0,this.forEach("pause"))}alternate(){return this.reversed=!this.reversed,this.forEach("reverse"),this.paused&&this.forEach("pause"),this}play(){return this.reversed&&this.alternate(),this.resume()}reverse(){return this.reversed||this.alternate(),this.resume()}seek(t,e=!1){return e&&(this.muteCallbacks=!0),t<this.duration&&(this.completed=!1),this.currentTime=t,this.muteCallbacks=!1,this.paused&&this.pause(),this}restart(){return this.completed=!1,this.seek(0,!0).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){return this.forEach("cancel"),this.pause()}revert(){return this.cancel(),this.targets.forEach(((t,e)=>t.setAttribute("style",this._inlineStyles[e]))),this}then(t=y){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=y};return new Promise((t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this)))}}const Ke={animate:(t,e)=>new Je(t,e),convertEase:Ie},ts=(t=y)=>new ne({duration:1*L.timeScale,onComplete:t},null,0).resume();function es(t,e,s){const i=Ft(t);if(!i.length)return;const[r]=i,n=Wt(r,e),o=xe(e,r,n);let h=Ht(r,o);if(z(s))return h;if(qt(h,jt),0===jt.t||1===jt.t){if(!1===s)return jt.n;{const t=$e(r,jt,s,!1);return`${lt(t.n,L.precision)}${t.u}`}}}const ss=(t,e)=>{if(!z(e))return e.duration=c,e.composition=Yt(e.composition,i.none),new Re(t,e,null,0,!0).resume()},is=(t,e,s)=>{let i=!1;return _t(e,(r=>{const n=r.target;if(t.includes(n)){const t=r.property,o=r._tweenType,h=xe(s,n,o);(!h||h&&h===t)&&(r.parent._tail===r&&3===r._tweenType&&r._prev&&3===r._prev._tweenType&&(r._prev._renderTransforms=1),vt(e,r),ee(r),i=!0)}}),!0),i},rs=(t,e,s)=>{const i=At(t),r=e||Bt,n=e&&e.controlAnimation&&e;for(let t=0,e=i.length;t<e;t++){const e=i[t];Qe(e,s,n)}let o;if(r._hasChildren){let e=0;_t(r,(n=>{if(!n._hasChildren)if(o=is(i,n,s),o&&!n._head)n.cancel(),vt(r,n);else{const t=n._offset+n._delay+n.duration;t>e&&(e=t)}n._head?rs(t,n,s):n._hasChildren=!1}),!0),z(r.iterationDuration)||(r.iterationDuration=e)}else o=is(i,r,s);return o&&!r._head&&(r._hasChildren=!1,r.cancel&&r.cancel()),i},ns=(t,e,s,i,r)=>i+(t-e)/(s-e)*(r-i),os=(t,e,s,i)=>{let r=u/L.defaults.frameRate;if(!1!==i){const t=i||Bt._hasChildren&&Bt;t&&t.deltaTime&&(r=t.deltaTime)}const n=1-Math.exp(-s*r*.1);return s?1===s?e:(1-n)*t+n*e:t},hs=t=>(...e)=>{const s=t(...e);return new Proxy(y,{apply:(t,e,[i])=>s(i),get:(t,e)=>hs(((...t)=>{const i=ls[e](...t);return t=>i(s(t))}))})},as=(t,e=0)=>(...s)=>(s.length<t.length?hs(((t,e=0)=>(...s)=>e?e=>t(...s,e):e=>t(e,...s))(t,e)):t)(...s),ls={$:Ft,get:es,set:ss,remove:rs,cleanInlineStyles:Ee,random:ut,randomPick:t=>t[ut(0,t.length-1)],shuffle:pt,lerp:os,sync:ts,keepTime:Tt,clamp:as(ht),round:as(lt),snap:as(ct),wrap:as(((t,e,s)=>((t-e)%(s-e)+(s-e))%(s-e)+e)),interpolate:as(dt,1),mapRange:as(ns),roundPad:as(((t,e)=>(+t).toFixed(e))),padStart:as(((t,e,s)=>`${t}`.padStart(e,s))),padEnd:as(((t,e,s)=>`${t}`.padEnd(e,s))),degToRad:as((t=>t*nt/180)),radToDeg:as((t=>180*t/nt))},cs=(t,e)=>{let s=t.iterationDuration;if(s===c&&(s=0),z(e))return s;if(R(+e))return+e;const i=e,r=t?t.labels:null,n=!Y(r),o=((t,e)=>{if(A(e,"<")){const s="<"===e[1],i=t._tail,r=i?i._offset+i._delay:0;return s?r:r+i.duration}})(t,i),h=!z(o),a=E.exec(i);if(a){const t=a[0],e=i.split(t),l=n&&e[0]?r[e[0]]:s,c=h?o:n?l:s,d=+e[1];return Ut(c,d,t[0])}return h?o:n?z(r[i])?s:r[i]:s};function ds(t,e,s,i,r,n){const o=R(t.duration)&&t.duration<=c?s-c:s;St(e,o,1,1,1);const h=i?new Re(i,t,e,o,!1,r,n):new ne(t,e,o);return h.init(1),bt(e,h),_t(e,(t=>{const s=t._offset+t._delay+t.duration;s>e.iterationDuration&&(e.iterationDuration=s)})),e.duration=function(t){return mt((t.iterationDuration+t._loopDelay)*t.iterationCount-t._loopDelay)||c}(e),e}class us extends ne{constructor(t={}){super(t,null,0),this.duration=0,this.labels={};const e=t.defaults,s=L.defaults;this.defaults=e?yt(e,s):s,this.onRender=t.onRender||s.onRender;const i=Yt(t.playbackEase,s.playbackEase);this._ease=i?Te(i):null,this.iterationDuration=0}add(t,e,s){const i=P(e),r=P(t);if(i||r){if(this._hasChildren=!0,i){const i=e;if(I(s)){const e=s,r=At(t),n=this.duration,o=this.iterationDuration,h=i.id;let a=0;const l=r.length;r.forEach((t=>{const s={...i};this.duration=n,this.iterationDuration=o,z(h)||(s.id=h+"-"+a),ds(s,this,cs(this,e(t,a,l,this)),t,a,l),a++}))}else ds(i,this,cs(this,s),t)}else ds(t,this,cs(this,e));return this.init(1)}}sync(t,e){if(z(t)||t&&z(t.pause))return this;t.pause();const s=+(t.effect?t.effect.getTiming().duration:t.duration);return this.add(t,{currentTime:[0,s],duration:s,ease:"linear"},e)}set(t,e,s){return z(e)?this:(e.duration=c,e.composition=i.replace,this.add(t,e,s))}call(t,e){return z(t)||t&&!I(t)?this:this.add({duration:0,onComplete:()=>t(this)},e)}label(t,e){return z(t)||t&&!M(t)||(this.labels[t]=cs(this,e)),this}remove(t,e){return rs(t,this,e),this}stretch(t){const e=this.duration;if(e===ft(t))return this;const s=t/e,i=this.labels;_t(this,(t=>t.stretch(t.duration*s)));for(let t in i)i[t]*=s;return super.stretch(t)}refresh(){return _t(this,(t=>{t.refresh&&t.refresh()})),this}revert(){return super.revert(),_t(this,(t=>t.revert),!0),Ee(this)}then(t){return super.then(t)}}const ps=t=>new us(t).init();class ms{constructor(t,e){B.current&&B.current.register(this);const s=()=>{if(this.callbacks.completed)return;let t=!0;for(let e in this.animations)if(!this.animations[e].paused&&t){t=!1;break}t&&this.callbacks.complete()},r={onBegin:()=>{this.callbacks.completed&&this.callbacks.reset(),this.callbacks.play()},onComplete:s,onPause:s},n={v:1,autoplay:!1},o={};if(this.targets=[],this.animations={},this.callbacks=null,!z(t)&&!z(e)){for(let t in e){const s=e[t];U(t)?o[t]=s:A(t,"on")?n[t]=s:r[t]=s}this.callbacks=new Re({v:0},n);for(let e in o){const s=o[e],n=P(s);let h={},a="+=0";if(n){const t=s.unit;M(t)&&(a+=t)}else h.duration=s;h[e]=n?yt({to:a},s):a;const l=yt(r,h);l.composition=i.replace,l.autoplay=!1;const c=this.animations[e]=new Re(t,l,null,0,!1).init();this.targets.length||this.targets.push(...c.targets),this[e]=(t,e,s)=>{const i=c._head;if(z(t)&&i){const t=i._numbers;return t&&t.length?t:i._modifier(i._number)}return _t(c,(e=>{if(O(t))for(let s=0,i=t.length;s<i;s++)z(e._numbers[s])||(e._fromNumbers[s]=e._modifier(e._numbers[s]),e._toNumbers[s]=t[s]);else e._fromNumber=e._modifier(e._number),e._toNumber=t;z(s)||(e._ease=Te(s)),e._currentTime=0})),z(e)||c.stretch(e),c.reset(1).resume(),this}}}}revert(){for(let t in this.animations)this[t]=y,this.animations[t].revert();return this.animations={},this.targets.length=0,this.callbacks&&this.callbacks.revert(),this}}const fs=(t,e)=>new ms(t,e),gs=10*u;class ys{constructor(t={}){this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/u,this.maxIterations=this.maxDuration/this.timeStep/u,this.m=ht(Yt(t.mass,1),0,gs),this.s=ht(Yt(t.stiffness,100),1,gs),this.d=ht(Yt(t.damping,10),.1,gs),this.v=ht(Yt(t.velocity,0),-1e4,gs),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.solverDuration=0,this.duration=0,this.compute(),this.ease=t=>0===t||1===t?t:this.solve(t*this.solverDuration)}solve(t){const{zeta:e,w0:s,wd:i,b:r}=this;let n=t;return n=e<1?K(-n*e*s)*(1*Z(i*n)+r*G(i*n)):(1+r*n)*K(-n*s),1-n}compute(){const{maxRestSteps:t,maxIterations:e,restThreshold:s,timeStep:i,m:r,d:n,s:o,v:h}=this,a=this.w0=ht(j(o/r),c,u),l=this.zeta=n/(2*j(o*r)),d=this.wd=l<1?a*j(1-l*l):0;this.b=l<1?(l*a-h)/d:-h+a;let p=0,m=0,f=0;for(;m<t&&f<e;)J(1-this.solve(p))<s?m++:m=0,this.solverDuration=p,p+=i,f++;this.duration=lt(this.solverDuration*u,0)*L.timeScale}get mass(){return this.m}set mass(t){this.m=ht(Yt(t,1),0,gs),this.compute()}get stiffness(){return this.s}set stiffness(t){this.s=ht(Yt(t,100),1,gs),this.compute()}get damping(){return this.d}set damping(t){this.d=ht(Yt(t,10),.1,gs),this.compute()}get velocity(){return this.v}set velocity(t){this.v=ht(Yt(t,0),-1e4,gs),this.compute()}}const _s=t=>new ys(t),vs=t=>{t.cancelable&&t.preventDefault()};class bs{constructor(t){this.el=t,this.zIndex=0,this.parentElement=null,this.classList={add:y,remove:y}}get x(){return this.el.x||0}set x(t){this.el.x=t}get y(){return this.el.y||0}set y(t){this.el.y=t}get width(){return this.el.width||0}set width(t){this.el.width=t}get height(){return this.el.height||0}set height(t){this.el.height=t}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class Ts{constructor(t){this.$el=t,this.inlineTransforms=[],this.point=new DOMPoint,this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(t,e){return this.point.x=t,this.point.y=e,this.point.matrixTransform(this.inversedMatrix)}traverseUp(t){let e=this.$el.parentElement,i=0;for(;e&&e!==s;)t(e,i),e=e.parentElement,i++}getMatrix(){const t=new DOMMatrix;return this.traverseUp((e=>{const s=getComputedStyle(e).transform;if(s){const e=new DOMMatrix(s);t.preMultiplySelf(e)}})),t}remove(){this.traverseUp(((t,e)=>{this.inlineTransforms[e]=t.style.transform,t.style.transform="none"}))}revert(){this.traverseUp(((t,e)=>{const s=this.inlineTransforms[e];""===s?t.style.removeProperty("transform"):t.style.transform=s}))}}const ws=(t,e)=>t&&I(t)?t(e):t;let xs=0;class Ss{constructor(t,i={}){if(!t)return;B.current&&B.current.register(this);const r=i.x,n=i.y,o=i.trigger,h=i.modifier,a=i.releaseEase,l=a&&Te(a),c=!z(a)&&!z(a.ease),u=P(r)&&!z(r.mapTo)?r.mapTo:"translateX",p=P(n)&&!z(n.mapTo)?n.mapTo:"translateY",m=ws(i.container,this);this.containerArray=O(m)?m:null,this.$container=m&&!this.containerArray?At(m)[0]:s.body,this.useWin=this.$container===s.body,this.$scrollContainer=this.useWin?e:this.$container,this.$target=P(t)?new bs(t):At(t)[0],this.$trigger=At(o||t)[0],this.fixed="fixed"===es(this.$target,"position"),this.isFinePointer=!0,this.containerPadding=[0,0,0,0],this.containerFriction=0,this.releaseContainerFriction=0,this.snapX=0,this.snapY=0,this.scrollSpeed=0,this.scrollThreshold=0,this.dragSpeed=0,this.maxVelocity=0,this.minVelocity=0,this.velocityMultiplier=0,this.cursor=!1,this.releaseXSpring=c?a:_s({mass:Yt(i.releaseMass,1),stiffness:Yt(i.releaseStiffness,80),damping:Yt(i.releaseDamping,20)}),this.releaseYSpring=c?a:_s({mass:Yt(i.releaseMass,1),stiffness:Yt(i.releaseStiffness,80),damping:Yt(i.releaseDamping,20)}),this.releaseEase=l||ve.outQuint,this.hasReleaseSpring=c,this.onGrab=i.onGrab||y,this.onDrag=i.onDrag||y,this.onRelease=i.onRelease||y,this.onUpdate=i.onUpdate||y,this.onSettle=i.onSettle||y,this.onSnap=i.onSnap||y,this.onResize=i.onResize||y,this.onAfterResize=i.onAfterResize||y,this.disabled=[0,0];const f={};if(h&&(f.modifier=h),z(r)||!0===r)f[u]=0;else if(P(r)){const t=r,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[u]=e}else!1===r&&(f[u]=0,this.disabled[0]=1);if(z(n)||!0===n)f[p]=0;else if(P(n)){const t=n,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[p]=e}else!1===n&&(f[p]=0,this.disabled[1]=1);this.animate=new ms(this.$target,f),this.xProp=u,this.yProp=p,this.destX=0,this.destY=0,this.deltaX=0,this.deltaY=0,this.scroll={x:0,y:0},this.coords=[this.x,this.y,0,0],this.snapped=[0,0],this.pointer=[0,0,0,0,0,0,0,0],this.scrollView=[0,0],this.dragArea=[0,0,0,0],this.containerBounds=[-1e12,d,d,-1e12],this.scrollBounds=[0,0,0,0],this.targetBounds=[0,0,0,0],this.window=[0,0],this.velocityStack=[0,0,0],this.velocityStackIndex=0,this.velocityTime=F(),this.velocity=0,this.angle=0,this.cursorStyles=null,this.triggerStyles=null,this.bodyStyles=null,this.targetStyles=null,this.touchActionStyles=null,this.transforms=new Ts(this.$target),this.overshootCoords={x:0,y:0},this.overshootTicker=new ne({autoplay:!1,onUpdate:()=>{this.updated=!0,this.manual=!0,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,1),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=!1,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,0),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init(),this.updateTicker=new ne({autoplay:!1,onUpdate:()=>this.update()},null,0).init(),this.contained=!z(m),this.manual=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.enabled=!1,this.initialized=!1,this.activeProp=this.disabled[1]?u:p,this.animate.callbacks.onRender=()=>{const t=this.updated,e=!(this.grabbed&&t)&&this.released,s=this.x,i=this.y,r=s-this.coords[2],n=i-this.coords[3];this.deltaX=r,this.deltaY=n,this.coords[2]=s,this.coords[3]=i,t&&(r||n)&&this.onUpdate(this),e?(this.computeVelocity(r,n),this.angle=rt(n,r)):this.updated=!1},this.animate.callbacks.onComplete=()=>{!this.grabbed&&this.released&&(this.released=!1),this.manual||(this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.onSettle(this))},this.resizeTicker=new ne({autoplay:!1,duration:150*L.timeScale,onComplete:()=>{this.onResize(this),this.refresh(),this.onAfterResize(this)}}).init(),this.parameters=i,this.resizeObserver=new ResizeObserver((()=>{this.initialized?this.resizeTicker.restart():this.initialized=!0})),this.enable(),this.refresh(),this.resizeObserver.observe(this.$container),P(t)||this.resizeObserver.observe(this.$target)}computeVelocity(t,e){const s=this.velocityTime,i=F(),r=i-s;if(r<17)return this.velocity;this.velocityTime=i;const n=this.velocityStack,o=this.velocityMultiplier,h=this.minVelocity,a=this.maxVelocity,l=this.velocityStackIndex;n[l]=lt(ht(j(t*t+e*e)/r*o,h,a),5);const c=it(n[0],n[1],n[2]);return this.velocity=c,this.velocityStackIndex=(l+1)%3,c}setX(t,e=!1){if(this.disabled[0])return;const s=lt(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destX=s,this.snapped[0]=ct(s,this.snapX),this.animate[this.xProp](s,0),this.manual=!1,this}setY(t,e=!1){if(this.disabled[1])return;const s=lt(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destY=s,this.snapped[1]=ct(s,this.snapY),this.animate[this.yProp](s,0),this.manual=!1,this}get x(){return lt(this.animate[this.xProp](),L.precision)}set x(t){this.setX(t,!1)}get y(){return lt(this.animate[this.yProp](),L.precision)}set y(t){this.setY(t,!1)}get progressX(){return ns(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(t){this.setX(ns(t,0,1,this.containerBounds[3],this.containerBounds[1]),!1)}get progressY(){return ns(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(t){this.setY(ns(t,0,1,this.containerBounds[0],this.containerBounds[2]),!1)}updateScrollCoords(){const t=lt(this.useWin?e.scrollX:this.$container.scrollLeft,0),s=lt(this.useWin?e.scrollY:this.$container.scrollTop,0),[i,r,n,o]=this.containerPadding,h=this.scrollThreshold;this.scroll.x=t,this.scroll.y=s,this.scrollBounds[0]=s-this.targetBounds[0]+i-h,this.scrollBounds[1]=t-this.targetBounds[1]-r+h,this.scrollBounds[2]=s-this.targetBounds[2]-n+h,this.scrollBounds[3]=t-this.targetBounds[3]+o-h}updateBoundingValues(){const t=this.$container;if(!t)return;const i=this.x,r=this.y,n=this.coords[2],o=this.coords[3];this.coords[2]=0,this.coords[3]=0,this.setX(0,!0),this.setY(0,!0),this.transforms.remove();const h=this.window[0]=e.innerWidth,a=this.window[1]=e.innerHeight,l=this.useWin,c=t.scrollWidth,d=t.scrollHeight,u=this.fixed,p=t.getBoundingClientRect(),[m,f,g,y]=this.containerPadding;this.dragArea[0]=l?0:p.left,this.dragArea[1]=l?0:p.top,this.scrollView[0]=l?ht(c,h,c):c,this.scrollView[1]=l?ht(d,a,d):d,this.updateScrollCoords();const{width:_,height:v,left:b,top:T,right:w,bottom:x}=t.getBoundingClientRect();this.dragArea[2]=lt(l?ht(_,h,h):_,0),this.dragArea[3]=lt(l?ht(v,a,a):v,0);const S=es(t,"overflow"),k="visible"===S,$="hidden"===S;if(this.canScroll=!u&&this.contained&&(t===s.body&&k||!$&&!k)&&(c>this.dragArea[2]+y-f||d>this.dragArea[3]+m-g)&&(!this.containerArray||this.containerArray&&!O(this.containerArray)),this.contained){const e=this.scroll.x,s=this.scroll.y,i=this.canScroll,r=this.$target.getBoundingClientRect(),n=i?l?0:t.scrollLeft:0,o=i?l?0:t.scrollTop:0,c=i?this.scrollView[0]-n-_:0,d=i?this.scrollView[1]-o-v:0;this.targetBounds[0]=lt(r.top+s-(l?0:T),0),this.targetBounds[1]=lt(r.right+e-(l?h:w),0),this.targetBounds[2]=lt(r.bottom+s-(l?a:x),0),this.targetBounds[3]=lt(r.left+e-(l?0:b),0),this.containerArray?(this.containerBounds[0]=this.containerArray[0]+m,this.containerBounds[1]=this.containerArray[1]-f,this.containerBounds[2]=this.containerArray[2]-g,this.containerBounds[3]=this.containerArray[3]+y):(this.containerBounds[0]=-lt(r.top-(u?ht(T,0,a):T)+o-m,0),this.containerBounds[1]=-lt(r.right-(u?ht(w,0,h):w)-c+f,0),this.containerBounds[2]=-lt(r.bottom-(u?ht(x,0,a):x)-d+g,0),this.containerBounds[3]=-lt(r.left-(u?ht(b,0,h):b)+n-y,0))}this.transforms.revert(),this.coords[2]=n,this.coords[3]=o,this.setX(i,!0),this.setY(r,!0)}isOutOfBounds(t,e,s){if(!this.contained)return 0;const[i,r,n,o]=t,[h,a]=this.disabled,l=!h&&e<o||!h&&e>r,c=!a&&s<i||!a&&s>n;return l&&!c?1:!l&&c?2:l&&c?3:0}refresh(){const t=this.parameters,i=t.x,r=t.y,n=ws(t.container,this),o=ws(t.containerPadding,this)||0,h=O(o)?o:[o,o,o,o],a=this.x,l=this.y,c=ws(t.cursor,this),d={onHover:"grab",onGrab:"grabbing"};if(c){const{onHover:t,onGrab:e}=c;t&&(d.onHover=t),e&&(d.onGrab=e)}this.containerArray=O(n)?n:null,this.$container=n&&!this.containerArray?At(n)[0]:s.body,this.useWin=this.$container===s.body,this.$scrollContainer=this.useWin?e:this.$container,this.isFinePointer=matchMedia("(pointer:fine)").matches,this.containerPadding=Yt(h,[0,0,0,0]),this.containerFriction=ht(Yt(ws(t.containerFriction,this),.8),0,1),this.releaseContainerFriction=ht(Yt(ws(t.releaseContainerFriction,this),this.containerFriction),0,1),this.snapX=ws(P(i)&&!z(i.snap)?i.snap:t.snap,this),this.snapY=ws(P(r)&&!z(r.snap)?r.snap:t.snap,this),this.scrollSpeed=Yt(ws(t.scrollSpeed,this),1.5),this.scrollThreshold=Yt(ws(t.scrollThreshold,this),20),this.dragSpeed=Yt(ws(t.dragSpeed,this),1),this.minVelocity=Yt(ws(t.minVelocity,this),0),this.maxVelocity=Yt(ws(t.maxVelocity,this),50),this.velocityMultiplier=Yt(ws(t.velocityMultiplier,this),1),this.cursor=!1!==c&&d,this.updateBoundingValues();const[u,p,m,f]=this.containerBounds;this.setX(ht(a,f,p),!0),this.setY(ht(l,u,m),!0)}update(){if(this.updateScrollCoords(),this.canScroll){const[t,e,s,i]=this.containerPadding,[r,n]=this.scrollView,o=this.dragArea[2],h=this.dragArea[3],a=this.scroll.x,l=this.scroll.y,c=this.$container.scrollWidth,d=this.$container.scrollHeight,u=this.useWin?ht(c,this.window[0],c):c,p=this.useWin?ht(d,this.window[1],d):d,m=r-u,f=n-p;this.dragged&&m>0&&(this.coords[0]-=m,this.scrollView[0]=u),this.dragged&&f>0&&(this.coords[1]-=f,this.scrollView[1]=p);const g=10*this.scrollSpeed,y=this.scrollThreshold,[_,v]=this.coords,[b,T,w,x]=this.scrollBounds,S=lt(ht((v-b+t)/y,-1,0)*g,0),k=lt(ht((_-T-e)/y,0,1)*g,0),$=lt(ht((v-w-s)/y,0,1)*g,0),E=lt(ht((_-x+i)/y,-1,0)*g,0);if(S||$||E||k){const[t,e]=this.disabled;let s=a,i=l;t||(s=lt(ht(a+(E||k),0,r-o),0),this.coords[0]-=a-s),e||(i=lt(ht(l+(S||$),0,n-h),0),this.coords[1]-=l-i),this.useWin?this.$scrollContainer.scrollBy(-(a-s),-(l-i)):this.$scrollContainer.scrollTo(s,i)}}const[t,e,s,i]=this.containerBounds,[r,n,o,h,a,l]=this.pointer;this.coords[0]+=(r-a)*this.dragSpeed,this.coords[1]+=(n-l)*this.dragSpeed,this.pointer[4]=r,this.pointer[5]=n;const[c,d]=this.coords,[u,p]=this.snapped,m=(1-this.containerFriction)*this.dragSpeed;this.setX(c>e?e+(c-e)*m:c<i?i+(c-i)*m:c,!1),this.setY(d>s?s+(d-s)*m:d<t?t+(d-t)*m:d,!1),this.computeVelocity(r-a,n-l),this.angle=rt(n-h,r-o);const[f,g]=this.snapped;(f!==u&&this.snapX||g!==p&&this.snapY)&&this.onSnap(this)}stop(){this.updateTicker.pause(),this.overshootTicker.pause();for(let t in this.animate.animations)this.animate.animations[t].pause();return rs(this,null,"x"),rs(this,null,"y"),rs(this,null,"progressX"),rs(this,null,"progressY"),rs(this.scroll),rs(this.overshootCoords),this}scrollInView(t,e=0,s=ve.inOutQuad){this.updateScrollCoords();const i=this.destX,r=this.destY,n=this.scroll,o=this.scrollBounds,h=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(o,i,r)){const[a,l,c,u]=o,p=lt(ht(r-a,-1e12,0),0),m=lt(ht(i-l,0,d),0),f=lt(ht(r-c,0,d),0),g=lt(ht(i-u,-1e12,0),0);new Re(n,{x:lt(n.x+(g?g-e:m?m+e:0),0),y:lt(n.y+(p?p-e:f?f+e:0),0),duration:z(t)?350*L.timeScale:t,ease:s,onUpdate:()=>{this.canScroll=!1,this.$scrollContainer.scrollTo(n.x,n.y)}}).init().then((()=>{this.canScroll=h}))}return this}handleHover(){this.isFinePointer&&this.cursor&&!this.cursorStyles&&(this.cursorStyles=ss(this.$trigger,{cursor:this.cursor.onHover}))}animateInView(t,e=0,s=ve.inOutQuad){this.stop(),this.updateBoundingValues();const i=this.x,r=this.y,[n,o,h,a]=this.containerPadding,l=this.scroll.y-this.targetBounds[0]+n+e,c=this.scroll.x-this.targetBounds[1]-o-e,d=this.scroll.y-this.targetBounds[2]-h-e,u=this.scroll.x-this.targetBounds[3]+a+e,p=this.isOutOfBounds([l,c,d,u],i,r);if(p){const[e,n]=this.disabled,o=ht(ct(i,this.snapX),u,c),h=ht(ct(r,this.snapY),l,d),a=z(t)?350*L.timeScale:t;e||1!==p&&3!==p||this.animate[this.xProp](o,a,s),n||2!==p&&3!==p||this.animate[this.yProp](h,a,s)}return this}handleDown(t){const e=t.target;if(this.grabbed||"range"===e.type)return;t.stopPropagation(),this.grabbed=!0,this.released=!1,this.stop(),this.updateBoundingValues();const i=t.changedTouches,r=i?i[0].clientX:t.clientX,n=i?i[0].clientY:t.clientY,{x:o,y:h}=this.transforms.normalizePoint(r,n),[a,l,c,d]=this.containerBounds,u=(1-this.containerFriction)*this.dragSpeed,p=this.x,m=this.y;this.coords[0]=this.coords[2]=u?p>l?l+(p-l)/u:p<d?d+(p-d)/u:p:p,this.coords[1]=this.coords[3]=u?m>c?c+(m-c)/u:m<a?a+(m-a)/u:m:m,this.pointer[0]=o,this.pointer[1]=h,this.pointer[2]=o,this.pointer[3]=h,this.pointer[4]=o,this.pointer[5]=h,this.pointer[6]=o,this.pointer[7]=h,this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null);const f=es(this.$target,"zIndex",!1);xs=(f>xs?f:xs)+1,this.targetStyles=ss(this.$target,{zIndex:xs}),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.isFinePointer&&this.cursor&&(this.bodyStyles=ss(s.body,{cursor:this.cursor.onGrab})),this.scrollInView(100,0,ve.out(3)),this.onGrab(this),s.addEventListener("touchmove",this),s.addEventListener("touchend",this),s.addEventListener("touchcancel",this),s.addEventListener("mousemove",this),s.addEventListener("mouseup",this),s.addEventListener("selectstart",this)}handleMove(t){if(!this.grabbed)return;const e=t.changedTouches,s=e?e[0].clientX:t.clientX,i=e?e[0].clientY:t.clientY,{x:r,y:n}=this.transforms.normalizePoint(s,i),o=r-this.pointer[6],h=n-this.pointer[7];let a=t.target,l=!1,c=!1,d=!1;for(;e&&a&&a!==this.$trigger;){const t=es(a,"overflow-y");if("hidden"!==t&&"visible"!==t){const{scrollTop:t,scrollHeight:e,clientHeight:s}=a;if(e>s){d=!0,l=t<=3,c=t>=e-s-3;break}}a=a.parentNode}d&&(!l&&!c||l&&h<0||c&&h>0)?(this.pointer[0]=r,this.pointer[1]=n,this.pointer[2]=r,this.pointer[3]=n,this.pointer[4]=r,this.pointer[5]=n,this.pointer[6]=r,this.pointer[7]=n):(vs(t),this.triggerStyles||(this.triggerStyles=ss(this.$trigger,{pointerEvents:"none"})),this.$trigger.addEventListener("touchstart",vs,{passive:!1}),this.$trigger.addEventListener("touchmove",vs,{passive:!1}),this.$trigger.addEventListener("touchend",vs),(!this.disabled[0]&&J(o)>3||!this.disabled[1]&&J(h)>3)&&(this.updateTicker.resume(),this.pointer[2]=this.pointer[0],this.pointer[3]=this.pointer[1],this.pointer[0]=r,this.pointer[1]=n,this.dragged=!0,this.released=!1,this.onDrag(this)))}handleUp(){if(!this.grabbed)return;this.updateTicker.pause(),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null);const[t,e]=this.disabled,[r,n,o,h,a,l]=this.pointer,[c,d,u,p]=this.containerBounds,[m,f]=this.snapped,g=this.releaseXSpring,y=this.releaseYSpring,_=this.releaseEase,v=this.hasReleaseSpring,b=this.overshootCoords,T=this.x,w=this.y,x=this.computeVelocity(r-a,n-l),S=this.angle=rt(n-h,r-o),k=150*x,$=(1-this.releaseContainerFriction)*this.dragSpeed,E=T+Z(S)*k,C=w+G(S)*k,B=E>d?d+(E-d)*$:E<p?p+(E-p)*$:E,D=C>u?u+(C-u)*$:C<c?c+(C-c)*$:C,N=this.destX=ht(lt(ct(B,this.snapX),5),p,d),A=this.destY=ht(lt(ct(D,this.snapY),5),c,u),F=this.isOutOfBounds(this.containerBounds,E,C);let O=0,P=0,R=_,M=_,I=0;if(b.x=T,b.y=w,!t){const t=N===d?T>d?-1:1:T<p?-1:1,s=lt(T-N,0);g.velocity=e&&v?s?k*t/J(s):0:x;const{ease:i,duration:r,restDuration:n}=g;O=T===N?0:v?r:r-n*L.timeScale,v&&(R=i),O>I&&(I=O)}if(!e){const e=A===u?w>u?-1:1:w<c?-1:1,s=lt(w-A,0);y.velocity=t&&v?s?k*e/J(s):0:x;const{ease:i,duration:r,restDuration:n}=y;P=w===A?0:v?r:r-n*L.timeScale,v&&(M=i),P>I&&(I=P)}if(!v&&F&&$&&(O||P)){const t=i.blend;new Re(b,{x:{to:B,duration:.65*O},y:{to:D,duration:.65*P},ease:_,composition:t}).init(),new Re(b,{x:{to:N,duration:O},y:{to:A,duration:P},ease:_,composition:t}).init(),this.overshootTicker.stretch(it(O,P)).restart()}else t||this.animate[this.xProp](N,O,R),e||this.animate[this.yProp](A,P,M);this.scrollInView(I,this.scrollThreshold,_);let z=!1;N!==m&&(this.snapped[0]=N,this.snapX&&(z=!0)),A!==f&&this.snapY&&(this.snapped[1]=A,this.snapY&&(z=!0)),z&&this.onSnap(this),this.grabbed=!1,this.dragged=!1,this.updated=!0,this.released=!0,this.onRelease(this),this.$trigger.removeEventListener("touchstart",vs),this.$trigger.removeEventListener("touchmove",vs),this.$trigger.removeEventListener("touchend",vs),s.removeEventListener("touchmove",this),s.removeEventListener("touchend",this),s.removeEventListener("touchcancel",this),s.removeEventListener("mousemove",this),s.removeEventListener("mouseup",this),s.removeEventListener("selectstart",this)}reset(){return this.stop(),this.resizeTicker.pause(),this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.setX(0,!0),this.setY(0,!0),this.coords[0]=0,this.coords[1]=0,this.pointer[0]=0,this.pointer[1]=0,this.pointer[2]=0,this.pointer[3]=0,this.pointer[4]=0,this.pointer[5]=0,this.pointer[6]=0,this.pointer[7]=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this}enable(){return this.enabled||(this.enabled=!0,this.$target.classList.remove("is-disabled"),this.touchActionStyles=ss(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"}),this.$trigger.addEventListener("touchstart",this,{passive:!0}),this.$trigger.addEventListener("mousedown",this,{passive:!0}),this.$trigger.addEventListener("mouseenter",this)),this}disable(){return this.enabled=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.touchActionStyles.revert(),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null),this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null),this.$target.classList.add("is-disabled"),this.$trigger.removeEventListener("touchstart",this),this.$trigger.removeEventListener("mousedown",this),this.$trigger.removeEventListener("mouseenter",this),s.removeEventListener("touchmove",this),s.removeEventListener("touchend",this),s.removeEventListener("touchcancel",this),s.removeEventListener("mousemove",this),s.removeEventListener("mouseup",this),s.removeEventListener("selectstart",this),this}revert(){return this.reset(),this.disable(),this.$target.classList.remove("is-disabled"),this.updateTicker.revert(),this.overshootTicker.revert(),this.resizeTicker.revert(),this.animate.revert(),this.resizeObserver.disconnect(),this}handleEvent(t){switch(t.type){case"mousedown":case"touchstart":this.handleDown(t);break;case"mousemove":case"touchmove":this.handleMove(t);break;case"mouseup":case"touchend":case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":vs(t)}}}const ks=(t,e)=>new Ss(t,e);class $s{constructor(t={}){B.current&&B.current.register(this);const i=t.root;let r=s;i&&(r=i.current||i.nativeElement||At(i)[0]||s);const n=t.defaults,o=L.defaults,h=t.mediaQueries;if(this.defaults=n?yt(n,o):o,this.root=r,this.constructors=[],this.revertConstructors=[],this.revertibles=[],this.constructorsOnce=[],this.revertConstructorsOnce=[],this.revertiblesOnce=[],this.once=!1,this.onceIndex=0,this.methods={},this.matches={},this.mediaQueryLists={},this.data={},h)for(let t in h){const s=e.matchMedia(h[t]);this.mediaQueryLists[t]=s,s.addEventListener("change",this)}}register(t){(this.once?this.revertiblesOnce:this.revertibles).push(t)}execute(t){let e=B.current,s=B.root,i=L.defaults;B.current=this,B.root=this.root,L.defaults=this.defaults;const r=this.mediaQueryLists;for(let t in r)this.matches[t]=r[t].matches;const n=t(this);return B.current=e,B.root=s,L.defaults=i,n}refresh(){return this.onceIndex=0,this.execute((()=>{let t=this.revertibles.length,e=this.revertConstructors.length;for(;t--;)this.revertibles[t].revert();for(;e--;)this.revertConstructors[e](this);this.revertibles.length=0,this.revertConstructors.length=0,this.constructors.forEach((t=>{const e=t(this);I(e)&&this.revertConstructors.push(e)}))})),this}add(t,e){if(this.once=!1,I(t)){const e=t;this.constructors.push(e),this.execute((()=>{const t=e(this);I(t)&&this.revertConstructors.push(t)}))}else this.methods[t]=(...t)=>this.execute((()=>e(...t)));return this}addOnce(t){if(this.once=!0,I(t)){const e=this.onceIndex++;if(this.constructorsOnce[e])return this;const s=t;this.constructorsOnce[e]=s,this.execute((()=>{const t=s(this);I(t)&&this.revertConstructorsOnce.push(t)}))}return this}keepTime(t){this.once=!0;const e=this.onceIndex++,s=this.constructorsOnce[e];if(I(s))return s(this);const i=Tt(t);let r;return this.constructorsOnce[e]=i,this.execute((()=>{r=i(this)})),r}handleEvent(t){"change"===t.type&&this.refresh()}revert(){const t=this.revertibles,e=this.revertConstructors,s=this.revertiblesOnce,i=this.revertConstructorsOnce,r=this.mediaQueryLists;let n=t.length,o=e.length,h=s.length,a=i.length;for(;n--;)t[n].revert();for(;o--;)e[o](this);for(;h--;)s[h].revert();for(;a--;)i[a](this);for(let t in r)r[t].removeEventListener("change",this);t.length=0,e.length=0,this.constructors.length=0,s.length=0,i.length=0,this.constructorsOnce.length=0,this.onceIndex=0,this.matches={},this.methods={},this.mediaQueryLists={},this.data={}}}const Es=t=>new $s(t),Cs=(t,e)=>t&&I(t)?t(e):t,Bs=new Map;class Ls{constructor(t){this.element=t,this.useWin=this.element===s.body,this.winWidth=0,this.winHeight=0,this.width=0,this.height=0,this.left=0,this.top=0,this.zIndex=0,this.scrollX=0,this.scrollY=0,this.prevScrollX=0,this.prevScrollY=0,this.scrollWidth=0,this.scrollHeight=0,this.velocity=0,this.backwardX=!1,this.backwardY=!1,this.scrollTicker=new ne({autoplay:!1,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const t=this.backwardX||this.backwardY;_t(this,(t=>t.handleScroll()),t)},onComplete:()=>this.dataTimer.pause()}).init(),this.dataTimer=new ne({autoplay:!1,frameRate:30,onUpdate:t=>{const e=t.deltaTime,s=this.prevScrollX,i=this.prevScrollY,r=this.scrollX,n=this.scrollY,o=s-r,h=i-n;this.prevScrollX=r,this.prevScrollY=n,o&&(this.backwardX=s>r),h&&(this.backwardY=i>n),this.velocity=lt(e>0?Math.sqrt(o*o+h*h)/e:0,5)}}).init(),this.resizeTicker=new ne({autoplay:!1,duration:250*L.timeScale,onComplete:()=>{this.updateWindowBounds(),this.refreshScrollObservers(),this.handleScroll()}}).init(),this.wakeTicker=new ne({autoplay:!1,duration:500*L.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init(),this._head=null,this._tail=null,this.updateScrollCoords(),this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll(),this.resizeObserver=new ResizeObserver((()=>this.resizeTicker.restart())),this.resizeObserver.observe(this.element),(this.useWin?e:this.element).addEventListener("scroll",this,!1)}updateScrollCoords(){const t=this.useWin,s=this.element;this.scrollX=lt(t?e.scrollX:s.scrollLeft,0),this.scrollY=lt(t?e.scrollY:s.scrollTop,0)}updateWindowBounds(){this.winWidth=e.innerWidth,this.winHeight=(()=>{const t=s.createElement("div");s.body.appendChild(t),t.style.height="100lvh";const e=t.offsetHeight;return s.body.removeChild(t),e})()}updateBounds(){const t=getComputedStyle(this.element),e=this.element;let s,i;if(this.scrollWidth=e.scrollWidth+parseFloat(t.marginLeft)+parseFloat(t.marginRight),this.scrollHeight=e.scrollHeight+parseFloat(t.marginTop)+parseFloat(t.marginBottom),this.updateWindowBounds(),this.useWin)s=this.winWidth,i=this.winHeight;else{const t=e.getBoundingClientRect();s=e.clientWidth,i=e.clientHeight,this.top=t.top,this.left=t.left}this.width=s,this.height=i}refreshScrollObservers(){_t(this,(t=>{t._debug&&t.removeDebug()})),this.updateBounds(),_t(this,(t=>{t.refresh(),t._debug&&t.debug()}))}refresh(){this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll()}handleScroll(){this.updateScrollCoords(),this.wakeTicker.restart()}handleEvent(t){"scroll"===t.type&&this.handleScroll()}revert(){this.scrollTicker.cancel(),this.dataTimer.cancel(),this.resizeTicker.cancel(),this.wakeTicker.cancel(),this.resizeObserver.disconnect(),(this.useWin?e:this.element).removeEventListener("scroll",this),Bs.delete(this.element)}}const Ds=(t,e,s,i,r)=>{const n="min"===e,o="max"===e,h="top"===e||"left"===e||"start"===e||n?0:"bottom"===e||"right"===e||"end"===e||o?"100%":"center"===e?"50%":e,{n:a,u:l}=qt(h,jt);let c=a;return"%"===l?c=a/100*s:l&&(c=$e(t,jt,"px",!0).n),o&&i<0&&(c+=i),n&&r>0&&(c+=r),c},Ns=(t,e,s,i,r)=>{let n;if(M(e)){const o=E.exec(e);if(o){const h=o[0],a=h[0],l=e.split(h),c="min"===l[0],d="max"===l[0],u=Ds(t,l[0],s,i,r),p=Ds(t,l[1],s,i,r);if(c){const e=Ut(Ds(t,"min",s),p,a);n=e<u?u:e}else if(d){const e=Ut(Ds(t,"max",s),p,a);n=e>u?u:e}else n=Ut(u,p,a)}else n=Ds(t,e,s,i,r)}else n=e;return lt(n,0)},As=t=>{let e;const s=t.targets;for(let t=0,i=s.length;t<i;t++){const i=s[t];if(i[n]){e=i;break}}return e};let Fs=0;const Os=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class Ps{constructor(t={}){B.current&&B.current.register(this);const e=Yt(t.sync,"play pause"),i=e?Te(e):null,r=e&&("linear"===e||e===he),n=e&&!(i===he&&!r),o=e&&(R(e)||!0===e||r),h=e&&M(e)&&!n&&!o,a=h?e.split(" ").map((t=>()=>{const e=this.linked;return e&&e[t]?e[t]():null})):null,l=h&&a.length>2;this.index=Fs++,this.id=z(t.id)?this.index:t.id,this.container=(t=>{const e=t&&At(t)[0]||s.body;let i=Bs.get(e);return i||(i=new Ls(e),Bs.set(e,i)),i})(t.container),this.target=null,this.linked=null,this.repeat=null,this.horizontal=null,this.enter=null,this.leave=null,this.sync=n||o||!!a,this.syncEase=n?i:null,this.syncSmooth=o?!0===e||r?1:e:null,this.onSyncEnter=a&&!l&&a[0]?a[0]:y,this.onSyncLeave=a&&!l&&a[1]?a[1]:y,this.onSyncEnterForward=a&&l&&a[0]?a[0]:y,this.onSyncLeaveForward=a&&l&&a[1]?a[1]:y,this.onSyncEnterBackward=a&&l&&a[2]?a[2]:y,this.onSyncLeaveBackward=a&&l&&a[3]?a[3]:y,this.onEnter=t.onEnter||y,this.onLeave=t.onLeave||y,this.onEnterForward=t.onEnterForward||y,this.onLeaveForward=t.onLeaveForward||y,this.onEnterBackward=t.onEnterBackward||y,this.onLeaveBackward=t.onLeaveBackward||y,this.onUpdate=t.onUpdate||y,this.onSyncComplete=t.onSyncComplete||y,this.reverted=!1,this.completed=!1,this.began=!1,this.isInView=!1,this.forceEnter=!1,this.hasEntered=!1,this.offset=0,this.offsetStart=0,this.offsetEnd=0,this.distance=0,this.prevProgress=0,this.thresholds=["start","end","end","start"],this.coords=[0,0,0,0],this.debugStyles=null,this.$debug=null,this._params=t,this._debug=Yt(t.debug,!1),this._next=null,this._prev=null,bt(this.container,this),ts((()=>{if(!this.reverted){if(!this.target){const e=At(t.target)[0];this.target=e||s.body,this.refresh()}this._debug&&this.debug()}}))}link(t){if(t&&(t.pause(),this.linked=t,!this._params.target)){let e;z(t.targets)?_t(t,(t=>{t.targets&&!e&&(e=As(t))})):e=As(t),this.target=e||s.body,this.refresh()}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const t=(this.scroll-this.offsetStart)/this.distance;return t===1/0||isNaN(t)?0:lt(ht(t,0,1),6)}refresh(){this.reverted=!1;const t=this._params;return this.repeat=Yt(Cs(t.repeat,this),!0),this.horizontal="x"===Yt(Cs(t.axis,this),"y"),this.enter=Yt(Cs(t.enter,this),"end start"),this.leave=Yt(Cs(t.leave,this),"start end"),this.updateBounds(),this.handleScroll(),this}removeDebug(){return this.$debug&&(this.$debug.parentNode.removeChild(this.$debug),this.$debug=null),this.debugStyles&&(this.debugStyles.revert(),this.$debug=null),this}debug(){this.removeDebug();const t=this.container,e=this.horizontal,i=t.element.querySelector(":scope > .animejs-onscroll-debug"),r=s.createElement("div"),n=s.createElement("div"),o=s.createElement("div"),h=Os[this.index%Os.length],a=t.useWin,l=a?t.winWidth:t.width,c=a?t.winHeight:t.height,d=t.scrollWidth,u=t.scrollHeight,p=this.container.width>360?320:260,m=e?0:10,f=e?10:0,g=e?24:p/2,y=e?g:15,_=e?60:g,v=e?_:y,b=e?"repeat-x":"repeat-y",T=t=>e?"0px "+t+"px":t+"px 2px",w=t=>`linear-gradient(${e?90:0}deg, ${t} 2px, transparent 1px)`,x=(t,e,s,i,r)=>`position:${t};left:${e}px;top:${s}px;width:${i}px;height:${r}px;`;r.style.cssText=`${x("absolute",m,f,e?d:p,e?p:u)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${e?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `,n.style.cssText=`${x("sticky",0,0,e?l:g,e?g:c)}`,i||(n.style.cssText+=`background:\n ${w("#FFFF")}${T(g-10)} / 100px 100px ${b},\n ${w("#FFF8")}${T(g-10)} / 10px 10px ${b};\n `),o.style.cssText=`${x("relative",0,0,e?d:g,e?g:u)}`,i||(o.style.cssText+=`background:\n ${w("#FFFF")}${T(0)} / ${e?"100px 10px":"10px 100px"} ${b},\n ${w("#FFF8")}${T(0)} / ${e?"10px 0px":"0px 10px"} ${b};\n `);const S=[" enter: "," leave: "];this.coords.forEach(((t,i)=>{const r=i>1,a=(r?0:this.offset)+t,m=i%2,f=a<v,g=a>(r?e?l:c:e?d:u)-v,b=(r?m&&!f:!m&&!f)||g,T=s.createElement("div"),w=s.createElement("div"),k=e?b?"right":"left":b?"bottom":"top",$=b?(e?_:y)+(r?e?-1:g?0:-2:e?-1:-2):e?1:0;w.innerHTML=`${this.id}${S[m]}${this.thresholds[i]}`,T.style.cssText=`${x("absolute",0,0,_,y)}\n display: flex;\n flex-direction: ${e?"column":"row"};\n justify-content: flex-${r?"start":"end"};\n align-items: flex-${b?"end":"start"};\n border-${k}: 2px solid ${h};\n `,w.style.cssText=`\n overflow: hidden;\n max-width: ${p/2-10}px;\n height: ${y};\n margin-${e?b?"right":"left":b?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${e&&b||!e&&!r?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${m?h:"rgba(0,0,0,.75)"};\n background-color: ${m?"rgba(0,0,0,.65)":h};\n border: 2px solid ${m?h:"transparent"};\n border-${e?b?"top-left":"top-right":b?"top-left":"bottom-left"}-radius: 5px;\n border-${e?b?"bottom-left":"bottom-right":b?"top-right":"bottom-right"}-radius: 5px;\n `,T.appendChild(w);let E=a-$+(e?1:0);T.style[e?"left":"top"]=`${E}px`,(r?n:o).appendChild(T)})),r.appendChild(n),r.appendChild(o),t.element.appendChild(r),i||r.classList.add("animejs-onscroll-debug"),this.$debug=r,"static"===es(t.element,"position")&&(this.debugStyles=ss(t.element,{position:"relative "}))}updateBounds(){let t;this._debug&&this.removeDebug();const e=this.target,i=this.container,r=this.horizontal,n=this.linked;let o,h=e;for(n&&(o=n.currentTime,n.seek(0,!0)),h.parentElement;h&&h!==i.element&&h!==s.body;){const e="sticky"===es(h,"position")&&ss(h,{position:"static"});h=h.parentElement,e&&(t||(t=[]),t.push(e))}const a=e.getBoundingClientRect(),l=r?a.left+i.scrollX-i.left:a.top+i.scrollY-i.top,c=r?a.width:a.height,d=r?i.width:i.height,u=(r?i.scrollWidth:i.scrollHeight)-d,p=this.enter,m=this.leave;let f="start",g="end",y="end",_="start";if(M(p)){const t=p.split(" ");y=t[0],f=t.length>1?t[1]:f}else if(P(p)){const t=p;z(t.container)||(y=t.container),z(t.target)||(f=t.target)}else R(p)&&(y=p);if(M(m)){const t=m.split(" ");_=t[0],g=t.length>1?t[1]:g}else if(P(m)){const t=m;z(t.container)||(_=t.container),z(t.target)||(g=t.target)}else R(m)&&(_=m);const v=Ns(e,f,c),b=Ns(e,g,c),T=v+l-d,w=b+l-u,x=Ns(e,y,d,T,w),S=Ns(e,_,d,T,w),k=v+l-x,$=b+l-S,E=$-k;this.offset=l,this.offsetStart=k,this.offsetEnd=$,this.distance=E<=0?0:E,this.thresholds=[f,g,y,_],this.coords=[v,b,x,S],t&&t.forEach((t=>t.revert())),n&&n.seek(o,!0),this._debug&&this.debug()}handleScroll(){const t=this.linked,e=this.sync,s=this.syncEase,i=this.syncSmooth,r=t&&(s||i),n=this.horizontal,o=this.container,h=this.scroll,a=h<=this.offsetStart,l=h>=this.offsetEnd,c=!a&&!l,d=h===this.offsetStart||h===this.offsetEnd,u=!this.hasEntered&&d,p=this._debug&&this.$debug;let m=!1,f=!1,g=this.progress;if(a&&this.began&&(this.began=!1),g>0&&!this.began&&(this.began=!0),r){const e=t.progress;if(i&&R(i)){if(i<1){const t=e<g&&1===g?1e-4:e>g&&!g?-1e-4:0;g=lt(os(e,g,dt(.01,.2,i),!1)+t,6)}}else s&&(g=s(g));m=g!==this.prevProgress,f=1===e,m&&!f&&i&&e&&o.wakeTicker.restart()}if(p){const t=n?o.scrollY:o.scrollX;p.style[n?"top":"left"]=t+10+"px"}(c&&!this.isInView||u&&!this.forceEnter&&!this.hasEntered)&&(c&&(this.isInView=!0),this.forceEnter&&this.hasEntered?c&&(this.forceEnter=!1):(p&&c&&(p.style.zIndex=""+this.container.zIndex++),this.onSyncEnter(this),this.onEnter(this),this.backward?(this.onSyncEnterBackward(this),this.onEnterBackward(this)):(this.onSyncEnterForward(this),this.onEnterForward(this)),this.hasEntered=!0,u&&(this.forceEnter=!0))),(c||!c&&this.isInView)&&(m=!0),m&&(r&&t.seek(t.duration*g),this.onUpdate(this)),!c&&this.isInView&&(this.isInView=!1,this.onSyncLeave(this),this.onLeave(this),this.backward?(this.onSyncLeaveBackward(this),this.onLeaveBackward(this)):(this.onSyncLeaveForward(this),this.onLeaveForward(this)),e&&!i&&(f=!0)),g>=1&&this.began&&!this.completed&&(e&&f||!e)&&(e&&this.onSyncComplete(this),this.completed=!0,(!this.repeat&&!t||!this.repeat&&t&&t.completed)&&this.revert()),g<1&&this.completed&&(this.completed=!1),this.prevProgress=g}revert(){if(this.reverted)return;const t=this.container;return vt(t,this),t._head||t.revert(),this._debug&&this.removeDebug(),this.reverted=!0,this}}const Rs=(t={})=>new Ps(t),Ms="undefined"!=typeof Intl&&Intl.Segmenter,Is=/\{value\}/g,zs=/\{i\}/g,Ys=/(\s+)/,Xs=/^\s+$/,Ws="line",Vs="word",Hs="char",Us="data-line";let qs=null,Qs=null,js=null;const Gs=t=>t.isWordLike||" "===t.segment||R(+t.segment),Zs=t=>t.setAttribute("aria-hidden","true"),Js=(t,e)=>[...t.querySelectorAll(`[data-${e}]:not([data-${e}] [data-${e}])`)],Ks={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"},ti=t=>{if(!t.childElementCount&&!t.textContent.trim()){const e=t.parentElement;t.remove(),e&&ti(e)}},ei=(t,e,s)=>{const i=t.getAttribute(Us);(null!==i&&+i!==e||"BR"===t.tagName)&&s.add(t);let r=t.childElementCount;for(;r--;)ei(t.children[r],e,s);return s},si=(t,e={})=>{let s="";const i=M(e.class)?` class="${e.class}"`:"",r=Yt(e.clone,!1),n=Yt(e.wrap,!1),o=n?!0===n?"clip":n:!!r&&"clip";return n&&(s+=`<span${o?` style="overflow:${o};"`:""}>`),s+=`<span${i}${r?' style="position:relative;"':""} data-${t}="{i}">`,r?(s+="<span>{value}</span>",s+=`<span inert style="position:absolute;top:${"top"===r?"-100%":"bottom"===r?"100%":"0"};left:${"left"===r?"-100%":"right"===r?"100%":"0"};white-space:nowrap;">{value}</span>`):s+="{value}",s+="</span>",n&&(s+="</span>"),s},ii=(t,e,s,i,r,n,o,h,a)=>{const l=r===Ws,c=r===Hs,d=`_${r}_`,u=I(t)?t(s):t,p=l?"block":"inline-block";js.innerHTML=u.replace(Is,`<i class="${d}"></i>`).replace(zs,`${c?a:l?o:h}`);const m=js.content,f=m.firstElementChild,g=m.querySelector(`[data-${r}]`)||f,y=m.querySelectorAll(`i.${d}`),_=y.length;if(_){f.style.display=p,g.style.display=p,g.setAttribute(Us,`${o}`),l||(g.setAttribute("data-word",`${h}`),c&&g.setAttribute("data-char",`${a}`));let t=_;for(;t--;){const e=y[t],i=e.parentElement;i.style.display=p,l?i.innerHTML=s.innerHTML:i.replaceChild(s.cloneNode(!0),e)}e.push(g),i.appendChild(m)}else console.warn('The expression "{value}" is missing from the provided template.');return n&&(f.style.outline=`1px dotted ${Ks[r]}`),f};class ri{constructor(e,i={}){qs||(qs=Ms?new Ms([],{granularity:Vs}):{segment:t=>{const e=[],s=t.split(Ys);for(let t=0,i=s.length;t<i;t++){const i=s[t];e.push({segment:i,isWordLike:!Xs.test(i)})}return e}}),Qs||(Qs=Ms?new Ms([],{granularity:"grapheme"}):{segment:t=>[...t].map((t=>({segment:t})))}),!js&&t&&(js=s.createElement("template")),B.current&&B.current.register(this);const{words:r,chars:n,lines:o,accessible:h,includeSpaces:a,debug:l}=i,c=(e=O(e)?e[0]:e)&&e.nodeType?e:(Nt(e)||[])[0],d=!0===o?{}:o,u=!0===r||z(r)?{}:r,p=!0===n?{}:n;this.debug=Yt(l,!1),this.includeSpaces=Yt(a,!1),this.accessible=Yt(h,!0),this.linesOnly=d&&!u&&!p,this.lineTemplate=P(d)?si(Ws,d):d,this.wordTemplate=P(u)||this.linesOnly?si(Vs,u):u,this.charTemplate=P(p)?si(Hs,p):p,this.$target=c,this.html=c&&c.innerHTML,this.lines=[],this.words=[],this.chars=[],this.effects=[],this.effectsCleanups=[],this.cache=null,this.ready=!1,this.width=0,this.resizeTimeout=null;const m=()=>this.html&&(d||u||p)&&this.split();this.resizeObserver=new ResizeObserver((()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout((()=>{const t=c.offsetWidth;t!==this.width&&(this.width=t,m())}),150)})),this.lineTemplate&&!this.ready?s.fonts.ready.then(m):m(),c?this.resizeObserver.observe(c):console.warn("No Text Splitter target found.")}addEffect(t){if(!I(t))return console.warn("Effect must return a function.");const e=Tt(t);return this.effects.push(e),this.ready&&(this.effectsCleanups[this.effects.length-1]=e(this)),this}revert(){return clearTimeout(this.resizeTimeout),this.lines.length=this.words.length=this.chars.length=0,this.resizeObserver.disconnect(),this.effectsCleanups.forEach((t=>I(t)?t(this):t.revert&&t.revert())),this.$target.innerHTML=this.html,this}splitNode(t){const e=this.wordTemplate,i=this.charTemplate,r=this.includeSpaces,n=this.debug,o=t.nodeType;if(3===o){const o=t.nodeValue;if(o.trim()){const h=[],a=this.words,l=this.chars,c=qs.segment(o),d=s.createDocumentFragment();let u=null;for(const t of c){const e=t.segment,s=Gs(t);if(!u||s&&u&&Gs(u))h.push(e);else{const t=h.length-1;h[t].includes(" ")||e.includes(" ")?h.push(e):h[t]+=e}u=t}for(let t=0,o=h.length;t<o;t++){const o=h[t];if(o.trim()){const c=h[t+1],u=r&&c&&!c.trim(),p=o,m=i?Qs.segment(p):null,f=i?s.createDocumentFragment():s.createTextNode(u?o+" ":o);if(i){const t=[...m];for(let e=0,r=t.length;e<r;e++){const o=t[e],h=e===r-1&&u?o.segment+" ":o.segment,c=s.createTextNode(h);ii(i,l,c,f,Hs,n,-1,a.length,l.length)}}e?ii(e,a,f,d,Vs,n,-1,a.length,l.length):i?d.appendChild(f):d.appendChild(s.createTextNode(o)),u&&t++}else{if(t&&r)continue;d.appendChild(s.createTextNode(o))}}t.parentNode.replaceChild(d,t)}}else if(1===o){const e=[...t.childNodes];for(let t=0,s=e.length;t<s;t++)this.splitNode(e[t])}}split(t=!1){const e=this.$target,i=!!this.cache&&!t,r=this.lineTemplate,n=this.wordTemplate,o=this.charTemplate,h="loading"!==s.fonts.status,a=r&&h;this.ready=!r||h,(a||t)&&this.effectsCleanups.forEach((t=>I(t)&&t(this))),i||(t&&(e.innerHTML=this.html,this.words.length=this.chars.length=0),this.splitNode(e),this.cache=e.innerHTML),a&&(i&&(e.innerHTML=this.cache),this.lines.length=0,n&&(this.words=Js(e,Vs))),o&&(a||n)&&(this.chars=Js(e,Hs));const l=this.words.length?this.words:this.chars;let c,d=0;for(let t=0,e=l.length;t<e;t++){const e=l[t],{top:s,height:i}=e.getBoundingClientRect();c&&s-c>.5*i&&d++,e.setAttribute(Us,`${d}`);const r=e.querySelectorAll(`[${Us}]`);let n=r.length;for(;n--;)r[n].setAttribute(Us,`${d}`);c=s}if(a){const t=s.createDocumentFragment(),i=new Set,h=[];for(let t=0;t<d+1;t++){const s=e.cloneNode(!0);ei(s,t,new Set).forEach((t=>{const e=t.parentElement;e&&i.add(e),t.remove()})),h.push(s)}i.forEach(ti);for(let e=0,s=h.length;e<s;e++)ii(r,this.lines,h[e],t,Ws,this.debug,e);e.innerHTML="",e.appendChild(t),n&&(this.words=Js(e,Vs)),o&&(this.chars=Js(e,Hs))}if(this.linesOnly){const t=this.words;let e=t.length;for(;e--;){const s=t[e];s.replaceWith(s.textContent)}t.length=0}if(this.accessible&&(a||!i)){const t=s.createElement("span");t.style.cssText="position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;",t.innerHTML=this.html,e.insertBefore(t,e.firstChild),this.lines.forEach(Zs),this.words.forEach(Zs),this.chars.forEach(Zs)}return this.width=e.offsetWidth,(a||t)&&this.effects.forEach(((t,e)=>this.effectsCleanups[e]=t(this))),this}refresh(){this.split(!0)}}const ni={split:(t,e)=>new ri(t,e)},oi=(t,e={})=>{let s=[],i=0;const r=e.from,n=e.reversed,o=e.ease,h=!z(o),a=h&&!z(o.ease)?o.ease:h?Te(o):null,l=e.grid,c=e.axis,d=e.total,u=z(r)||0===r||"first"===r,m="center"===r,f="last"===r,g="random"===r,y=O(t),_=e.use,v=q(y?t[0]:t),b=y?q(t[1]):0,T=S.exec((y?t[1]:t)+p),w=e.start||0+(y?v:0);let x=u?0:R(r)?r:0;return(t,r,o,h)=>{const[u]=Ft(t),p=z(d)?o:d,S=!z(_)&&(I(_)?_(u,r,p):Ht(u,_)),k=R(S)||M(S)&&R(+S)?+S:r;if(m&&(x=(p-1)/2),f&&(x=p-1),!s.length){for(let t=0;t<p;t++){if(l){const e=m?(l[0]-1)/2:x%l[0],i=m?(l[1]-1)/2:et(x/l[0]),r=e-t%l[0],n=i-et(t/l[0]);let o=j(r*r+n*n);"x"===c&&(o=-r),"y"===c&&(o=-n),s.push(o)}else s.push(J(x-t));i=it(...s)}a&&(s=s.map((t=>a(t/i)*i))),n&&(s=s.map((t=>c?t<0?-1*t:-t:J(i-t)))),g&&(s=pt(s))}const $=y?(b-v)/i:v;let E=(h?cs(h,z(e.start)?h.iterationDuration:w):w)+($*lt(s[k],2)||0);return e.modifier&&(E=e.modifier(E)),T&&(E=`${E}${T[2]}`),E}};export{ms as Animatable,Ss as Draggable,Re as JSAnimation,$s as Scope,Ps as ScrollObserver,ys as Spring,ri as TextSplitter,us as Timeline,ne as Timer,Je as WAAPIAnimation,Me as animate,fs as createAnimatable,ks as createDraggable,Es as createScope,_s as createSpring,ps as createTimeline,oe as createTimer,ve as eases,Bt as engine,Rs as onScroll,Bs as scrollContainers,oi as stagger,It as svg,ni as text,ls as utils,Ke as waapi};
diff --git a/lib/anime.iife.js b/lib/anime.iife.js
deleted file mode 100644
index 7033b414..00000000
--- a/lib/anime.iife.js
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * anime.js - IIFE
- * @version v4.1.3
- * @author Julian Garnier
- * @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
- */
-var anime=function(exports){"use strict";const isBrowser=typeof window!=="undefined";const win=isBrowser?window:null;const doc=isBrowser?document:null;const tweenTypes={OBJECT:0,ATTRIBUTE:1,CSS:2,TRANSFORM:3,CSS_VAR:4};const valueTypes={NUMBER:0,UNIT:1,COLOR:2,COMPLEX:3};const tickModes={NONE:0,AUTO:1,FORCE:2};const compositionTypes={replace:0,none:1,blend:2};const isRegisteredTargetSymbol=Symbol();const isDomSymbol=Symbol();const isSvgSymbol=Symbol();const transformsSymbol=Symbol();const morphPointsSymbol=Symbol();const proxyTargetSymbol=Symbol();const minValue=1e-11;const maxValue=1e12;const K=1e3;const maxFps=120;const emptyString="";const shortTransforms=(()=>{const map=new Map;map.set("x","translateX");map.set("y","translateY");map.set("z","translateZ");return map})();const validTransforms=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"];const transformsFragmentStrings=validTransforms.reduce(((a,v)=>({...a,[v]:v+"("})),{});const noop=()=>{};const hexTestRgx=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;const rgbExecRgx=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;const rgbaExecRgx=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;const hslExecRgx=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;const hslaExecRgx=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;const digitWithExponentRgx=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;const unitsExecRgx=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;const lowerCaseRgx=/([a-z])([A-Z])/g;const transformsExecRgx=/(\w+)(\([^)]+\)+)/g;const relativeValuesExecRgx=/(\*=|\+=|-=)/;const defaults={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:maxFps,loop:0,reversed:false,alternate:false,autoplay:true,duration:K,delay:0,loopDelay:0,ease:"out(2)",composition:compositionTypes.replace,modifier:v=>v,onBegin:noop,onBeforeUpdate:noop,onUpdate:noop,onLoop:noop,onPause:noop,onComplete:noop,onRender:noop};const scope={current:null,root:doc};const globals={defaults:defaults,precision:4,timeScale:1,tickThreshold:200};const globalVersions={version:"4.1.3",engine:null};if(isBrowser){if(!win.AnimeJS)win.AnimeJS=[];win.AnimeJS.push(globalVersions)}const toLowerCase=str=>str.replace(lowerCaseRgx,"$1-$2").toLowerCase();const stringStartsWith=(str,sub)=>str.indexOf(sub)===0;const now=Date.now;const isArr=Array.isArray;const isObj=a=>a&&a.constructor===Object;const isNum=a=>typeof a==="number"&&!isNaN(a);const isStr=a=>typeof a==="string";const isFnc=a=>typeof a==="function";const isUnd=a=>typeof a==="undefined";const isNil=a=>isUnd(a)||a===null;const isSvg=a=>isBrowser&&a instanceof SVGElement;const isHex=a=>hexTestRgx.test(a);const isRgb=a=>stringStartsWith(a,"rgb");const isHsl=a=>stringStartsWith(a,"hsl");const isCol=a=>isHex(a)||isRgb(a)||isHsl(a);const isKey=a=>!globals.defaults.hasOwnProperty(a);const parseNumber=str=>isStr(str)?parseFloat(str):str;const pow=Math.pow;const sqrt=Math.sqrt;const sin=Math.sin;const cos=Math.cos;const abs=Math.abs;const exp=Math.exp;const ceil=Math.ceil;const floor=Math.floor;const asin=Math.asin;const max=Math.max;const atan2=Math.atan2;const PI=Math.PI;const _round=Math.round;const clamp=(v,min,max)=>v<min?min:v>max?max:v;const powCache={};const round=(v,decimalLength)=>{if(decimalLength<0)return v;if(!decimalLength)return _round(v);let p=powCache[decimalLength];if(!p)p=powCache[decimalLength]=10**decimalLength;return _round(v*p)/p};const snap=(v,increment)=>isArr(increment)?increment.reduce(((closest,cv)=>abs(cv-v)<abs(closest-v)?cv:closest)):increment?_round(v/increment)*increment:v;const interpolate=(start,end,progress)=>start+(end-start)*progress;const random=(min,max,decimalLength)=>{const m=10**(decimalLength||0);return floor((Math.random()*(max-min+1/m)+min)*m)/m};const shuffle=items=>{let m=items.length,t,i;while(m){i=random(0,--m);t=items[m];items[m]=items[i];items[i]=t}return items};const clampInfinity=v=>v===Infinity?maxValue:v===-Infinity?-1e12:v;const normalizeTime=v=>v<=minValue?minValue:clampInfinity(round(v,11));const cloneArray=a=>isArr(a)?[...a]:a;const mergeObjects=(o1,o2)=>{const merged={...o1};for(let p in o2){const o1p=o1[p];merged[p]=isUnd(o1p)?o2[p]:o1p}return merged};const forEachChildren=(parent,callback,reverse,prevProp="_prev",nextProp="_next")=>{let next=parent._head;let adjustedNextProp=nextProp;if(reverse){next=parent._tail;adjustedNextProp=prevProp}while(next){const currentNext=next[adjustedNextProp];callback(next);next=currentNext}};const removeChild=(parent,child,prevProp="_prev",nextProp="_next")=>{const prev=child[prevProp];const next=child[nextProp];prev?prev[nextProp]=next:parent._head=next;next?next[prevProp]=prev:parent._tail=prev;child[prevProp]=null;child[nextProp]=null};const addChild=(parent,child,sortMethod,prevProp="_prev",nextProp="_next")=>{let prev=parent._tail;while(prev&&sortMethod&&sortMethod(prev,child))prev=prev[prevProp];const next=prev?prev[nextProp]:parent._head;prev?prev[nextProp]=child:parent._head=child;next?next[prevProp]=child:parent._tail=child;child[prevProp]=prev;child[nextProp]=next};const createRefreshable=constructor=>{let tracked;return(...args)=>{let currentIteration,currentIterationProgress,reversed,alternate;if(tracked){currentIteration=tracked.currentIteration;currentIterationProgress=tracked.iterationProgress;reversed=tracked.reversed;alternate=tracked._alternate;tracked.revert()}const cleanup=constructor(...args);if(cleanup&&!isFnc(cleanup)&&cleanup.revert)tracked=cleanup;if(!isUnd(currentIterationProgress)){tracked.currentIteration=currentIteration;tracked.iterationProgress=(alternate?!(currentIteration%2)?reversed:!reversed:reversed)?1-currentIterationProgress:currentIterationProgress}return cleanup||noop}};class Clock{constructor(initTime=0){this.deltaTime=0;this._currentTime=initTime;this._elapsedTime=initTime;this._startTime=initTime;this._lastTime=initTime;this._scheduledTime=0;this._frameDuration=round(K/maxFps,0);this._fps=maxFps;this._speed=1;this._hasChildren=false;this._head=null;this._tail=null}get fps(){return this._fps}set fps(frameRate){const previousFrameDuration=this._frameDuration;const fr=+frameRate;const fps=fr<minValue?minValue:fr;const frameDuration=round(K/fps,0);this._fps=fps;this._frameDuration=frameDuration;this._scheduledTime+=frameDuration-previousFrameDuration}get speed(){return this._speed}set speed(playbackRate){const pbr=+playbackRate;this._speed=pbr<minValue?minValue:pbr}requestTick(time){const scheduledTime=this._scheduledTime;const elapsedTime=this._elapsedTime;this._elapsedTime+=time-elapsedTime;if(elapsedTime<scheduledTime)return tickModes.NONE;const frameDuration=this._frameDuration;const frameDelta=elapsedTime-scheduledTime;this._scheduledTime+=frameDelta<frameDuration?frameDuration:frameDelta;return tickModes.AUTO}computeDeltaTime(time){const delta=time-this._lastTime;this.deltaTime=delta;this._lastTime=time;return delta}}const render=(tickable,time,muteCallbacks,internalRender,tickMode)=>{const parent=tickable.parent;const duration=tickable.duration;const completed=tickable.completed;const iterationDuration=tickable.iterationDuration;const iterationCount=tickable.iterationCount;const _currentIteration=tickable._currentIteration;const _loopDelay=tickable._loopDelay;const _reversed=tickable._reversed;const _alternate=tickable._alternate;const _hasChildren=tickable._hasChildren;const tickableDelay=tickable._delay;const tickablePrevAbsoluteTime=tickable._currentTime;const tickableEndTime=tickableDelay+iterationDuration;const tickableAbsoluteTime=time-tickableDelay;const tickablePrevTime=clamp(tickablePrevAbsoluteTime,-tickableDelay,duration);const tickableCurrentTime=clamp(tickableAbsoluteTime,-tickableDelay,duration);const deltaTime=tickableAbsoluteTime-tickablePrevAbsoluteTime;const isCurrentTimeAboveZero=tickableCurrentTime>0;const isCurrentTimeEqualOrAboveDuration=tickableCurrentTime>=duration;const isSetter=duration<=minValue;const forcedTick=tickMode===tickModes.FORCE;let isOdd=0;let iterationElapsedTime=tickableAbsoluteTime;let hasRendered=0;if(iterationCount>1){const currentIteration=~~(tickableCurrentTime/(iterationDuration+(isCurrentTimeEqualOrAboveDuration?0:_loopDelay)));tickable._currentIteration=clamp(currentIteration,0,iterationCount);if(isCurrentTimeEqualOrAboveDuration)tickable._currentIteration--;isOdd=tickable._currentIteration%2;iterationElapsedTime=tickableCurrentTime%(iterationDuration+_loopDelay)||0}const isReversed=_reversed^(_alternate&&isOdd);const _ease=tickable._ease;let iterationTime=isCurrentTimeEqualOrAboveDuration?isReversed?0:duration:isReversed?iterationDuration-iterationElapsedTime:iterationElapsedTime;if(_ease)iterationTime=iterationDuration*_ease(iterationTime/iterationDuration)||0;const isRunningBackwards=(parent?parent.backwards:tickableAbsoluteTime<tickablePrevAbsoluteTime)?!isReversed:!!isReversed;tickable._currentTime=tickableAbsoluteTime;tickable._iterationTime=iterationTime;tickable.backwards=isRunningBackwards;if(isCurrentTimeAboveZero&&!tickable.began){tickable.began=true;if(!muteCallbacks&&!(parent&&(isRunningBackwards||!parent.began))){tickable.onBegin(tickable)}}else if(tickableAbsoluteTime<=0){tickable.began=false}if(!muteCallbacks&&!_hasChildren&&isCurrentTimeAboveZero&&tickable._currentIteration!==_currentIteration){tickable.onLoop(tickable)}if(forcedTick||tickMode===tickModes.AUTO&&(time>=tickableDelay&&time<=tickableEndTime||time<=tickableDelay&&tickablePrevTime>tickableDelay||time>=tickableEndTime&&tickablePrevTime!==duration)||iterationTime>=tickableEndTime&&tickablePrevTime!==duration||iterationTime<=tickableDelay&&tickablePrevTime>0||time<=tickablePrevTime&&tickablePrevTime===duration&&completed||isCurrentTimeEqualOrAboveDuration&&!completed&&isSetter){if(isCurrentTimeAboveZero){tickable.computeDeltaTime(tickablePrevTime);if(!muteCallbacks)tickable.onBeforeUpdate(tickable)}if(!_hasChildren){const forcedRender=forcedTick||(isRunningBackwards?deltaTime*-1:deltaTime)>=globals.tickThreshold;const absoluteTime=tickable._offset+(parent?parent._offset:0)+tickableDelay+iterationTime;let tween=tickable._head;let tweenTarget;let tweenStyle;let tweenTargetTransforms;let tweenTargetTransformsProperties;let tweenTransformsNeedUpdate=0;while(tween){const tweenComposition=tween._composition;const tweenCurrentTime=tween._currentTime;const tweenChangeDuration=tween._changeDuration;const tweenAbsEndTime=tween._absoluteStartTime+tween._changeDuration;const tweenNextRep=tween._nextRep;const tweenPrevRep=tween._prevRep;const tweenHasComposition=tweenComposition!==compositionTypes.none;if((forcedRender||(tweenCurrentTime!==tweenChangeDuration||absoluteTime<=tweenAbsEndTime+(tweenNextRep?tweenNextRep._delay:0))&&(tweenCurrentTime!==0||absoluteTime>=tween._absoluteStartTime))&&(!tweenHasComposition||!tween._isOverridden&&(!tween._isOverlapped||absoluteTime<=tweenAbsEndTime)&&(!tweenNextRep||(tweenNextRep._isOverridden||absoluteTime<=tweenNextRep._absoluteStartTime))&&(!tweenPrevRep||(tweenPrevRep._isOverridden||absoluteTime>=tweenPrevRep._absoluteStartTime+tweenPrevRep._changeDuration+tween._delay)))){const tweenNewTime=tween._currentTime=clamp(iterationTime-tween._startTime,0,tweenChangeDuration);const tweenProgress=tween._ease(tweenNewTime/tween._updateDuration);const tweenModifier=tween._modifier;const tweenValueType=tween._valueType;const tweenType=tween._tweenType;const tweenIsObject=tweenType===tweenTypes.OBJECT;const tweenIsNumber=tweenValueType===valueTypes.NUMBER;const tweenPrecision=tweenIsNumber&&tweenIsObject||tweenProgress===0||tweenProgress===1?-1:globals.precision;let value;let number;if(tweenIsNumber){value=number=tweenModifier(round(interpolate(tween._fromNumber,tween._toNumber,tweenProgress),tweenPrecision))}else if(tweenValueType===valueTypes.UNIT){number=tweenModifier(round(interpolate(tween._fromNumber,tween._toNumber,tweenProgress),tweenPrecision));value=`${number}${tween._unit}`}else if(tweenValueType===valueTypes.COLOR){const fn=tween._fromNumbers;const tn=tween._toNumbers;const r=round(clamp(tweenModifier(interpolate(fn[0],tn[0],tweenProgress)),0,255),0);const g=round(clamp(tweenModifier(interpolate(fn[1],tn[1],tweenProgress)),0,255),0);const b=round(clamp(tweenModifier(interpolate(fn[2],tn[2],tweenProgress)),0,255),0);const a=clamp(tweenModifier(round(interpolate(fn[3],tn[3],tweenProgress),tweenPrecision)),0,1);value=`rgba(${r},${g},${b},${a})`;if(tweenHasComposition){const ns=tween._numbers;ns[0]=r;ns[1]=g;ns[2]=b;ns[3]=a}}else if(tweenValueType===valueTypes.COMPLEX){value=tween._strings[0];for(let j=0,l=tween._toNumbers.length;j<l;j++){const n=tweenModifier(round(interpolate(tween._fromNumbers[j],tween._toNumbers[j],tweenProgress),tweenPrecision));const s=tween._strings[j+1];value+=`${s?n+s:n}`;if(tweenHasComposition){tween._numbers[j]=n}}}if(tweenHasComposition){tween._number=number}if(!internalRender&&tweenComposition!==compositionTypes.blend){const tweenProperty=tween.property;tweenTarget=tween.target;if(tweenIsObject){tweenTarget[tweenProperty]=value}else if(tweenType===tweenTypes.ATTRIBUTE){tweenTarget.setAttribute(tweenProperty,value)}else{tweenStyle=tweenTarget.style;if(tweenType===tweenTypes.TRANSFORM){if(tweenTarget!==tweenTargetTransforms){tweenTargetTransforms=tweenTarget;tweenTargetTransformsProperties=tweenTarget[transformsSymbol]}tweenTargetTransformsProperties[tweenProperty]=value;tweenTransformsNeedUpdate=1}else if(tweenType===tweenTypes.CSS){tweenStyle[tweenProperty]=value}else if(tweenType===tweenTypes.CSS_VAR){tweenStyle.setProperty(tweenProperty,value)}}if(isCurrentTimeAboveZero)hasRendered=1}else{tween._value=value}}if(tweenTransformsNeedUpdate&&tween._renderTransforms){let str=emptyString;for(let key in tweenTargetTransformsProperties){str+=`${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `}tweenStyle.transform=str;tweenTransformsNeedUpdate=0}tween=tween._next}if(!muteCallbacks&&hasRendered){tickable.onRender(tickable)}}if(!muteCallbacks&&isCurrentTimeAboveZero){tickable.onUpdate(tickable)}}if(parent&&isSetter){if(!muteCallbacks&&(parent.began&&!isRunningBackwards&&tickableAbsoluteTime>=duration&&!completed||isRunningBackwards&&tickableAbsoluteTime<=minValue&&completed)){tickable.onComplete(tickable);tickable.completed=!isRunningBackwards}}else if(isCurrentTimeAboveZero&&isCurrentTimeEqualOrAboveDuration){if(iterationCount===Infinity){tickable._startTime+=tickable.duration}else if(tickable._currentIteration>=iterationCount-1){tickable.paused=true;if(!completed&&!_hasChildren){tickable.completed=true;if(!muteCallbacks&&!(parent&&(isRunningBackwards||!parent.began))){tickable.onComplete(tickable);tickable._resolve(tickable)}}}}else{tickable.completed=false}return hasRendered};const tick=(tickable,time,muteCallbacks,internalRender,tickMode)=>{const _currentIteration=tickable._currentIteration;render(tickable,time,muteCallbacks,internalRender,tickMode);if(tickable._hasChildren){const tl=tickable;const tlIsRunningBackwards=tl.backwards;const tlChildrenTime=internalRender?time:tl._iterationTime;const tlCildrenTickTime=now();let tlChildrenHasRendered=0;let tlChildrenHaveCompleted=true;if(!internalRender&&tl._currentIteration!==_currentIteration){const tlIterationDuration=tl.iterationDuration;forEachChildren(tl,(child=>{if(!tlIsRunningBackwards){if(!child.completed&&!child.backwards&&child._currentTime<child.iterationDuration){render(child,tlIterationDuration,muteCallbacks,1,tickModes.FORCE)}child.began=false;child.completed=false}else{const childDuration=child.duration;const childStartTime=child._offset+child._delay;const childEndTime=childStartTime+childDuration;if(!muteCallbacks&&childDuration<=minValue&&(!childStartTime||childEndTime===tlIterationDuration)){child.onComplete(child)}}}));if(!muteCallbacks)tl.onLoop(tl)}forEachChildren(tl,(child=>{const childTime=round((tlChildrenTime-child._offset)*child._speed,12);const childTickMode=child._fps<tl._fps?child.requestTick(tlCildrenTickTime):tickMode;tlChildrenHasRendered+=render(child,childTime,muteCallbacks,internalRender,childTickMode);if(!child.completed&&tlChildrenHaveCompleted)tlChildrenHaveCompleted=false}),tlIsRunningBackwards);if(!muteCallbacks&&tlChildrenHasRendered)tl.onRender(tl);if((tlChildrenHaveCompleted||tlIsRunningBackwards)&&tl._currentTime>=tl.duration){tl.paused=true;if(!tl.completed){tl.completed=true;if(!muteCallbacks){tl.onComplete(tl);tl._resolve(tl)}}}}};const additive={animation:null,update:noop};const addAdditiveAnimation=lookups=>{let animation=additive.animation;if(!animation){animation={duration:minValue,computeDeltaTime:noop,_offset:0,_delay:0,_head:null,_tail:null};additive.animation=animation;additive.update=()=>{lookups.forEach((propertyAnimation=>{for(let propertyName in propertyAnimation){const tweens=propertyAnimation[propertyName];const lookupTween=tweens._head;if(lookupTween){const valueType=lookupTween._valueType;const additiveValues=valueType===valueTypes.COMPLEX||valueType===valueTypes.COLOR?cloneArray(lookupTween._fromNumbers):null;let additiveValue=lookupTween._fromNumber;let tween=tweens._tail;while(tween&&tween!==lookupTween){if(additiveValues){for(let i=0,l=tween._numbers.length;i<l;i++)additiveValues[i]+=tween._numbers[i]}else{additiveValue+=tween._number}tween=tween._prevAdd}lookupTween._toNumber=additiveValue;lookupTween._toNumbers=additiveValues}}}));render(animation,1,1,0,tickModes.FORCE)}}return animation};const engineTickMethod=(()=>isBrowser?requestAnimationFrame:setImmediate)();const engineCancelMethod=(()=>isBrowser?cancelAnimationFrame:clearImmediate)();class Engine extends Clock{constructor(initTime){super(initTime);this.useDefaultMainLoop=true;this.pauseOnDocumentHidden=true;this.defaults=defaults;this.paused=true;this.reqId=0}update(){const time=this._currentTime=now();if(this.requestTick(time)){this.computeDeltaTime(time);const engineSpeed=this._speed;const engineFps=this._fps;let activeTickable=this._head;while(activeTickable){const nextTickable=activeTickable._next;if(!activeTickable.paused){tick(activeTickable,(time-activeTickable._startTime)*activeTickable._speed*engineSpeed,0,0,activeTickable._fps<engineFps?activeTickable.requestTick(time):tickModes.AUTO)}else{removeChild(this,activeTickable);this._hasChildren=!!this._tail;activeTickable._running=false;if(activeTickable.completed&&!activeTickable._cancelled){activeTickable.cancel()}}activeTickable=nextTickable}additive.update()}}wake(){if(this.useDefaultMainLoop&&!this.reqId){this.requestTick(now());this.reqId=engineTickMethod(tickEngine)}return this}pause(){if(!this.reqId)return;this.paused=true;return killEngine()}resume(){if(!this.paused)return;this.paused=false;forEachChildren(this,(child=>child.resetTime()));return this.wake()}get speed(){return this._speed*(globals.timeScale===1?1:K)}set speed(playbackRate){this._speed=playbackRate*globals.timeScale;forEachChildren(this,(child=>child.speed=child._speed))}get timeUnit(){return globals.timeScale===1?"ms":"s"}set timeUnit(unit){const secondsScale=.001;const isSecond=unit==="s";const newScale=isSecond?secondsScale:1;if(globals.timeScale!==newScale){globals.timeScale=newScale;globals.tickThreshold=200*newScale;const scaleFactor=isSecond?secondsScale:K;this.defaults.duration*=scaleFactor;this._speed*=scaleFactor}}get precision(){return globals.precision}set precision(precision){globals.precision=precision}}const engine=(()=>{const engine=new Engine(now());if(isBrowser){globalVersions.engine=engine;doc.addEventListener("visibilitychange",(()=>{if(!engine.pauseOnDocumentHidden)return;doc.hidden?engine.pause():engine.resume()}))}return engine})();const tickEngine=()=>{if(engine._head){engine.reqId=engineTickMethod(tickEngine);engine.update()}else{engine.reqId=0}};const killEngine=()=>{engineCancelMethod(engine.reqId);engine.reqId=0;return engine};const parseInlineTransforms=(target,propName,animationInlineStyles)=>{const inlineTransforms=target.style.transform;let inlinedStylesPropertyValue;if(inlineTransforms){const cachedTransforms=target[transformsSymbol];let t;while(t=transformsExecRgx.exec(inlineTransforms)){const inlinePropertyName=t[1];const inlinePropertyValue=t[2].slice(1,-1);cachedTransforms[inlinePropertyName]=inlinePropertyValue;if(inlinePropertyName===propName){inlinedStylesPropertyValue=inlinePropertyValue;if(animationInlineStyles){animationInlineStyles[propName]=inlinePropertyValue}}}}return inlineTransforms&&!isUnd(inlinedStylesPropertyValue)?inlinedStylesPropertyValue:stringStartsWith(propName,"scale")?"1":stringStartsWith(propName,"rotate")||stringStartsWith(propName,"skew")?"0deg":"0px"};function getNodeList(v){const n=isStr(v)?scope.root.querySelectorAll(v):v;if(n instanceof NodeList||n instanceof HTMLCollection)return n}function parseTargets(targets){if(isNil(targets))return[];if(!isBrowser)return isArr(targets)&&targets.flat(Infinity)||[targets];if(isArr(targets)){const flattened=targets.flat(Infinity);const parsed=[];for(let i=0,l=flattened.length;i<l;i++){const item=flattened[i];if(!isNil(item)){const nodeList=getNodeList(item);if(nodeList){for(let j=0,jl=nodeList.length;j<jl;j++){const subItem=nodeList[j];if(!isNil(subItem)){let isDuplicate=false;for(let k=0,kl=parsed.length;k<kl;k++){if(parsed[k]===subItem){isDuplicate=true;break}}if(!isDuplicate){parsed.push(subItem)}}}}else{let isDuplicate=false;for(let j=0,jl=parsed.length;j<jl;j++){if(parsed[j]===item){isDuplicate=true;break}}if(!isDuplicate){parsed.push(item)}}}}return parsed}const nodeList=getNodeList(targets);if(nodeList)return Array.from(nodeList);return[targets]}function registerTargets(targets){const parsedTargetsArray=parseTargets(targets);const parsedTargetsLength=parsedTargetsArray.length;if(parsedTargetsLength){for(let i=0;i<parsedTargetsLength;i++){const target=parsedTargetsArray[i];if(!target[isRegisteredTargetSymbol]){target[isRegisteredTargetSymbol]=true;const isSvgType=isSvg(target);const isDom=target.nodeType||isSvgType;if(isDom){target[isDomSymbol]=true;target[isSvgSymbol]=isSvgType;target[transformsSymbol]={}}}}}return parsedTargetsArray}const getPath=path=>{const parsedTargets=parseTargets(path);const $parsedSvg=parsedTargets[0];if(!$parsedSvg||!isSvg($parsedSvg))return;return $parsedSvg};const morphTo=(path2,precision=.33)=>$path1=>{const $path2=getPath(path2);if(!$path2)return;const isPath=$path1.tagName==="path";const separator=isPath?" ":",";const previousPoints=$path1[morphPointsSymbol];if(previousPoints)$path1.setAttribute(isPath?"d":"points",previousPoints);let v1="",v2="";if(!precision){v1=$path1.getAttribute(isPath?"d":"points");v2=$path2.getAttribute(isPath?"d":"points")}else{const length1=$path1.getTotalLength();const length2=$path2.getTotalLength();const maxPoints=Math.max(Math.ceil(length1*precision),Math.ceil(length2*precision));for(let i=0;i<maxPoints;i++){const t=i/(maxPoints-1);const pointOnPath1=$path1.getPointAtLength(length1*t);const pointOnPath2=$path2.getPointAtLength(length2*t);const prefix=isPath?i===0?"M":"L":"";v1+=prefix+round(pointOnPath1.x,3)+separator+pointOnPath1.y+" ";v2+=prefix+round(pointOnPath2.x,3)+separator+pointOnPath2.y+" "}}$path1[morphPointsSymbol]=v2;return[v1,v2]};const getScaleFactor=$el=>{let scaleFactor=1;if($el&&$el.getCTM){const ctm=$el.getCTM();if(ctm){const scaleX=sqrt(ctm.a*ctm.a+ctm.b*ctm.b);const scaleY=sqrt(ctm.c*ctm.c+ctm.d*ctm.d);scaleFactor=(scaleX+scaleY)/2}}return scaleFactor};const createDrawableProxy=($el,start,end)=>{const pathLength=K;const computedStyles=getComputedStyle($el);const strokeLineCap=computedStyles.strokeLinecap;const $scalled=computedStyles.vectorEffect==="non-scaling-stroke"?$el:null;let currentCap=strokeLineCap;const proxy=new Proxy($el,{get(target,property){const value=target[property];if(property===proxyTargetSymbol)return target;if(property==="setAttribute"){return(...args)=>{if(args[0]==="draw"){const value=args[1];const values=value.split(" ");const v1=+values[0];const v2=+values[1];const scaleFactor=getScaleFactor($scalled);const os=v1*-1e3*scaleFactor;const d1=v2*pathLength*scaleFactor+os;const d2=pathLength*scaleFactor+(v1===0&&v2===1||v1===1&&v2===0?0:10*scaleFactor)-d1;if(strokeLineCap!=="butt"){const newCap=v1===v2?"butt":strokeLineCap;if(currentCap!==newCap){target.style.strokeLinecap=`${newCap}`;currentCap=newCap}}target.setAttribute("stroke-dashoffset",`${os}`);target.setAttribute("stroke-dasharray",`${d1} ${d2}`)}return Reflect.apply(value,target,args)}}if(isFnc(value)){return(...args)=>Reflect.apply(value,target,args)}else{return value}}});if($el.getAttribute("pathLength")!==`${pathLength}`){$el.setAttribute("pathLength",`${pathLength}`);proxy.setAttribute("draw",`${start} ${end}`)}return proxy};const createDrawable=(selector,start=0,end=0)=>{const els=parseTargets(selector);return els.map(($el=>createDrawableProxy($el,start,end)))};const getPathPoint=($path,progress,lookup=0)=>$path.getPointAtLength(progress+lookup>=1?progress+lookup:0);const getPathProgess=($path,pathProperty)=>$el=>{const totalLength=+$path.getTotalLength();const inSvg=$el[isSvgSymbol];const ctm=$path.getCTM();return{from:0,to:totalLength,modifier:progress=>{if(pathProperty==="a"){const p0=getPathPoint($path,progress,-1);const p1=getPathPoint($path,progress,1);return atan2(p1.y-p0.y,p1.x-p0.x)*180/PI}else{const p=getPathPoint($path,progress,0);return pathProperty==="x"?inSvg||!ctm?p.x:p.x*ctm.a+p.y*ctm.c+ctm.e:inSvg||!ctm?p.y:p.x*ctm.b+p.y*ctm.d+ctm.f}}}};const createMotionPath=path=>{const $path=getPath(path);if(!$path)return;return{translateX:getPathProgess($path,"x"),translateY:getPathProgess($path,"y"),rotate:getPathProgess($path,"a")}};const cssReservedProperties=["opacity","rotate","overflow","color"];const isValidSVGAttribute=(el,propertyName)=>{if(cssReservedProperties.includes(propertyName))return false;if(el.getAttribute(propertyName)||propertyName in el){if(propertyName==="scale"){const elParentNode=el.parentNode;return elParentNode&&elParentNode.tagName==="filter"}return true}};const svg={morphTo:morphTo,createMotionPath:createMotionPath,createDrawable:createDrawable};const rgbToRgba=rgbValue=>{const rgba=rgbExecRgx.exec(rgbValue)||rgbaExecRgx.exec(rgbValue);const a=!isUnd(rgba[4])?+rgba[4]:1;return[+rgba[1],+rgba[2],+rgba[3],a]};const hexToRgba=hexValue=>{const hexLength=hexValue.length;const isShort=hexLength===4||hexLength===5;return[+("0x"+hexValue[1]+hexValue[isShort?1:2]),+("0x"+hexValue[isShort?2:3]+hexValue[isShort?2:4]),+("0x"+hexValue[isShort?3:5]+hexValue[isShort?3:6]),hexLength===5||hexLength===9?+(+("0x"+hexValue[isShort?4:7]+hexValue[isShort?4:8])/255).toFixed(3):1]};const hue2rgb=(p,q,t)=>{if(t<0)t+=1;if(t>1)t-=1;return t<1/6?p+(q-p)*6*t:t<1/2?q:t<2/3?p+(q-p)*(2/3-t)*6:p};const hslToRgba=hslValue=>{const hsla=hslExecRgx.exec(hslValue)||hslaExecRgx.exec(hslValue);const h=+hsla[1]/360;const s=+hsla[2]/100;const l=+hsla[3]/100;const a=!isUnd(hsla[4])?+hsla[4]:1;let r,g,b;if(s===0){r=g=b=l}else{const q=l<.5?l*(1+s):l+s-l*s;const p=2*l-q;r=round(hue2rgb(p,q,h+1/3)*255,0);g=round(hue2rgb(p,q,h)*255,0);b=round(hue2rgb(p,q,h-1/3)*255,0)}return[r,g,b,a]};const convertColorStringValuesToRgbaArray=colorString=>isRgb(colorString)?rgbToRgba(colorString):isHex(colorString)?hexToRgba(colorString):isHsl(colorString)?hslToRgba(colorString):[0,0,0,1];const setValue=(targetValue,defaultValue)=>isUnd(targetValue)?defaultValue:targetValue;const getFunctionValue=(value,target,index,total,store)=>{if(isFnc(value)){const func=()=>{const computed=value(target,index,total);return!isNaN(+computed)?+computed:computed||0};if(store){store.func=func}return func()}else{return value}};const getTweenType=(target,prop)=>!target[isDomSymbol]?tweenTypes.OBJECT:target[isSvgSymbol]&&isValidSVGAttribute(target,prop)?tweenTypes.ATTRIBUTE:validTransforms.includes(prop)||shortTransforms.get(prop)?tweenTypes.TRANSFORM:stringStartsWith(prop,"--")?tweenTypes.CSS_VAR:prop in target.style?tweenTypes.CSS:prop in target?tweenTypes.OBJECT:tweenTypes.ATTRIBUTE;const getCSSValue=(target,propName,animationInlineStyles)=>{const inlineStyles=target.style[propName];if(inlineStyles&&animationInlineStyles){animationInlineStyles[propName]=inlineStyles}const value=inlineStyles||getComputedStyle(target[proxyTargetSymbol]||target).getPropertyValue(propName);return value==="auto"?"0":value};const getOriginalAnimatableValue=(target,propName,tweenType,animationInlineStyles)=>{const type=!isUnd(tweenType)?tweenType:getTweenType(target,propName);return type===tweenTypes.OBJECT?target[propName]||0:type===tweenTypes.ATTRIBUTE?target.getAttribute(propName):type===tweenTypes.TRANSFORM?parseInlineTransforms(target,propName,animationInlineStyles):type===tweenTypes.CSS_VAR?getCSSValue(target,propName,animationInlineStyles).trimStart():getCSSValue(target,propName,animationInlineStyles)};const getRelativeValue=(x,y,operator)=>operator==="-"?x-y:operator==="+"?x+y:x*y;const createDecomposedValueTargetObject=()=>({t:valueTypes.NUMBER,n:0,u:null,o:null,d:null,s:null});const decomposeRawValue=(rawValue,targetObject)=>{targetObject.t=valueTypes.NUMBER;targetObject.n=0;targetObject.u=null;targetObject.o=null;targetObject.d=null;targetObject.s=null;if(!rawValue)return targetObject;const num=+rawValue;if(!isNaN(num)){targetObject.n=num;return targetObject}else{let str=rawValue;if(str[1]==="="){targetObject.o=str[0];str=str.slice(2)}const unitMatch=str.includes(" ")?false:unitsExecRgx.exec(str);if(unitMatch){targetObject.t=valueTypes.UNIT;targetObject.n=+unitMatch[1];targetObject.u=unitMatch[2];return targetObject}else if(targetObject.o){targetObject.n=+str;return targetObject}else if(isCol(str)){targetObject.t=valueTypes.COLOR;targetObject.d=convertColorStringValuesToRgbaArray(str);return targetObject}else{const matchedNumbers=str.match(digitWithExponentRgx);targetObject.t=valueTypes.COMPLEX;targetObject.d=matchedNumbers?matchedNumbers.map(Number):[];targetObject.s=str.split(digitWithExponentRgx)||[];return targetObject}}};const decomposeTweenValue=(tween,targetObject)=>{targetObject.t=tween._valueType;targetObject.n=tween._toNumber;targetObject.u=tween._unit;targetObject.o=null;targetObject.d=cloneArray(tween._toNumbers);targetObject.s=cloneArray(tween._strings);return targetObject};const decomposedOriginalValue=createDecomposedValueTargetObject();const lookups={_rep:new WeakMap,_add:new Map};const getTweenSiblings=(target,property,lookup="_rep")=>{const lookupMap=lookups[lookup];let targetLookup=lookupMap.get(target);if(!targetLookup){targetLookup={};lookupMap.set(target,targetLookup)}return targetLookup[property]?targetLookup[property]:targetLookup[property]={_head:null,_tail:null}};const addTweenSortMethod=(p,c)=>p._isOverridden||p._absoluteStartTime>c._absoluteStartTime;const overrideTween=tween=>{tween._isOverlapped=1;tween._isOverridden=1;tween._changeDuration=minValue;tween._currentTime=minValue};const composeTween=(tween,siblings)=>{const tweenCompositionType=tween._composition;if(tweenCompositionType===compositionTypes.replace){const tweenAbsStartTime=tween._absoluteStartTime;addChild(siblings,tween,addTweenSortMethod,"_prevRep","_nextRep");const prevSibling=tween._prevRep;if(prevSibling){const prevParent=prevSibling.parent;const prevAbsEndTime=prevSibling._absoluteStartTime+prevSibling._changeDuration;if(tween.parent.id!==prevParent.id&&prevParent.iterationCount>1&&prevAbsEndTime+(prevParent.duration-prevParent.iterationDuration)>tweenAbsStartTime){overrideTween(prevSibling);let prevPrevSibling=prevSibling._prevRep;while(prevPrevSibling&&prevPrevSibling.parent.id===prevParent.id){overrideTween(prevPrevSibling);prevPrevSibling=prevPrevSibling._prevRep}}const absoluteUpdateStartTime=tweenAbsStartTime-tween._delay;if(prevAbsEndTime>absoluteUpdateStartTime){const prevChangeStartTime=prevSibling._startTime;const prevTLOffset=prevAbsEndTime-(prevChangeStartTime+prevSibling._updateDuration);const updatedPrevChangeDuration=round(absoluteUpdateStartTime-prevTLOffset-prevChangeStartTime,12);prevSibling._changeDuration=updatedPrevChangeDuration;prevSibling._currentTime=updatedPrevChangeDuration;prevSibling._isOverlapped=1;if(updatedPrevChangeDuration<minValue){overrideTween(prevSibling)}}let pausePrevParentAnimation=true;forEachChildren(prevParent,(t=>{if(!t._isOverlapped)pausePrevParentAnimation=false}));if(pausePrevParentAnimation){const prevParentTL=prevParent.parent;if(prevParentTL){let pausePrevParentTL=true;forEachChildren(prevParentTL,(a=>{if(a!==prevParent){forEachChildren(a,(t=>{if(!t._isOverlapped)pausePrevParentTL=false}))}}));if(pausePrevParentTL){prevParentTL.cancel()}}else{prevParent.cancel()}}}}else if(tweenCompositionType===compositionTypes.blend){const additiveTweenSiblings=getTweenSiblings(tween.target,tween.property,"_add");const additiveAnimation=addAdditiveAnimation(lookups._add);let lookupTween=additiveTweenSiblings._head;if(!lookupTween){lookupTween={...tween};lookupTween._composition=compositionTypes.replace;lookupTween._updateDuration=minValue;lookupTween._startTime=0;lookupTween._numbers=cloneArray(tween._fromNumbers);lookupTween._number=0;lookupTween._next=null;lookupTween._prev=null;addChild(additiveTweenSiblings,lookupTween);addChild(additiveAnimation,lookupTween)}const toNumber=tween._toNumber;tween._fromNumber=lookupTween._fromNumber-toNumber;tween._toNumber=0;tween._numbers=cloneArray(tween._fromNumbers);tween._number=0;lookupTween._fromNumber=toNumber;if(tween._toNumbers){const toNumbers=cloneArray(tween._toNumbers);if(toNumbers){toNumbers.forEach(((value,i)=>{tween._fromNumbers[i]=lookupTween._fromNumbers[i]-value;tween._toNumbers[i]=0}))}lookupTween._fromNumbers=toNumbers}addChild(additiveTweenSiblings,tween,null,"_prevAdd","_nextAdd")}return tween};const removeTweenSliblings=tween=>{const tweenComposition=tween._composition;if(tweenComposition!==compositionTypes.none){const tweenTarget=tween.target;const tweenProperty=tween.property;const replaceTweensLookup=lookups._rep;const replaceTargetProps=replaceTweensLookup.get(tweenTarget);const tweenReplaceSiblings=replaceTargetProps[tweenProperty];removeChild(tweenReplaceSiblings,tween,"_prevRep","_nextRep");if(tweenComposition===compositionTypes.blend){const addTweensLookup=lookups._add;const addTargetProps=addTweensLookup.get(tweenTarget);if(!addTargetProps)return;const additiveTweenSiblings=addTargetProps[tweenProperty];const additiveAnimation=additive.animation;removeChild(additiveTweenSiblings,tween,"_prevAdd","_nextAdd");const lookupTween=additiveTweenSiblings._head;if(lookupTween&&lookupTween===additiveTweenSiblings._tail){removeChild(additiveTweenSiblings,lookupTween,"_prevAdd","_nextAdd");removeChild(additiveAnimation,lookupTween);let shouldClean=true;for(let prop in addTargetProps){if(addTargetProps[prop]._head){shouldClean=false;break}}if(shouldClean){addTweensLookup.delete(tweenTarget)}}}}return tween};const resetTimerProperties=timer=>{timer.paused=true;timer.began=false;timer.completed=false;return timer};const reviveTimer=timer=>{if(!timer._cancelled)return timer;if(timer._hasChildren){forEachChildren(timer,reviveTimer)}else{forEachChildren(timer,(tween=>{if(tween._composition!==compositionTypes.none){composeTween(tween,getTweenSiblings(tween.target,tween.property))}}))}timer._cancelled=0;return timer};let timerId=0;class Timer extends Clock{constructor(parameters={},parent=null,parentPosition=0){super(0);const{id:id,delay:delay,duration:duration,reversed:reversed,alternate:alternate,loop:loop,loopDelay:loopDelay,autoplay:autoplay,frameRate:frameRate,playbackRate:playbackRate,onComplete:onComplete,onLoop:onLoop,onPause:onPause,onBegin:onBegin,onBeforeUpdate:onBeforeUpdate,onUpdate:onUpdate}=parameters;if(scope.current)scope.current.register(this);const timerInitTime=parent?0:engine._elapsedTime;const timerDefaults=parent?parent.defaults:globals.defaults;const timerDelay=isFnc(delay)||isUnd(delay)?timerDefaults.delay:+delay;const timerDuration=isFnc(duration)||isUnd(duration)?Infinity:+duration;const timerLoop=setValue(loop,timerDefaults.loop);const timerLoopDelay=setValue(loopDelay,timerDefaults.loopDelay);const timerIterationCount=timerLoop===true||timerLoop===Infinity||timerLoop<0?Infinity:timerLoop+1;let offsetPosition=0;if(parent){offsetPosition=parentPosition}else{if(!engine.reqId)engine.requestTick(now());offsetPosition=(engine._elapsedTime-engine._startTime)*globals.timeScale}this.id=!isUnd(id)?id:++timerId;this.parent=parent;this.duration=clampInfinity((timerDuration+timerLoopDelay)*timerIterationCount-timerLoopDelay)||minValue;this.backwards=false;this.paused=true;this.began=false;this.completed=false;this.onBegin=onBegin||timerDefaults.onBegin;this.onBeforeUpdate=onBeforeUpdate||timerDefaults.onBeforeUpdate;this.onUpdate=onUpdate||timerDefaults.onUpdate;this.onLoop=onLoop||timerDefaults.onLoop;this.onPause=onPause||timerDefaults.onPause;this.onComplete=onComplete||timerDefaults.onComplete;this.iterationDuration=timerDuration;this.iterationCount=timerIterationCount;this._autoplay=parent?false:setValue(autoplay,timerDefaults.autoplay);this._offset=offsetPosition;this._delay=timerDelay;this._loopDelay=timerLoopDelay;this._iterationTime=0;this._currentIteration=0;this._resolve=noop;this._running=false;this._reversed=+setValue(reversed,timerDefaults.reversed);this._reverse=this._reversed;this._cancelled=0;this._alternate=setValue(alternate,timerDefaults.alternate);this._prev=null;this._next=null;this._elapsedTime=timerInitTime;this._startTime=timerInitTime;this._lastTime=timerInitTime;this._fps=setValue(frameRate,timerDefaults.frameRate);this._speed=setValue(playbackRate,timerDefaults.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(cancelled){cancelled?this.cancel():this.reset(1).play()}get currentTime(){return clamp(round(this._currentTime,globals.precision),-this._delay,this.duration)}set currentTime(time){const paused=this.paused;this.pause().seek(+time);if(!paused)this.resume()}get iterationCurrentTime(){return round(this._iterationTime,globals.precision)}set iterationCurrentTime(time){this.currentTime=this.iterationDuration*this._currentIteration+time}get progress(){return clamp(round(this._currentTime/this.duration,10),0,1)}set progress(progress){this.currentTime=this.duration*progress}get iterationProgress(){return clamp(round(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(progress){const iterationDuration=this.iterationDuration;this.currentTime=iterationDuration*this._currentIteration+iterationDuration*progress}get currentIteration(){return this._currentIteration}set currentIteration(iterationCount){this.currentTime=this.iterationDuration*clamp(+iterationCount,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(reverse){reverse?this.reverse():this.play()}get speed(){return super.speed}set speed(playbackRate){super.speed=playbackRate;this.resetTime()}reset(internalRender=0){reviveTimer(this);if(this._reversed&&!this._reverse)this.reversed=false;this._iterationTime=this.iterationDuration;tick(this,0,1,internalRender,tickModes.FORCE);resetTimerProperties(this);if(this._hasChildren){forEachChildren(this,resetTimerProperties)}return this}init(internalRender=0){this.fps=this._fps;this.speed=this._speed;if(!internalRender&&this._hasChildren){tick(this,this.duration,1,internalRender,tickModes.FORCE)}this.reset(internalRender);const autoplay=this._autoplay;if(autoplay===true){this.resume()}else if(autoplay&&!isUnd(autoplay.linked)){autoplay.link(this)}return this}resetTime(){const timeScale=1/(this._speed*engine._speed);this._startTime=now()-(this._currentTime+this._delay)*timeScale;return this}pause(){if(this.paused)return this;this.paused=true;this.onPause(this);return this}resume(){if(!this.paused)return this;this.paused=false;if(this.duration<=minValue&&!this._hasChildren){tick(this,minValue,0,0,tickModes.FORCE)}else{if(!this._running){addChild(engine,this);engine._hasChildren=true;this._running=true}this.resetTime();this._startTime-=12;engine.wake()}return this}restart(){return this.reset(0).resume()}seek(time,muteCallbacks=0,internalRender=0){reviveTimer(this);this.completed=false;const isPaused=this.paused;this.paused=true;tick(this,time+this._delay,~~muteCallbacks,~~internalRender,tickModes.AUTO);return isPaused?this:this.resume()}alternate(){const reversed=this._reversed;const count=this.iterationCount;const duration=this.iterationDuration;const iterations=count===Infinity?floor(maxValue/duration):count;this._reversed=+(this._alternate&&!(iterations%2)?reversed:!reversed);if(count===Infinity){this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress}else{this.seek(duration*iterations-this._currentTime)}this.resetTime();return this}play(){if(this._reversed)this.alternate();return this.resume()}reverse(){if(!this._reversed)this.alternate();return this.resume()}cancel(){if(this._hasChildren){forEachChildren(this,(child=>child.cancel()),true)}else{forEachChildren(this,removeTweenSliblings)}this._cancelled=1;return this.pause()}stretch(newDuration){const currentDuration=this.duration;const normlizedDuration=normalizeTime(newDuration);if(currentDuration===normlizedDuration)return this;const timeScale=newDuration/currentDuration;const isSetter=newDuration<=minValue;this.duration=isSetter?minValue:normlizedDuration;this.iterationDuration=isSetter?minValue:normalizeTime(this.iterationDuration*timeScale);this._offset*=timeScale;this._delay*=timeScale;this._loopDelay*=timeScale;return this}revert(){tick(this,0,1,0,tickModes.AUTO);const ap=this._autoplay;if(ap&&ap.linked&&ap.linked===this)ap.revert();return this.cancel()}complete(){return this.seek(this.duration).cancel()}then(callback=noop){const then=this.then;const onResolve=()=>{this.then=null;callback(this);this.then=then;this._resolve=noop};return new Promise((r=>{this._resolve=()=>r(onResolve());if(this.completed)this._resolve();return this}))}}const createTimer=parameters=>new Timer(parameters,null,0).init();const none=t=>t;const calcBezier=(aT,aA1,aA2)=>(((1-3*aA2+3*aA1)*aT+(3*aA2-6*aA1))*aT+3*aA1)*aT;const binarySubdivide=(aX,mX1,mX2)=>{let aA=0,aB=1,currentX,currentT,i=0;do{currentT=aA+(aB-aA)/2;currentX=calcBezier(currentT,mX1,mX2)-aX;if(currentX>0){aB=currentT}else{aA=currentT}}while(abs(currentX)>1e-7&&++i<100);return currentT};const cubicBezier=(mX1=.5,mY1=0,mX2=.5,mY2=1)=>mX1===mY1&&mX2===mY2?none:t=>t===0||t===1?t:calcBezier(binarySubdivide(t,mX1,mX2),mY1,mY2);const steps=(steps=10,fromStart)=>{const roundMethod=fromStart?ceil:floor;return t=>roundMethod(clamp(t,0,1)*steps)*(1/steps)};const linear=(...args)=>{const argsLength=args.length;if(!argsLength)return none;const totalPoints=argsLength-1;const firstArg=args[0];const lastArg=args[totalPoints];const xPoints=[0];const yPoints=[parseNumber(firstArg)];for(let i=1;i<totalPoints;i++){const arg=args[i];const splitValue=isStr(arg)?arg.trim().split(" "):[arg];const value=splitValue[0];const percent=splitValue[1];xPoints.push(!isUnd(percent)?parseNumber(percent)/100:i/totalPoints);yPoints.push(parseNumber(value))}yPoints.push(parseNumber(lastArg));xPoints.push(1);return function easeLinear(t){for(let i=1,l=xPoints.length;i<l;i++){const currentX=xPoints[i];if(t<=currentX){const prevX=xPoints[i-1];const prevY=yPoints[i-1];return prevY+(yPoints[i]-prevY)*(t-prevX)/(currentX-prevX)}}return yPoints[yPoints.length-1]}};const irregular=(length=10,randomness=1)=>{const values=[0];const total=length-1;for(let i=1;i<total;i++){const previousValue=values[i-1];const spacing=i/total;const segmentEnd=(i+1)/total;const randomVariation=spacing+(segmentEnd-spacing)*Math.random();const randomValue=spacing*(1-randomness)+randomVariation*randomness;values.push(clamp(randomValue,previousValue,1))}values.push(1);return linear(...values)};const halfPI=PI/2;const doublePI=PI*2;const easeInPower=(p=1.68)=>t=>pow(t,+p);const easeInFunctions={[emptyString]:easeInPower,Quad:easeInPower(2),Cubic:easeInPower(3),Quart:easeInPower(4),Quint:easeInPower(5),Sine:t=>1-cos(t*halfPI),Circ:t=>1-sqrt(1-t*t),Expo:t=>t?pow(2,10*t-10):0,Bounce:t=>{let pow2,b=4;while(t<((pow2=pow(2,--b))-1)/11);return 1/pow(4,3-b)-7.5625*pow((pow2*3-2)/22-t,2)},Back:(overshoot=1.70158)=>t=>(+overshoot+1)*t*t*t-+overshoot*t*t,Elastic:(amplitude=1,period=.3)=>{const a=clamp(+amplitude,1,10);const p=clamp(+period,minValue,2);const s=p/doublePI*asin(1/a);const e=doublePI/p;return t=>t===0||t===1?t:-a*pow(2,-10*(1-t))*sin((1-t-s)*e)}};const easeTypes={in:easeIn=>t=>easeIn(t),out:easeIn=>t=>1-easeIn(1-t),inOut:easeIn=>t=>t<.5?easeIn(t*2)/2:1-easeIn(t*-2+2)/2,outIn:easeIn=>t=>t<.5?(1-easeIn(1-t*2))/2:(easeIn(t*2-1)+1)/2};const parseEaseString=(string,easesFunctions,easesLookups)=>{if(easesLookups[string])return easesLookups[string];if(string.indexOf("(")<=-1){const hasParams=easeTypes[string]||string.includes("Back")||string.includes("Elastic");const parsedFn=hasParams?easesFunctions[string]():easesFunctions[string];return parsedFn?easesLookups[string]=parsedFn:none}else{const split=string.slice(0,-1).split("(");const parsedFn=easesFunctions[split[0]];return parsedFn?easesLookups[string]=parsedFn(...split[1].split(",")):none}};const eases=(()=>{const list={linear:linear,irregular:irregular,steps:steps,cubicBezier:cubicBezier};for(let type in easeTypes){for(let name in easeInFunctions){const easeIn=easeInFunctions[name];const easeType=easeTypes[type];list[type+name]=name===emptyString||name==="Back"||name==="Elastic"?(a,b)=>easeType(easeIn(a,b)):easeType(easeIn)}}return list})();const JSEasesLookups={linear:none};const parseEasings=ease=>isFnc(ease)?ease:isStr(ease)?parseEaseString(ease,eases,JSEasesLookups):none;const propertyNamesCache={};const sanitizePropertyName=(propertyName,target,tweenType)=>{if(tweenType===tweenTypes.TRANSFORM){const t=shortTransforms.get(propertyName);return t?t:propertyName}else if(tweenType===tweenTypes.CSS||tweenType===tweenTypes.ATTRIBUTE&&(isSvg(target)&&propertyName in target.style)){const cachedPropertyName=propertyNamesCache[propertyName];if(cachedPropertyName){return cachedPropertyName}else{const lowerCaseName=propertyName?toLowerCase(propertyName):propertyName;propertyNamesCache[propertyName]=lowerCaseName;return lowerCaseName}}else{return propertyName}};const angleUnitsMap={deg:1,rad:180/PI,turn:360};const convertedValuesCache={};const convertValueUnit=(el,decomposedValue,unit,force=false)=>{const currentUnit=decomposedValue.u;const currentNumber=decomposedValue.n;if(decomposedValue.t===valueTypes.UNIT&&currentUnit===unit){return decomposedValue}const cachedKey=currentNumber+currentUnit+unit;const cached=convertedValuesCache[cachedKey];if(!isUnd(cached)&&!force){decomposedValue.n=cached}else{let convertedValue;if(currentUnit in angleUnitsMap){convertedValue=currentNumber*angleUnitsMap[currentUnit]/angleUnitsMap[unit]}else{const baseline=100;const tempEl=el.cloneNode();const parentNode=el.parentNode;const parentEl=parentNode&&parentNode!==doc?parentNode:doc.body;parentEl.appendChild(tempEl);const elStyle=tempEl.style;elStyle.width=baseline+currentUnit;const currentUnitWidth=tempEl.offsetWidth||baseline;elStyle.width=baseline+unit;const newUnitWidth=tempEl.offsetWidth||baseline;const factor=currentUnitWidth/newUnitWidth;parentEl.removeChild(tempEl);convertedValue=factor*currentNumber}decomposedValue.n=convertedValue;convertedValuesCache[cachedKey]=convertedValue}decomposedValue.t===valueTypes.UNIT;decomposedValue.u=unit;return decomposedValue};const cleanInlineStyles=renderable=>{if(renderable._hasChildren){forEachChildren(renderable,cleanInlineStyles,true)}else{const animation=renderable;animation.pause();forEachChildren(animation,(tween=>{const tweenProperty=tween.property;const tweenTarget=tween.target;if(tweenTarget[isDomSymbol]){const targetStyle=tweenTarget.style;const originalInlinedValue=animation._inlineStyles[tweenProperty];if(tween._tweenType===tweenTypes.TRANSFORM){const cachedTransforms=tweenTarget[transformsSymbol];if(isUnd(originalInlinedValue)||originalInlinedValue===emptyString){delete cachedTransforms[tweenProperty]}else{cachedTransforms[tweenProperty]=originalInlinedValue}if(tween._renderTransforms){if(!Object.keys(cachedTransforms).length){targetStyle.removeProperty("transform")}else{let str=emptyString;for(let key in cachedTransforms){str+=transformsFragmentStrings[key]+cachedTransforms[key]+") "}targetStyle.transform=str}}}else{if(isUnd(originalInlinedValue)||originalInlinedValue===emptyString){targetStyle.removeProperty(tweenProperty)}else{targetStyle[tweenProperty]=originalInlinedValue}}if(animation._tail===tween){animation.targets.forEach((t=>{if(t.getAttribute&&t.getAttribute("style")===emptyString){t.removeAttribute("style")}}))}}}))}return renderable};const fromTargetObject=createDecomposedValueTargetObject();const toTargetObject=createDecomposedValueTargetObject();const toFunctionStore={func:null};const keyframesTargetArray=[null];const fastSetValuesArray=[null,null];const keyObjectTarget={to:null};let tweenId=0;let keyframes;let key;const generateKeyframes=(keyframes,parameters)=>{const properties={};if(isArr(keyframes)){const propertyNames=[].concat(...keyframes.map((key=>Object.keys(key)))).filter(isKey);for(let i=0,l=propertyNames.length;i<l;i++){const propName=propertyNames[i];const propArray=keyframes.map((key=>{const newKey={};for(let p in key){const keyValue=key[p];if(isKey(p)){if(p===propName){newKey.to=keyValue}}else{newKey[p]=keyValue}}return newKey}));properties[propName]=propArray}}else{const totalDuration=setValue(parameters.duration,globals.defaults.duration);const keys=Object.keys(keyframes).map((key=>({o:parseFloat(key)/100,p:keyframes[key]}))).sort(((a,b)=>a.o-b.o));keys.forEach((key=>{const offset=key.o;const prop=key.p;for(let name in prop){if(isKey(name)){let propArray=properties[name];if(!propArray)propArray=properties[name]=[];const duration=offset*totalDuration;let length=propArray.length;let prevKey=propArray[length-1];const keyObj={to:prop[name]};let durProgress=0;for(let i=0;i<length;i++){durProgress+=propArray[i].duration}if(length===1){keyObj.from=prevKey.to}if(prop.ease){keyObj.ease=prop.ease}keyObj.duration=duration-(length?durProgress:0);propArray.push(keyObj)}}return key}));for(let name in properties){const propArray=properties[name];let prevEase;for(let i=0,l=propArray.length;i<l;i++){const prop=propArray[i];const currentEase=prop.ease;prop.ease=prevEase?prevEase:undefined;prevEase=currentEase}if(!propArray[0].duration){propArray.shift()}}}return properties};class JSAnimation extends Timer{constructor(targets,parameters,parent,parentPosition,fastSet=false,index=0,length=0){super(parameters,parent,parentPosition);const parsedTargets=registerTargets(targets);const targetsLength=parsedTargets.length;const kfParams=parameters.keyframes;const params=kfParams?mergeObjects(generateKeyframes(kfParams,parameters),parameters):parameters;const{delay:delay,duration:duration,ease:ease,playbackEase:playbackEase,modifier:modifier,composition:composition,onRender:onRender}=params;const animDefaults=parent?parent.defaults:globals.defaults;const animaPlaybackEase=setValue(playbackEase,animDefaults.playbackEase);const animEase=animaPlaybackEase?parseEasings(animaPlaybackEase):null;const hasSpring=!isUnd(ease)&&!isUnd(ease.ease);const tEasing=hasSpring?ease.ease:setValue(ease,animEase?"linear":animDefaults.ease);const tDuration=hasSpring?ease.duration:setValue(duration,animDefaults.duration);const tDelay=setValue(delay,animDefaults.delay);const tModifier=modifier||animDefaults.modifier;const tComposition=isUnd(composition)&&targetsLength>=K?compositionTypes.none:!isUnd(composition)?composition:animDefaults.composition;const animInlineStyles={};const absoluteOffsetTime=this._offset+(parent?parent._offset:0);let iterationDuration=NaN;let iterationDelay=NaN;let animationAnimationLength=0;let shouldTriggerRender=0;for(let targetIndex=0;targetIndex<targetsLength;targetIndex++){const target=parsedTargets[targetIndex];const ti=index||targetIndex;const tl=length||targetsLength;let lastTransformGroupIndex=NaN;let lastTransformGroupLength=NaN;for(let p in params){if(isKey(p)){const tweenType=getTweenType(target,p);const propName=sanitizePropertyName(p,target,tweenType);let propValue=params[p];const isPropValueArray=isArr(propValue);if(fastSet&&!isPropValueArray){fastSetValuesArray[0]=propValue;fastSetValuesArray[1]=propValue;propValue=fastSetValuesArray}if(isPropValueArray){const arrayLength=propValue.length;const isNotObjectValue=!isObj(propValue[0]);if(arrayLength===2&&isNotObjectValue){keyObjectTarget.to=propValue;keyframesTargetArray[0]=keyObjectTarget;keyframes=keyframesTargetArray}else if(arrayLength>2&&isNotObjectValue){keyframes=[];propValue.forEach(((v,i)=>{if(!i){fastSetValuesArray[0]=v}else if(i===1){fastSetValuesArray[1]=v;keyframes.push(fastSetValuesArray)}else{keyframes.push(v)}}))}else{keyframes=propValue}}else{keyframesTargetArray[0]=propValue;keyframes=keyframesTargetArray}let siblings=null;let prevTween=null;let firstTweenChangeStartTime=NaN;let lastTweenChangeEndTime=0;let tweenIndex=0;for(let l=keyframes.length;tweenIndex<l;tweenIndex++){const keyframe=keyframes[tweenIndex];if(isObj(keyframe)){key=keyframe}else{keyObjectTarget.to=keyframe;key=keyObjectTarget}toFunctionStore.func=null;const computedToValue=getFunctionValue(key.to,target,ti,tl,toFunctionStore);let tweenToValue;if(isObj(computedToValue)&&!isUnd(computedToValue.to)){key=computedToValue;tweenToValue=computedToValue.to}else{tweenToValue=computedToValue}const tweenFromValue=getFunctionValue(key.from,target,ti,tl);const keyEasing=key.ease;const hasSpring=!isUnd(keyEasing)&&!isUnd(keyEasing.ease);const tweenEasing=hasSpring?keyEasing.ease:keyEasing||tEasing;const tweenDuration=hasSpring?keyEasing.duration:getFunctionValue(setValue(key.duration,l>1?getFunctionValue(tDuration,target,ti,tl)/l:tDuration),target,ti,tl);const tweenDelay=getFunctionValue(setValue(key.delay,!tweenIndex?tDelay:0),target,ti,tl);const computedComposition=getFunctionValue(setValue(key.composition,tComposition),target,ti,tl);const tweenComposition=isNum(computedComposition)?computedComposition:compositionTypes[computedComposition];const tweenModifier=key.modifier||tModifier;const hasFromvalue=!isUnd(tweenFromValue);const hasToValue=!isUnd(tweenToValue);const isFromToArray=isArr(tweenToValue);const isFromToValue=isFromToArray||hasFromvalue&&hasToValue;const tweenStartTime=prevTween?lastTweenChangeEndTime+tweenDelay:tweenDelay;const absoluteStartTime=round(absoluteOffsetTime+tweenStartTime,12);if(!shouldTriggerRender&&(hasFromvalue||isFromToArray))shouldTriggerRender=1;let prevSibling=prevTween;if(tweenComposition!==compositionTypes.none){if(!siblings)siblings=getTweenSiblings(target,propName);let nextSibling=siblings._head;while(nextSibling&&!nextSibling._isOverridden&&nextSibling._absoluteStartTime<=absoluteStartTime){prevSibling=nextSibling;nextSibling=nextSibling._nextRep;if(nextSibling&&nextSibling._absoluteStartTime>=absoluteStartTime){while(nextSibling){overrideTween(nextSibling);nextSibling=nextSibling._nextRep}}}}if(isFromToValue){decomposeRawValue(isFromToArray?getFunctionValue(tweenToValue[0],target,ti,tl):tweenFromValue,fromTargetObject);decomposeRawValue(isFromToArray?getFunctionValue(tweenToValue[1],target,ti,tl,toFunctionStore):tweenToValue,toTargetObject);if(fromTargetObject.t===valueTypes.NUMBER){if(prevSibling){if(prevSibling._valueType===valueTypes.UNIT){fromTargetObject.t=valueTypes.UNIT;fromTargetObject.u=prevSibling._unit}}else{decomposeRawValue(getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),decomposedOriginalValue);if(decomposedOriginalValue.t===valueTypes.UNIT){fromTargetObject.t=valueTypes.UNIT;fromTargetObject.u=decomposedOriginalValue.u}}}}else{if(hasToValue){decomposeRawValue(tweenToValue,toTargetObject)}else{if(prevTween){decomposeTweenValue(prevTween,toTargetObject)}else{decomposeRawValue(parent&&prevSibling&&prevSibling.parent.parent===parent?prevSibling._value:getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),toTargetObject)}}if(hasFromvalue){decomposeRawValue(tweenFromValue,fromTargetObject)}else{if(prevTween){decomposeTweenValue(prevTween,fromTargetObject)}else{decomposeRawValue(parent&&prevSibling&&prevSibling.parent.parent===parent?prevSibling._value:getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),fromTargetObject)}}}if(fromTargetObject.o){fromTargetObject.n=getRelativeValue(!prevSibling?decomposeRawValue(getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),decomposedOriginalValue).n:prevSibling._toNumber,fromTargetObject.n,fromTargetObject.o)}if(toTargetObject.o){toTargetObject.n=getRelativeValue(fromTargetObject.n,toTargetObject.n,toTargetObject.o)}if(fromTargetObject.t!==toTargetObject.t){if(fromTargetObject.t===valueTypes.COMPLEX||toTargetObject.t===valueTypes.COMPLEX){const complexValue=fromTargetObject.t===valueTypes.COMPLEX?fromTargetObject:toTargetObject;const notComplexValue=fromTargetObject.t===valueTypes.COMPLEX?toTargetObject:fromTargetObject;notComplexValue.t=valueTypes.COMPLEX;notComplexValue.s=cloneArray(complexValue.s);notComplexValue.d=complexValue.d.map((()=>notComplexValue.n))}else if(fromTargetObject.t===valueTypes.UNIT||toTargetObject.t===valueTypes.UNIT){const unitValue=fromTargetObject.t===valueTypes.UNIT?fromTargetObject:toTargetObject;const notUnitValue=fromTargetObject.t===valueTypes.UNIT?toTargetObject:fromTargetObject;notUnitValue.t=valueTypes.UNIT;notUnitValue.u=unitValue.u}else if(fromTargetObject.t===valueTypes.COLOR||toTargetObject.t===valueTypes.COLOR){const colorValue=fromTargetObject.t===valueTypes.COLOR?fromTargetObject:toTargetObject;const notColorValue=fromTargetObject.t===valueTypes.COLOR?toTargetObject:fromTargetObject;notColorValue.t=valueTypes.COLOR;notColorValue.s=colorValue.s;notColorValue.d=[0,0,0,1]}}if(fromTargetObject.u!==toTargetObject.u){let valueToConvert=toTargetObject.u?fromTargetObject:toTargetObject;valueToConvert=convertValueUnit(target,valueToConvert,toTargetObject.u?toTargetObject.u:fromTargetObject.u,false)}if(toTargetObject.d&&fromTargetObject.d&&toTargetObject.d.length!==fromTargetObject.d.length){const longestValue=fromTargetObject.d.length>toTargetObject.d.length?fromTargetObject:toTargetObject;const shortestValue=longestValue===fromTargetObject?toTargetObject:fromTargetObject;shortestValue.d=longestValue.d.map(((_,i)=>isUnd(shortestValue.d[i])?0:shortestValue.d[i]));shortestValue.s=cloneArray(longestValue.s)}const tweenUpdateDuration=round(+tweenDuration||minValue,12);const tween={parent:this,id:tweenId++,property:propName,target:target,_value:null,_func:toFunctionStore.func,_ease:parseEasings(tweenEasing),_fromNumbers:cloneArray(fromTargetObject.d),_toNumbers:cloneArray(toTargetObject.d),_strings:cloneArray(toTargetObject.s),_fromNumber:fromTargetObject.n,_toNumber:toTargetObject.n,_numbers:cloneArray(fromTargetObject.d),_number:fromTargetObject.n,_unit:toTargetObject.u,_modifier:tweenModifier,_currentTime:0,_startTime:tweenStartTime,_delay:+tweenDelay,_updateDuration:tweenUpdateDuration,_changeDuration:tweenUpdateDuration,_absoluteStartTime:absoluteStartTime,_tweenType:tweenType,_valueType:toTargetObject.t,_composition:tweenComposition,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};if(tweenComposition!==compositionTypes.none){composeTween(tween,siblings)}if(isNaN(firstTweenChangeStartTime)){firstTweenChangeStartTime=tween._startTime}lastTweenChangeEndTime=round(tweenStartTime+tweenUpdateDuration,12);prevTween=tween;animationAnimationLength++;addChild(this,tween)}if(isNaN(iterationDelay)||firstTweenChangeStartTime<iterationDelay){iterationDelay=firstTweenChangeStartTime}if(isNaN(iterationDuration)||lastTweenChangeEndTime>iterationDuration){iterationDuration=lastTweenChangeEndTime}if(tweenType===tweenTypes.TRANSFORM){lastTransformGroupIndex=animationAnimationLength-tweenIndex;lastTransformGroupLength=animationAnimationLength}}}if(!isNaN(lastTransformGroupIndex)){let i=0;forEachChildren(this,(tween=>{if(i>=lastTransformGroupIndex&&i<lastTransformGroupLength){tween._renderTransforms=1;if(tween._composition===compositionTypes.blend){forEachChildren(additive.animation,(additiveTween=>{if(additiveTween.id===tween.id){additiveTween._renderTransforms=1}}))}}i++}))}}if(!targetsLength){console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`)}if(iterationDelay){forEachChildren(this,(tween=>{if(!(tween._startTime-tween._delay)){tween._delay-=iterationDelay}tween._startTime-=iterationDelay}));iterationDuration-=iterationDelay}else{iterationDelay=0}if(!iterationDuration){iterationDuration=minValue;this.iterationCount=0}this.targets=parsedTargets;this.duration=iterationDuration===minValue?minValue:clampInfinity((iterationDuration+this._loopDelay)*this.iterationCount-this._loopDelay)||minValue;this.onRender=onRender||animDefaults.onRender;this._ease=animEase;this._delay=iterationDelay;this.iterationDuration=iterationDuration;this._inlineStyles=animInlineStyles;if(!this._autoplay&&shouldTriggerRender)this.onRender(this)}stretch(newDuration){const currentDuration=this.duration;if(currentDuration===normalizeTime(newDuration))return this;const timeScale=newDuration/currentDuration;forEachChildren(this,(tween=>{tween._updateDuration=normalizeTime(tween._updateDuration*timeScale);tween._changeDuration=normalizeTime(tween._changeDuration*timeScale);tween._currentTime*=timeScale;tween._startTime*=timeScale;tween._absoluteStartTime*=timeScale}));return super.stretch(newDuration)}refresh(){forEachChildren(this,(tween=>{const tweenFunc=tween._func;if(tweenFunc){const ogValue=getOriginalAnimatableValue(tween.target,tween.property,tween._tweenType);decomposeRawValue(ogValue,decomposedOriginalValue);decomposeRawValue(tweenFunc(),toTargetObject);tween._fromNumbers=cloneArray(decomposedOriginalValue.d);tween._fromNumber=decomposedOriginalValue.n;tween._toNumbers=cloneArray(toTargetObject.d);tween._strings=cloneArray(toTargetObject.s);tween._toNumber=toTargetObject.o?getRelativeValue(decomposedOriginalValue.n,toTargetObject.n,toTargetObject.o):toTargetObject.n}}));return this}revert(){super.revert();return cleanInlineStyles(this)}then(callback){return super.then(callback)}}const animate=(targets,parameters)=>new JSAnimation(targets,parameters,null,0,false).init();const easingToLinear=(fn,samples=100)=>{const points=[];for(let i=0;i<=samples;i++)points.push(fn(i/samples));return`linear(${points.join(", ")})`};const WAAPIEasesLookups={in:"ease-in",out:"ease-out",inOut:"ease-in-out"};const WAAPIeases=(()=>{const list={};for(let type in easeTypes)list[type]=p=>easeTypes[type](easeInPower(p));return list})();const parseWAAPIEasing=ease=>{let parsedEase=WAAPIEasesLookups[ease];if(parsedEase)return parsedEase;parsedEase="linear";if(isStr(ease)){if(stringStartsWith(ease,"linear")||stringStartsWith(ease,"cubic-")||stringStartsWith(ease,"steps")||stringStartsWith(ease,"ease")){parsedEase=ease}else if(stringStartsWith(ease,"cubicB")){parsedEase=toLowerCase(ease)}else{const parsed=parseEaseString(ease,WAAPIeases,WAAPIEasesLookups);if(isFnc(parsed))parsedEase=parsed===none?"linear":easingToLinear(parsed)}WAAPIEasesLookups[ease]=parsedEase}else if(isFnc(ease)){const easing=easingToLinear(ease);if(easing)parsedEase=easing}else if(ease.ease){parsedEase=easingToLinear(ease.ease)}return parsedEase};const transformsShorthands=["x","y","z"];const commonDefaultPXProperties=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",...transformsShorthands];const validIndividualTransforms=(()=>[...transformsShorthands,...validTransforms.filter((t=>["X","Y","Z"].some((axis=>t.endsWith(axis)))))])();let transformsPropertiesRegistered=null;const WAAPIAnimationsLookups={_head:null,_tail:null};const removeWAAPIAnimation=($el,property,parent)=>{let nextLookup=WAAPIAnimationsLookups._head;while(nextLookup){const next=nextLookup._next;const matchTarget=nextLookup.$el===$el;const matchProperty=!property||nextLookup.property===property;const matchParent=!parent||nextLookup.parent===parent;if(matchTarget&&matchProperty&&matchParent){const anim=nextLookup.animation;try{anim.commitStyles()}catch{}anim.cancel();removeChild(WAAPIAnimationsLookups,nextLookup);const lookupParent=nextLookup.parent;if(lookupParent){lookupParent._completed++;if(lookupParent.animations.length===lookupParent._completed){lookupParent.completed=true;if(!lookupParent.muteCallbacks){lookupParent.paused=true;lookupParent.onComplete(lookupParent);lookupParent._resolve(lookupParent)}}}}nextLookup=next}};const addWAAPIAnimation=(parent,$el,property,keyframes,params)=>{const animation=$el.animate(keyframes,params);const animTotalDuration=params.delay+ +params.duration*params.iterations;animation.playbackRate=parent._speed;if(parent.paused)animation.pause();if(parent.duration<animTotalDuration){parent.duration=animTotalDuration;parent.controlAnimation=animation}parent.animations.push(animation);removeWAAPIAnimation($el,property);addChild(WAAPIAnimationsLookups,{parent:parent,animation:animation,$el:$el,property:property,_next:null,_prev:null});const handleRemove=()=>{removeWAAPIAnimation($el,property,parent)};animation.onremove=handleRemove;animation.onfinish=handleRemove;return animation};const normalizeTweenValue=(propName,value,$el,i,targetsLength)=>{let v=getFunctionValue(value,$el,i,targetsLength);if(!isNum(v))return v;if(commonDefaultPXProperties.includes(propName)||stringStartsWith(propName,"translate"))return`${v}px`;if(stringStartsWith(propName,"rotate")||stringStartsWith(propName,"skew"))return`${v}deg`;return`${v}`};const parseIndividualTweenValue=($el,propName,from,to,i,targetsLength)=>{let tweenValue="0";const computedTo=!isUnd(to)?normalizeTweenValue(propName,to,$el,i,targetsLength):getComputedStyle($el)[propName];if(!isUnd(from)){const computedFrom=normalizeTweenValue(propName,from,$el,i,targetsLength);tweenValue=[computedFrom,computedTo]}else{tweenValue=isArr(to)?to.map((v=>normalizeTweenValue(propName,v,$el,i,targetsLength))):computedTo}return tweenValue};class WAAPIAnimation{constructor(targets,params){if(scope.current)scope.current.register(this);if(isNil(transformsPropertiesRegistered)){if(isBrowser&&(isUnd(CSS)||!Object.hasOwnProperty.call(CSS,"registerProperty"))){transformsPropertiesRegistered=false}else{validTransforms.forEach((t=>{const isSkew=stringStartsWith(t,"skew");const isScale=stringStartsWith(t,"scale");const isRotate=stringStartsWith(t,"rotate");const isTranslate=stringStartsWith(t,"translate");const isAngle=isRotate||isSkew;const syntax=isAngle?"<angle>":isScale?"<number>":isTranslate?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:syntax,inherits:false,initialValue:isTranslate?"0px":isAngle?"0deg":isScale?"1":"0"})}catch{}}));transformsPropertiesRegistered=true}}const parsedTargets=registerTargets(targets);const targetsLength=parsedTargets.length;if(!targetsLength){console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`)}const ease=setValue(params.ease,parseWAAPIEasing(globals.defaults.ease));const spring=ease.ease&&ease;const autoplay=setValue(params.autoplay,globals.defaults.autoplay);const scroll=autoplay&&autoplay.link?autoplay:false;const alternate=params.alternate&&params.alternate===true;const reversed=params.reversed&&params.reversed===true;const loop=setValue(params.loop,globals.defaults.loop);const iterations=loop===true||loop===Infinity?Infinity:isNum(loop)?loop+1:1;const direction=alternate?reversed?"alternate-reverse":"alternate":reversed?"reverse":"normal";const fill="forwards";const easing=parseWAAPIEasing(ease);const timeScale=globals.timeScale===1?1:K;this.targets=parsedTargets;this.animations=[];this.controlAnimation=null;this.onComplete=params.onComplete||noop;this.duration=0;this.muteCallbacks=false;this.completed=false;this.paused=!autoplay||scroll!==false;this.reversed=reversed;this.autoplay=autoplay;this._speed=setValue(params.playbackRate,globals.defaults.playbackRate);this._resolve=noop;this._completed=0;this._inlineStyles=parsedTargets.map(($el=>$el.getAttribute("style")));parsedTargets.forEach((($el,i)=>{const cachedTransforms=$el[transformsSymbol];const hasIndividualTransforms=validIndividualTransforms.some((t=>params.hasOwnProperty(t)));const duration=(spring?spring.duration:getFunctionValue(setValue(params.duration,globals.defaults.duration),$el,i,targetsLength))*timeScale;const delay=getFunctionValue(setValue(params.delay,globals.defaults.delay),$el,i,targetsLength)*timeScale;const composite=setValue(params.composition,"replace");for(let name in params){if(!isKey(name))continue;const keyframes={};const tweenParams={iterations:iterations,direction:direction,fill:fill,easing:easing,duration:duration,delay:delay,composite:composite};const propertyValue=params[name];const individualTransformProperty=hasIndividualTransforms?validTransforms.includes(name)?name:shortTransforms.get(name):false;let parsedPropertyValue;if(isObj(propertyValue)){const tweenOptions=propertyValue;const tweenOptionsEase=setValue(tweenOptions.ease,ease);const tweenOptionsSpring=tweenOptionsEase.ease&&tweenOptionsEase;const to=tweenOptions.to;const from=tweenOptions.from;tweenParams.duration=(tweenOptionsSpring?tweenOptionsSpring.duration:getFunctionValue(setValue(tweenOptions.duration,duration),$el,i,targetsLength))*timeScale;tweenParams.delay=getFunctionValue(setValue(tweenOptions.delay,delay),$el,i,targetsLength)*timeScale;tweenParams.composite=setValue(tweenOptions.composition,composite);tweenParams.easing=parseWAAPIEasing(tweenOptionsEase);parsedPropertyValue=parseIndividualTweenValue($el,name,from,to,i,targetsLength);if(individualTransformProperty){keyframes[`--${individualTransformProperty}`]=parsedPropertyValue;cachedTransforms[individualTransformProperty]=parsedPropertyValue}else{keyframes[name]=parseIndividualTweenValue($el,name,from,to,i,targetsLength)}addWAAPIAnimation(this,$el,name,keyframes,tweenParams);if(!isUnd(from)){if(!individualTransformProperty){$el.style[name]=keyframes[name][0]}else{const key=`--${individualTransformProperty}`;$el.style.setProperty(key,keyframes[key][0])}}}else{parsedPropertyValue=isArr(propertyValue)?propertyValue.map((v=>normalizeTweenValue(name,v,$el,i,targetsLength))):normalizeTweenValue(name,propertyValue,$el,i,targetsLength);if(individualTransformProperty){keyframes[`--${individualTransformProperty}`]=parsedPropertyValue;cachedTransforms[individualTransformProperty]=parsedPropertyValue}else{keyframes[name]=parsedPropertyValue}addWAAPIAnimation(this,$el,name,keyframes,tweenParams)}}if(hasIndividualTransforms){let transforms=emptyString;for(let t in cachedTransforms){transforms+=`${transformsFragmentStrings[t]}var(--${t})) `}$el.style.transform=transforms}}));if(scroll){this.autoplay.link(this)}}forEach(callback){const cb=isStr(callback)?a=>a[callback]():callback;this.animations.forEach(cb);return this}get speed(){return this._speed}set speed(speed){this._speed=+speed;this.forEach((anim=>anim.playbackRate=speed))}get currentTime(){const controlAnimation=this.controlAnimation;const timeScale=globals.timeScale;return this.completed?this.duration:controlAnimation?+controlAnimation.currentTime*(timeScale===1?1:timeScale):0}set currentTime(time){const t=time*(globals.timeScale===1?1:K);this.forEach((anim=>{if(t>=this.duration)anim.play();anim.currentTime=t}))}get progress(){return this.currentTime/this.duration}set progress(progress){this.forEach((anim=>anim.currentTime=progress*this.duration||0))}resume(){if(!this.paused)return this;this.paused=false;return this.forEach("play")}pause(){if(this.paused)return this;this.paused=true;return this.forEach("pause")}alternate(){this.reversed=!this.reversed;this.forEach("reverse");if(this.paused)this.forEach("pause");return this}play(){if(this.reversed)this.alternate();return this.resume()}reverse(){if(!this.reversed)this.alternate();return this.resume()}seek(time,muteCallbacks=false){if(muteCallbacks)this.muteCallbacks=true;if(time<this.duration)this.completed=false;this.currentTime=time;this.muteCallbacks=false;if(this.paused)this.pause();return this}restart(){this.completed=false;return this.seek(0,true).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){this.forEach("cancel");return this.pause()}revert(){this.cancel();this.targets.forEach((($el,i)=>$el.setAttribute("style",this._inlineStyles[i])));return this}then(callback=noop){const then=this.then;const onResolve=()=>{this.then=null;callback(this);this.then=then;this._resolve=noop};return new Promise((r=>{this._resolve=()=>r(onResolve());if(this.completed)this._resolve();return this}))}}const waapi={animate:(targets,params)=>new WAAPIAnimation(targets,params),convertEase:easingToLinear};const sync=(callback=noop)=>new Timer({duration:1*globals.timeScale,onComplete:callback},null,0).resume();function getTargetValue(targetSelector,propName,unit){const targets=registerTargets(targetSelector);if(!targets.length)return;const[target]=targets;const tweenType=getTweenType(target,propName);const normalizePropName=sanitizePropertyName(propName,target,tweenType);let originalValue=getOriginalAnimatableValue(target,normalizePropName);if(isUnd(unit)){return originalValue}else{decomposeRawValue(originalValue,decomposedOriginalValue);if(decomposedOriginalValue.t===valueTypes.NUMBER||decomposedOriginalValue.t===valueTypes.UNIT){if(unit===false){return decomposedOriginalValue.n}else{const convertedValue=convertValueUnit(target,decomposedOriginalValue,unit,false);return`${round(convertedValue.n,globals.precision)}${convertedValue.u}`}}}}const setTargetValues=(targets,parameters)=>{if(isUnd(parameters))return;parameters.duration=minValue;parameters.composition=setValue(parameters.composition,compositionTypes.none);return new JSAnimation(targets,parameters,null,0,true).resume()};const removeTargetsFromAnimation=(targetsArray,animation,propertyName)=>{let tweensMatchesTargets=false;forEachChildren(animation,(tween=>{const tweenTarget=tween.target;if(targetsArray.includes(tweenTarget)){const tweenName=tween.property;const tweenType=tween._tweenType;const normalizePropName=sanitizePropertyName(propertyName,tweenTarget,tweenType);if(!normalizePropName||normalizePropName&&normalizePropName===tweenName){if(tween.parent._tail===tween&&tween._tweenType===tweenTypes.TRANSFORM&&tween._prev&&tween._prev._tweenType===tweenTypes.TRANSFORM){tween._prev._renderTransforms=1}removeChild(animation,tween);removeTweenSliblings(tween);tweensMatchesTargets=true}}}),true);return tweensMatchesTargets};const remove=(targets,renderable,propertyName)=>{const targetsArray=parseTargets(targets);const parent=renderable?renderable:engine;const waapiAnimation=renderable&&renderable.controlAnimation&&renderable;for(let i=0,l=targetsArray.length;i<l;i++){const $el=targetsArray[i];removeWAAPIAnimation($el,propertyName,waapiAnimation)}let removeMatches;if(parent._hasChildren){let iterationDuration=0;forEachChildren(parent,(child=>{if(!child._hasChildren){removeMatches=removeTargetsFromAnimation(targetsArray,child,propertyName);if(removeMatches&&!child._head){child.cancel();removeChild(parent,child)}else{const childTLOffset=child._offset+child._delay;const childDur=childTLOffset+child.duration;if(childDur>iterationDuration){iterationDuration=childDur}}}if(child._head){remove(targets,child,propertyName)}else{child._hasChildren=false}}),true);if(!isUnd(parent.iterationDuration)){parent.iterationDuration=iterationDuration}}else{removeMatches=removeTargetsFromAnimation(targetsArray,parent,propertyName)}if(removeMatches&&!parent._head){parent._hasChildren=false;if(parent.cancel)parent.cancel()}return targetsArray};const keepTime=createRefreshable;const randomPick=items=>items[random(0,items.length-1)];const roundPad=(v,decimalLength)=>(+v).toFixed(decimalLength);const padStart=(v,totalLength,padString)=>`${v}`.padStart(totalLength,padString);const padEnd=(v,totalLength,padString)=>`${v}`.padEnd(totalLength,padString);const wrap=(v,min,max)=>((v-min)%(max-min)+(max-min))%(max-min)+min;const mapRange=(value,inLow,inHigh,outLow,outHigh)=>outLow+(value-inLow)/(inHigh-inLow)*(outHigh-outLow);const degToRad=degrees=>degrees*PI/180;const radToDeg=radians=>radians*180/PI;const lerp=(start,end,amount,renderable)=>{let dt=K/globals.defaults.frameRate;if(renderable!==false){const ticker=renderable||engine._hasChildren&&engine;if(ticker&&ticker.deltaTime){dt=ticker.deltaTime}}const t=1-Math.exp(-amount*dt*.1);return!amount?start:amount===1?end:(1-t)*start+t*end};const curry=(fn,last=0)=>(...args)=>last?v=>fn(...args,v):v=>fn(v,...args);const chain=fn=>(...args)=>{const result=fn(...args);return new Proxy(noop,{apply:(_,__,[v])=>result(v),get:(_,prop)=>chain(((...nextArgs)=>{const nextResult=utils[prop](...nextArgs);return v=>nextResult(result(v))}))})};const makeChainable=(fn,right=0)=>(...args)=>(args.length<fn.length?chain(curry(fn,right)):fn)(...args);const utils={$:registerTargets,get:getTargetValue,set:setTargetValues,remove:remove,cleanInlineStyles:cleanInlineStyles,random:random,randomPick:randomPick,shuffle:shuffle,lerp:lerp,sync:sync,keepTime:keepTime,clamp:makeChainable(clamp),round:makeChainable(round),snap:makeChainable(snap),wrap:makeChainable(wrap),interpolate:makeChainable(interpolate,1),mapRange:makeChainable(mapRange),roundPad:makeChainable(roundPad),padStart:makeChainable(padStart),padEnd:makeChainable(padEnd),degToRad:makeChainable(degToRad),radToDeg:makeChainable(radToDeg)};const getPrevChildOffset=(timeline,timePosition)=>{if(stringStartsWith(timePosition,"<")){const goToPrevAnimationOffset=timePosition[1]==="<";const prevAnimation=timeline._tail;const prevOffset=prevAnimation?prevAnimation._offset+prevAnimation._delay:0;return goToPrevAnimationOffset?prevOffset:prevOffset+prevAnimation.duration}};const parseTimelinePosition=(timeline,timePosition)=>{let tlDuration=timeline.iterationDuration;if(tlDuration===minValue)tlDuration=0;if(isUnd(timePosition))return tlDuration;if(isNum(+timePosition))return+timePosition;const timePosStr=timePosition;const tlLabels=timeline?timeline.labels:null;const hasLabels=!isNil(tlLabels);const prevOffset=getPrevChildOffset(timeline,timePosStr);const hasSibling=!isUnd(prevOffset);const matchedRelativeOperator=relativeValuesExecRgx.exec(timePosStr);if(matchedRelativeOperator){const fullOperator=matchedRelativeOperator[0];const split=timePosStr.split(fullOperator);const labelOffset=hasLabels&&split[0]?tlLabels[split[0]]:tlDuration;const parsedOffset=hasSibling?prevOffset:hasLabels?labelOffset:tlDuration;const parsedNumericalOffset=+split[1];return getRelativeValue(parsedOffset,parsedNumericalOffset,fullOperator[0])}else{return hasSibling?prevOffset:hasLabels?!isUnd(tlLabels[timePosStr])?tlLabels[timePosStr]:tlDuration:tlDuration}};function getTimelineTotalDuration(tl){return clampInfinity((tl.iterationDuration+tl._loopDelay)*tl.iterationCount-tl._loopDelay)||minValue}function addTlChild(childParams,tl,timePosition,targets,index,length){const isSetter=isNum(childParams.duration)&&childParams.duration<=minValue;const adjustedPosition=isSetter?timePosition-minValue:timePosition;tick(tl,adjustedPosition,1,1,tickModes.AUTO);const tlChild=targets?new JSAnimation(targets,childParams,tl,adjustedPosition,false,index,length):new Timer(childParams,tl,adjustedPosition);tlChild.init(1);addChild(tl,tlChild);forEachChildren(tl,(child=>{const childTLOffset=child._offset+child._delay;const childDur=childTLOffset+child.duration;if(childDur>tl.iterationDuration)tl.iterationDuration=childDur}));tl.duration=getTimelineTotalDuration(tl);return tl}class Timeline extends Timer{constructor(parameters={}){super(parameters,null,0);this.duration=0;this.labels={};const defaultsParams=parameters.defaults;const globalDefaults=globals.defaults;this.defaults=defaultsParams?mergeObjects(defaultsParams,globalDefaults):globalDefaults;this.onRender=parameters.onRender||globalDefaults.onRender;const tlPlaybackEase=setValue(parameters.playbackEase,globalDefaults.playbackEase);this._ease=tlPlaybackEase?parseEasings(tlPlaybackEase):null;this.iterationDuration=0}add(a1,a2,a3){const isAnim=isObj(a2);const isTimer=isObj(a1);if(isAnim||isTimer){this._hasChildren=true;if(isAnim){const childParams=a2;if(isFnc(a3)){const staggeredPosition=a3;const parsedTargetsArray=parseTargets(a1);const tlDuration=this.duration;const tlIterationDuration=this.iterationDuration;const id=childParams.id;let i=0;const parsedLength=parsedTargetsArray.length;parsedTargetsArray.forEach((target=>{const staggeredChildParams={...childParams};this.duration=tlDuration;this.iterationDuration=tlIterationDuration;if(!isUnd(id))staggeredChildParams.id=id+"-"+i;addTlChild(staggeredChildParams,this,parseTimelinePosition(this,staggeredPosition(target,i,parsedLength,this)),target,i,parsedLength);i++}))}else{addTlChild(childParams,this,parseTimelinePosition(this,a3),a1)}}else{addTlChild(a1,this,parseTimelinePosition(this,a2))}return this.init(1)}}sync(synced,position){if(isUnd(synced)||synced&&isUnd(synced.pause))return this;synced.pause();const duration=+(synced.effect?synced.effect.getTiming().duration:synced.duration);return this.add(synced,{currentTime:[0,duration],duration:duration,ease:"linear"},position)}set(targets,parameters,position){if(isUnd(parameters))return this;parameters.duration=minValue;parameters.composition=compositionTypes.replace;return this.add(targets,parameters,position)}call(callback,position){if(isUnd(callback)||callback&&!isFnc(callback))return this;return this.add({duration:0,onComplete:()=>callback(this)},position)}label(labelName,position){if(isUnd(labelName)||labelName&&!isStr(labelName))return this;this.labels[labelName]=parseTimelinePosition(this,position);return this}remove(targets,propertyName){remove(targets,this,propertyName);return this}stretch(newDuration){const currentDuration=this.duration;if(currentDuration===normalizeTime(newDuration))return this;const timeScale=newDuration/currentDuration;const labels=this.labels;forEachChildren(this,(child=>child.stretch(child.duration*timeScale)));for(let labelName in labels)labels[labelName]*=timeScale;return super.stretch(newDuration)}refresh(){forEachChildren(this,(child=>{if(child.refresh)child.refresh()}));return this}revert(){super.revert();forEachChildren(this,(child=>child.revert),true);return cleanInlineStyles(this)}then(callback){return super.then(callback)}}const createTimeline=parameters=>new Timeline(parameters).init();class Animatable{constructor(targets,parameters){if(scope.current)scope.current.register(this);const beginHandler=()=>{if(this.callbacks.completed)this.callbacks.reset();this.callbacks.play()};const pauseHandler=()=>{if(this.callbacks.completed)return;let paused=true;for(let name in this.animations){const anim=this.animations[name];if(!anim.paused&&paused){paused=false;break}}if(paused){this.callbacks.complete()}};const globalParams={onBegin:beginHandler,onComplete:pauseHandler,onPause:pauseHandler};const callbacksAnimationParams={v:1,autoplay:false};const properties={};this.targets=[];this.animations={};this.callbacks=null;if(isUnd(targets)||isUnd(parameters))return;for(let propName in parameters){const paramValue=parameters[propName];if(isKey(propName)){properties[propName]=paramValue}else if(stringStartsWith(propName,"on")){callbacksAnimationParams[propName]=paramValue}else{globalParams[propName]=paramValue}}this.callbacks=new JSAnimation({v:0},callbacksAnimationParams);for(let propName in properties){const propValue=properties[propName];const isObjValue=isObj(propValue);let propParams={};let to="+=0";if(isObjValue){const unit=propValue.unit;if(isStr(unit))to+=unit}else{propParams.duration=propValue}propParams[propName]=isObjValue?mergeObjects({to:to},propValue):to;const animParams=mergeObjects(globalParams,propParams);animParams.composition=compositionTypes.replace;animParams.autoplay=false;const animation=this.animations[propName]=new JSAnimation(targets,animParams,null,0,false).init();if(!this.targets.length)this.targets.push(...animation.targets);this[propName]=(to,duration,ease)=>{const tween=animation._head;if(isUnd(to)&&tween){const numbers=tween._numbers;if(numbers&&numbers.length){return numbers}else{return tween._modifier(tween._number)}}else{forEachChildren(animation,(tween=>{if(isArr(to)){for(let i=0,l=to.length;i<l;i++){if(!isUnd(tween._numbers[i])){tween._fromNumbers[i]=tween._modifier(tween._numbers[i]);tween._toNumbers[i]=to[i]}}}else{tween._fromNumber=tween._modifier(tween._number);tween._toNumber=to}if(!isUnd(ease))tween._ease=parseEasings(ease);tween._currentTime=0}));if(!isUnd(duration))animation.stretch(duration);animation.reset(1).resume();return this}}}}revert(){for(let propName in this.animations){this[propName]=noop;this.animations[propName].revert()}this.animations={};this.targets.length=0;if(this.callbacks)this.callbacks.revert();return this}}const createAnimatable=(targets,parameters)=>new Animatable(targets,parameters);const maxSpringParamValue=K*10;class Spring{constructor(parameters={}){this.timeStep=.02;this.restThreshold=5e-4;this.restDuration=200;this.maxDuration=6e4;this.maxRestSteps=this.restDuration/this.timeStep/K;this.maxIterations=this.maxDuration/this.timeStep/K;this.m=clamp(setValue(parameters.mass,1),0,maxSpringParamValue);this.s=clamp(setValue(parameters.stiffness,100),1,maxSpringParamValue);this.d=clamp(setValue(parameters.damping,10),.1,maxSpringParamValue);this.v=clamp(setValue(parameters.velocity,0),-1e4,maxSpringParamValue);this.w0=0;this.zeta=0;this.wd=0;this.b=0;this.solverDuration=0;this.duration=0;this.compute();this.ease=t=>t===0||t===1?t:this.solve(t*this.solverDuration)}solve(time){const{zeta:zeta,w0:w0,wd:wd,b:b}=this;let t=time;if(zeta<1){t=exp(-t*zeta*w0)*(1*cos(wd*t)+b*sin(wd*t))}else{t=(1+b*t)*exp(-t*w0)}return 1-t}compute(){const{maxRestSteps:maxRestSteps,maxIterations:maxIterations,restThreshold:restThreshold,timeStep:timeStep,m:m,d:d,s:s,v:v}=this;const w0=this.w0=clamp(sqrt(s/m),minValue,K);const zeta=this.zeta=d/(2*sqrt(s*m));const wd=this.wd=zeta<1?w0*sqrt(1-zeta*zeta):0;this.b=zeta<1?(zeta*w0+-v)/wd:-v+w0;let solverTime=0;let restSteps=0;let iterations=0;while(restSteps<maxRestSteps&&iterations<maxIterations){if(abs(1-this.solve(solverTime))<restThreshold){restSteps++}else{restSteps=0}this.solverDuration=solverTime;solverTime+=timeStep;iterations++}this.duration=round(this.solverDuration*K,0)*globals.timeScale}get mass(){return this.m}set mass(v){this.m=clamp(setValue(v,1),0,maxSpringParamValue);this.compute()}get stiffness(){return this.s}set stiffness(v){this.s=clamp(setValue(v,100),1,maxSpringParamValue);this.compute()}get damping(){return this.d}set damping(v){this.d=clamp(setValue(v,10),.1,maxSpringParamValue);this.compute()}get velocity(){return this.v}set velocity(v){this.v=clamp(setValue(v,0),-1e4,maxSpringParamValue);this.compute()}}const createSpring=parameters=>new Spring(parameters);const preventDefault=e=>{if(e.cancelable)e.preventDefault()};class DOMProxy{constructor(el){this.el=el;this.zIndex=0;this.parentElement=null;this.classList={add:noop,remove:noop}}get x(){return this.el.x||0}set x(v){this.el.x=v}get y(){return this.el.y||0}set y(v){this.el.y=v}get width(){return this.el.width||0}set width(v){this.el.width=v}get height(){return this.el.height||0}set height(v){this.el.height=v}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class Transforms{constructor($el){this.$el=$el;this.inlineTransforms=[];this.point=new DOMPoint;this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(x,y){this.point.x=x;this.point.y=y;return this.point.matrixTransform(this.inversedMatrix)}traverseUp(cb){let $el=this.$el.parentElement,i=0;while($el&&$el!==doc){cb($el,i);$el=$el.parentElement;i++}}getMatrix(){const matrix=new DOMMatrix;this.traverseUp(($el=>{const transformValue=getComputedStyle($el).transform;if(transformValue){const elMatrix=new DOMMatrix(transformValue);matrix.preMultiplySelf(elMatrix)}}));return matrix}remove(){this.traverseUp((($el,i)=>{this.inlineTransforms[i]=$el.style.transform;$el.style.transform="none"}))}revert(){this.traverseUp((($el,i)=>{const ct=this.inlineTransforms[i];if(ct===""){$el.style.removeProperty("transform")}else{$el.style.transform=ct}}))}}const parseDraggableFunctionParameter=(value,draggable)=>value&&isFnc(value)?value(draggable):value;let zIndex=0;class Draggable{constructor(target,parameters={}){if(!target)return;if(scope.current)scope.current.register(this);const paramX=parameters.x;const paramY=parameters.y;const trigger=parameters.trigger;const modifier=parameters.modifier;const ease=parameters.releaseEase;const customEase=ease&&parseEasings(ease);const hasSpring=!isUnd(ease)&&!isUnd(ease.ease);const xProp=isObj(paramX)&&!isUnd(paramX.mapTo)?paramX.mapTo:"translateX";const yProp=isObj(paramY)&&!isUnd(paramY.mapTo)?paramY.mapTo:"translateY";const container=parseDraggableFunctionParameter(parameters.container,this);this.containerArray=isArr(container)?container:null;this.$container=container&&!this.containerArray?parseTargets(container)[0]:doc.body;this.useWin=this.$container===doc.body;this.$scrollContainer=this.useWin?win:this.$container;this.$target=isObj(target)?new DOMProxy(target):parseTargets(target)[0];this.$trigger=parseTargets(trigger?trigger:target)[0];this.fixed=getTargetValue(this.$target,"position")==="fixed";this.isFinePointer=true;this.containerPadding=[0,0,0,0];this.containerFriction=0;this.releaseContainerFriction=0;this.snapX=0;this.snapY=0;this.scrollSpeed=0;this.scrollThreshold=0;this.dragSpeed=0;this.maxVelocity=0;this.minVelocity=0;this.velocityMultiplier=0;this.cursor=false;this.releaseXSpring=hasSpring?ease:createSpring({mass:setValue(parameters.releaseMass,1),stiffness:setValue(parameters.releaseStiffness,80),damping:setValue(parameters.releaseDamping,20)});this.releaseYSpring=hasSpring?ease:createSpring({mass:setValue(parameters.releaseMass,1),stiffness:setValue(parameters.releaseStiffness,80),damping:setValue(parameters.releaseDamping,20)});this.releaseEase=customEase||eases.outQuint;this.hasReleaseSpring=hasSpring;this.onGrab=parameters.onGrab||noop;this.onDrag=parameters.onDrag||noop;this.onRelease=parameters.onRelease||noop;this.onUpdate=parameters.onUpdate||noop;this.onSettle=parameters.onSettle||noop;this.onSnap=parameters.onSnap||noop;this.onResize=parameters.onResize||noop;this.onAfterResize=parameters.onAfterResize||noop;this.disabled=[0,0];const animatableParams={};if(modifier)animatableParams.modifier=modifier;if(isUnd(paramX)||paramX===true){animatableParams[xProp]=0}else if(isObj(paramX)){const paramXObject=paramX;const animatableXParams={};if(paramXObject.modifier)animatableXParams.modifier=paramXObject.modifier;if(paramXObject.composition)animatableXParams.composition=paramXObject.composition;animatableParams[xProp]=animatableXParams}else if(paramX===false){animatableParams[xProp]=0;this.disabled[0]=1}if(isUnd(paramY)||paramY===true){animatableParams[yProp]=0}else if(isObj(paramY)){const paramYObject=paramY;const animatableYParams={};if(paramYObject.modifier)animatableYParams.modifier=paramYObject.modifier;if(paramYObject.composition)animatableYParams.composition=paramYObject.composition;animatableParams[yProp]=animatableYParams}else if(paramY===false){animatableParams[yProp]=0;this.disabled[1]=1}this.animate=new Animatable(this.$target,animatableParams);this.xProp=xProp;this.yProp=yProp;this.destX=0;this.destY=0;this.deltaX=0;this.deltaY=0;this.scroll={x:0,y:0};this.coords=[this.x,this.y,0,0];this.snapped=[0,0];this.pointer=[0,0,0,0,0,0,0,0];this.scrollView=[0,0];this.dragArea=[0,0,0,0];this.containerBounds=[-1e12,maxValue,maxValue,-1e12];this.scrollBounds=[0,0,0,0];this.targetBounds=[0,0,0,0];this.window=[0,0];this.velocityStack=[0,0,0];this.velocityStackIndex=0;this.velocityTime=now();this.velocity=0;this.angle=0;this.cursorStyles=null;this.triggerStyles=null;this.bodyStyles=null;this.targetStyles=null;this.touchActionStyles=null;this.transforms=new Transforms(this.$target);this.overshootCoords={x:0,y:0};this.overshootTicker=new Timer({autoplay:false,onUpdate:()=>{this.updated=true;this.manual=true;if(!this.disabled[0])this.animate[this.xProp](this.overshootCoords.x,1);if(!this.disabled[1])this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=false;if(!this.disabled[0])this.animate[this.xProp](this.overshootCoords.x,0);if(!this.disabled[1])this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init();this.updateTicker=new Timer({autoplay:false,onUpdate:()=>this.update()},null,0).init();this.contained=!isUnd(container);this.manual=false;this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.enabled=false;this.initialized=false;this.activeProp=this.disabled[1]?xProp:yProp;this.animate.callbacks.onRender=()=>{const hasUpdated=this.updated;const hasMoved=this.grabbed&&hasUpdated;const hasReleased=!hasMoved&&this.released;const x=this.x;const y=this.y;const dx=x-this.coords[2];const dy=y-this.coords[3];this.deltaX=dx;this.deltaY=dy;this.coords[2]=x;this.coords[3]=y;if(hasUpdated&&(dx||dy)){this.onUpdate(this)}if(!hasReleased){this.updated=false}else{this.computeVelocity(dx,dy);this.angle=atan2(dy,dx)}};this.animate.callbacks.onComplete=()=>{if(!this.grabbed&&this.released){this.released=false}if(!this.manual){this.deltaX=0;this.deltaY=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.onSettle(this)}};this.resizeTicker=new Timer({autoplay:false,duration:150*globals.timeScale,onComplete:()=>{this.onResize(this);this.refresh();this.onAfterResize(this)}}).init();this.parameters=parameters;this.resizeObserver=new ResizeObserver((()=>{if(this.initialized){this.resizeTicker.restart()}else{this.initialized=true}}));this.enable();this.refresh();this.resizeObserver.observe(this.$container);if(!isObj(target))this.resizeObserver.observe(this.$target)}computeVelocity(dx,dy){const prevTime=this.velocityTime;const curTime=now();const elapsed=curTime-prevTime;if(elapsed<17)return this.velocity;this.velocityTime=curTime;const velocityStack=this.velocityStack;const vMul=this.velocityMultiplier;const minV=this.minVelocity;const maxV=this.maxVelocity;const vi=this.velocityStackIndex;velocityStack[vi]=round(clamp(sqrt(dx*dx+dy*dy)/elapsed*vMul,minV,maxV),5);const velocity=max(velocityStack[0],velocityStack[1],velocityStack[2]);this.velocity=velocity;this.velocityStackIndex=(vi+1)%3;return velocity}setX(x,muteUpdateCallback=false){if(this.disabled[0])return;const v=round(x,5);this.overshootTicker.pause();this.manual=true;this.updated=!muteUpdateCallback;this.destX=v;this.snapped[0]=snap(v,this.snapX);this.animate[this.xProp](v,0);this.manual=false;return this}setY(y,muteUpdateCallback=false){if(this.disabled[1])return;const v=round(y,5);this.overshootTicker.pause();this.manual=true;this.updated=!muteUpdateCallback;this.destY=v;this.snapped[1]=snap(v,this.snapY);this.animate[this.yProp](v,0);this.manual=false;return this}get x(){return round(this.animate[this.xProp](),globals.precision)}set x(x){this.setX(x,false)}get y(){return round(this.animate[this.yProp](),globals.precision)}set y(y){this.setY(y,false)}get progressX(){return mapRange(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(x){this.setX(mapRange(x,0,1,this.containerBounds[3],this.containerBounds[1]),false)}get progressY(){return mapRange(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(y){this.setY(mapRange(y,0,1,this.containerBounds[0],this.containerBounds[2]),false)}updateScrollCoords(){const sx=round(this.useWin?win.scrollX:this.$container.scrollLeft,0);const sy=round(this.useWin?win.scrollY:this.$container.scrollTop,0);const[cpt,cpr,cpb,cpl]=this.containerPadding;const threshold=this.scrollThreshold;this.scroll.x=sx;this.scroll.y=sy;this.scrollBounds[0]=sy-this.targetBounds[0]+cpt-threshold;this.scrollBounds[1]=sx-this.targetBounds[1]-cpr+threshold;this.scrollBounds[2]=sy-this.targetBounds[2]-cpb+threshold;this.scrollBounds[3]=sx-this.targetBounds[3]+cpl-threshold}updateBoundingValues(){const $container=this.$container;if(!$container)return;const cx=this.x;const cy=this.y;const cx2=this.coords[2];const cy2=this.coords[3];this.coords[2]=0;this.coords[3]=0;this.setX(0,true);this.setY(0,true);this.transforms.remove();const iw=this.window[0]=win.innerWidth;const ih=this.window[1]=win.innerHeight;const uw=this.useWin;const sw=$container.scrollWidth;const sh=$container.scrollHeight;const fx=this.fixed;const transformContainerRect=$container.getBoundingClientRect();const[cpt,cpr,cpb,cpl]=this.containerPadding;this.dragArea[0]=uw?0:transformContainerRect.left;this.dragArea[1]=uw?0:transformContainerRect.top;this.scrollView[0]=uw?clamp(sw,iw,sw):sw;this.scrollView[1]=uw?clamp(sh,ih,sh):sh;this.updateScrollCoords();const{width:width,height:height,left:left,top:top,right:right,bottom:bottom}=$container.getBoundingClientRect();this.dragArea[2]=round(uw?clamp(width,iw,iw):width,0);this.dragArea[3]=round(uw?clamp(height,ih,ih):height,0);const containerOverflow=getTargetValue($container,"overflow");const visibleOverflow=containerOverflow==="visible";const hiddenOverflow=containerOverflow==="hidden";this.canScroll=fx?false:this.contained&&($container===doc.body&&visibleOverflow||!hiddenOverflow&&!visibleOverflow)&&(sw>this.dragArea[2]+cpl-cpr||sh>this.dragArea[3]+cpt-cpb)&&(!this.containerArray||this.containerArray&&!isArr(this.containerArray));if(this.contained){const sx=this.scroll.x;const sy=this.scroll.y;const canScroll=this.canScroll;const targetRect=this.$target.getBoundingClientRect();const hiddenLeft=canScroll?uw?0:$container.scrollLeft:0;const hiddenTop=canScroll?uw?0:$container.scrollTop:0;const hiddenRight=canScroll?this.scrollView[0]-hiddenLeft-width:0;const hiddenBottom=canScroll?this.scrollView[1]-hiddenTop-height:0;this.targetBounds[0]=round(targetRect.top+sy-(uw?0:top),0);this.targetBounds[1]=round(targetRect.right+sx-(uw?iw:right),0);this.targetBounds[2]=round(targetRect.bottom+sy-(uw?ih:bottom),0);this.targetBounds[3]=round(targetRect.left+sx-(uw?0:left),0);if(this.containerArray){this.containerBounds[0]=this.containerArray[0]+cpt;this.containerBounds[1]=this.containerArray[1]-cpr;this.containerBounds[2]=this.containerArray[2]-cpb;this.containerBounds[3]=this.containerArray[3]+cpl}else{this.containerBounds[0]=-round(targetRect.top-(fx?clamp(top,0,ih):top)+hiddenTop-cpt,0);this.containerBounds[1]=-round(targetRect.right-(fx?clamp(right,0,iw):right)-hiddenRight+cpr,0);this.containerBounds[2]=-round(targetRect.bottom-(fx?clamp(bottom,0,ih):bottom)-hiddenBottom+cpb,0);this.containerBounds[3]=-round(targetRect.left-(fx?clamp(left,0,iw):left)+hiddenLeft-cpl,0)}}this.transforms.revert();this.coords[2]=cx2;this.coords[3]=cy2;this.setX(cx,true);this.setY(cy,true)}isOutOfBounds(bounds,x,y){if(!this.contained)return 0;const[bt,br,bb,bl]=bounds;const[dx,dy]=this.disabled;const obx=!dx&&x<bl||!dx&&x>br;const oby=!dy&&y<bt||!dy&&y>bb;return obx&&!oby?1:!obx&&oby?2:obx&&oby?3:0}refresh(){const params=this.parameters;const paramX=params.x;const paramY=params.y;const container=parseDraggableFunctionParameter(params.container,this);const cp=parseDraggableFunctionParameter(params.containerPadding,this)||0;const containerPadding=isArr(cp)?cp:[cp,cp,cp,cp];const cx=this.x;const cy=this.y;const parsedCursorStyles=parseDraggableFunctionParameter(params.cursor,this);const cursorStyles={onHover:"grab",onGrab:"grabbing"};if(parsedCursorStyles){const{onHover:onHover,onGrab:onGrab}=parsedCursorStyles;if(onHover)cursorStyles.onHover=onHover;if(onGrab)cursorStyles.onGrab=onGrab}this.containerArray=isArr(container)?container:null;this.$container=container&&!this.containerArray?parseTargets(container)[0]:doc.body;this.useWin=this.$container===doc.body;this.$scrollContainer=this.useWin?win:this.$container;this.isFinePointer=matchMedia("(pointer:fine)").matches;this.containerPadding=setValue(containerPadding,[0,0,0,0]);this.containerFriction=clamp(setValue(parseDraggableFunctionParameter(params.containerFriction,this),.8),0,1);this.releaseContainerFriction=clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction,this),this.containerFriction),0,1);this.snapX=parseDraggableFunctionParameter(isObj(paramX)&&!isUnd(paramX.snap)?paramX.snap:params.snap,this);this.snapY=parseDraggableFunctionParameter(isObj(paramY)&&!isUnd(paramY.snap)?paramY.snap:params.snap,this);this.scrollSpeed=setValue(parseDraggableFunctionParameter(params.scrollSpeed,this),1.5);this.scrollThreshold=setValue(parseDraggableFunctionParameter(params.scrollThreshold,this),20);this.dragSpeed=setValue(parseDraggableFunctionParameter(params.dragSpeed,this),1);this.minVelocity=setValue(parseDraggableFunctionParameter(params.minVelocity,this),0);this.maxVelocity=setValue(parseDraggableFunctionParameter(params.maxVelocity,this),50);this.velocityMultiplier=setValue(parseDraggableFunctionParameter(params.velocityMultiplier,this),1);this.cursor=parsedCursorStyles===false?false:cursorStyles;this.updateBoundingValues();const[bt,br,bb,bl]=this.containerBounds;this.setX(clamp(cx,bl,br),true);this.setY(clamp(cy,bt,bb),true)}update(){this.updateScrollCoords();if(this.canScroll){const[cpt,cpr,cpb,cpl]=this.containerPadding;const[sw,sh]=this.scrollView;const daw=this.dragArea[2];const dah=this.dragArea[3];const csx=this.scroll.x;const csy=this.scroll.y;const nsw=this.$container.scrollWidth;const nsh=this.$container.scrollHeight;const csw=this.useWin?clamp(nsw,this.window[0],nsw):nsw;const csh=this.useWin?clamp(nsh,this.window[1],nsh):nsh;const swd=sw-csw;const shd=sh-csh;if(this.dragged&&swd>0){this.coords[0]-=swd;this.scrollView[0]=csw}if(this.dragged&&shd>0){this.coords[1]-=shd;this.scrollView[1]=csh}const s=this.scrollSpeed*10;const threshold=this.scrollThreshold;const[x,y]=this.coords;const[st,sr,sb,sl]=this.scrollBounds;const t=round(clamp((y-st+cpt)/threshold,-1,0)*s,0);const r=round(clamp((x-sr-cpr)/threshold,0,1)*s,0);const b=round(clamp((y-sb-cpb)/threshold,0,1)*s,0);const l=round(clamp((x-sl+cpl)/threshold,-1,0)*s,0);if(t||b||l||r){const[nx,ny]=this.disabled;let scrollX=csx;let scrollY=csy;if(!nx){scrollX=round(clamp(csx+(l||r),0,sw-daw),0);this.coords[0]-=csx-scrollX}if(!ny){scrollY=round(clamp(csy+(t||b),0,sh-dah),0);this.coords[1]-=csy-scrollY}if(this.useWin){this.$scrollContainer.scrollBy(-(csx-scrollX),-(csy-scrollY))}else{this.$scrollContainer.scrollTo(scrollX,scrollY)}}}const[ct,cr,cb,cl]=this.containerBounds;const[px1,py1,px2,py2,px3,py3]=this.pointer;this.coords[0]+=(px1-px3)*this.dragSpeed;this.coords[1]+=(py1-py3)*this.dragSpeed;this.pointer[4]=px1;this.pointer[5]=py1;const[cx,cy]=this.coords;const[sx,sy]=this.snapped;const cf=(1-this.containerFriction)*this.dragSpeed;this.setX(cx>cr?cr+(cx-cr)*cf:cx<cl?cl+(cx-cl)*cf:cx,false);this.setY(cy>cb?cb+(cy-cb)*cf:cy<ct?ct+(cy-ct)*cf:cy,false);this.computeVelocity(px1-px3,py1-py3);this.angle=atan2(py1-py2,px1-px2);const[nsx,nsy]=this.snapped;if(nsx!==sx&&this.snapX||nsy!==sy&&this.snapY){this.onSnap(this)}}stop(){this.updateTicker.pause();this.overshootTicker.pause();for(let prop in this.animate.animations)this.animate.animations[prop].pause();remove(this,null,"x");remove(this,null,"y");remove(this,null,"progressX");remove(this,null,"progressY");remove(this.scroll);remove(this.overshootCoords);return this}scrollInView(duration,gap=0,ease=eases.inOutQuad){this.updateScrollCoords();const x=this.destX;const y=this.destY;const scroll=this.scroll;const scrollBounds=this.scrollBounds;const canScroll=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(scrollBounds,x,y)){const[st,sr,sb,sl]=scrollBounds;const t=round(clamp(y-st,-1e12,0),0);const r=round(clamp(x-sr,0,maxValue),0);const b=round(clamp(y-sb,0,maxValue),0);const l=round(clamp(x-sl,-1e12,0),0);new JSAnimation(scroll,{x:round(scroll.x+(l?l-gap:r?r+gap:0),0),y:round(scroll.y+(t?t-gap:b?b+gap:0),0),duration:isUnd(duration)?350*globals.timeScale:duration,ease:ease,onUpdate:()=>{this.canScroll=false;this.$scrollContainer.scrollTo(scroll.x,scroll.y)}}).init().then((()=>{this.canScroll=canScroll}))}return this}handleHover(){if(this.isFinePointer&&this.cursor&&!this.cursorStyles){this.cursorStyles=setTargetValues(this.$trigger,{cursor:this.cursor.onHover})}}animateInView(duration,gap=0,ease=eases.inOutQuad){this.stop();this.updateBoundingValues();const x=this.x;const y=this.y;const[cpt,cpr,cpb,cpl]=this.containerPadding;const bt=this.scroll.y-this.targetBounds[0]+cpt+gap;const br=this.scroll.x-this.targetBounds[1]-cpr-gap;const bb=this.scroll.y-this.targetBounds[2]-cpb-gap;const bl=this.scroll.x-this.targetBounds[3]+cpl+gap;const ob=this.isOutOfBounds([bt,br,bb,bl],x,y);if(ob){const[disabledX,disabledY]=this.disabled;const destX=clamp(snap(x,this.snapX),bl,br);const destY=clamp(snap(y,this.snapY),bt,bb);const dur=isUnd(duration)?350*globals.timeScale:duration;if(!disabledX&&(ob===1||ob===3))this.animate[this.xProp](destX,dur,ease);if(!disabledY&&(ob===2||ob===3))this.animate[this.yProp](destY,dur,ease)}return this}handleDown(e){const $eTarget=e.target;if(this.grabbed||$eTarget.type==="range")return;e.stopPropagation();this.grabbed=true;this.released=false;this.stop();this.updateBoundingValues();const touches=e.changedTouches;const eventX=touches?touches[0].clientX:e.clientX;const eventY=touches?touches[0].clientY:e.clientY;const{x:x,y:y}=this.transforms.normalizePoint(eventX,eventY);const[ct,cr,cb,cl]=this.containerBounds;const cf=(1-this.containerFriction)*this.dragSpeed;const cx=this.x;const cy=this.y;this.coords[0]=this.coords[2]=!cf?cx:cx>cr?cr+(cx-cr)/cf:cx<cl?cl+(cx-cl)/cf:cx;this.coords[1]=this.coords[3]=!cf?cy:cy>cb?cb+(cy-cb)/cf:cy<ct?ct+(cy-ct)/cf:cy;this.pointer[0]=x;this.pointer[1]=y;this.pointer[2]=x;this.pointer[3]=y;this.pointer[4]=x;this.pointer[5]=y;this.pointer[6]=x;this.pointer[7]=y;this.deltaX=0;this.deltaY=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.angle=0;if(this.targetStyles){this.targetStyles.revert();this.targetStyles=null}const z=getTargetValue(this.$target,"zIndex",false);zIndex=(z>zIndex?z:zIndex)+1;this.targetStyles=setTargetValues(this.$target,{zIndex:zIndex});if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.cursorStyles){this.cursorStyles.revert();this.cursorStyles=null}if(this.isFinePointer&&this.cursor){this.bodyStyles=setTargetValues(doc.body,{cursor:this.cursor.onGrab})}this.scrollInView(100,0,eases.out(3));this.onGrab(this);doc.addEventListener("touchmove",this);doc.addEventListener("touchend",this);doc.addEventListener("touchcancel",this);doc.addEventListener("mousemove",this);doc.addEventListener("mouseup",this);doc.addEventListener("selectstart",this)}handleMove(e){if(!this.grabbed)return;const touches=e.changedTouches;const eventX=touches?touches[0].clientX:e.clientX;const eventY=touches?touches[0].clientY:e.clientY;const{x:x,y:y}=this.transforms.normalizePoint(eventX,eventY);const movedX=x-this.pointer[6];const movedY=y-this.pointer[7];let $parent=e.target;let isAtTop=false;let isAtBottom=false;let canTouchScroll=false;while(touches&&$parent&&$parent!==this.$trigger){const overflowY=getTargetValue($parent,"overflow-y");if(overflowY!=="hidden"&&overflowY!=="visible"){const{scrollTop:scrollTop,scrollHeight:scrollHeight,clientHeight:clientHeight}=$parent;if(scrollHeight>clientHeight){canTouchScroll=true;isAtTop=scrollTop<=3;isAtBottom=scrollTop>=scrollHeight-clientHeight-3;break}}$parent=$parent.parentNode}if(canTouchScroll&&(!isAtTop&&!isAtBottom||isAtTop&&movedY<0||isAtBottom&&movedY>0)){this.pointer[0]=x;this.pointer[1]=y;this.pointer[2]=x;this.pointer[3]=y;this.pointer[4]=x;this.pointer[5]=y;this.pointer[6]=x;this.pointer[7]=y}else{preventDefault(e);if(!this.triggerStyles)this.triggerStyles=setTargetValues(this.$trigger,{pointerEvents:"none"});this.$trigger.addEventListener("touchstart",preventDefault,{passive:false});this.$trigger.addEventListener("touchmove",preventDefault,{passive:false});this.$trigger.addEventListener("touchend",preventDefault);if(!this.disabled[0]&&abs(movedX)>3||!this.disabled[1]&&abs(movedY)>3){this.updateTicker.resume();this.pointer[2]=this.pointer[0];this.pointer[3]=this.pointer[1];this.pointer[0]=x;this.pointer[1]=y;this.dragged=true;this.released=false;this.onDrag(this)}}}handleUp(){if(!this.grabbed)return;this.updateTicker.pause();if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.bodyStyles){this.bodyStyles.revert();this.bodyStyles=null}const[disabledX,disabledY]=this.disabled;const[px1,py1,px2,py2,px3,py3]=this.pointer;const[ct,cr,cb,cl]=this.containerBounds;const[sx,sy]=this.snapped;const springX=this.releaseXSpring;const springY=this.releaseYSpring;const releaseEase=this.releaseEase;const hasReleaseSpring=this.hasReleaseSpring;const overshootCoords=this.overshootCoords;const cx=this.x;const cy=this.y;const pv=this.computeVelocity(px1-px3,py1-py3);const pa=this.angle=atan2(py1-py2,px1-px2);const ds=pv*150;const cf=(1-this.releaseContainerFriction)*this.dragSpeed;const nx=cx+cos(pa)*ds;const ny=cy+sin(pa)*ds;const bx=nx>cr?cr+(nx-cr)*cf:nx<cl?cl+(nx-cl)*cf:nx;const by=ny>cb?cb+(ny-cb)*cf:ny<ct?ct+(ny-ct)*cf:ny;const dx=this.destX=clamp(round(snap(bx,this.snapX),5),cl,cr);const dy=this.destY=clamp(round(snap(by,this.snapY),5),ct,cb);const ob=this.isOutOfBounds(this.containerBounds,nx,ny);let durationX=0;let durationY=0;let easeX=releaseEase;let easeY=releaseEase;let longestReleaseDuration=0;overshootCoords.x=cx;overshootCoords.y=cy;if(!disabledX){const directionX=dx===cr?cx>cr?-1:1:cx<cl?-1:1;const distanceX=round(cx-dx,0);springX.velocity=disabledY&&hasReleaseSpring?distanceX?ds*directionX/abs(distanceX):0:pv;const{ease:ease,duration:duration,restDuration:restDuration}=springX;durationX=cx===dx?0:hasReleaseSpring?duration:duration-restDuration*globals.timeScale;if(hasReleaseSpring)easeX=ease;if(durationX>longestReleaseDuration)longestReleaseDuration=durationX}if(!disabledY){const directionY=dy===cb?cy>cb?-1:1:cy<ct?-1:1;const distanceY=round(cy-dy,0);springY.velocity=disabledX&&hasReleaseSpring?distanceY?ds*directionY/abs(distanceY):0:pv;const{ease:ease,duration:duration,restDuration:restDuration}=springY;durationY=cy===dy?0:hasReleaseSpring?duration:duration-restDuration*globals.timeScale;if(hasReleaseSpring)easeY=ease;if(durationY>longestReleaseDuration)longestReleaseDuration=durationY}if(!hasReleaseSpring&&ob&&cf&&(durationX||durationY)){const composition=compositionTypes.blend;new JSAnimation(overshootCoords,{x:{to:bx,duration:durationX*.65},y:{to:by,duration:durationY*.65},ease:releaseEase,composition:composition}).init();new JSAnimation(overshootCoords,{x:{to:dx,duration:durationX},y:{to:dy,duration:durationY},ease:releaseEase,composition:composition}).init();this.overshootTicker.stretch(max(durationX,durationY)).restart()}else{if(!disabledX)this.animate[this.xProp](dx,durationX,easeX);if(!disabledY)this.animate[this.yProp](dy,durationY,easeY)}this.scrollInView(longestReleaseDuration,this.scrollThreshold,releaseEase);let hasSnapped=false;if(dx!==sx){this.snapped[0]=dx;if(this.snapX)hasSnapped=true}if(dy!==sy&&this.snapY){this.snapped[1]=dy;if(this.snapY)hasSnapped=true}if(hasSnapped)this.onSnap(this);this.grabbed=false;this.dragged=false;this.updated=true;this.released=true;this.onRelease(this);this.$trigger.removeEventListener("touchstart",preventDefault);this.$trigger.removeEventListener("touchmove",preventDefault);this.$trigger.removeEventListener("touchend",preventDefault);doc.removeEventListener("touchmove",this);doc.removeEventListener("touchend",this);doc.removeEventListener("touchcancel",this);doc.removeEventListener("mousemove",this);doc.removeEventListener("mouseup",this);doc.removeEventListener("selectstart",this)}reset(){this.stop();this.resizeTicker.pause();this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.setX(0,true);this.setY(0,true);this.coords[0]=0;this.coords[1]=0;this.pointer[0]=0;this.pointer[1]=0;this.pointer[2]=0;this.pointer[3]=0;this.pointer[4]=0;this.pointer[5]=0;this.pointer[6]=0;this.pointer[7]=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.angle=0;return this}enable(){if(!this.enabled){this.enabled=true;this.$target.classList.remove("is-disabled");this.touchActionStyles=setTargetValues(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"});this.$trigger.addEventListener("touchstart",this,{passive:true});this.$trigger.addEventListener("mousedown",this,{passive:true});this.$trigger.addEventListener("mouseenter",this)}return this}disable(){this.enabled=false;this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.touchActionStyles.revert();if(this.cursorStyles){this.cursorStyles.revert();this.cursorStyles=null}if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.bodyStyles){this.bodyStyles.revert();this.bodyStyles=null}if(this.targetStyles){this.targetStyles.revert();this.targetStyles=null}this.$target.classList.add("is-disabled");this.$trigger.removeEventListener("touchstart",this);this.$trigger.removeEventListener("mousedown",this);this.$trigger.removeEventListener("mouseenter",this);doc.removeEventListener("touchmove",this);doc.removeEventListener("touchend",this);doc.removeEventListener("touchcancel",this);doc.removeEventListener("mousemove",this);doc.removeEventListener("mouseup",this);doc.removeEventListener("selectstart",this);return this}revert(){this.reset();this.disable();this.$target.classList.remove("is-disabled");this.updateTicker.revert();this.overshootTicker.revert();this.resizeTicker.revert();this.animate.revert();this.resizeObserver.disconnect();return this}handleEvent(e){switch(e.type){case"mousedown":this.handleDown(e);break;case"touchstart":this.handleDown(e);break;case"mousemove":this.handleMove(e);break;case"touchmove":this.handleMove(e);break;case"mouseup":this.handleUp();break;case"touchend":this.handleUp();break;case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":preventDefault(e);break}}}const createDraggable=(target,parameters)=>new Draggable(target,parameters);class Scope{constructor(parameters={}){if(scope.current)scope.current.register(this);const rootParam=parameters.root;let root=doc;if(rootParam){root=rootParam.current||rootParam.nativeElement||parseTargets(rootParam)[0]||doc}const scopeDefaults=parameters.defaults;const globalDefault=globals.defaults;const mediaQueries=parameters.mediaQueries;this.defaults=scopeDefaults?mergeObjects(scopeDefaults,globalDefault):globalDefault;this.root=root;this.constructors=[];this.revertConstructors=[];this.revertibles=[];this.constructorsOnce=[];this.revertConstructorsOnce=[];this.revertiblesOnce=[];this.once=false;this.onceIndex=0;this.methods={};this.matches={};this.mediaQueryLists={};this.data={};if(mediaQueries){for(let mq in mediaQueries){const _mq=win.matchMedia(mediaQueries[mq]);this.mediaQueryLists[mq]=_mq;_mq.addEventListener("change",this)}}}register(revertible){const store=this.once?this.revertiblesOnce:this.revertibles;store.push(revertible)}execute(cb){let activeScope=scope.current;let activeRoot=scope.root;let activeDefaults=globals.defaults;scope.current=this;scope.root=this.root;globals.defaults=this.defaults;const mqs=this.mediaQueryLists;for(let mq in mqs)this.matches[mq]=mqs[mq].matches;const returned=cb(this);scope.current=activeScope;scope.root=activeRoot;globals.defaults=activeDefaults;return returned}refresh(){this.onceIndex=0;this.execute((()=>{let i=this.revertibles.length;let y=this.revertConstructors.length;while(i--)this.revertibles[i].revert();while(y--)this.revertConstructors[y](this);this.revertibles.length=0;this.revertConstructors.length=0;this.constructors.forEach((constructor=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructors.push(revertConstructor)}}))}));return this}add(a1,a2){this.once=false;if(isFnc(a1)){const constructor=a1;this.constructors.push(constructor);this.execute((()=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructors.push(revertConstructor)}}))}else{this.methods[a1]=(...args)=>this.execute((()=>a2(...args)))}return this}addOnce(scopeConstructorCallback){this.once=true;if(isFnc(scopeConstructorCallback)){const currentIndex=this.onceIndex++;const tracked=this.constructorsOnce[currentIndex];if(tracked)return this;const constructor=scopeConstructorCallback;this.constructorsOnce[currentIndex]=constructor;this.execute((()=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructorsOnce.push(revertConstructor)}}))}return this}keepTime(cb){this.once=true;const currentIndex=this.onceIndex++;const tracked=this.constructorsOnce[currentIndex];if(isFnc(tracked))return tracked(this);const constructor=createRefreshable(cb);this.constructorsOnce[currentIndex]=constructor;let trackedTickable;this.execute((()=>{trackedTickable=constructor(this)}));return trackedTickable}handleEvent(e){switch(e.type){case"change":this.refresh();break}}revert(){const revertibles=this.revertibles;const revertConstructors=this.revertConstructors;const revertiblesOnce=this.revertiblesOnce;const revertConstructorsOnce=this.revertConstructorsOnce;const mqs=this.mediaQueryLists;let i=revertibles.length;let j=revertConstructors.length;let k=revertiblesOnce.length;let l=revertConstructorsOnce.length;while(i--)revertibles[i].revert();while(j--)revertConstructors[j](this);while(k--)revertiblesOnce[k].revert();while(l--)revertConstructorsOnce[l](this);for(let mq in mqs)mqs[mq].removeEventListener("change",this);revertibles.length=0;revertConstructors.length=0;this.constructors.length=0;revertiblesOnce.length=0;revertConstructorsOnce.length=0;this.constructorsOnce.length=0;this.onceIndex=0;this.matches={};this.methods={};this.mediaQueryLists={};this.data={}}}const createScope=params=>new Scope(params);const getMaxViewHeight=()=>{const $el=doc.createElement("div");doc.body.appendChild($el);$el.style.height="100lvh";const height=$el.offsetHeight;doc.body.removeChild($el);return height};const parseScrollObserverFunctionParameter=(value,scroller)=>value&&isFnc(value)?value(scroller):value;const scrollContainers=new Map;class ScrollContainer{constructor($el){this.element=$el;this.useWin=this.element===doc.body;this.winWidth=0;this.winHeight=0;this.width=0;this.height=0;this.left=0;this.top=0;this.zIndex=0;this.scrollX=0;this.scrollY=0;this.prevScrollX=0;this.prevScrollY=0;this.scrollWidth=0;this.scrollHeight=0;this.velocity=0;this.backwardX=false;this.backwardY=false;this.scrollTicker=new Timer({autoplay:false,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const backwards=this.backwardX||this.backwardY;forEachChildren(this,(child=>child.handleScroll()),backwards)},onComplete:()=>this.dataTimer.pause()}).init();this.dataTimer=new Timer({autoplay:false,frameRate:30,onUpdate:self=>{const dt=self.deltaTime;const px=this.prevScrollX;const py=this.prevScrollY;const nx=this.scrollX;const ny=this.scrollY;const dx=px-nx;const dy=py-ny;this.prevScrollX=nx;this.prevScrollY=ny;if(dx)this.backwardX=px>nx;if(dy)this.backwardY=py>ny;this.velocity=round(dt>0?Math.sqrt(dx*dx+dy*dy)/dt:0,5)}}).init();this.resizeTicker=new Timer({autoplay:false,duration:250*globals.timeScale,onComplete:()=>{this.updateWindowBounds();this.refreshScrollObservers();this.handleScroll()}}).init();this.wakeTicker=new Timer({autoplay:false,duration:500*globals.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init();this._head=null;this._tail=null;this.updateScrollCoords();this.updateWindowBounds();this.updateBounds();this.refreshScrollObservers();this.handleScroll();this.resizeObserver=new ResizeObserver((()=>this.resizeTicker.restart()));this.resizeObserver.observe(this.element);(this.useWin?win:this.element).addEventListener("scroll",this,false)}updateScrollCoords(){const useWin=this.useWin;const $el=this.element;this.scrollX=round(useWin?win.scrollX:$el.scrollLeft,0);this.scrollY=round(useWin?win.scrollY:$el.scrollTop,0)}updateWindowBounds(){this.winWidth=win.innerWidth;this.winHeight=getMaxViewHeight()}updateBounds(){const style=getComputedStyle(this.element);const $el=this.element;this.scrollWidth=$el.scrollWidth+parseFloat(style.marginLeft)+parseFloat(style.marginRight);this.scrollHeight=$el.scrollHeight+parseFloat(style.marginTop)+parseFloat(style.marginBottom);this.updateWindowBounds();let width,height;if(this.useWin){width=this.winWidth;height=this.winHeight}else{const elRect=$el.getBoundingClientRect();width=$el.clientWidth;height=$el.clientHeight;this.top=elRect.top;this.left=elRect.left}this.width=width;this.height=height}refreshScrollObservers(){forEachChildren(this,(child=>{if(child._debug){child.removeDebug()}}));this.updateBounds();forEachChildren(this,(child=>{child.refresh();if(child._debug){child.debug()}}))}refresh(){this.updateWindowBounds();this.updateBounds();this.refreshScrollObservers();this.handleScroll()}handleScroll(){this.updateScrollCoords();this.wakeTicker.restart()}handleEvent(e){switch(e.type){case"scroll":this.handleScroll();break}}revert(){this.scrollTicker.cancel();this.dataTimer.cancel();this.resizeTicker.cancel();this.wakeTicker.cancel();this.resizeObserver.disconnect();(this.useWin?win:this.element).removeEventListener("scroll",this);scrollContainers.delete(this.element)}}const registerAndGetScrollContainer=target=>{const $el=target?parseTargets(target)[0]||doc.body:doc.body;let scrollContainer=scrollContainers.get($el);if(!scrollContainer){scrollContainer=new ScrollContainer($el);scrollContainers.set($el,scrollContainer)}return scrollContainer};const convertValueToPx=($el,v,size,under,over)=>{const clampMin=v==="min";const clampMax=v==="max";const value=v==="top"||v==="left"||v==="start"||clampMin?0:v==="bottom"||v==="right"||v==="end"||clampMax?"100%":v==="center"?"50%":v;const{n:n,u:u}=decomposeRawValue(value,decomposedOriginalValue);let px=n;if(u==="%"){px=n/100*size}else if(u){px=convertValueUnit($el,decomposedOriginalValue,"px",true).n}if(clampMax&&under<0)px+=under;if(clampMin&&over>0)px+=over;return px};const parseBoundValue=($el,v,size,under,over)=>{let value;if(isStr(v)){const matchedOperator=relativeValuesExecRgx.exec(v);if(matchedOperator){const splitter=matchedOperator[0];const operator=splitter[0];const splitted=v.split(splitter);const clampMin=splitted[0]==="min";const clampMax=splitted[0]==="max";const valueAPx=convertValueToPx($el,splitted[0],size,under,over);const valueBPx=convertValueToPx($el,splitted[1],size,under,over);if(clampMin){const min=getRelativeValue(convertValueToPx($el,"min",size),valueBPx,operator);value=min<valueAPx?valueAPx:min}else if(clampMax){const max=getRelativeValue(convertValueToPx($el,"max",size),valueBPx,operator);value=max>valueAPx?valueAPx:max}else{value=getRelativeValue(valueAPx,valueBPx,operator)}}else{value=convertValueToPx($el,v,size,under,over)}}else{value=v}return round(value,0)};const getAnimationDomTarget=linked=>{let $linkedTarget;const linkedTargets=linked.targets;for(let i=0,l=linkedTargets.length;i<l;i++){const target=linkedTargets[i];if(target[isDomSymbol]){$linkedTarget=target;break}}return $linkedTarget};let scrollerIndex=0;const debugColors$1=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class ScrollObserver{constructor(parameters={}){if(scope.current)scope.current.register(this);const syncMode=setValue(parameters.sync,"play pause");const ease=syncMode?parseEasings(syncMode):null;const isLinear=syncMode&&(syncMode==="linear"||syncMode===none);const isEase=syncMode&&!(ease===none&&!isLinear);const isSmooth=syncMode&&(isNum(syncMode)||syncMode===true||isLinear);const isMethods=syncMode&&(isStr(syncMode)&&!isEase&&!isSmooth);const syncMethods=isMethods?syncMode.split(" ").map((m=>()=>{const linked=this.linked;return linked&&linked[m]?linked[m]():null})):null;const biDirSync=isMethods&&syncMethods.length>2;this.index=scrollerIndex++;this.id=!isUnd(parameters.id)?parameters.id:this.index;this.container=registerAndGetScrollContainer(parameters.container);this.target=null;this.linked=null;this.repeat=null;this.horizontal=null;this.enter=null;this.leave=null;this.sync=isEase||isSmooth||!!syncMethods;this.syncEase=isEase?ease:null;this.syncSmooth=isSmooth?syncMode===true||isLinear?1:syncMode:null;this.onSyncEnter=syncMethods&&!biDirSync&&syncMethods[0]?syncMethods[0]:noop;this.onSyncLeave=syncMethods&&!biDirSync&&syncMethods[1]?syncMethods[1]:noop;this.onSyncEnterForward=syncMethods&&biDirSync&&syncMethods[0]?syncMethods[0]:noop;this.onSyncLeaveForward=syncMethods&&biDirSync&&syncMethods[1]?syncMethods[1]:noop;this.onSyncEnterBackward=syncMethods&&biDirSync&&syncMethods[2]?syncMethods[2]:noop;this.onSyncLeaveBackward=syncMethods&&biDirSync&&syncMethods[3]?syncMethods[3]:noop;this.onEnter=parameters.onEnter||noop;this.onLeave=parameters.onLeave||noop;this.onEnterForward=parameters.onEnterForward||noop;this.onLeaveForward=parameters.onLeaveForward||noop;this.onEnterBackward=parameters.onEnterBackward||noop;this.onLeaveBackward=parameters.onLeaveBackward||noop;this.onUpdate=parameters.onUpdate||noop;this.onSyncComplete=parameters.onSyncComplete||noop;this.reverted=false;this.completed=false;this.began=false;this.isInView=false;this.forceEnter=false;this.hasEntered=false;this.offset=0;this.offsetStart=0;this.offsetEnd=0;this.distance=0;this.prevProgress=0;this.thresholds=["start","end","end","start"];this.coords=[0,0,0,0];this.debugStyles=null;this.$debug=null;this._params=parameters;this._debug=setValue(parameters.debug,false);this._next=null;this._prev=null;addChild(this.container,this);sync((()=>{if(this.reverted)return;if(!this.target){const target=parseTargets(parameters.target)[0];this.target=target||doc.body;this.refresh()}if(this._debug)this.debug()}))}link(linked){if(linked){linked.pause();this.linked=linked;if(!this._params.target){let $linkedTarget;if(!isUnd(linked.targets)){$linkedTarget=getAnimationDomTarget(linked)}else{forEachChildren(linked,(child=>{if(child.targets&&!$linkedTarget){$linkedTarget=getAnimationDomTarget(child)}}))}this.target=$linkedTarget||doc.body;this.refresh()}}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const p=(this.scroll-this.offsetStart)/this.distance;return p===Infinity||isNaN(p)?0:round(clamp(p,0,1),6)}refresh(){this.reverted=false;const params=this._params;this.repeat=setValue(parseScrollObserverFunctionParameter(params.repeat,this),true);this.horizontal=setValue(parseScrollObserverFunctionParameter(params.axis,this),"y")==="x";this.enter=setValue(parseScrollObserverFunctionParameter(params.enter,this),"end start");this.leave=setValue(parseScrollObserverFunctionParameter(params.leave,this),"start end");this.updateBounds();this.handleScroll();return this}removeDebug(){if(this.$debug){this.$debug.parentNode.removeChild(this.$debug);this.$debug=null}if(this.debugStyles){this.debugStyles.revert();this.$debug=null}return this}debug(){this.removeDebug();const container=this.container;const isHori=this.horizontal;const $existingDebug=container.element.querySelector(":scope > .animejs-onscroll-debug");const $debug=doc.createElement("div");const $thresholds=doc.createElement("div");const $triggers=doc.createElement("div");const color=debugColors$1[this.index%debugColors$1.length];const useWin=container.useWin;const containerWidth=useWin?container.winWidth:container.width;const containerHeight=useWin?container.winHeight:container.height;const scrollWidth=container.scrollWidth;const scrollHeight=container.scrollHeight;const size=this.container.width>360?320:260;const offLeft=isHori?0:10;const offTop=isHori?10:0;const half=isHori?24:size/2;const labelHeight=isHori?half:15;const labelWidth=isHori?60:half;const labelSize=isHori?labelWidth:labelHeight;const repeat=isHori?"repeat-x":"repeat-y";const gradientOffset=v=>isHori?"0px "+v+"px":v+"px"+" 2px";const lineCSS=c=>`linear-gradient(${isHori?90:0}deg, ${c} 2px, transparent 1px)`;const baseCSS=(p,l,t,w,h)=>`position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`;$debug.style.cssText=`${baseCSS("absolute",offLeft,offTop,isHori?scrollWidth:size,isHori?size:scrollHeight)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${isHori?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `;$thresholds.style.cssText=`${baseCSS("sticky",0,0,isHori?containerWidth:half,isHori?half:containerHeight)}`;if(!$existingDebug){$thresholds.style.cssText+=`background:\n ${lineCSS("#FFFF")}${gradientOffset(half-10)} / ${isHori?"100px 100px":"100px 100px"} ${repeat},\n ${lineCSS("#FFF8")}${gradientOffset(half-10)} / ${isHori?"10px 10px":"10px 10px"} ${repeat};\n `}$triggers.style.cssText=`${baseCSS("relative",0,0,isHori?scrollWidth:half,isHori?half:scrollHeight)}`;if(!$existingDebug){$triggers.style.cssText+=`background:\n ${lineCSS("#FFFF")}${gradientOffset(0)} / ${isHori?"100px 10px":"10px 100px"} ${repeat},\n ${lineCSS("#FFF8")}${gradientOffset(0)} / ${isHori?"10px 0px":"0px 10px"} ${repeat};\n `}const labels=[" enter: "," leave: "];this.coords.forEach(((v,i)=>{const isView=i>1;const value=(isView?0:this.offset)+v;const isTail=i%2;const isFirst=value<labelSize;const isOver=value>(isView?isHori?containerWidth:containerHeight:isHori?scrollWidth:scrollHeight)-labelSize;const isFlip=(isView?isTail&&!isFirst:!isTail&&!isFirst)||isOver;const $label=doc.createElement("div");const $text=doc.createElement("div");const dirProp=isHori?isFlip?"right":"left":isFlip?"bottom":"top";const flipOffset=isFlip?(isHori?labelWidth:labelHeight)+(!isView?isHori?-1:-2:isHori?-1:isOver?0:-2):!isView?isHori?1:0:isHori?1:0;$text.innerHTML=`${this.id}${labels[isTail]}${this.thresholds[i]}`;$label.style.cssText=`${baseCSS("absolute",0,0,labelWidth,labelHeight)}\n display: flex;\n flex-direction: ${isHori?"column":"row"};\n justify-content: flex-${isView?"start":"end"};\n align-items: flex-${isFlip?"end":"start"};\n border-${dirProp}: 2px ${isTail?"solid":"solid"} ${color};\n `;$text.style.cssText=`\n overflow: hidden;\n max-width: ${size/2-10}px;\n height: ${labelHeight};\n margin-${isHori?isFlip?"right":"left":isFlip?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${isHori&&isFlip||!isHori&&!isView?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${isTail?color:"rgba(0,0,0,.75)"};\n background-color: ${isTail?"rgba(0,0,0,.65)":color};\n border: 2px solid ${isTail?color:"transparent"};\n border-${isHori?isFlip?"top-left":"top-right":isFlip?"top-left":"bottom-left"}-radius: 5px;\n border-${isHori?isFlip?"bottom-left":"bottom-right":isFlip?"top-right":"bottom-right"}-radius: 5px;\n `;$label.appendChild($text);let position=value-flipOffset+(isHori?1:0);$label.style[isHori?"left":"top"]=`${position}px`;(isView?$thresholds:$triggers).appendChild($label)}));$debug.appendChild($thresholds);$debug.appendChild($triggers);container.element.appendChild($debug);if(!$existingDebug)$debug.classList.add("animejs-onscroll-debug");this.$debug=$debug;const containerPosition=getTargetValue(container.element,"position");if(containerPosition==="static"){this.debugStyles=setTargetValues(container.element,{position:"relative "})}}updateBounds(){if(this._debug){this.removeDebug()}let stickys;const $target=this.target;const container=this.container;const isHori=this.horizontal;const linked=this.linked;let linkedTime;let $el=$target;if(linked){linkedTime=linked.currentTime;linked.seek(0,true)}$el.parentElement;while($el&&$el!==container.element&&$el!==doc.body){const isSticky=getTargetValue($el,"position")==="sticky"?setTargetValues($el,{position:"static"}):false;$el=$el.parentElement;if(isSticky){if(!stickys)stickys=[];stickys.push(isSticky)}}const rect=$target.getBoundingClientRect();const offset=isHori?rect.left+container.scrollX-container.left:rect.top+container.scrollY-container.top;const targetSize=isHori?rect.width:rect.height;const containerSize=isHori?container.width:container.height;const scrollSize=isHori?container.scrollWidth:container.scrollHeight;const maxScroll=scrollSize-containerSize;const enter=this.enter;const leave=this.leave;let enterTarget="start";let leaveTarget="end";let enterContainer="end";let leaveContainer="start";if(isStr(enter)){const splitted=enter.split(" ");enterContainer=splitted[0];enterTarget=splitted.length>1?splitted[1]:enterTarget}else if(isObj(enter)){const e=enter;if(!isUnd(e.container))enterContainer=e.container;if(!isUnd(e.target))enterTarget=e.target}else if(isNum(enter)){enterContainer=enter}if(isStr(leave)){const splitted=leave.split(" ");leaveContainer=splitted[0];leaveTarget=splitted.length>1?splitted[1]:leaveTarget}else if(isObj(leave)){const t=leave;if(!isUnd(t.container))leaveContainer=t.container;if(!isUnd(t.target))leaveTarget=t.target}else if(isNum(leave)){leaveContainer=leave}const parsedEnterTarget=parseBoundValue($target,enterTarget,targetSize);const parsedLeaveTarget=parseBoundValue($target,leaveTarget,targetSize);const under=parsedEnterTarget+offset-containerSize;const over=parsedLeaveTarget+offset-maxScroll;const parsedEnterContainer=parseBoundValue($target,enterContainer,containerSize,under,over);const parsedLeaveContainer=parseBoundValue($target,leaveContainer,containerSize,under,over);const offsetStart=parsedEnterTarget+offset-parsedEnterContainer;const offsetEnd=parsedLeaveTarget+offset-parsedLeaveContainer;const scrollDelta=offsetEnd-offsetStart;this.offset=offset;this.offsetStart=offsetStart;this.offsetEnd=offsetEnd;this.distance=scrollDelta<=0?0:scrollDelta;this.thresholds=[enterTarget,leaveTarget,enterContainer,leaveContainer];this.coords=[parsedEnterTarget,parsedLeaveTarget,parsedEnterContainer,parsedLeaveContainer];if(stickys){stickys.forEach((sticky=>sticky.revert()))}if(linked){linked.seek(linkedTime,true)}if(this._debug){this.debug()}}handleScroll(){const linked=this.linked;const sync=this.sync;const syncEase=this.syncEase;const syncSmooth=this.syncSmooth;const shouldSeek=linked&&(syncEase||syncSmooth);const isHori=this.horizontal;const container=this.container;const scroll=this.scroll;const isBefore=scroll<=this.offsetStart;const isAfter=scroll>=this.offsetEnd;const isInView=!isBefore&&!isAfter;const isOnTheEdge=scroll===this.offsetStart||scroll===this.offsetEnd;const forceEnter=!this.hasEntered&&isOnTheEdge;const $debug=this._debug&&this.$debug;let hasUpdated=false;let syncCompleted=false;let p=this.progress;if(isBefore&&this.began){this.began=false}if(p>0&&!this.began){this.began=true}if(shouldSeek){const lp=linked.progress;if(syncSmooth&&isNum(syncSmooth)){if(syncSmooth<1){const step=1e-4;const snap=lp<p&&p===1?step:lp>p&&!p?-1e-4:0;p=round(lerp(lp,p,interpolate(.01,.2,syncSmooth),false)+snap,6)}}else if(syncEase){p=syncEase(p)}hasUpdated=p!==this.prevProgress;syncCompleted=lp===1;if(hasUpdated&&!syncCompleted&&(syncSmooth&&lp)){container.wakeTicker.restart()}}if($debug){const sticky=isHori?container.scrollY:container.scrollX;$debug.style[isHori?"top":"left"]=sticky+10+"px"}if(isInView&&!this.isInView||forceEnter&&!this.forceEnter&&!this.hasEntered){if(isInView)this.isInView=true;if(!this.forceEnter||!this.hasEntered){if($debug&&isInView)$debug.style.zIndex=`${this.container.zIndex++}`;this.onSyncEnter(this);this.onEnter(this);if(this.backward){this.onSyncEnterBackward(this);this.onEnterBackward(this)}else{this.onSyncEnterForward(this);this.onEnterForward(this)}this.hasEntered=true;if(forceEnter)this.forceEnter=true}else if(isInView){this.forceEnter=false}}if(isInView||!isInView&&this.isInView){hasUpdated=true}if(hasUpdated){if(shouldSeek)linked.seek(linked.duration*p);this.onUpdate(this)}if(!isInView&&this.isInView){this.isInView=false;this.onSyncLeave(this);this.onLeave(this);if(this.backward){this.onSyncLeaveBackward(this);this.onLeaveBackward(this)}else{this.onSyncLeaveForward(this);this.onLeaveForward(this)}if(sync&&!syncSmooth){syncCompleted=true}}if(p>=1&&this.began&&!this.completed&&(sync&&syncCompleted||!sync)){if(sync){this.onSyncComplete(this)}this.completed=true;if(!this.repeat&&!linked||!this.repeat&&linked&&linked.completed){this.revert()}}if(p<1&&this.completed){this.completed=false}this.prevProgress=p}revert(){if(this.reverted)return;const container=this.container;removeChild(container,this);if(!container._head){container.revert()}if(this._debug){this.removeDebug()}this.reverted=true;return this}}const onScroll=(parameters={})=>new ScrollObserver(parameters);const segmenter=typeof Intl!=="undefined"&&Intl.Segmenter;const valueRgx=/\{value\}/g;const indexRgx=/\{i\}/g;const whiteSpaceGroupRgx=/(\s+)/;const whiteSpaceRgx=/^\s+$/;const lineType="line";const wordType="word";const charType="char";const dataLine=`data-line`;let wordSegmenter=null;let graphemeSegmenter=null;let $splitTemplate=null;const isSegmentWordLike=seg=>seg.isWordLike||seg.segment===" "||isNum(+seg.segment);const setAriaHidden=$el=>$el.setAttribute("aria-hidden","true");const getAllTopLevelElements=($el,type)=>[...$el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`)];const debugColors={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"};const filterEmptyElements=$el=>{if(!$el.childElementCount&&!$el.textContent.trim()){const $parent=$el.parentElement;$el.remove();if($parent)filterEmptyElements($parent)}};const filterLineElements=($el,lineIndex,bin)=>{const dataLineAttr=$el.getAttribute(dataLine);if(dataLineAttr!==null&&+dataLineAttr!==lineIndex||$el.tagName==="BR")bin.add($el);let i=$el.childElementCount;while(i--)filterLineElements($el.children[i],lineIndex,bin);return bin};const generateTemplate=(type,params={})=>{let template=``;const classString=isStr(params.class)?` class="${params.class}"`:"";const cloneType=setValue(params.clone,false);const wrapType=setValue(params.wrap,false);const overflow=wrapType?wrapType===true?"clip":wrapType:cloneType?"clip":false;if(wrapType)template+=`<span${overflow?` style="overflow:${overflow};"`:""}>`;template+=`<span${classString}${cloneType?` style="position:relative;"`:""} data-${type}="{i}">`;if(cloneType){const left=cloneType==="left"?"-100%":cloneType==="right"?"100%":"0";const top=cloneType==="top"?"-100%":cloneType==="bottom"?"100%":"0";template+=`<span>{value}</span>`;template+=`<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`}else{template+=`{value}`}template+=`</span>`;if(wrapType)template+=`</span>`;return template};const processHTMLTemplate=(htmlTemplate,store,node,$parentFragment,type,debug,lineIndex,wordIndex,charIndex)=>{const isLine=type===lineType;const isChar=type===charType;const className=`_${type}_`;const template=isFnc(htmlTemplate)?htmlTemplate(node):htmlTemplate;const displayStyle=isLine?"block":"inline-block";$splitTemplate.innerHTML=template.replace(valueRgx,`<i class="${className}"></i>`).replace(indexRgx,`${isChar?charIndex:isLine?lineIndex:wordIndex}`);const $content=$splitTemplate.content;const $highestParent=$content.firstElementChild;const $split=$content.querySelector(`[data-${type}]`)||$highestParent;const $replacables=$content.querySelectorAll(`i.${className}`);const replacablesLength=$replacables.length;if(replacablesLength){$highestParent.style.display=displayStyle;$split.style.display=displayStyle;$split.setAttribute(dataLine,`${lineIndex}`);if(!isLine){$split.setAttribute("data-word",`${wordIndex}`);if(isChar)$split.setAttribute("data-char",`${charIndex}`)}let i=replacablesLength;while(i--){const $replace=$replacables[i];const $closestParent=$replace.parentElement;$closestParent.style.display=displayStyle;if(isLine){$closestParent.innerHTML=node.innerHTML}else{$closestParent.replaceChild(node.cloneNode(true),$replace)}}store.push($split);$parentFragment.appendChild($content)}else{console.warn(`The expression "{value}" is missing from the provided template.`)}if(debug)$highestParent.style.outline=`1px dotted ${debugColors[type]}`;return $highestParent};class TextSplitter{constructor(target,parameters={}){if(!wordSegmenter)wordSegmenter=segmenter?new segmenter([],{granularity:wordType}):{segment:text=>{const segments=[];const words=text.split(whiteSpaceGroupRgx);for(let i=0,l=words.length;i<l;i++){const segment=words[i];segments.push({segment:segment,isWordLike:!whiteSpaceRgx.test(segment)})}return segments}};if(!graphemeSegmenter)graphemeSegmenter=segmenter?new segmenter([],{granularity:"grapheme"}):{segment:text=>[...text].map((char=>({segment:char})))};if(!$splitTemplate&&isBrowser)$splitTemplate=doc.createElement("template");if(scope.current)scope.current.register(this);const{words:words,chars:chars,lines:lines,accessible:accessible,includeSpaces:includeSpaces,debug:debug}=parameters;const $target=(target=isArr(target)?target[0]:target)&&target.nodeType?target:(getNodeList(target)||[])[0];const lineParams=lines===true?{}:lines;const wordParams=words===true||isUnd(words)?{}:words;const charParams=chars===true?{}:chars;this.debug=setValue(debug,false);this.includeSpaces=setValue(includeSpaces,false);this.accessible=setValue(accessible,true);this.linesOnly=lineParams&&(!wordParams&&!charParams);this.lineTemplate=isObj(lineParams)?generateTemplate(lineType,lineParams):lineParams;this.wordTemplate=isObj(wordParams)||this.linesOnly?generateTemplate(wordType,wordParams):wordParams;this.charTemplate=isObj(charParams)?generateTemplate(charType,charParams):charParams;this.$target=$target;this.html=$target&&$target.innerHTML;this.lines=[];this.words=[];this.chars=[];this.effects=[];this.effectsCleanups=[];this.cache=null;this.ready=false;this.width=0;this.resizeTimeout=null;const handleSplit=()=>this.html&&(lineParams||wordParams||charParams)&&this.split();this.resizeObserver=new ResizeObserver((()=>{clearTimeout(this.resizeTimeout);this.resizeTimeout=setTimeout((()=>{const currentWidth=$target.offsetWidth;if(currentWidth===this.width)return;this.width=currentWidth;handleSplit()}),150)}));if(this.lineTemplate&&!this.ready){doc.fonts.ready.then(handleSplit)}else{handleSplit()}$target?this.resizeObserver.observe($target):console.warn("No Text Splitter target found.")}addEffect(effect){if(!isFnc(effect))return console.warn("Effect must return a function.");const refreshableEffect=createRefreshable(effect);this.effects.push(refreshableEffect);if(this.ready)this.effectsCleanups[this.effects.length-1]=refreshableEffect(this);return this}revert(){clearTimeout(this.resizeTimeout);this.lines.length=this.words.length=this.chars.length=0;this.resizeObserver.disconnect();this.effectsCleanups.forEach((cleanup=>isFnc(cleanup)?cleanup(this):cleanup.revert&&cleanup.revert()));this.$target.innerHTML=this.html;return this}splitNode(node){const wordTemplate=this.wordTemplate;const charTemplate=this.charTemplate;const includeSpaces=this.includeSpaces;const debug=this.debug;const nodeType=node.nodeType;if(nodeType===3){const nodeText=node.nodeValue;if(nodeText.trim()){const tempWords=[];const words=this.words;const chars=this.chars;const wordSegments=wordSegmenter.segment(nodeText);const $wordsFragment=doc.createDocumentFragment();let prevSeg=null;for(const wordSegment of wordSegments){const segment=wordSegment.segment;const isWordLike=isSegmentWordLike(wordSegment);if(!prevSeg||isWordLike&&(prevSeg&&isSegmentWordLike(prevSeg))){tempWords.push(segment)}else{const lastWordIndex=tempWords.length-1;const lastWord=tempWords[lastWordIndex];if(!lastWord.includes(" ")&&!segment.includes(" ")){tempWords[lastWordIndex]+=segment}else{tempWords.push(segment)}}prevSeg=wordSegment}for(let i=0,l=tempWords.length;i<l;i++){const word=tempWords[i];if(!word.trim()){if(i&&includeSpaces)continue;$wordsFragment.appendChild(doc.createTextNode(word))}else{const nextWord=tempWords[i+1];const hasWordFollowingSpace=includeSpaces&&nextWord&&!nextWord.trim();const wordToProcess=word;const charSegments=charTemplate?graphemeSegmenter.segment(wordToProcess):null;const $charsFragment=charTemplate?doc.createDocumentFragment():doc.createTextNode(hasWordFollowingSpace?word+" ":word);if(charTemplate){const charSegmentsArray=[...charSegments];for(let j=0,jl=charSegmentsArray.length;j<jl;j++){const charSegment=charSegmentsArray[j];const isLastChar=j===jl-1;const charText=isLastChar&&hasWordFollowingSpace?charSegment.segment+" ":charSegment.segment;const $charNode=doc.createTextNode(charText);processHTMLTemplate(charTemplate,chars,$charNode,$charsFragment,charType,debug,-1,words.length,chars.length)}}if(wordTemplate){processHTMLTemplate(wordTemplate,words,$charsFragment,$wordsFragment,wordType,debug,-1,words.length,chars.length)}else if(charTemplate){$wordsFragment.appendChild($charsFragment)}else{$wordsFragment.appendChild(doc.createTextNode(word))}if(hasWordFollowingSpace)i++}}node.parentNode.replaceChild($wordsFragment,node)}}else if(nodeType===1){const childNodes=[...node.childNodes];for(let i=0,l=childNodes.length;i<l;i++)this.splitNode(childNodes[i])}}split(clearCache=false){const $el=this.$target;const isCached=!!this.cache&&!clearCache;const lineTemplate=this.lineTemplate;const wordTemplate=this.wordTemplate;const charTemplate=this.charTemplate;const fontsReady=doc.fonts.status!=="loading";const canSplitLines=lineTemplate&&fontsReady;this.ready=!lineTemplate||fontsReady;if(canSplitLines||clearCache){this.effectsCleanups.forEach((cleanup=>isFnc(cleanup)&&cleanup(this)))}if(!isCached){if(clearCache){$el.innerHTML=this.html;this.words.length=this.chars.length=0}this.splitNode($el);this.cache=$el.innerHTML}if(canSplitLines){if(isCached)$el.innerHTML=this.cache;this.lines.length=0;if(wordTemplate)this.words=getAllTopLevelElements($el,wordType)}if(charTemplate&&(canSplitLines||wordTemplate)){this.chars=getAllTopLevelElements($el,charType)}const elementsArray=this.words.length?this.words:this.chars;let y,linesCount=0;for(let i=0,l=elementsArray.length;i<l;i++){const $el=elementsArray[i];const{top:top,height:height}=$el.getBoundingClientRect();if(y&&top-y>height*.5)linesCount++;$el.setAttribute(dataLine,`${linesCount}`);const nested=$el.querySelectorAll(`[${dataLine}]`);let c=nested.length;while(c--)nested[c].setAttribute(dataLine,`${linesCount}`);y=top}if(canSplitLines){const linesFragment=doc.createDocumentFragment();const parents=new Set;const clones=[];for(let lineIndex=0;lineIndex<linesCount+1;lineIndex++){const $clone=$el.cloneNode(true);filterLineElements($clone,lineIndex,new Set).forEach(($el=>{const $parent=$el.parentElement;if($parent)parents.add($parent);$el.remove()}));clones.push($clone)}parents.forEach(filterEmptyElements);for(let cloneIndex=0,clonesLength=clones.length;cloneIndex<clonesLength;cloneIndex++){processHTMLTemplate(lineTemplate,this.lines,clones[cloneIndex],linesFragment,lineType,this.debug,cloneIndex)}$el.innerHTML="";$el.appendChild(linesFragment);if(wordTemplate)this.words=getAllTopLevelElements($el,wordType);if(charTemplate)this.chars=getAllTopLevelElements($el,charType)}if(this.linesOnly){const words=this.words;let w=words.length;while(w--){const $word=words[w];$word.replaceWith($word.textContent)}words.length=0}if(this.accessible&&(canSplitLines||!isCached)){const $accessible=doc.createElement("span");$accessible.style.cssText=`position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;$accessible.innerHTML=this.html;$el.insertBefore($accessible,$el.firstChild);this.lines.forEach(setAriaHidden);this.words.forEach(setAriaHidden);this.chars.forEach(setAriaHidden)}this.width=$el.offsetWidth;if(canSplitLines||clearCache){this.effects.forEach(((effect,i)=>this.effectsCleanups[i]=effect(this)))}return this}refresh(){this.split(true)}}const split=(target,parameters)=>new TextSplitter(target,parameters);const text={split:split};const stagger=(val,params={})=>{let values=[];let maxValue=0;const from=params.from;const reversed=params.reversed;const ease=params.ease;const hasEasing=!isUnd(ease);const hasSpring=hasEasing&&!isUnd(ease.ease);const staggerEase=hasSpring?ease.ease:hasEasing?parseEasings(ease):null;const grid=params.grid;const axis=params.axis;const customTotal=params.total;const fromFirst=isUnd(from)||from===0||from==="first";const fromCenter=from==="center";const fromLast=from==="last";const fromRandom=from==="random";const isRange=isArr(val);const useProp=params.use;const val1=isRange?parseNumber(val[0]):parseNumber(val);const val2=isRange?parseNumber(val[1]):0;const unitMatch=unitsExecRgx.exec((isRange?val[1]:val)+emptyString);const start=params.start||0+(isRange?val1:0);let fromIndex=fromFirst?0:isNum(from)?from:0;return(target,i,t,tl)=>{const[registeredTarget]=registerTargets(target);const total=isUnd(customTotal)?t:customTotal;const customIndex=!isUnd(useProp)?isFnc(useProp)?useProp(registeredTarget,i,total):getOriginalAnimatableValue(registeredTarget,useProp):false;const staggerIndex=isNum(customIndex)||isStr(customIndex)&&isNum(+customIndex)?+customIndex:i;if(fromCenter)fromIndex=(total-1)/2;if(fromLast)fromIndex=total-1;if(!values.length){for(let index=0;index<total;index++){if(!grid){values.push(abs(fromIndex-index))}else{const fromX=!fromCenter?fromIndex%grid[0]:(grid[0]-1)/2;const fromY=!fromCenter?floor(fromIndex/grid[0]):(grid[1]-1)/2;const toX=index%grid[0];const toY=floor(index/grid[0]);const distanceX=fromX-toX;const distanceY=fromY-toY;let value=sqrt(distanceX*distanceX+distanceY*distanceY);if(axis==="x")value=-distanceX;if(axis==="y")value=-distanceY;values.push(value)}maxValue=max(...values)}if(staggerEase)values=values.map((val=>staggerEase(val/maxValue)*maxValue));if(reversed)values=values.map((val=>axis?val<0?val*-1:-val:abs(maxValue-val)));if(fromRandom)values=shuffle(values)}const spacing=isRange?(val2-val1)/maxValue:val1;const offset=tl?parseTimelinePosition(tl,isUnd(params.start)?tl.iterationDuration:start):start;let output=offset+(spacing*round(values[staggerIndex],2)||0);if(params.modifier)output=params.modifier(output);if(unitMatch)output=`${output}${unitMatch[2]}`;return output}};exports.Animatable=Animatable;exports.Draggable=Draggable;exports.JSAnimation=JSAnimation;exports.Scope=Scope;exports.ScrollObserver=ScrollObserver;exports.Spring=Spring;exports.TextSplitter=TextSplitter;exports.Timeline=Timeline;exports.Timer=Timer;exports.WAAPIAnimation=WAAPIAnimation;exports.animate=animate;exports.createAnimatable=createAnimatable;exports.createDraggable=createDraggable;exports.createScope=createScope;exports.createSpring=createSpring;exports.createTimeline=createTimeline;exports.createTimer=createTimer;exports.eases=eases;exports.engine=engine;exports.onScroll=onScroll;exports.scrollContainers=scrollContainers;exports.stagger=stagger;exports.svg=svg;exports.text=text;exports.utils=utils;exports.waapi=waapi;return exports}({});
diff --git a/lib/anime.iife.min.js b/lib/anime.iife.min.js
deleted file mode 100644
index d227d045..00000000
--- a/lib/anime.iife.min.js
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * anime.js - IIFE
- * @version v4.1.3
- * @author Julian Garnier
- * @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
- */
-var anime=function(t){"use strict";const e="undefined"!=typeof window,s=e?window:null,i=e?document:null,r={replace:0,none:1,blend:2},n=Symbol(),o=Symbol(),a=Symbol(),h=Symbol(),l=Symbol(),c=Symbol(),d=1e-11,u=1e12,p=1e3,m="",f=(()=>{const t=new Map;return t.set("x","translateX"),t.set("y","translateY"),t.set("z","translateZ"),t})(),g=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],y=g.reduce(((t,e)=>({...t,[e]:e+"("})),{}),_=()=>{},v=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i,b=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i,T=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,w=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i,S=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,x=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi,k=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i,$=/([a-z])([A-Z])/g,C=/(\w+)(\([^)]+\)+)/g,E=/(\*=|\+=|-=)/,B={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:120,loop:0,reversed:!1,alternate:!1,autoplay:!0,duration:p,delay:0,loopDelay:0,ease:"out(2)",composition:r.replace,modifier:t=>t,onBegin:_,onBeforeUpdate:_,onUpdate:_,onLoop:_,onPause:_,onComplete:_,onRender:_},L={current:null,root:i},D={defaults:B,precision:4,timeScale:1,tickThreshold:200},A={version:"4.1.3",engine:null};e&&(s.AnimeJS||(s.AnimeJS=[]),s.AnimeJS.push(A));const N=t=>t.replace($,"$1-$2").toLowerCase(),F=(t,e)=>0===t.indexOf(e),O=Date.now,P=Array.isArray,R=t=>t&&t.constructor===Object,M=t=>"number"==typeof t&&!isNaN(t),I=t=>"string"==typeof t,z=t=>"function"==typeof t,Y=t=>void 0===t,X=t=>Y(t)||null===t,W=t=>e&&t instanceof SVGElement,V=t=>v.test(t),H=t=>F(t,"rgb"),U=t=>F(t,"hsl"),q=t=>!D.defaults.hasOwnProperty(t),Q=t=>I(t)?parseFloat(t):t,j=Math.pow,G=Math.sqrt,Z=Math.sin,J=Math.cos,K=Math.abs,tt=Math.exp,et=Math.ceil,st=Math.floor,it=Math.asin,rt=Math.max,nt=Math.atan2,ot=Math.PI,at=Math.round,ht=(t,e,s)=>t<e?e:t>s?s:t,lt={},ct=(t,e)=>{if(e<0)return t;if(!e)return at(t);let s=lt[e];return s||(s=lt[e]=10**e),at(t*s)/s},dt=(t,e)=>P(e)?e.reduce(((e,s)=>K(s-t)<K(e-t)?s:e)):e?at(t/e)*e:t,ut=(t,e,s)=>t+(e-t)*s,pt=(t,e,s)=>{const i=10**(s||0);return st((Math.random()*(e-t+1/i)+t)*i)/i},mt=t=>{let e,s,i=t.length;for(;i;)s=pt(0,--i),e=t[i],t[i]=t[s],t[s]=e;return t},ft=t=>t===1/0?u:t===-1/0?-1e12:t,gt=t=>t<=d?d:ft(ct(t,11)),yt=t=>P(t)?[...t]:t,_t=(t,e)=>{const s={...t};for(let i in e){const r=t[i];s[i]=Y(r)?e[i]:r}return s},vt=(t,e,s,i="_prev",r="_next")=>{let n=t._head,o=r;for(s&&(n=t._tail,o=i);n;){const t=n[o];e(n),n=t}},bt=(t,e,s="_prev",i="_next")=>{const r=e[s],n=e[i];r?r[i]=n:t._head=n,n?n[s]=r:t._tail=r,e[s]=null,e[i]=null},Tt=(t,e,s,i="_prev",r="_next")=>{let n=t._tail;for(;n&&s&&s(n,e);)n=n[i];const o=n?n[r]:t._head;n?n[r]=e:t._head=e,o?o[i]=e:t._tail=e,e[i]=n,e[r]=o},wt=t=>{let e;return(...s)=>{let i,r,n,o;e&&(i=e.currentIteration,r=e.iterationProgress,n=e.reversed,o=e._alternate,e.revert());const a=t(...s);return a&&!z(a)&&a.revert&&(e=a),Y(r)||(e.currentIteration=i,e.iterationProgress=(o&&i%2?!n:n)?1-r:r),a||_}};class St{constructor(t=0){this.deltaTime=0,this._currentTime=t,this._elapsedTime=t,this._startTime=t,this._lastTime=t,this._scheduledTime=0,this._frameDuration=ct(p/120,0),this._fps=120,this._speed=1,this._hasChildren=!1,this._head=null,this._tail=null}get fps(){return this._fps}set fps(t){const e=this._frameDuration,s=+t,i=s<d?d:s,r=ct(p/i,0);this._fps=i,this._frameDuration=r,this._scheduledTime+=r-e}get speed(){return this._speed}set speed(t){const e=+t;this._speed=e<d?d:e}requestTick(t){const e=this._scheduledTime,s=this._elapsedTime;if(this._elapsedTime+=t-s,s<e)return 0;const i=this._frameDuration,r=s-e;return this._scheduledTime+=r<i?i:r,1}computeDeltaTime(t){const e=t-this._lastTime;return this.deltaTime=e,this._lastTime=t,e}}const xt=(t,e,s,i,n)=>{const o=t.parent,a=t.duration,l=t.completed,c=t.iterationDuration,u=t.iterationCount,p=t._currentIteration,f=t._loopDelay,g=t._reversed,_=t._alternate,v=t._hasChildren,b=t._delay,T=t._currentTime,w=b+c,S=e-b,x=ht(T,-b,a),k=ht(S,-b,a),$=S-T,C=k>0,E=k>=a,B=a<=d,L=2===n;let A=0,N=S,F=0;if(u>1){const e=~~(k/(c+(E?0:f)));t._currentIteration=ht(e,0,u),E&&t._currentIteration--,A=t._currentIteration%2,N=k%(c+f)||0}const O=g^(_&&A),P=t._ease;let R=E?O?0:a:O?c-N:N;P&&(R=c*P(R/c)||0);const M=(o?o.backwards:S<T)?!O:!!O;if(t._currentTime=S,t._iterationTime=R,t.backwards=M,C&&!t.began?(t.began=!0,s||o&&(M||!o.began)||t.onBegin(t)):S<=0&&(t.began=!1),s||v||!C||t._currentIteration===p||t.onLoop(t),L||1===n&&(e>=b&&e<=w||e<=b&&x>b||e>=w&&x!==a)||R>=w&&x!==a||R<=b&&x>0||e<=x&&x===a&&l||E&&!l&&B){if(C&&(t.computeDeltaTime(x),s||t.onBeforeUpdate(t)),!v){const e=L||(M?-1*$:$)>=D.tickThreshold,n=t._offset+(o?o._offset:0)+b+R;let a,l,c,d,u=t._head,p=0;for(;u;){const t=u._composition,s=u._currentTime,o=u._changeDuration,f=u._absoluteStartTime+u._changeDuration,g=u._nextRep,_=u._prevRep,v=t!==r.none;if((e||(s!==o||n<=f+(g?g._delay:0))&&(0!==s||n>=u._absoluteStartTime))&&(!v||!u._isOverridden&&(!u._isOverlapped||n<=f)&&(!g||g._isOverridden||n<=g._absoluteStartTime)&&(!_||_._isOverridden||n>=_._absoluteStartTime+_._changeDuration+u._delay))){const e=u._currentTime=ht(R-u._startTime,0,o),s=u._ease(e/u._updateDuration),n=u._modifier,m=u._valueType,f=u._tweenType,g=0===f,y=0===m,_=y&&g||0===s||1===s?-1:D.precision;let b,T;if(y)b=T=n(ct(ut(u._fromNumber,u._toNumber,s),_));else if(1===m)T=n(ct(ut(u._fromNumber,u._toNumber,s),_)),b=`${T}${u._unit}`;else if(2===m){const t=u._fromNumbers,e=u._toNumbers,i=ct(ht(n(ut(t[0],e[0],s)),0,255),0),r=ct(ht(n(ut(t[1],e[1],s)),0,255),0),o=ct(ht(n(ut(t[2],e[2],s)),0,255),0),a=ht(n(ct(ut(t[3],e[3],s),_)),0,1);if(b=`rgba(${i},${r},${o},${a})`,v){const t=u._numbers;t[0]=i,t[1]=r,t[2]=o,t[3]=a}}else if(3===m){b=u._strings[0];for(let t=0,e=u._toNumbers.length;t<e;t++){const e=n(ct(ut(u._fromNumbers[t],u._toNumbers[t],s),_)),i=u._strings[t+1];b+=`${i?e+i:e}`,v&&(u._numbers[t]=e)}}if(v&&(u._number=T),i||t===r.blend)u._value=b;else{const t=u.property;a=u.target,g?a[t]=b:1===f?a.setAttribute(t,b):(l=a.style,3===f?(a!==c&&(c=a,d=a[h]),d[t]=b,p=1):2===f?l[t]=b:4===f&&l.setProperty(t,b)),C&&(F=1)}}if(p&&u._renderTransforms){let t=m;for(let e in d)t+=`${y[e]}${d[e]}) `;l.transform=t,p=0}u=u._next}!s&&F&&t.onRender(t)}!s&&C&&t.onUpdate(t)}return o&&B?!s&&(o.began&&!M&&S>=a&&!l||M&&S<=d&&l)&&(t.onComplete(t),t.completed=!M):C&&E?u===1/0?t._startTime+=t.duration:t._currentIteration>=u-1&&(t.paused=!0,l||v||(t.completed=!0,s||o&&(M||!o.began)||(t.onComplete(t),t._resolve(t)))):t.completed=!1,F},kt=(t,e,s,i,r)=>{const n=t._currentIteration;if(xt(t,e,s,i,r),t._hasChildren){const o=t,a=o.backwards,h=i?e:o._iterationTime,l=O();let c=0,u=!0;if(!i&&o._currentIteration!==n){const t=o.iterationDuration;vt(o,(e=>{if(a){const i=e.duration,r=e._offset+e._delay;s||!(i<=d)||r&&r+i!==t||e.onComplete(e)}else!e.completed&&!e.backwards&&e._currentTime<e.iterationDuration&&xt(e,t,s,1,2),e.began=!1,e.completed=!1})),s||o.onLoop(o)}vt(o,(t=>{const e=ct((h-t._offset)*t._speed,12),n=t._fps<o._fps?t.requestTick(l):r;c+=xt(t,e,s,i,n),!t.completed&&u&&(u=!1)}),a),!s&&c&&o.onRender(o),(u||a)&&o._currentTime>=o.duration&&(o.paused=!0,o.completed||(o.completed=!0,s||(o.onComplete(o),o._resolve(o))))}},$t={animation:null,update:_},Ct=(()=>e?requestAnimationFrame:setImmediate)(),Et=(()=>e?cancelAnimationFrame:clearImmediate)();class Bt extends St{constructor(t){super(t),this.useDefaultMainLoop=!0,this.pauseOnDocumentHidden=!0,this.defaults=B,this.paused=!0,this.reqId=0}update(){const t=this._currentTime=O();if(this.requestTick(t)){this.computeDeltaTime(t);const e=this._speed,s=this._fps;let i=this._head;for(;i;){const r=i._next;i.paused?(bt(this,i),this._hasChildren=!!this._tail,i._running=!1,i.completed&&!i._cancelled&&i.cancel()):kt(i,(t-i._startTime)*i._speed*e,0,0,i._fps<s?i.requestTick(t):1),i=r}$t.update()}}wake(){return this.useDefaultMainLoop&&!this.reqId&&(this.requestTick(O()),this.reqId=Ct(Dt)),this}pause(){if(this.reqId)return this.paused=!0,At()}resume(){if(this.paused)return this.paused=!1,vt(this,(t=>t.resetTime())),this.wake()}get speed(){return this._speed*(1===D.timeScale?1:p)}set speed(t){this._speed=t*D.timeScale,vt(this,(t=>t.speed=t._speed))}get timeUnit(){return 1===D.timeScale?"ms":"s"}set timeUnit(t){const e="s"===t,s=e?.001:1;if(D.timeScale!==s){D.timeScale=s,D.tickThreshold=200*s;const t=e?.001:p;this.defaults.duration*=t,this._speed*=t}}get precision(){return D.precision}set precision(t){D.precision=t}}const Lt=(()=>{const t=new Bt(O());return e&&(A.engine=t,i.addEventListener("visibilitychange",(()=>{t.pauseOnDocumentHidden&&(i.hidden?t.pause():t.resume())}))),t})(),Dt=()=>{Lt._head?(Lt.reqId=Ct(Dt),Lt.update()):Lt.reqId=0},At=()=>(Et(Lt.reqId),Lt.reqId=0,Lt);function Nt(t){const e=I(t)?L.root.querySelectorAll(t):t;if(e instanceof NodeList||e instanceof HTMLCollection)return e}function Ft(t){if(X(t))return[];if(!e)return P(t)&&t.flat(1/0)||[t];if(P(t)){const e=t.flat(1/0),s=[];for(let t=0,i=e.length;t<i;t++){const i=e[t];if(!X(i)){const t=Nt(i);if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!X(i)){let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}else{let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}}return s}const s=Nt(t);return s?Array.from(s):[t]}function Ot(t){const e=Ft(t),s=e.length;if(s)for(let t=0;t<s;t++){const s=e[t];if(!s[n]){s[n]=!0;const t=W(s);(s.nodeType||t)&&(s[o]=!0,s[a]=t,s[h]={})}}return e}const Pt=t=>{const e=Ft(t)[0];if(e&&W(e))return e},Rt=(t,e,s=0)=>t.getPointAtLength(e+s>=1?e+s:0),Mt=(t,e)=>s=>{const i=+t.getTotalLength(),r=s[a],n=t.getCTM();return{from:0,to:i,modifier:s=>{if("a"===e){const e=Rt(t,s,-1),i=Rt(t,s,1);return 180*nt(i.y-e.y,i.x-e.x)/ot}{const i=Rt(t,s,0);return"x"===e?r||!n?i.x:i.x*n.a+i.y*n.c+n.e:r||!n?i.y:i.x*n.b+i.y*n.d+n.f}}}},It=["opacity","rotate","overflow","color"],zt={morphTo:(t,e=.33)=>s=>{const i=Pt(t);if(!i)return;const r="path"===s.tagName,n=r?" ":",",o=s[l];o&&s.setAttribute(r?"d":"points",o);let a="",h="";if(e){const t=s.getTotalLength(),o=i.getTotalLength(),l=Math.max(Math.ceil(t*e),Math.ceil(o*e));for(let e=0;e<l;e++){const c=e/(l-1),d=s.getPointAtLength(t*c),u=i.getPointAtLength(o*c),p=r?0===e?"M":"L":"";a+=p+ct(d.x,3)+n+d.y+" ",h+=p+ct(u.x,3)+n+u.y+" "}}else a=s.getAttribute(r?"d":"points"),h=i.getAttribute(r?"d":"points");return s[l]=h,[a,h]},createMotionPath:t=>{const e=Pt(t);if(e)return{translateX:Mt(e,"x"),translateY:Mt(e,"y"),rotate:Mt(e,"a")}},createDrawable:(t,e=0,s=0)=>Ft(t).map((t=>((t,e,s)=>{const i=p,r=getComputedStyle(t),n=r.strokeLinecap,o="non-scaling-stroke"===r.vectorEffect?t:null;let a=n;const h=new Proxy(t,{get(t,e){const s=t[e];return e===c?t:"setAttribute"===e?(...e)=>{if("draw"===e[0]){const s=e[1].split(" "),r=+s[0],h=+s[1],l=(t=>{let e=1;if(t&&t.getCTM){const s=t.getCTM();s&&(e=(G(s.a*s.a+s.b*s.b)+G(s.c*s.c+s.d*s.d))/2)}return e})(o),c=-1e3*r*l,d=h*i*l+c,u=i*l+(0===r&&1===h||1===r&&0===h?0:10*l)-d;if("butt"!==n){const e=r===h?"butt":n;a!==e&&(t.style.strokeLinecap=`${e}`,a=e)}t.setAttribute("stroke-dashoffset",`${c}`),t.setAttribute("stroke-dasharray",`${d} ${u}`)}return Reflect.apply(s,t,e)}:z(s)?(...e)=>Reflect.apply(s,t,e):s}});return"1000"!==t.getAttribute("pathLength")&&(t.setAttribute("pathLength","1000"),h.setAttribute("draw",`${e} ${s}`)),h})(t,e,s)))},Yt=(t,e,s)=>(s<0&&(s+=1),s>1&&(s-=1),s<1/6?t+6*(e-t)*s:s<.5?e:s<2/3?t+(e-t)*(2/3-s)*6:t),Xt=(t,e)=>Y(t)?e:t,Wt=(t,e,s,i,r)=>{if(z(t)){const n=()=>{const r=t(e,s,i);return isNaN(+r)?r||0:+r};return r&&(r.func=n),n()}return t},Vt=(t,e)=>t[o]?t[a]&&((t,e)=>{if(It.includes(e))return!1;if(t.getAttribute(e)||e in t){if("scale"===e){const e=t.parentNode;return e&&"filter"===e.tagName}return!0}})(t,e)?1:g.includes(e)||f.get(e)?3:F(e,"--")?4:e in t.style?2:e in t?0:1:0,Ht=(t,e,s)=>{const i=t.style[e];i&&s&&(s[e]=i);const r=i||getComputedStyle(t[c]||t).getPropertyValue(e);return"auto"===r?"0":r},Ut=(t,e,s,i)=>{const r=Y(s)?Vt(t,e):s;return 0===r?t[e]||0:1===r?t.getAttribute(e):3===r?((t,e,s)=>{const i=t.style.transform;let r;if(i){const n=t[h];let o;for(;o=C.exec(i);){const t=o[1],i=o[2].slice(1,-1);n[t]=i,t===e&&(r=i,s&&(s[e]=i))}}return i&&!Y(r)?r:F(e,"scale")?"1":F(e,"rotate")||F(e,"skew")?"0deg":"0px"})(t,e,i):4===r?Ht(t,e,i).trimStart():Ht(t,e,i)},qt=(t,e,s)=>"-"===s?t-e:"+"===s?t+e:t*e,Qt=(t,e)=>{if(e.t=0,e.n=0,e.u=null,e.o=null,e.d=null,e.s=null,!t)return e;const s=+t;if(isNaN(s)){let s=t;"="===s[1]&&(e.o=s[0],s=s.slice(2));const n=!s.includes(" ")&&k.exec(s);if(n)return e.t=1,e.n=+n[1],e.u=n[2],e;if(e.o)return e.n=+s,e;if(V(r=s)||H(r)||U(r))return e.t=2,e.d=H(i=s)?(t=>{const e=b.exec(t)||T.exec(t),s=Y(e[4])?1:+e[4];return[+e[1],+e[2],+e[3],s]})(i):V(i)?(t=>{const e=t.length,s=4===e||5===e;return[+("0x"+t[1]+t[s?1:2]),+("0x"+t[s?2:3]+t[s?2:4]),+("0x"+t[s?3:5]+t[s?3:6]),5===e||9===e?+(+("0x"+t[s?4:7]+t[s?4:8])/255).toFixed(3):1]})(i):U(i)?(t=>{const e=w.exec(t)||S.exec(t),s=+e[1]/360,i=+e[2]/100,r=+e[3]/100,n=Y(e[4])?1:+e[4];let o,a,h;if(0===i)o=a=h=r;else{const t=r<.5?r*(1+i):r+i-r*i,e=2*r-t;o=ct(255*Yt(e,t,s+1/3),0),a=ct(255*Yt(e,t,s),0),h=ct(255*Yt(e,t,s-1/3),0)}return[o,a,h,n]})(i):[0,0,0,1],e;{const t=s.match(x);return e.t=3,e.d=t?t.map(Number):[],e.s=s.split(x)||[],e}}var i,r;return e.n=s,e},jt=(t,e)=>(e.t=t._valueType,e.n=t._toNumber,e.u=t._unit,e.o=null,e.d=yt(t._toNumbers),e.s=yt(t._strings),e),Gt={t:0,n:0,u:null,o:null,d:null,s:null},Zt={_rep:new WeakMap,_add:new Map},Jt=(t,e,s="_rep")=>{const i=Zt[s];let r=i.get(t);return r||(r={},i.set(t,r)),r[e]?r[e]:r[e]={_head:null,_tail:null}},Kt=(t,e)=>t._isOverridden||t._absoluteStartTime>e._absoluteStartTime,te=t=>{t._isOverlapped=1,t._isOverridden=1,t._changeDuration=d,t._currentTime=d},ee=(t,e)=>{const s=t._composition;if(s===r.replace){const s=t._absoluteStartTime;Tt(e,t,Kt,"_prevRep","_nextRep");const i=t._prevRep;if(i){const e=i.parent,r=i._absoluteStartTime+i._changeDuration;if(t.parent.id!==e.id&&e.iterationCount>1&&r+(e.duration-e.iterationDuration)>s){te(i);let t=i._prevRep;for(;t&&t.parent.id===e.id;)te(t),t=t._prevRep}const n=s-t._delay;if(r>n){const t=i._startTime,e=r-(t+i._updateDuration),s=ct(n-e-t,12);i._changeDuration=s,i._currentTime=s,i._isOverlapped=1,s<d&&te(i)}let o=!0;if(vt(e,(t=>{t._isOverlapped||(o=!1)})),o){const t=e.parent;if(t){let s=!0;vt(t,(t=>{t!==e&&vt(t,(t=>{t._isOverlapped||(s=!1)}))})),s&&t.cancel()}else e.cancel()}}}else if(s===r.blend){const e=Jt(t.target,t.property,"_add"),s=(t=>{let e=$t.animation;return e||(e={duration:d,computeDeltaTime:_,_offset:0,_delay:0,_head:null,_tail:null},$t.animation=e,$t.update=()=>{t.forEach((t=>{for(let e in t){const s=t[e],i=s._head;if(i){const t=i._valueType,e=3===t||2===t?yt(i._fromNumbers):null;let r=i._fromNumber,n=s._tail;for(;n&&n!==i;){if(e)for(let t=0,s=n._numbers.length;t<s;t++)e[t]+=n._numbers[t];else r+=n._number;n=n._prevAdd}i._toNumber=r,i._toNumbers=e}}})),xt(e,1,1,0,2)}),e})(Zt._add);let i=e._head;i||(i={...t},i._composition=r.replace,i._updateDuration=d,i._startTime=0,i._numbers=yt(t._fromNumbers),i._number=0,i._next=null,i._prev=null,Tt(e,i),Tt(s,i));const n=t._toNumber;if(t._fromNumber=i._fromNumber-n,t._toNumber=0,t._numbers=yt(t._fromNumbers),t._number=0,i._fromNumber=n,t._toNumbers){const e=yt(t._toNumbers);e&&e.forEach(((e,s)=>{t._fromNumbers[s]=i._fromNumbers[s]-e,t._toNumbers[s]=0})),i._fromNumbers=e}Tt(e,t,null,"_prevAdd","_nextAdd")}return t},se=t=>{const e=t._composition;if(e!==r.none){const s=t.target,i=t.property,n=Zt._rep.get(s)[i];if(bt(n,t,"_prevRep","_nextRep"),e===r.blend){const e=Zt._add,r=e.get(s);if(!r)return;const n=r[i],o=$t.animation;bt(n,t,"_prevAdd","_nextAdd");const a=n._head;if(a&&a===n._tail){bt(n,a,"_prevAdd","_nextAdd"),bt(o,a);let t=!0;for(let e in r)if(r[e]._head){t=!1;break}t&&e.delete(s)}}}return t},ie=t=>(t.paused=!0,t.began=!1,t.completed=!1,t),re=t=>t._cancelled?(t._hasChildren?vt(t,re):vt(t,(t=>{t._composition!==r.none&&ee(t,Jt(t.target,t.property))})),t._cancelled=0,t):t;let ne=0;class oe extends St{constructor(t={},e=null,s=0){super(0);const{id:i,delay:r,duration:n,reversed:o,alternate:a,loop:h,loopDelay:l,autoplay:c,frameRate:u,playbackRate:p,onComplete:m,onLoop:f,onPause:g,onBegin:y,onBeforeUpdate:v,onUpdate:b}=t;L.current&&L.current.register(this);const T=e?0:Lt._elapsedTime,w=e?e.defaults:D.defaults,S=z(r)||Y(r)?w.delay:+r,x=z(n)||Y(n)?1/0:+n,k=Xt(h,w.loop),$=Xt(l,w.loopDelay),C=!0===k||k===1/0||k<0?1/0:k+1;let E=0;e?E=s:(Lt.reqId||Lt.requestTick(O()),E=(Lt._elapsedTime-Lt._startTime)*D.timeScale),this.id=Y(i)?++ne:i,this.parent=e,this.duration=ft((x+$)*C-$)||d,this.backwards=!1,this.paused=!0,this.began=!1,this.completed=!1,this.onBegin=y||w.onBegin,this.onBeforeUpdate=v||w.onBeforeUpdate,this.onUpdate=b||w.onUpdate,this.onLoop=f||w.onLoop,this.onPause=g||w.onPause,this.onComplete=m||w.onComplete,this.iterationDuration=x,this.iterationCount=C,this._autoplay=!e&&Xt(c,w.autoplay),this._offset=E,this._delay=S,this._loopDelay=$,this._iterationTime=0,this._currentIteration=0,this._resolve=_,this._running=!1,this._reversed=+Xt(o,w.reversed),this._reverse=this._reversed,this._cancelled=0,this._alternate=Xt(a,w.alternate),this._prev=null,this._next=null,this._elapsedTime=T,this._startTime=T,this._lastTime=T,this._fps=Xt(u,w.frameRate),this._speed=Xt(p,w.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(t){t?this.cancel():this.reset(1).play()}get currentTime(){return ht(ct(this._currentTime,D.precision),-this._delay,this.duration)}set currentTime(t){const e=this.paused;this.pause().seek(+t),e||this.resume()}get iterationCurrentTime(){return ct(this._iterationTime,D.precision)}set iterationCurrentTime(t){this.currentTime=this.iterationDuration*this._currentIteration+t}get progress(){return ht(ct(this._currentTime/this.duration,10),0,1)}set progress(t){this.currentTime=this.duration*t}get iterationProgress(){return ht(ct(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(t){const e=this.iterationDuration;this.currentTime=e*this._currentIteration+e*t}get currentIteration(){return this._currentIteration}set currentIteration(t){this.currentTime=this.iterationDuration*ht(+t,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(t){t?this.reverse():this.play()}get speed(){return super.speed}set speed(t){super.speed=t,this.resetTime()}reset(t=0){return re(this),this._reversed&&!this._reverse&&(this.reversed=!1),this._iterationTime=this.iterationDuration,kt(this,0,1,t,2),ie(this),this._hasChildren&&vt(this,ie),this}init(t=0){this.fps=this._fps,this.speed=this._speed,!t&&this._hasChildren&&kt(this,this.duration,1,t,2),this.reset(t);const e=this._autoplay;return!0===e?this.resume():e&&!Y(e.linked)&&e.link(this),this}resetTime(){const t=1/(this._speed*Lt._speed);return this._startTime=O()-(this._currentTime+this._delay)*t,this}pause(){return this.paused||(this.paused=!0,this.onPause(this)),this}resume(){return this.paused?(this.paused=!1,this.duration<=d&&!this._hasChildren?kt(this,d,0,0,2):(this._running||(Tt(Lt,this),Lt._hasChildren=!0,this._running=!0),this.resetTime(),this._startTime-=12,Lt.wake()),this):this}restart(){return this.reset(0).resume()}seek(t,e=0,s=0){re(this),this.completed=!1;const i=this.paused;return this.paused=!0,kt(this,t+this._delay,~~e,~~s,1),i?this:this.resume()}alternate(){const t=this._reversed,e=this.iterationCount,s=this.iterationDuration,i=e===1/0?st(u/s):e;return this._reversed=+(!this._alternate||i%2?!t:t),e===1/0?this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress:this.seek(s*i-this._currentTime),this.resetTime(),this}play(){return this._reversed&&this.alternate(),this.resume()}reverse(){return this._reversed||this.alternate(),this.resume()}cancel(){return this._hasChildren?vt(this,(t=>t.cancel()),!0):vt(this,se),this._cancelled=1,this.pause()}stretch(t){const e=this.duration,s=gt(t);if(e===s)return this;const i=t/e,r=t<=d;return this.duration=r?d:s,this.iterationDuration=r?d:gt(this.iterationDuration*i),this._offset*=i,this._delay*=i,this._loopDelay*=i,this}revert(){kt(this,0,1,0,1);const t=this._autoplay;return t&&t.linked&&t.linked===this&&t.revert(),this.cancel()}complete(){return this.seek(this.duration).cancel()}then(t=_){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=_};return new Promise((t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this)))}}const ae=t=>t,he=(t,e,s)=>(((1-3*s+3*e)*t+(3*s-6*e))*t+3*e)*t,le=(t=.5,e=0,s=.5,i=1)=>t===e&&s===i?ae:r=>0===r||1===r?r:he(((t,e,s)=>{let i,r,n=0,o=1,a=0;do{r=n+(o-n)/2,i=he(r,e,s)-t,i>0?o=r:n=r}while(K(i)>1e-7&&++a<100);return r})(r,t,s),e,i),ce=(t=10,e)=>{const s=e?et:st;return e=>s(ht(e,0,1)*t)*(1/t)},de=(...t)=>{const e=t.length;if(!e)return ae;const s=e-1,i=t[0],r=t[s],n=[0],o=[Q(i)];for(let e=1;e<s;e++){const i=t[e],r=I(i)?i.trim().split(" "):[i],a=r[0],h=r[1];n.push(Y(h)?e/s:Q(h)/100),o.push(Q(a))}return o.push(Q(r)),n.push(1),function(t){for(let e=1,s=n.length;e<s;e++){const s=n[e];if(t<=s){const i=n[e-1],r=o[e-1];return r+(o[e]-r)*(t-i)/(s-i)}}return o[o.length-1]}},ue=(t=10,e=1)=>{const s=[0],i=t-1;for(let t=1;t<i;t++){const r=s[t-1],n=t/i,o=n*(1-e)+(n+((t+1)/i-n)*Math.random())*e;s.push(ht(o,r,1))}return s.push(1),de(...s)},pe=ot/2,me=2*ot,fe=(t=1.68)=>e=>j(e,+t),ge={[m]:fe,Quad:fe(2),Cubic:fe(3),Quart:fe(4),Quint:fe(5),Sine:t=>1-J(t*pe),Circ:t=>1-G(1-t*t),Expo:t=>t?j(2,10*t-10):0,Bounce:t=>{let e,s=4;for(;t<((e=j(2,--s))-1)/11;);return 1/j(4,3-s)-7.5625*j((3*e-2)/22-t,2)},Back:(t=1.70158)=>e=>(+t+1)*e*e*e-+t*e*e,Elastic:(t=1,e=.3)=>{const s=ht(+t,1,10),i=ht(+e,d,2),r=i/me*it(1/s),n=me/i;return t=>0===t||1===t?t:-s*j(2,-10*(1-t))*Z((1-t-r)*n)}},ye={in:t=>e=>t(e),out:t=>e=>1-t(1-e),inOut:t=>e=>e<.5?t(2*e)/2:1-t(-2*e+2)/2,outIn:t=>e=>e<.5?(1-t(1-2*e))/2:(t(2*e-1)+1)/2},_e=(t,e,s)=>{if(s[t])return s[t];if(t.indexOf("(")<=-1){const i=ye[t]||t.includes("Back")||t.includes("Elastic")?e[t]():e[t];return i?s[t]=i:ae}{const i=t.slice(0,-1).split("("),r=e[i[0]];return r?s[t]=r(...i[1].split(",")):ae}},ve=(()=>{const t={linear:de,irregular:ue,steps:ce,cubicBezier:le};for(let e in ye)for(let s in ge){const i=ge[s],r=ye[e];t[e+s]=s===m||"Back"===s||"Elastic"===s?(t,e)=>r(i(t,e)):r(i)}return t})(),be={linear:ae},Te=t=>z(t)?t:I(t)?_e(t,ve,be):ae,we={},Se=(t,e,s)=>{if(3===s)return f.get(t)||t;if(2===s||1===s&&W(e)&&t in e.style){const e=we[t];if(e)return e;{const e=t?N(t):t;return we[t]=e,e}}return t},xe={deg:1,rad:180/ot,turn:360},ke={},$e=(t,e,s,r=!1)=>{const n=e.u,o=e.n;if(1===e.t&&n===s)return e;const a=o+n+s,h=ke[a];if(Y(h)||r){let r;if(n in xe)r=o*xe[n]/xe[s];else{const e=100,a=t.cloneNode(),h=t.parentNode,l=h&&h!==i?h:i.body;l.appendChild(a);const c=a.style;c.width=e+n;const d=a.offsetWidth||e;c.width=e+s;const u=d/(a.offsetWidth||e);l.removeChild(a),r=u*o}e.n=r,ke[a]=r}else e.n=h;return e.t,e.u=s,e},Ce=t=>{if(t._hasChildren)vt(t,Ce,!0);else{const e=t;e.pause(),vt(e,(t=>{const s=t.property,i=t.target;if(i[o]){const r=i.style,n=e._inlineStyles[s];if(3===t._tweenType){const e=i[h];if(Y(n)||n===m?delete e[s]:e[s]=n,t._renderTransforms)if(Object.keys(e).length){let t=m;for(let s in e)t+=y[s]+e[s]+") ";r.transform=t}else r.removeProperty("transform")}else Y(n)||n===m?r.removeProperty(s):r[s]=n;e._tail===t&&e.targets.forEach((t=>{t.getAttribute&&t.getAttribute("style")===m&&t.removeAttribute("style")}))}}))}return t},Ee={t:0,n:0,u:null,o:null,d:null,s:null},Be={t:0,n:0,u:null,o:null,d:null,s:null},Le={func:null},De=[null],Ae=[null,null],Ne={to:null};let Fe,Oe,Pe=0;class Re extends oe{constructor(t,e,s,i,n=!1,o=0,a=0){super(e,s,i);const h=Ot(t),l=h.length,c=e.keyframes,u=c?_t(((t,e)=>{const s={};if(P(t)){const e=[].concat(...t.map((t=>Object.keys(t)))).filter(q);for(let i=0,r=e.length;i<r;i++){const r=e[i],n=t.map((t=>{const e={};for(let s in t){const i=t[s];q(s)?s===r&&(e.to=i):e[s]=i}return e}));s[r]=n}}else{const i=Xt(e.duration,D.defaults.duration),r=Object.keys(t).map((e=>({o:parseFloat(e)/100,p:t[e]}))).sort(((t,e)=>t.o-e.o));r.forEach((t=>{const e=t.o,r=t.p;for(let t in r)if(q(t)){let n=s[t];n||(n=s[t]=[]);const o=e*i;let a=n.length,h=n[a-1];const l={to:r[t]};let c=0;for(let t=0;t<a;t++)c+=n[t].duration;1===a&&(l.from=h.to),r.ease&&(l.ease=r.ease),l.duration=o-(a?c:0),n.push(l)}return t}));for(let t in s){const e=s[t];let i;for(let t=0,s=e.length;t<s;t++){const s=e[t],r=s.ease;s.ease=i||void 0,i=r}e[0].duration||e.shift()}}return s})(c,e),e):e,{delay:m,duration:f,ease:g,playbackEase:y,modifier:_,composition:v,onRender:b}=u,T=s?s.defaults:D.defaults,w=Xt(y,T.playbackEase),S=w?Te(w):null,x=!Y(g)&&!Y(g.ease),k=x?g.ease:Xt(g,S?"linear":T.ease),$=x?g.duration:Xt(f,T.duration),C=Xt(m,T.delay),E=_||T.modifier,B=Y(v)&&l>=p?r.none:Y(v)?T.composition:v,L={},A=this._offset+(s?s._offset:0);let N=NaN,F=NaN,O=0,I=0;for(let t=0;t<l;t++){const e=h[t],i=o||t,c=a||l;let p=NaN,m=NaN;for(let t in u)if(q(t)){const o=Vt(e,t),a=Se(t,e,o);let h=u[t];const l=P(h);if(n&&!l&&(Ae[0]=h,Ae[1]=h,h=Ae),l){const t=h.length,e=!R(h[0]);2===t&&e?(Ne.to=h,De[0]=Ne,Fe=De):t>2&&e?(Fe=[],h.forEach(((t,e)=>{e?1===e?(Ae[1]=t,Fe.push(Ae)):Fe.push(t):Ae[0]=t}))):Fe=h}else De[0]=h,Fe=De;let f=null,g=null,y=NaN,_=0,v=0;for(let t=Fe.length;v<t;v++){const n=Fe[v];R(n)?Oe=n:(Ne.to=n,Oe=Ne),Le.func=null;const h=Wt(Oe.to,e,i,c,Le);let l;R(h)&&!Y(h.to)?(Oe=h,l=h.to):l=h;const u=Wt(Oe.from,e,i,c),p=Oe.ease,m=!Y(p)&&!Y(p.ease),b=m?p.ease:p||k,T=m?p.duration:Wt(Xt(Oe.duration,t>1?Wt($,e,i,c)/t:$),e,i,c),w=Wt(Xt(Oe.delay,v?0:C),e,i,c),S=Wt(Xt(Oe.composition,B),e,i,c),x=M(S)?S:r[S],D=Oe.modifier||E,N=!Y(u),F=!Y(l),z=P(l),X=z||N&&F,W=g?_+w:w,V=ct(A+W,12);I||!N&&!z||(I=1);let H=g;if(x!==r.none){f||(f=Jt(e,a));let t=f._head;for(;t&&!t._isOverridden&&t._absoluteStartTime<=V;)if(H=t,t=t._nextRep,t&&t._absoluteStartTime>=V)for(;t;)te(t),t=t._nextRep}if(X?(Qt(z?Wt(l[0],e,i,c):u,Ee),Qt(z?Wt(l[1],e,i,c,Le):l,Be),0===Ee.t&&(H?1===H._valueType&&(Ee.t=1,Ee.u=H._unit):(Qt(Ut(e,a,o,L),Gt),1===Gt.t&&(Ee.t=1,Ee.u=Gt.u)))):(F?Qt(l,Be):g?jt(g,Be):Qt(s&&H&&H.parent.parent===s?H._value:Ut(e,a,o,L),Be),N?Qt(u,Ee):g?jt(g,Ee):Qt(s&&H&&H.parent.parent===s?H._value:Ut(e,a,o,L),Ee)),Ee.o&&(Ee.n=qt(H?H._toNumber:Qt(Ut(e,a,o,L),Gt).n,Ee.n,Ee.o)),Be.o&&(Be.n=qt(Ee.n,Be.n,Be.o)),Ee.t!==Be.t)if(3===Ee.t||3===Be.t){const t=3===Ee.t?Ee:Be,e=3===Ee.t?Be:Ee;e.t=3,e.s=yt(t.s),e.d=t.d.map((()=>e.n))}else if(1===Ee.t||1===Be.t){const t=1===Ee.t?Ee:Be,e=1===Ee.t?Be:Ee;e.t=1,e.u=t.u}else if(2===Ee.t||2===Be.t){const t=2===Ee.t?Ee:Be,e=2===Ee.t?Be:Ee;e.t=2,e.s=t.s,e.d=[0,0,0,1]}if(Ee.u!==Be.u){let t=Be.u?Ee:Be;t=$e(e,t,Be.u?Be.u:Ee.u,!1)}if(Be.d&&Ee.d&&Be.d.length!==Ee.d.length){const t=Ee.d.length>Be.d.length?Ee:Be,e=t===Ee?Be:Ee;e.d=t.d.map(((t,s)=>Y(e.d[s])?0:e.d[s])),e.s=yt(t.s)}const U=ct(+T||d,12),q={parent:this,id:Pe++,property:a,target:e,_value:null,_func:Le.func,_ease:Te(b),_fromNumbers:yt(Ee.d),_toNumbers:yt(Be.d),_strings:yt(Be.s),_fromNumber:Ee.n,_toNumber:Be.n,_numbers:yt(Ee.d),_number:Ee.n,_unit:Be.u,_modifier:D,_currentTime:0,_startTime:W,_delay:+w,_updateDuration:U,_changeDuration:U,_absoluteStartTime:V,_tweenType:o,_valueType:Be.t,_composition:x,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};x!==r.none&&ee(q,f),isNaN(y)&&(y=q._startTime),_=ct(W+U,12),g=q,O++,Tt(this,q)}(isNaN(F)||y<F)&&(F=y),(isNaN(N)||_>N)&&(N=_),3===o&&(p=O-v,m=O)}if(!isNaN(p)){let t=0;vt(this,(e=>{t>=p&&t<m&&(e._renderTransforms=1,e._composition===r.blend&&vt($t.animation,(t=>{t.id===e.id&&(t._renderTransforms=1)}))),t++}))}}l||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation."),F?(vt(this,(t=>{t._startTime-t._delay||(t._delay-=F),t._startTime-=F})),N-=F):F=0,N||(N=d,this.iterationCount=0),this.targets=h,this.duration=N===d?d:ft((N+this._loopDelay)*this.iterationCount-this._loopDelay)||d,this.onRender=b||T.onRender,this._ease=S,this._delay=F,this.iterationDuration=N,this._inlineStyles=L,!this._autoplay&&I&&this.onRender(this)}stretch(t){const e=this.duration;if(e===gt(t))return this;const s=t/e;return vt(this,(t=>{t._updateDuration=gt(t._updateDuration*s),t._changeDuration=gt(t._changeDuration*s),t._currentTime*=s,t._startTime*=s,t._absoluteStartTime*=s})),super.stretch(t)}refresh(){return vt(this,(t=>{const e=t._func;if(e){const s=Ut(t.target,t.property,t._tweenType);Qt(s,Gt),Qt(e(),Be),t._fromNumbers=yt(Gt.d),t._fromNumber=Gt.n,t._toNumbers=yt(Be.d),t._strings=yt(Be.s),t._toNumber=Be.o?qt(Gt.n,Be.n,Be.o):Be.n}})),this}revert(){return super.revert(),Ce(this)}then(t){return super.then(t)}}const Me=(t,e=100)=>{const s=[];for(let i=0;i<=e;i++)s.push(t(i/e));return`linear(${s.join(", ")})`},Ie={in:"ease-in",out:"ease-out",inOut:"ease-in-out"},ze=(()=>{const t={};for(let e in ye)t[e]=t=>ye[e](fe(t));return t})(),Ye=t=>{let e=Ie[t];if(e)return e;if(e="linear",I(t)){if(F(t,"linear")||F(t,"cubic-")||F(t,"steps")||F(t,"ease"))e=t;else if(F(t,"cubicB"))e=N(t);else{const s=_e(t,ze,Ie);z(s)&&(e=s===ae?"linear":Me(s))}Ie[t]=e}else if(z(t)){const s=Me(t);s&&(e=s)}else t.ease&&(e=Me(t.ease));return e},Xe=["x","y","z"],We=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",...Xe],Ve=(()=>[...Xe,...g.filter((t=>["X","Y","Z"].some((e=>t.endsWith(e)))))])();let He=null;const Ue={_head:null,_tail:null},qe=(t,e,s)=>{let i=Ue._head;for(;i;){const r=i._next,n=i.$el===t,o=!e||i.property===e,a=!s||i.parent===s;if(n&&o&&a){const t=i.animation;try{t.commitStyles()}catch{}t.cancel(),bt(Ue,i);const e=i.parent;e&&(e._completed++,e.animations.length===e._completed&&(e.completed=!0,e.muteCallbacks||(e.paused=!0,e.onComplete(e),e._resolve(e))))}i=r}},Qe=(t,e,s,i,r)=>{const n=e.animate(i,r),o=r.delay+ +r.duration*r.iterations;n.playbackRate=t._speed,t.paused&&n.pause(),t.duration<o&&(t.duration=o,t.controlAnimation=n),t.animations.push(n),qe(e,s),Tt(Ue,{parent:t,animation:n,$el:e,property:s,_next:null,_prev:null});const a=()=>{qe(e,s,t)};return n.onremove=a,n.onfinish=a,n},je=(t,e,s,i,r)=>{let n=Wt(e,s,i,r);return M(n)?We.includes(t)||F(t,"translate")?`${n}px`:F(t,"rotate")||F(t,"skew")?`${n}deg`:`${n}`:n},Ge=(t,e,s,i,r,n)=>{let o="0";const a=Y(i)?getComputedStyle(t)[e]:je(e,i,t,r,n);return o=Y(s)?P(i)?i.map((s=>je(e,s,t,r,n))):a:[je(e,s,t,r,n),a],o};class Ze{constructor(t,s){L.current&&L.current.register(this),X(He)&&(!e||!Y(CSS)&&Object.hasOwnProperty.call(CSS,"registerProperty")?(g.forEach((t=>{const e=F(t,"skew"),s=F(t,"scale"),i=F(t,"rotate"),r=F(t,"translate"),n=i||e,o=n?"<angle>":s?"<number>":r?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:o,inherits:!1,initialValue:r?"0px":n?"0deg":s?"1":"0"})}catch{}})),He=!0):He=!1);const i=Ot(t),r=i.length;r||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation.");const n=Xt(s.ease,Ye(D.defaults.ease)),o=n.ease&&n,a=Xt(s.autoplay,D.defaults.autoplay),l=!(!a||!a.link)&&a,c=s.alternate&&!0===s.alternate,d=s.reversed&&!0===s.reversed,u=Xt(s.loop,D.defaults.loop),v=!0===u||u===1/0?1/0:M(u)?u+1:1,b=c?d?"alternate-reverse":"alternate":d?"reverse":"normal",T=Ye(n),w=1===D.timeScale?1:p;this.targets=i,this.animations=[],this.controlAnimation=null,this.onComplete=s.onComplete||_,this.duration=0,this.muteCallbacks=!1,this.completed=!1,this.paused=!a||!1!==l,this.reversed=d,this.autoplay=a,this._speed=Xt(s.playbackRate,D.defaults.playbackRate),this._resolve=_,this._completed=0,this._inlineStyles=i.map((t=>t.getAttribute("style"))),i.forEach(((t,e)=>{const i=t[h],a=Ve.some((t=>s.hasOwnProperty(t))),l=(o?o.duration:Wt(Xt(s.duration,D.defaults.duration),t,e,r))*w,c=Wt(Xt(s.delay,D.defaults.delay),t,e,r)*w,d=Xt(s.composition,"replace");for(let o in s){if(!q(o))continue;const h={},u={iterations:v,direction:b,fill:"forwards",easing:T,duration:l,delay:c,composite:d},p=s[o],m=!!a&&(g.includes(o)?o:f.get(o));let y;if(R(p)){const s=p,a=Xt(s.ease,n),f=a.ease&&a,g=s.to,_=s.from;if(u.duration=(f?f.duration:Wt(Xt(s.duration,l),t,e,r))*w,u.delay=Wt(Xt(s.delay,c),t,e,r)*w,u.composite=Xt(s.composition,d),u.easing=Ye(a),y=Ge(t,o,_,g,e,r),m?(h[`--${m}`]=y,i[m]=y):h[o]=Ge(t,o,_,g,e,r),Qe(this,t,o,h,u),!Y(_))if(m){const e=`--${m}`;t.style.setProperty(e,h[e][0])}else t.style[o]=h[o][0]}else y=P(p)?p.map((s=>je(o,s,t,e,r))):je(o,p,t,e,r),m?(h[`--${m}`]=y,i[m]=y):h[o]=y,Qe(this,t,o,h,u)}if(a){let e=m;for(let t in i)e+=`${y[t]}var(--${t})) `;t.style.transform=e}})),l&&this.autoplay.link(this)}forEach(t){const e=I(t)?e=>e[t]():t;return this.animations.forEach(e),this}get speed(){return this._speed}set speed(t){this._speed=+t,this.forEach((e=>e.playbackRate=t))}get currentTime(){const t=this.controlAnimation,e=D.timeScale;return this.completed?this.duration:t?+t.currentTime*(1===e?1:e):0}set currentTime(t){const e=t*(1===D.timeScale?1:p);this.forEach((t=>{e>=this.duration&&t.play(),t.currentTime=e}))}get progress(){return this.currentTime/this.duration}set progress(t){this.forEach((e=>e.currentTime=t*this.duration||0))}resume(){return this.paused?(this.paused=!1,this.forEach("play")):this}pause(){return this.paused?this:(this.paused=!0,this.forEach("pause"))}alternate(){return this.reversed=!this.reversed,this.forEach("reverse"),this.paused&&this.forEach("pause"),this}play(){return this.reversed&&this.alternate(),this.resume()}reverse(){return this.reversed||this.alternate(),this.resume()}seek(t,e=!1){return e&&(this.muteCallbacks=!0),t<this.duration&&(this.completed=!1),this.currentTime=t,this.muteCallbacks=!1,this.paused&&this.pause(),this}restart(){return this.completed=!1,this.seek(0,!0).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){return this.forEach("cancel"),this.pause()}revert(){return this.cancel(),this.targets.forEach(((t,e)=>t.setAttribute("style",this._inlineStyles[e]))),this}then(t=_){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=_};return new Promise((t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this)))}}const Je={animate:(t,e)=>new Ze(t,e),convertEase:Me},Ke=(t=_)=>new oe({duration:1*D.timeScale,onComplete:t},null,0).resume();function ts(t,e,s){const i=Ot(t);if(!i.length)return;const[r]=i,n=Vt(r,e),o=Se(e,r,n);let a=Ut(r,o);if(Y(s))return a;if(Qt(a,Gt),0===Gt.t||1===Gt.t){if(!1===s)return Gt.n;{const t=$e(r,Gt,s,!1);return`${ct(t.n,D.precision)}${t.u}`}}}const es=(t,e)=>{if(!Y(e))return e.duration=d,e.composition=Xt(e.composition,r.none),new Re(t,e,null,0,!0).resume()},ss=(t,e,s)=>{let i=!1;return vt(e,(r=>{const n=r.target;if(t.includes(n)){const t=r.property,o=r._tweenType,a=Se(s,n,o);(!a||a&&a===t)&&(r.parent._tail===r&&3===r._tweenType&&r._prev&&3===r._prev._tweenType&&(r._prev._renderTransforms=1),bt(e,r),se(r),i=!0)}}),!0),i},is=(t,e,s)=>{const i=Ft(t),r=e||Lt,n=e&&e.controlAnimation&&e;for(let t=0,e=i.length;t<e;t++){const e=i[t];qe(e,s,n)}let o;if(r._hasChildren){let e=0;vt(r,(n=>{if(!n._hasChildren)if(o=ss(i,n,s),o&&!n._head)n.cancel(),bt(r,n);else{const t=n._offset+n._delay+n.duration;t>e&&(e=t)}n._head?is(t,n,s):n._hasChildren=!1}),!0),Y(r.iterationDuration)||(r.iterationDuration=e)}else o=ss(i,r,s);return o&&!r._head&&(r._hasChildren=!1,r.cancel&&r.cancel()),i},rs=(t,e,s,i,r)=>i+(t-e)/(s-e)*(r-i),ns=(t,e,s,i)=>{let r=p/D.defaults.frameRate;if(!1!==i){const t=i||Lt._hasChildren&&Lt;t&&t.deltaTime&&(r=t.deltaTime)}const n=1-Math.exp(-s*r*.1);return s?1===s?e:(1-n)*t+n*e:t},os=t=>(...e)=>{const s=t(...e);return new Proxy(_,{apply:(t,e,[i])=>s(i),get:(t,e)=>os(((...t)=>{const i=hs[e](...t);return t=>i(s(t))}))})},as=(t,e=0)=>(...s)=>(s.length<t.length?os(((t,e=0)=>(...s)=>e?e=>t(...s,e):e=>t(e,...s))(t,e)):t)(...s),hs={$:Ot,get:ts,set:es,remove:is,cleanInlineStyles:Ce,random:pt,randomPick:t=>t[pt(0,t.length-1)],shuffle:mt,lerp:ns,sync:Ke,keepTime:wt,clamp:as(ht),round:as(ct),snap:as(dt),wrap:as(((t,e,s)=>((t-e)%(s-e)+(s-e))%(s-e)+e)),interpolate:as(ut,1),mapRange:as(rs),roundPad:as(((t,e)=>(+t).toFixed(e))),padStart:as(((t,e,s)=>`${t}`.padStart(e,s))),padEnd:as(((t,e,s)=>`${t}`.padEnd(e,s))),degToRad:as((t=>t*ot/180)),radToDeg:as((t=>180*t/ot))},ls=(t,e)=>{let s=t.iterationDuration;if(s===d&&(s=0),Y(e))return s;if(M(+e))return+e;const i=e,r=t?t.labels:null,n=!X(r),o=((t,e)=>{if(F(e,"<")){const s="<"===e[1],i=t._tail,r=i?i._offset+i._delay:0;return s?r:r+i.duration}})(t,i),a=!Y(o),h=E.exec(i);if(h){const t=h[0],e=i.split(t),l=n&&e[0]?r[e[0]]:s,c=a?o:n?l:s,d=+e[1];return qt(c,d,t[0])}return a?o:n?Y(r[i])?s:r[i]:s};function cs(t,e,s,i,r,n){const o=M(t.duration)&&t.duration<=d?s-d:s;kt(e,o,1,1,1);const a=i?new Re(i,t,e,o,!1,r,n):new oe(t,e,o);return a.init(1),Tt(e,a),vt(e,(t=>{const s=t._offset+t._delay+t.duration;s>e.iterationDuration&&(e.iterationDuration=s)})),e.duration=function(t){return ft((t.iterationDuration+t._loopDelay)*t.iterationCount-t._loopDelay)||d}(e),e}class ds extends oe{constructor(t={}){super(t,null,0),this.duration=0,this.labels={};const e=t.defaults,s=D.defaults;this.defaults=e?_t(e,s):s,this.onRender=t.onRender||s.onRender;const i=Xt(t.playbackEase,s.playbackEase);this._ease=i?Te(i):null,this.iterationDuration=0}add(t,e,s){const i=R(e),r=R(t);if(i||r){if(this._hasChildren=!0,i){const i=e;if(z(s)){const e=s,r=Ft(t),n=this.duration,o=this.iterationDuration,a=i.id;let h=0;const l=r.length;r.forEach((t=>{const s={...i};this.duration=n,this.iterationDuration=o,Y(a)||(s.id=a+"-"+h),cs(s,this,ls(this,e(t,h,l,this)),t,h,l),h++}))}else cs(i,this,ls(this,s),t)}else cs(t,this,ls(this,e));return this.init(1)}}sync(t,e){if(Y(t)||t&&Y(t.pause))return this;t.pause();const s=+(t.effect?t.effect.getTiming().duration:t.duration);return this.add(t,{currentTime:[0,s],duration:s,ease:"linear"},e)}set(t,e,s){return Y(e)?this:(e.duration=d,e.composition=r.replace,this.add(t,e,s))}call(t,e){return Y(t)||t&&!z(t)?this:this.add({duration:0,onComplete:()=>t(this)},e)}label(t,e){return Y(t)||t&&!I(t)||(this.labels[t]=ls(this,e)),this}remove(t,e){return is(t,this,e),this}stretch(t){const e=this.duration;if(e===gt(t))return this;const s=t/e,i=this.labels;vt(this,(t=>t.stretch(t.duration*s)));for(let t in i)i[t]*=s;return super.stretch(t)}refresh(){return vt(this,(t=>{t.refresh&&t.refresh()})),this}revert(){return super.revert(),vt(this,(t=>t.revert),!0),Ce(this)}then(t){return super.then(t)}}class us{constructor(t,e){L.current&&L.current.register(this);const s=()=>{if(this.callbacks.completed)return;let t=!0;for(let e in this.animations)if(!this.animations[e].paused&&t){t=!1;break}t&&this.callbacks.complete()},i={onBegin:()=>{this.callbacks.completed&&this.callbacks.reset(),this.callbacks.play()},onComplete:s,onPause:s},n={v:1,autoplay:!1},o={};if(this.targets=[],this.animations={},this.callbacks=null,!Y(t)&&!Y(e)){for(let t in e){const s=e[t];q(t)?o[t]=s:F(t,"on")?n[t]=s:i[t]=s}this.callbacks=new Re({v:0},n);for(let e in o){const s=o[e],n=R(s);let a={},h="+=0";if(n){const t=s.unit;I(t)&&(h+=t)}else a.duration=s;a[e]=n?_t({to:h},s):h;const l=_t(i,a);l.composition=r.replace,l.autoplay=!1;const c=this.animations[e]=new Re(t,l,null,0,!1).init();this.targets.length||this.targets.push(...c.targets),this[e]=(t,e,s)=>{const i=c._head;if(Y(t)&&i){const t=i._numbers;return t&&t.length?t:i._modifier(i._number)}return vt(c,(e=>{if(P(t))for(let s=0,i=t.length;s<i;s++)Y(e._numbers[s])||(e._fromNumbers[s]=e._modifier(e._numbers[s]),e._toNumbers[s]=t[s]);else e._fromNumber=e._modifier(e._number),e._toNumber=t;Y(s)||(e._ease=Te(s)),e._currentTime=0})),Y(e)||c.stretch(e),c.reset(1).resume(),this}}}}revert(){for(let t in this.animations)this[t]=_,this.animations[t].revert();return this.animations={},this.targets.length=0,this.callbacks&&this.callbacks.revert(),this}}const ps=10*p;class ms{constructor(t={}){this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/p,this.maxIterations=this.maxDuration/this.timeStep/p,this.m=ht(Xt(t.mass,1),0,ps),this.s=ht(Xt(t.stiffness,100),1,ps),this.d=ht(Xt(t.damping,10),.1,ps),this.v=ht(Xt(t.velocity,0),-1e4,ps),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.solverDuration=0,this.duration=0,this.compute(),this.ease=t=>0===t||1===t?t:this.solve(t*this.solverDuration)}solve(t){const{zeta:e,w0:s,wd:i,b:r}=this;let n=t;return n=e<1?tt(-n*e*s)*(1*J(i*n)+r*Z(i*n)):(1+r*n)*tt(-n*s),1-n}compute(){const{maxRestSteps:t,maxIterations:e,restThreshold:s,timeStep:i,m:r,d:n,s:o,v:a}=this,h=this.w0=ht(G(o/r),d,p),l=this.zeta=n/(2*G(o*r)),c=this.wd=l<1?h*G(1-l*l):0;this.b=l<1?(l*h-a)/c:-a+h;let u=0,m=0,f=0;for(;m<t&&f<e;)K(1-this.solve(u))<s?m++:m=0,this.solverDuration=u,u+=i,f++;this.duration=ct(this.solverDuration*p,0)*D.timeScale}get mass(){return this.m}set mass(t){this.m=ht(Xt(t,1),0,ps),this.compute()}get stiffness(){return this.s}set stiffness(t){this.s=ht(Xt(t,100),1,ps),this.compute()}get damping(){return this.d}set damping(t){this.d=ht(Xt(t,10),.1,ps),this.compute()}get velocity(){return this.v}set velocity(t){this.v=ht(Xt(t,0),-1e4,ps),this.compute()}}const fs=t=>new ms(t),gs=t=>{t.cancelable&&t.preventDefault()};class ys{constructor(t){this.el=t,this.zIndex=0,this.parentElement=null,this.classList={add:_,remove:_}}get x(){return this.el.x||0}set x(t){this.el.x=t}get y(){return this.el.y||0}set y(t){this.el.y=t}get width(){return this.el.width||0}set width(t){this.el.width=t}get height(){return this.el.height||0}set height(t){this.el.height=t}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class _s{constructor(t){this.$el=t,this.inlineTransforms=[],this.point=new DOMPoint,this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(t,e){return this.point.x=t,this.point.y=e,this.point.matrixTransform(this.inversedMatrix)}traverseUp(t){let e=this.$el.parentElement,s=0;for(;e&&e!==i;)t(e,s),e=e.parentElement,s++}getMatrix(){const t=new DOMMatrix;return this.traverseUp((e=>{const s=getComputedStyle(e).transform;if(s){const e=new DOMMatrix(s);t.preMultiplySelf(e)}})),t}remove(){this.traverseUp(((t,e)=>{this.inlineTransforms[e]=t.style.transform,t.style.transform="none"}))}revert(){this.traverseUp(((t,e)=>{const s=this.inlineTransforms[e];""===s?t.style.removeProperty("transform"):t.style.transform=s}))}}const vs=(t,e)=>t&&z(t)?t(e):t;let bs=0;class Ts{constructor(t,e={}){if(!t)return;L.current&&L.current.register(this);const r=e.x,n=e.y,o=e.trigger,a=e.modifier,h=e.releaseEase,l=h&&Te(h),c=!Y(h)&&!Y(h.ease),d=R(r)&&!Y(r.mapTo)?r.mapTo:"translateX",p=R(n)&&!Y(n.mapTo)?n.mapTo:"translateY",m=vs(e.container,this);this.containerArray=P(m)?m:null,this.$container=m&&!this.containerArray?Ft(m)[0]:i.body,this.useWin=this.$container===i.body,this.$scrollContainer=this.useWin?s:this.$container,this.$target=R(t)?new ys(t):Ft(t)[0],this.$trigger=Ft(o||t)[0],this.fixed="fixed"===ts(this.$target,"position"),this.isFinePointer=!0,this.containerPadding=[0,0,0,0],this.containerFriction=0,this.releaseContainerFriction=0,this.snapX=0,this.snapY=0,this.scrollSpeed=0,this.scrollThreshold=0,this.dragSpeed=0,this.maxVelocity=0,this.minVelocity=0,this.velocityMultiplier=0,this.cursor=!1,this.releaseXSpring=c?h:fs({mass:Xt(e.releaseMass,1),stiffness:Xt(e.releaseStiffness,80),damping:Xt(e.releaseDamping,20)}),this.releaseYSpring=c?h:fs({mass:Xt(e.releaseMass,1),stiffness:Xt(e.releaseStiffness,80),damping:Xt(e.releaseDamping,20)}),this.releaseEase=l||ve.outQuint,this.hasReleaseSpring=c,this.onGrab=e.onGrab||_,this.onDrag=e.onDrag||_,this.onRelease=e.onRelease||_,this.onUpdate=e.onUpdate||_,this.onSettle=e.onSettle||_,this.onSnap=e.onSnap||_,this.onResize=e.onResize||_,this.onAfterResize=e.onAfterResize||_,this.disabled=[0,0];const f={};if(a&&(f.modifier=a),Y(r)||!0===r)f[d]=0;else if(R(r)){const t=r,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[d]=e}else!1===r&&(f[d]=0,this.disabled[0]=1);if(Y(n)||!0===n)f[p]=0;else if(R(n)){const t=n,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[p]=e}else!1===n&&(f[p]=0,this.disabled[1]=1);this.animate=new us(this.$target,f),this.xProp=d,this.yProp=p,this.destX=0,this.destY=0,this.deltaX=0,this.deltaY=0,this.scroll={x:0,y:0},this.coords=[this.x,this.y,0,0],this.snapped=[0,0],this.pointer=[0,0,0,0,0,0,0,0],this.scrollView=[0,0],this.dragArea=[0,0,0,0],this.containerBounds=[-1e12,u,u,-1e12],this.scrollBounds=[0,0,0,0],this.targetBounds=[0,0,0,0],this.window=[0,0],this.velocityStack=[0,0,0],this.velocityStackIndex=0,this.velocityTime=O(),this.velocity=0,this.angle=0,this.cursorStyles=null,this.triggerStyles=null,this.bodyStyles=null,this.targetStyles=null,this.touchActionStyles=null,this.transforms=new _s(this.$target),this.overshootCoords={x:0,y:0},this.overshootTicker=new oe({autoplay:!1,onUpdate:()=>{this.updated=!0,this.manual=!0,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,1),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=!1,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,0),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init(),this.updateTicker=new oe({autoplay:!1,onUpdate:()=>this.update()},null,0).init(),this.contained=!Y(m),this.manual=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.enabled=!1,this.initialized=!1,this.activeProp=this.disabled[1]?d:p,this.animate.callbacks.onRender=()=>{const t=this.updated,e=!(this.grabbed&&t)&&this.released,s=this.x,i=this.y,r=s-this.coords[2],n=i-this.coords[3];this.deltaX=r,this.deltaY=n,this.coords[2]=s,this.coords[3]=i,t&&(r||n)&&this.onUpdate(this),e?(this.computeVelocity(r,n),this.angle=nt(n,r)):this.updated=!1},this.animate.callbacks.onComplete=()=>{!this.grabbed&&this.released&&(this.released=!1),this.manual||(this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.onSettle(this))},this.resizeTicker=new oe({autoplay:!1,duration:150*D.timeScale,onComplete:()=>{this.onResize(this),this.refresh(),this.onAfterResize(this)}}).init(),this.parameters=e,this.resizeObserver=new ResizeObserver((()=>{this.initialized?this.resizeTicker.restart():this.initialized=!0})),this.enable(),this.refresh(),this.resizeObserver.observe(this.$container),R(t)||this.resizeObserver.observe(this.$target)}computeVelocity(t,e){const s=this.velocityTime,i=O(),r=i-s;if(r<17)return this.velocity;this.velocityTime=i;const n=this.velocityStack,o=this.velocityMultiplier,a=this.minVelocity,h=this.maxVelocity,l=this.velocityStackIndex;n[l]=ct(ht(G(t*t+e*e)/r*o,a,h),5);const c=rt(n[0],n[1],n[2]);return this.velocity=c,this.velocityStackIndex=(l+1)%3,c}setX(t,e=!1){if(this.disabled[0])return;const s=ct(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destX=s,this.snapped[0]=dt(s,this.snapX),this.animate[this.xProp](s,0),this.manual=!1,this}setY(t,e=!1){if(this.disabled[1])return;const s=ct(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destY=s,this.snapped[1]=dt(s,this.snapY),this.animate[this.yProp](s,0),this.manual=!1,this}get x(){return ct(this.animate[this.xProp](),D.precision)}set x(t){this.setX(t,!1)}get y(){return ct(this.animate[this.yProp](),D.precision)}set y(t){this.setY(t,!1)}get progressX(){return rs(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(t){this.setX(rs(t,0,1,this.containerBounds[3],this.containerBounds[1]),!1)}get progressY(){return rs(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(t){this.setY(rs(t,0,1,this.containerBounds[0],this.containerBounds[2]),!1)}updateScrollCoords(){const t=ct(this.useWin?s.scrollX:this.$container.scrollLeft,0),e=ct(this.useWin?s.scrollY:this.$container.scrollTop,0),[i,r,n,o]=this.containerPadding,a=this.scrollThreshold;this.scroll.x=t,this.scroll.y=e,this.scrollBounds[0]=e-this.targetBounds[0]+i-a,this.scrollBounds[1]=t-this.targetBounds[1]-r+a,this.scrollBounds[2]=e-this.targetBounds[2]-n+a,this.scrollBounds[3]=t-this.targetBounds[3]+o-a}updateBoundingValues(){const t=this.$container;if(!t)return;const e=this.x,r=this.y,n=this.coords[2],o=this.coords[3];this.coords[2]=0,this.coords[3]=0,this.setX(0,!0),this.setY(0,!0),this.transforms.remove();const a=this.window[0]=s.innerWidth,h=this.window[1]=s.innerHeight,l=this.useWin,c=t.scrollWidth,d=t.scrollHeight,u=this.fixed,p=t.getBoundingClientRect(),[m,f,g,y]=this.containerPadding;this.dragArea[0]=l?0:p.left,this.dragArea[1]=l?0:p.top,this.scrollView[0]=l?ht(c,a,c):c,this.scrollView[1]=l?ht(d,h,d):d,this.updateScrollCoords();const{width:_,height:v,left:b,top:T,right:w,bottom:S}=t.getBoundingClientRect();this.dragArea[2]=ct(l?ht(_,a,a):_,0),this.dragArea[3]=ct(l?ht(v,h,h):v,0);const x=ts(t,"overflow"),k="visible"===x,$="hidden"===x;if(this.canScroll=!u&&this.contained&&(t===i.body&&k||!$&&!k)&&(c>this.dragArea[2]+y-f||d>this.dragArea[3]+m-g)&&(!this.containerArray||this.containerArray&&!P(this.containerArray)),this.contained){const e=this.scroll.x,s=this.scroll.y,i=this.canScroll,r=this.$target.getBoundingClientRect(),n=i?l?0:t.scrollLeft:0,o=i?l?0:t.scrollTop:0,c=i?this.scrollView[0]-n-_:0,d=i?this.scrollView[1]-o-v:0;this.targetBounds[0]=ct(r.top+s-(l?0:T),0),this.targetBounds[1]=ct(r.right+e-(l?a:w),0),this.targetBounds[2]=ct(r.bottom+s-(l?h:S),0),this.targetBounds[3]=ct(r.left+e-(l?0:b),0),this.containerArray?(this.containerBounds[0]=this.containerArray[0]+m,this.containerBounds[1]=this.containerArray[1]-f,this.containerBounds[2]=this.containerArray[2]-g,this.containerBounds[3]=this.containerArray[3]+y):(this.containerBounds[0]=-ct(r.top-(u?ht(T,0,h):T)+o-m,0),this.containerBounds[1]=-ct(r.right-(u?ht(w,0,a):w)-c+f,0),this.containerBounds[2]=-ct(r.bottom-(u?ht(S,0,h):S)-d+g,0),this.containerBounds[3]=-ct(r.left-(u?ht(b,0,a):b)+n-y,0))}this.transforms.revert(),this.coords[2]=n,this.coords[3]=o,this.setX(e,!0),this.setY(r,!0)}isOutOfBounds(t,e,s){if(!this.contained)return 0;const[i,r,n,o]=t,[a,h]=this.disabled,l=!a&&e<o||!a&&e>r,c=!h&&s<i||!h&&s>n;return l&&!c?1:!l&&c?2:l&&c?3:0}refresh(){const t=this.parameters,e=t.x,r=t.y,n=vs(t.container,this),o=vs(t.containerPadding,this)||0,a=P(o)?o:[o,o,o,o],h=this.x,l=this.y,c=vs(t.cursor,this),d={onHover:"grab",onGrab:"grabbing"};if(c){const{onHover:t,onGrab:e}=c;t&&(d.onHover=t),e&&(d.onGrab=e)}this.containerArray=P(n)?n:null,this.$container=n&&!this.containerArray?Ft(n)[0]:i.body,this.useWin=this.$container===i.body,this.$scrollContainer=this.useWin?s:this.$container,this.isFinePointer=matchMedia("(pointer:fine)").matches,this.containerPadding=Xt(a,[0,0,0,0]),this.containerFriction=ht(Xt(vs(t.containerFriction,this),.8),0,1),this.releaseContainerFriction=ht(Xt(vs(t.releaseContainerFriction,this),this.containerFriction),0,1),this.snapX=vs(R(e)&&!Y(e.snap)?e.snap:t.snap,this),this.snapY=vs(R(r)&&!Y(r.snap)?r.snap:t.snap,this),this.scrollSpeed=Xt(vs(t.scrollSpeed,this),1.5),this.scrollThreshold=Xt(vs(t.scrollThreshold,this),20),this.dragSpeed=Xt(vs(t.dragSpeed,this),1),this.minVelocity=Xt(vs(t.minVelocity,this),0),this.maxVelocity=Xt(vs(t.maxVelocity,this),50),this.velocityMultiplier=Xt(vs(t.velocityMultiplier,this),1),this.cursor=!1!==c&&d,this.updateBoundingValues();const[u,p,m,f]=this.containerBounds;this.setX(ht(h,f,p),!0),this.setY(ht(l,u,m),!0)}update(){if(this.updateScrollCoords(),this.canScroll){const[t,e,s,i]=this.containerPadding,[r,n]=this.scrollView,o=this.dragArea[2],a=this.dragArea[3],h=this.scroll.x,l=this.scroll.y,c=this.$container.scrollWidth,d=this.$container.scrollHeight,u=this.useWin?ht(c,this.window[0],c):c,p=this.useWin?ht(d,this.window[1],d):d,m=r-u,f=n-p;this.dragged&&m>0&&(this.coords[0]-=m,this.scrollView[0]=u),this.dragged&&f>0&&(this.coords[1]-=f,this.scrollView[1]=p);const g=10*this.scrollSpeed,y=this.scrollThreshold,[_,v]=this.coords,[b,T,w,S]=this.scrollBounds,x=ct(ht((v-b+t)/y,-1,0)*g,0),k=ct(ht((_-T-e)/y,0,1)*g,0),$=ct(ht((v-w-s)/y,0,1)*g,0),C=ct(ht((_-S+i)/y,-1,0)*g,0);if(x||$||C||k){const[t,e]=this.disabled;let s=h,i=l;t||(s=ct(ht(h+(C||k),0,r-o),0),this.coords[0]-=h-s),e||(i=ct(ht(l+(x||$),0,n-a),0),this.coords[1]-=l-i),this.useWin?this.$scrollContainer.scrollBy(-(h-s),-(l-i)):this.$scrollContainer.scrollTo(s,i)}}const[t,e,s,i]=this.containerBounds,[r,n,o,a,h,l]=this.pointer;this.coords[0]+=(r-h)*this.dragSpeed,this.coords[1]+=(n-l)*this.dragSpeed,this.pointer[4]=r,this.pointer[5]=n;const[c,d]=this.coords,[u,p]=this.snapped,m=(1-this.containerFriction)*this.dragSpeed;this.setX(c>e?e+(c-e)*m:c<i?i+(c-i)*m:c,!1),this.setY(d>s?s+(d-s)*m:d<t?t+(d-t)*m:d,!1),this.computeVelocity(r-h,n-l),this.angle=nt(n-a,r-o);const[f,g]=this.snapped;(f!==u&&this.snapX||g!==p&&this.snapY)&&this.onSnap(this)}stop(){this.updateTicker.pause(),this.overshootTicker.pause();for(let t in this.animate.animations)this.animate.animations[t].pause();return is(this,null,"x"),is(this,null,"y"),is(this,null,"progressX"),is(this,null,"progressY"),is(this.scroll),is(this.overshootCoords),this}scrollInView(t,e=0,s=ve.inOutQuad){this.updateScrollCoords();const i=this.destX,r=this.destY,n=this.scroll,o=this.scrollBounds,a=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(o,i,r)){const[h,l,c,d]=o,p=ct(ht(r-h,-1e12,0),0),m=ct(ht(i-l,0,u),0),f=ct(ht(r-c,0,u),0),g=ct(ht(i-d,-1e12,0),0);new Re(n,{x:ct(n.x+(g?g-e:m?m+e:0),0),y:ct(n.y+(p?p-e:f?f+e:0),0),duration:Y(t)?350*D.timeScale:t,ease:s,onUpdate:()=>{this.canScroll=!1,this.$scrollContainer.scrollTo(n.x,n.y)}}).init().then((()=>{this.canScroll=a}))}return this}handleHover(){this.isFinePointer&&this.cursor&&!this.cursorStyles&&(this.cursorStyles=es(this.$trigger,{cursor:this.cursor.onHover}))}animateInView(t,e=0,s=ve.inOutQuad){this.stop(),this.updateBoundingValues();const i=this.x,r=this.y,[n,o,a,h]=this.containerPadding,l=this.scroll.y-this.targetBounds[0]+n+e,c=this.scroll.x-this.targetBounds[1]-o-e,d=this.scroll.y-this.targetBounds[2]-a-e,u=this.scroll.x-this.targetBounds[3]+h+e,p=this.isOutOfBounds([l,c,d,u],i,r);if(p){const[e,n]=this.disabled,o=ht(dt(i,this.snapX),u,c),a=ht(dt(r,this.snapY),l,d),h=Y(t)?350*D.timeScale:t;e||1!==p&&3!==p||this.animate[this.xProp](o,h,s),n||2!==p&&3!==p||this.animate[this.yProp](a,h,s)}return this}handleDown(t){const e=t.target;if(this.grabbed||"range"===e.type)return;t.stopPropagation(),this.grabbed=!0,this.released=!1,this.stop(),this.updateBoundingValues();const s=t.changedTouches,r=s?s[0].clientX:t.clientX,n=s?s[0].clientY:t.clientY,{x:o,y:a}=this.transforms.normalizePoint(r,n),[h,l,c,d]=this.containerBounds,u=(1-this.containerFriction)*this.dragSpeed,p=this.x,m=this.y;this.coords[0]=this.coords[2]=u?p>l?l+(p-l)/u:p<d?d+(p-d)/u:p:p,this.coords[1]=this.coords[3]=u?m>c?c+(m-c)/u:m<h?h+(m-h)/u:m:m,this.pointer[0]=o,this.pointer[1]=a,this.pointer[2]=o,this.pointer[3]=a,this.pointer[4]=o,this.pointer[5]=a,this.pointer[6]=o,this.pointer[7]=a,this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null);const f=ts(this.$target,"zIndex",!1);bs=(f>bs?f:bs)+1,this.targetStyles=es(this.$target,{zIndex:bs}),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.isFinePointer&&this.cursor&&(this.bodyStyles=es(i.body,{cursor:this.cursor.onGrab})),this.scrollInView(100,0,ve.out(3)),this.onGrab(this),i.addEventListener("touchmove",this),i.addEventListener("touchend",this),i.addEventListener("touchcancel",this),i.addEventListener("mousemove",this),i.addEventListener("mouseup",this),i.addEventListener("selectstart",this)}handleMove(t){if(!this.grabbed)return;const e=t.changedTouches,s=e?e[0].clientX:t.clientX,i=e?e[0].clientY:t.clientY,{x:r,y:n}=this.transforms.normalizePoint(s,i),o=r-this.pointer[6],a=n-this.pointer[7];let h=t.target,l=!1,c=!1,d=!1;for(;e&&h&&h!==this.$trigger;){const t=ts(h,"overflow-y");if("hidden"!==t&&"visible"!==t){const{scrollTop:t,scrollHeight:e,clientHeight:s}=h;if(e>s){d=!0,l=t<=3,c=t>=e-s-3;break}}h=h.parentNode}d&&(!l&&!c||l&&a<0||c&&a>0)?(this.pointer[0]=r,this.pointer[1]=n,this.pointer[2]=r,this.pointer[3]=n,this.pointer[4]=r,this.pointer[5]=n,this.pointer[6]=r,this.pointer[7]=n):(gs(t),this.triggerStyles||(this.triggerStyles=es(this.$trigger,{pointerEvents:"none"})),this.$trigger.addEventListener("touchstart",gs,{passive:!1}),this.$trigger.addEventListener("touchmove",gs,{passive:!1}),this.$trigger.addEventListener("touchend",gs),(!this.disabled[0]&&K(o)>3||!this.disabled[1]&&K(a)>3)&&(this.updateTicker.resume(),this.pointer[2]=this.pointer[0],this.pointer[3]=this.pointer[1],this.pointer[0]=r,this.pointer[1]=n,this.dragged=!0,this.released=!1,this.onDrag(this)))}handleUp(){if(!this.grabbed)return;this.updateTicker.pause(),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null);const[t,e]=this.disabled,[s,n,o,a,h,l]=this.pointer,[c,d,u,p]=this.containerBounds,[m,f]=this.snapped,g=this.releaseXSpring,y=this.releaseYSpring,_=this.releaseEase,v=this.hasReleaseSpring,b=this.overshootCoords,T=this.x,w=this.y,S=this.computeVelocity(s-h,n-l),x=this.angle=nt(n-a,s-o),k=150*S,$=(1-this.releaseContainerFriction)*this.dragSpeed,C=T+J(x)*k,E=w+Z(x)*k,B=C>d?d+(C-d)*$:C<p?p+(C-p)*$:C,L=E>u?u+(E-u)*$:E<c?c+(E-c)*$:E,A=this.destX=ht(ct(dt(B,this.snapX),5),p,d),N=this.destY=ht(ct(dt(L,this.snapY),5),c,u),F=this.isOutOfBounds(this.containerBounds,C,E);let O=0,P=0,R=_,M=_,I=0;if(b.x=T,b.y=w,!t){const t=A===d?T>d?-1:1:T<p?-1:1,s=ct(T-A,0);g.velocity=e&&v?s?k*t/K(s):0:S;const{ease:i,duration:r,restDuration:n}=g;O=T===A?0:v?r:r-n*D.timeScale,v&&(R=i),O>I&&(I=O)}if(!e){const e=N===u?w>u?-1:1:w<c?-1:1,s=ct(w-N,0);y.velocity=t&&v?s?k*e/K(s):0:S;const{ease:i,duration:r,restDuration:n}=y;P=w===N?0:v?r:r-n*D.timeScale,v&&(M=i),P>I&&(I=P)}if(!v&&F&&$&&(O||P)){const t=r.blend;new Re(b,{x:{to:B,duration:.65*O},y:{to:L,duration:.65*P},ease:_,composition:t}).init(),new Re(b,{x:{to:A,duration:O},y:{to:N,duration:P},ease:_,composition:t}).init(),this.overshootTicker.stretch(rt(O,P)).restart()}else t||this.animate[this.xProp](A,O,R),e||this.animate[this.yProp](N,P,M);this.scrollInView(I,this.scrollThreshold,_);let z=!1;A!==m&&(this.snapped[0]=A,this.snapX&&(z=!0)),N!==f&&this.snapY&&(this.snapped[1]=N,this.snapY&&(z=!0)),z&&this.onSnap(this),this.grabbed=!1,this.dragged=!1,this.updated=!0,this.released=!0,this.onRelease(this),this.$trigger.removeEventListener("touchstart",gs),this.$trigger.removeEventListener("touchmove",gs),this.$trigger.removeEventListener("touchend",gs),i.removeEventListener("touchmove",this),i.removeEventListener("touchend",this),i.removeEventListener("touchcancel",this),i.removeEventListener("mousemove",this),i.removeEventListener("mouseup",this),i.removeEventListener("selectstart",this)}reset(){return this.stop(),this.resizeTicker.pause(),this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.setX(0,!0),this.setY(0,!0),this.coords[0]=0,this.coords[1]=0,this.pointer[0]=0,this.pointer[1]=0,this.pointer[2]=0,this.pointer[3]=0,this.pointer[4]=0,this.pointer[5]=0,this.pointer[6]=0,this.pointer[7]=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this}enable(){return this.enabled||(this.enabled=!0,this.$target.classList.remove("is-disabled"),this.touchActionStyles=es(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"}),this.$trigger.addEventListener("touchstart",this,{passive:!0}),this.$trigger.addEventListener("mousedown",this,{passive:!0}),this.$trigger.addEventListener("mouseenter",this)),this}disable(){return this.enabled=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.touchActionStyles.revert(),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null),this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null),this.$target.classList.add("is-disabled"),this.$trigger.removeEventListener("touchstart",this),this.$trigger.removeEventListener("mousedown",this),this.$trigger.removeEventListener("mouseenter",this),i.removeEventListener("touchmove",this),i.removeEventListener("touchend",this),i.removeEventListener("touchcancel",this),i.removeEventListener("mousemove",this),i.removeEventListener("mouseup",this),i.removeEventListener("selectstart",this),this}revert(){return this.reset(),this.disable(),this.$target.classList.remove("is-disabled"),this.updateTicker.revert(),this.overshootTicker.revert(),this.resizeTicker.revert(),this.animate.revert(),this.resizeObserver.disconnect(),this}handleEvent(t){switch(t.type){case"mousedown":case"touchstart":this.handleDown(t);break;case"mousemove":case"touchmove":this.handleMove(t);break;case"mouseup":case"touchend":case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":gs(t)}}}class ws{constructor(t={}){L.current&&L.current.register(this);const e=t.root;let r=i;e&&(r=e.current||e.nativeElement||Ft(e)[0]||i);const n=t.defaults,o=D.defaults,a=t.mediaQueries;if(this.defaults=n?_t(n,o):o,this.root=r,this.constructors=[],this.revertConstructors=[],this.revertibles=[],this.constructorsOnce=[],this.revertConstructorsOnce=[],this.revertiblesOnce=[],this.once=!1,this.onceIndex=0,this.methods={},this.matches={},this.mediaQueryLists={},this.data={},a)for(let t in a){const e=s.matchMedia(a[t]);this.mediaQueryLists[t]=e,e.addEventListener("change",this)}}register(t){(this.once?this.revertiblesOnce:this.revertibles).push(t)}execute(t){let e=L.current,s=L.root,i=D.defaults;L.current=this,L.root=this.root,D.defaults=this.defaults;const r=this.mediaQueryLists;for(let t in r)this.matches[t]=r[t].matches;const n=t(this);return L.current=e,L.root=s,D.defaults=i,n}refresh(){return this.onceIndex=0,this.execute((()=>{let t=this.revertibles.length,e=this.revertConstructors.length;for(;t--;)this.revertibles[t].revert();for(;e--;)this.revertConstructors[e](this);this.revertibles.length=0,this.revertConstructors.length=0,this.constructors.forEach((t=>{const e=t(this);z(e)&&this.revertConstructors.push(e)}))})),this}add(t,e){if(this.once=!1,z(t)){const e=t;this.constructors.push(e),this.execute((()=>{const t=e(this);z(t)&&this.revertConstructors.push(t)}))}else this.methods[t]=(...t)=>this.execute((()=>e(...t)));return this}addOnce(t){if(this.once=!0,z(t)){const e=this.onceIndex++;if(this.constructorsOnce[e])return this;const s=t;this.constructorsOnce[e]=s,this.execute((()=>{const t=s(this);z(t)&&this.revertConstructorsOnce.push(t)}))}return this}keepTime(t){this.once=!0;const e=this.onceIndex++,s=this.constructorsOnce[e];if(z(s))return s(this);const i=wt(t);let r;return this.constructorsOnce[e]=i,this.execute((()=>{r=i(this)})),r}handleEvent(t){"change"===t.type&&this.refresh()}revert(){const t=this.revertibles,e=this.revertConstructors,s=this.revertiblesOnce,i=this.revertConstructorsOnce,r=this.mediaQueryLists;let n=t.length,o=e.length,a=s.length,h=i.length;for(;n--;)t[n].revert();for(;o--;)e[o](this);for(;a--;)s[a].revert();for(;h--;)i[h](this);for(let t in r)r[t].removeEventListener("change",this);t.length=0,e.length=0,this.constructors.length=0,s.length=0,i.length=0,this.constructorsOnce.length=0,this.onceIndex=0,this.matches={},this.methods={},this.mediaQueryLists={},this.data={}}}const Ss=(t,e)=>t&&z(t)?t(e):t,xs=new Map;class ks{constructor(t){this.element=t,this.useWin=this.element===i.body,this.winWidth=0,this.winHeight=0,this.width=0,this.height=0,this.left=0,this.top=0,this.zIndex=0,this.scrollX=0,this.scrollY=0,this.prevScrollX=0,this.prevScrollY=0,this.scrollWidth=0,this.scrollHeight=0,this.velocity=0,this.backwardX=!1,this.backwardY=!1,this.scrollTicker=new oe({autoplay:!1,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const t=this.backwardX||this.backwardY;vt(this,(t=>t.handleScroll()),t)},onComplete:()=>this.dataTimer.pause()}).init(),this.dataTimer=new oe({autoplay:!1,frameRate:30,onUpdate:t=>{const e=t.deltaTime,s=this.prevScrollX,i=this.prevScrollY,r=this.scrollX,n=this.scrollY,o=s-r,a=i-n;this.prevScrollX=r,this.prevScrollY=n,o&&(this.backwardX=s>r),a&&(this.backwardY=i>n),this.velocity=ct(e>0?Math.sqrt(o*o+a*a)/e:0,5)}}).init(),this.resizeTicker=new oe({autoplay:!1,duration:250*D.timeScale,onComplete:()=>{this.updateWindowBounds(),this.refreshScrollObservers(),this.handleScroll()}}).init(),this.wakeTicker=new oe({autoplay:!1,duration:500*D.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init(),this._head=null,this._tail=null,this.updateScrollCoords(),this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll(),this.resizeObserver=new ResizeObserver((()=>this.resizeTicker.restart())),this.resizeObserver.observe(this.element),(this.useWin?s:this.element).addEventListener("scroll",this,!1)}updateScrollCoords(){const t=this.useWin,e=this.element;this.scrollX=ct(t?s.scrollX:e.scrollLeft,0),this.scrollY=ct(t?s.scrollY:e.scrollTop,0)}updateWindowBounds(){this.winWidth=s.innerWidth,this.winHeight=(()=>{const t=i.createElement("div");i.body.appendChild(t),t.style.height="100lvh";const e=t.offsetHeight;return i.body.removeChild(t),e})()}updateBounds(){const t=getComputedStyle(this.element),e=this.element;let s,i;if(this.scrollWidth=e.scrollWidth+parseFloat(t.marginLeft)+parseFloat(t.marginRight),this.scrollHeight=e.scrollHeight+parseFloat(t.marginTop)+parseFloat(t.marginBottom),this.updateWindowBounds(),this.useWin)s=this.winWidth,i=this.winHeight;else{const t=e.getBoundingClientRect();s=e.clientWidth,i=e.clientHeight,this.top=t.top,this.left=t.left}this.width=s,this.height=i}refreshScrollObservers(){vt(this,(t=>{t._debug&&t.removeDebug()})),this.updateBounds(),vt(this,(t=>{t.refresh(),t._debug&&t.debug()}))}refresh(){this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll()}handleScroll(){this.updateScrollCoords(),this.wakeTicker.restart()}handleEvent(t){"scroll"===t.type&&this.handleScroll()}revert(){this.scrollTicker.cancel(),this.dataTimer.cancel(),this.resizeTicker.cancel(),this.wakeTicker.cancel(),this.resizeObserver.disconnect(),(this.useWin?s:this.element).removeEventListener("scroll",this),xs.delete(this.element)}}const $s=(t,e,s,i,r)=>{const n="min"===e,o="max"===e,a="top"===e||"left"===e||"start"===e||n?0:"bottom"===e||"right"===e||"end"===e||o?"100%":"center"===e?"50%":e,{n:h,u:l}=Qt(a,Gt);let c=h;return"%"===l?c=h/100*s:l&&(c=$e(t,Gt,"px",!0).n),o&&i<0&&(c+=i),n&&r>0&&(c+=r),c},Cs=(t,e,s,i,r)=>{let n;if(I(e)){const o=E.exec(e);if(o){const a=o[0],h=a[0],l=e.split(a),c="min"===l[0],d="max"===l[0],u=$s(t,l[0],s,i,r),p=$s(t,l[1],s,i,r);if(c){const e=qt($s(t,"min",s),p,h);n=e<u?u:e}else if(d){const e=qt($s(t,"max",s),p,h);n=e>u?u:e}else n=qt(u,p,h)}else n=$s(t,e,s,i,r)}else n=e;return ct(n,0)},Es=t=>{let e;const s=t.targets;for(let t=0,i=s.length;t<i;t++){const i=s[t];if(i[o]){e=i;break}}return e};let Bs=0;const Ls=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class Ds{constructor(t={}){L.current&&L.current.register(this);const e=Xt(t.sync,"play pause"),s=e?Te(e):null,r=e&&("linear"===e||e===ae),n=e&&!(s===ae&&!r),o=e&&(M(e)||!0===e||r),a=e&&I(e)&&!n&&!o,h=a?e.split(" ").map((t=>()=>{const e=this.linked;return e&&e[t]?e[t]():null})):null,l=a&&h.length>2;this.index=Bs++,this.id=Y(t.id)?this.index:t.id,this.container=(t=>{const e=t&&Ft(t)[0]||i.body;let s=xs.get(e);return s||(s=new ks(e),xs.set(e,s)),s})(t.container),this.target=null,this.linked=null,this.repeat=null,this.horizontal=null,this.enter=null,this.leave=null,this.sync=n||o||!!h,this.syncEase=n?s:null,this.syncSmooth=o?!0===e||r?1:e:null,this.onSyncEnter=h&&!l&&h[0]?h[0]:_,this.onSyncLeave=h&&!l&&h[1]?h[1]:_,this.onSyncEnterForward=h&&l&&h[0]?h[0]:_,this.onSyncLeaveForward=h&&l&&h[1]?h[1]:_,this.onSyncEnterBackward=h&&l&&h[2]?h[2]:_,this.onSyncLeaveBackward=h&&l&&h[3]?h[3]:_,this.onEnter=t.onEnter||_,this.onLeave=t.onLeave||_,this.onEnterForward=t.onEnterForward||_,this.onLeaveForward=t.onLeaveForward||_,this.onEnterBackward=t.onEnterBackward||_,this.onLeaveBackward=t.onLeaveBackward||_,this.onUpdate=t.onUpdate||_,this.onSyncComplete=t.onSyncComplete||_,this.reverted=!1,this.completed=!1,this.began=!1,this.isInView=!1,this.forceEnter=!1,this.hasEntered=!1,this.offset=0,this.offsetStart=0,this.offsetEnd=0,this.distance=0,this.prevProgress=0,this.thresholds=["start","end","end","start"],this.coords=[0,0,0,0],this.debugStyles=null,this.$debug=null,this._params=t,this._debug=Xt(t.debug,!1),this._next=null,this._prev=null,Tt(this.container,this),Ke((()=>{if(!this.reverted){if(!this.target){const e=Ft(t.target)[0];this.target=e||i.body,this.refresh()}this._debug&&this.debug()}}))}link(t){if(t&&(t.pause(),this.linked=t,!this._params.target)){let e;Y(t.targets)?vt(t,(t=>{t.targets&&!e&&(e=Es(t))})):e=Es(t),this.target=e||i.body,this.refresh()}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const t=(this.scroll-this.offsetStart)/this.distance;return t===1/0||isNaN(t)?0:ct(ht(t,0,1),6)}refresh(){this.reverted=!1;const t=this._params;return this.repeat=Xt(Ss(t.repeat,this),!0),this.horizontal="x"===Xt(Ss(t.axis,this),"y"),this.enter=Xt(Ss(t.enter,this),"end start"),this.leave=Xt(Ss(t.leave,this),"start end"),this.updateBounds(),this.handleScroll(),this}removeDebug(){return this.$debug&&(this.$debug.parentNode.removeChild(this.$debug),this.$debug=null),this.debugStyles&&(this.debugStyles.revert(),this.$debug=null),this}debug(){this.removeDebug();const t=this.container,e=this.horizontal,s=t.element.querySelector(":scope > .animejs-onscroll-debug"),r=i.createElement("div"),n=i.createElement("div"),o=i.createElement("div"),a=Ls[this.index%Ls.length],h=t.useWin,l=h?t.winWidth:t.width,c=h?t.winHeight:t.height,d=t.scrollWidth,u=t.scrollHeight,p=this.container.width>360?320:260,m=e?0:10,f=e?10:0,g=e?24:p/2,y=e?g:15,_=e?60:g,v=e?_:y,b=e?"repeat-x":"repeat-y",T=t=>e?"0px "+t+"px":t+"px 2px",w=t=>`linear-gradient(${e?90:0}deg, ${t} 2px, transparent 1px)`,S=(t,e,s,i,r)=>`position:${t};left:${e}px;top:${s}px;width:${i}px;height:${r}px;`;r.style.cssText=`${S("absolute",m,f,e?d:p,e?p:u)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${e?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `,n.style.cssText=`${S("sticky",0,0,e?l:g,e?g:c)}`,s||(n.style.cssText+=`background:\n ${w("#FFFF")}${T(g-10)} / 100px 100px ${b},\n ${w("#FFF8")}${T(g-10)} / 10px 10px ${b};\n `),o.style.cssText=`${S("relative",0,0,e?d:g,e?g:u)}`,s||(o.style.cssText+=`background:\n ${w("#FFFF")}${T(0)} / ${e?"100px 10px":"10px 100px"} ${b},\n ${w("#FFF8")}${T(0)} / ${e?"10px 0px":"0px 10px"} ${b};\n `);const x=[" enter: "," leave: "];this.coords.forEach(((t,s)=>{const r=s>1,h=(r?0:this.offset)+t,m=s%2,f=h<v,g=h>(r?e?l:c:e?d:u)-v,b=(r?m&&!f:!m&&!f)||g,T=i.createElement("div"),w=i.createElement("div"),k=e?b?"right":"left":b?"bottom":"top",$=b?(e?_:y)+(r?e?-1:g?0:-2:e?-1:-2):e?1:0;w.innerHTML=`${this.id}${x[m]}${this.thresholds[s]}`,T.style.cssText=`${S("absolute",0,0,_,y)}\n display: flex;\n flex-direction: ${e?"column":"row"};\n justify-content: flex-${r?"start":"end"};\n align-items: flex-${b?"end":"start"};\n border-${k}: 2px solid ${a};\n `,w.style.cssText=`\n overflow: hidden;\n max-width: ${p/2-10}px;\n height: ${y};\n margin-${e?b?"right":"left":b?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${e&&b||!e&&!r?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${m?a:"rgba(0,0,0,.75)"};\n background-color: ${m?"rgba(0,0,0,.65)":a};\n border: 2px solid ${m?a:"transparent"};\n border-${e?b?"top-left":"top-right":b?"top-left":"bottom-left"}-radius: 5px;\n border-${e?b?"bottom-left":"bottom-right":b?"top-right":"bottom-right"}-radius: 5px;\n `,T.appendChild(w);let C=h-$+(e?1:0);T.style[e?"left":"top"]=`${C}px`,(r?n:o).appendChild(T)})),r.appendChild(n),r.appendChild(o),t.element.appendChild(r),s||r.classList.add("animejs-onscroll-debug"),this.$debug=r,"static"===ts(t.element,"position")&&(this.debugStyles=es(t.element,{position:"relative "}))}updateBounds(){let t;this._debug&&this.removeDebug();const e=this.target,s=this.container,r=this.horizontal,n=this.linked;let o,a=e;for(n&&(o=n.currentTime,n.seek(0,!0)),a.parentElement;a&&a!==s.element&&a!==i.body;){const e="sticky"===ts(a,"position")&&es(a,{position:"static"});a=a.parentElement,e&&(t||(t=[]),t.push(e))}const h=e.getBoundingClientRect(),l=r?h.left+s.scrollX-s.left:h.top+s.scrollY-s.top,c=r?h.width:h.height,d=r?s.width:s.height,u=(r?s.scrollWidth:s.scrollHeight)-d,p=this.enter,m=this.leave;let f="start",g="end",y="end",_="start";if(I(p)){const t=p.split(" ");y=t[0],f=t.length>1?t[1]:f}else if(R(p)){const t=p;Y(t.container)||(y=t.container),Y(t.target)||(f=t.target)}else M(p)&&(y=p);if(I(m)){const t=m.split(" ");_=t[0],g=t.length>1?t[1]:g}else if(R(m)){const t=m;Y(t.container)||(_=t.container),Y(t.target)||(g=t.target)}else M(m)&&(_=m);const v=Cs(e,f,c),b=Cs(e,g,c),T=v+l-d,w=b+l-u,S=Cs(e,y,d,T,w),x=Cs(e,_,d,T,w),k=v+l-S,$=b+l-x,C=$-k;this.offset=l,this.offsetStart=k,this.offsetEnd=$,this.distance=C<=0?0:C,this.thresholds=[f,g,y,_],this.coords=[v,b,S,x],t&&t.forEach((t=>t.revert())),n&&n.seek(o,!0),this._debug&&this.debug()}handleScroll(){const t=this.linked,e=this.sync,s=this.syncEase,i=this.syncSmooth,r=t&&(s||i),n=this.horizontal,o=this.container,a=this.scroll,h=a<=this.offsetStart,l=a>=this.offsetEnd,c=!h&&!l,d=a===this.offsetStart||a===this.offsetEnd,u=!this.hasEntered&&d,p=this._debug&&this.$debug;let m=!1,f=!1,g=this.progress;if(h&&this.began&&(this.began=!1),g>0&&!this.began&&(this.began=!0),r){const e=t.progress;if(i&&M(i)){if(i<1){const t=e<g&&1===g?1e-4:e>g&&!g?-1e-4:0;g=ct(ns(e,g,ut(.01,.2,i),!1)+t,6)}}else s&&(g=s(g));m=g!==this.prevProgress,f=1===e,m&&!f&&i&&e&&o.wakeTicker.restart()}if(p){const t=n?o.scrollY:o.scrollX;p.style[n?"top":"left"]=t+10+"px"}(c&&!this.isInView||u&&!this.forceEnter&&!this.hasEntered)&&(c&&(this.isInView=!0),this.forceEnter&&this.hasEntered?c&&(this.forceEnter=!1):(p&&c&&(p.style.zIndex=""+this.container.zIndex++),this.onSyncEnter(this),this.onEnter(this),this.backward?(this.onSyncEnterBackward(this),this.onEnterBackward(this)):(this.onSyncEnterForward(this),this.onEnterForward(this)),this.hasEntered=!0,u&&(this.forceEnter=!0))),(c||!c&&this.isInView)&&(m=!0),m&&(r&&t.seek(t.duration*g),this.onUpdate(this)),!c&&this.isInView&&(this.isInView=!1,this.onSyncLeave(this),this.onLeave(this),this.backward?(this.onSyncLeaveBackward(this),this.onLeaveBackward(this)):(this.onSyncLeaveForward(this),this.onLeaveForward(this)),e&&!i&&(f=!0)),g>=1&&this.began&&!this.completed&&(e&&f||!e)&&(e&&this.onSyncComplete(this),this.completed=!0,(!this.repeat&&!t||!this.repeat&&t&&t.completed)&&this.revert()),g<1&&this.completed&&(this.completed=!1),this.prevProgress=g}revert(){if(this.reverted)return;const t=this.container;return bt(t,this),t._head||t.revert(),this._debug&&this.removeDebug(),this.reverted=!0,this}}const As="undefined"!=typeof Intl&&Intl.Segmenter,Ns=/\{value\}/g,Fs=/\{i\}/g,Os=/(\s+)/,Ps=/^\s+$/,Rs="line",Ms="word",Is="char",zs="data-line";let Ys=null,Xs=null,Ws=null;const Vs=t=>t.isWordLike||" "===t.segment||M(+t.segment),Hs=t=>t.setAttribute("aria-hidden","true"),Us=(t,e)=>[...t.querySelectorAll(`[data-${e}]:not([data-${e}] [data-${e}])`)],qs={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"},Qs=t=>{if(!t.childElementCount&&!t.textContent.trim()){const e=t.parentElement;t.remove(),e&&Qs(e)}},js=(t,e,s)=>{const i=t.getAttribute(zs);(null!==i&&+i!==e||"BR"===t.tagName)&&s.add(t);let r=t.childElementCount;for(;r--;)js(t.children[r],e,s);return s},Gs=(t,e={})=>{let s="";const i=I(e.class)?` class="${e.class}"`:"",r=Xt(e.clone,!1),n=Xt(e.wrap,!1),o=n?!0===n?"clip":n:!!r&&"clip";return n&&(s+=`<span${o?` style="overflow:${o};"`:""}>`),s+=`<span${i}${r?' style="position:relative;"':""} data-${t}="{i}">`,r?(s+="<span>{value}</span>",s+=`<span inert style="position:absolute;top:${"top"===r?"-100%":"bottom"===r?"100%":"0"};left:${"left"===r?"-100%":"right"===r?"100%":"0"};white-space:nowrap;">{value}</span>`):s+="{value}",s+="</span>",n&&(s+="</span>"),s},Zs=(t,e,s,i,r,n,o,a,h)=>{const l=r===Rs,c=r===Is,d=`_${r}_`,u=z(t)?t(s):t,p=l?"block":"inline-block";Ws.innerHTML=u.replace(Ns,`<i class="${d}"></i>`).replace(Fs,`${c?h:l?o:a}`);const m=Ws.content,f=m.firstElementChild,g=m.querySelector(`[data-${r}]`)||f,y=m.querySelectorAll(`i.${d}`),_=y.length;if(_){f.style.display=p,g.style.display=p,g.setAttribute(zs,`${o}`),l||(g.setAttribute("data-word",`${a}`),c&&g.setAttribute("data-char",`${h}`));let t=_;for(;t--;){const e=y[t],i=e.parentElement;i.style.display=p,l?i.innerHTML=s.innerHTML:i.replaceChild(s.cloneNode(!0),e)}e.push(g),i.appendChild(m)}else console.warn('The expression "{value}" is missing from the provided template.');return n&&(f.style.outline=`1px dotted ${qs[r]}`),f};class Js{constructor(t,s={}){Ys||(Ys=As?new As([],{granularity:Ms}):{segment:t=>{const e=[],s=t.split(Os);for(let t=0,i=s.length;t<i;t++){const i=s[t];e.push({segment:i,isWordLike:!Ps.test(i)})}return e}}),Xs||(Xs=As?new As([],{granularity:"grapheme"}):{segment:t=>[...t].map((t=>({segment:t})))}),!Ws&&e&&(Ws=i.createElement("template")),L.current&&L.current.register(this);const{words:r,chars:n,lines:o,accessible:a,includeSpaces:h,debug:l}=s,c=(t=P(t)?t[0]:t)&&t.nodeType?t:(Nt(t)||[])[0],d=!0===o?{}:o,u=!0===r||Y(r)?{}:r,p=!0===n?{}:n;this.debug=Xt(l,!1),this.includeSpaces=Xt(h,!1),this.accessible=Xt(a,!0),this.linesOnly=d&&!u&&!p,this.lineTemplate=R(d)?Gs(Rs,d):d,this.wordTemplate=R(u)||this.linesOnly?Gs(Ms,u):u,this.charTemplate=R(p)?Gs(Is,p):p,this.$target=c,this.html=c&&c.innerHTML,this.lines=[],this.words=[],this.chars=[],this.effects=[],this.effectsCleanups=[],this.cache=null,this.ready=!1,this.width=0,this.resizeTimeout=null;const m=()=>this.html&&(d||u||p)&&this.split();this.resizeObserver=new ResizeObserver((()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout((()=>{const t=c.offsetWidth;t!==this.width&&(this.width=t,m())}),150)})),this.lineTemplate&&!this.ready?i.fonts.ready.then(m):m(),c?this.resizeObserver.observe(c):console.warn("No Text Splitter target found.")}addEffect(t){if(!z(t))return console.warn("Effect must return a function.");const e=wt(t);return this.effects.push(e),this.ready&&(this.effectsCleanups[this.effects.length-1]=e(this)),this}revert(){return clearTimeout(this.resizeTimeout),this.lines.length=this.words.length=this.chars.length=0,this.resizeObserver.disconnect(),this.effectsCleanups.forEach((t=>z(t)?t(this):t.revert&&t.revert())),this.$target.innerHTML=this.html,this}splitNode(t){const e=this.wordTemplate,s=this.charTemplate,r=this.includeSpaces,n=this.debug,o=t.nodeType;if(3===o){const o=t.nodeValue;if(o.trim()){const a=[],h=this.words,l=this.chars,c=Ys.segment(o),d=i.createDocumentFragment();let u=null;for(const t of c){const e=t.segment,s=Vs(t);if(!u||s&&u&&Vs(u))a.push(e);else{const t=a.length-1;a[t].includes(" ")||e.includes(" ")?a.push(e):a[t]+=e}u=t}for(let t=0,o=a.length;t<o;t++){const o=a[t];if(o.trim()){const c=a[t+1],u=r&&c&&!c.trim(),p=o,m=s?Xs.segment(p):null,f=s?i.createDocumentFragment():i.createTextNode(u?o+" ":o);if(s){const t=[...m];for(let e=0,r=t.length;e<r;e++){const o=t[e],a=e===r-1&&u?o.segment+" ":o.segment,c=i.createTextNode(a);Zs(s,l,c,f,Is,n,-1,h.length,l.length)}}e?Zs(e,h,f,d,Ms,n,-1,h.length,l.length):s?d.appendChild(f):d.appendChild(i.createTextNode(o)),u&&t++}else{if(t&&r)continue;d.appendChild(i.createTextNode(o))}}t.parentNode.replaceChild(d,t)}}else if(1===o){const e=[...t.childNodes];for(let t=0,s=e.length;t<s;t++)this.splitNode(e[t])}}split(t=!1){const e=this.$target,s=!!this.cache&&!t,r=this.lineTemplate,n=this.wordTemplate,o=this.charTemplate,a="loading"!==i.fonts.status,h=r&&a;this.ready=!r||a,(h||t)&&this.effectsCleanups.forEach((t=>z(t)&&t(this))),s||(t&&(e.innerHTML=this.html,this.words.length=this.chars.length=0),this.splitNode(e),this.cache=e.innerHTML),h&&(s&&(e.innerHTML=this.cache),this.lines.length=0,n&&(this.words=Us(e,Ms))),o&&(h||n)&&(this.chars=Us(e,Is));const l=this.words.length?this.words:this.chars;let c,d=0;for(let t=0,e=l.length;t<e;t++){const e=l[t],{top:s,height:i}=e.getBoundingClientRect();c&&s-c>.5*i&&d++,e.setAttribute(zs,`${d}`);const r=e.querySelectorAll(`[${zs}]`);let n=r.length;for(;n--;)r[n].setAttribute(zs,`${d}`);c=s}if(h){const t=i.createDocumentFragment(),s=new Set,a=[];for(let t=0;t<d+1;t++){const i=e.cloneNode(!0);js(i,t,new Set).forEach((t=>{const e=t.parentElement;e&&s.add(e),t.remove()})),a.push(i)}s.forEach(Qs);for(let e=0,s=a.length;e<s;e++)Zs(r,this.lines,a[e],t,Rs,this.debug,e);e.innerHTML="",e.appendChild(t),n&&(this.words=Us(e,Ms)),o&&(this.chars=Us(e,Is))}if(this.linesOnly){const t=this.words;let e=t.length;for(;e--;){const s=t[e];s.replaceWith(s.textContent)}t.length=0}if(this.accessible&&(h||!s)){const t=i.createElement("span");t.style.cssText="position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;",t.innerHTML=this.html,e.insertBefore(t,e.firstChild),this.lines.forEach(Hs),this.words.forEach(Hs),this.chars.forEach(Hs)}return this.width=e.offsetWidth,(h||t)&&this.effects.forEach(((t,e)=>this.effectsCleanups[e]=t(this))),this}refresh(){this.split(!0)}}const Ks={split:(t,e)=>new Js(t,e)};return t.Animatable=us,t.Draggable=Ts,t.JSAnimation=Re,t.Scope=ws,t.ScrollObserver=Ds,t.Spring=ms,t.TextSplitter=Js,t.Timeline=ds,t.Timer=oe,t.WAAPIAnimation=Ze,t.animate=(t,e)=>new Re(t,e,null,0,!1).init(),t.createAnimatable=(t,e)=>new us(t,e),t.createDraggable=(t,e)=>new Ts(t,e),t.createScope=t=>new ws(t),t.createSpring=fs,t.createTimeline=t=>new ds(t).init(),t.createTimer=t=>new oe(t,null,0).init(),t.eases=ve,t.engine=Lt,t.onScroll=(t={})=>new Ds(t),t.scrollContainers=xs,t.stagger=(t,e={})=>{let s=[],i=0;const r=e.from,n=e.reversed,o=e.ease,a=!Y(o),h=a&&!Y(o.ease)?o.ease:a?Te(o):null,l=e.grid,c=e.axis,d=e.total,u=Y(r)||0===r||"first"===r,p="center"===r,f="last"===r,g="random"===r,y=P(t),_=e.use,v=Q(y?t[0]:t),b=y?Q(t[1]):0,T=k.exec((y?t[1]:t)+m),w=e.start||0+(y?v:0);let S=u?0:M(r)?r:0;return(t,r,o,a)=>{const[u]=Ot(t),m=Y(d)?o:d,x=!Y(_)&&(z(_)?_(u,r,m):Ut(u,_)),k=M(x)||I(x)&&M(+x)?+x:r;if(p&&(S=(m-1)/2),f&&(S=m-1),!s.length){for(let t=0;t<m;t++){if(l){const e=p?(l[0]-1)/2:S%l[0],i=p?(l[1]-1)/2:st(S/l[0]),r=e-t%l[0],n=i-st(t/l[0]);let o=G(r*r+n*n);"x"===c&&(o=-r),"y"===c&&(o=-n),s.push(o)}else s.push(K(S-t));i=rt(...s)}h&&(s=s.map((t=>h(t/i)*i))),n&&(s=s.map((t=>c?t<0?-1*t:-t:K(i-t)))),g&&(s=mt(s))}const $=y?(b-v)/i:v;let C=(a?ls(a,Y(e.start)?a.iterationDuration:w):w)+($*ct(s[k],2)||0);return e.modifier&&(C=e.modifier(C)),T&&(C=`${C}${T[2]}`),C}},t.svg=zt,t.text=Ks,t.utils=hs,t.waapi=Je,t}({});
diff --git a/lib/anime.min.cjs b/lib/anime.min.cjs
deleted file mode 100644
index 46677863..00000000
--- a/lib/anime.min.cjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * anime.js - CJS
- * @version v4.1.3
- * @author Julian Garnier
- * @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
- */
-"use strict";const t="undefined"!=typeof window,e=t?window:null,s=t?document:null,i={replace:0,none:1,blend:2},r=Symbol(),n=Symbol(),o=Symbol(),a=Symbol(),h=Symbol(),l=Symbol(),c=1e-11,d=1e12,u=1e3,p="",m=(()=>{const t=new Map;return t.set("x","translateX"),t.set("y","translateY"),t.set("z","translateZ"),t})(),f=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],g=f.reduce(((t,e)=>({...t,[e]:e+"("})),{}),y=()=>{},_=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i,v=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i,b=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,x=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i,T=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,w=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi,S=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i,k=/([a-z])([A-Z])/g,$=/(\w+)(\([^)]+\)+)/g,C=/(\*=|\+=|-=)/,E={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:120,loop:0,reversed:!1,alternate:!1,autoplay:!0,duration:u,delay:0,loopDelay:0,ease:"out(2)",composition:i.replace,modifier:t=>t,onBegin:y,onBeforeUpdate:y,onUpdate:y,onLoop:y,onPause:y,onComplete:y,onRender:y},B={current:null,root:s},L={defaults:E,precision:4,timeScale:1,tickThreshold:200},D={version:"4.1.3",engine:null};t&&(e.AnimeJS||(e.AnimeJS=[]),e.AnimeJS.push(D));const A=t=>t.replace(k,"$1-$2").toLowerCase(),N=(t,e)=>0===t.indexOf(e),F=Date.now,O=Array.isArray,P=t=>t&&t.constructor===Object,R=t=>"number"==typeof t&&!isNaN(t),M=t=>"string"==typeof t,I=t=>"function"==typeof t,z=t=>void 0===t,Y=t=>z(t)||null===t,X=e=>t&&e instanceof SVGElement,W=t=>_.test(t),V=t=>N(t,"rgb"),H=t=>N(t,"hsl"),U=t=>!L.defaults.hasOwnProperty(t),q=t=>M(t)?parseFloat(t):t,Q=Math.pow,j=Math.sqrt,G=Math.sin,Z=Math.cos,J=Math.abs,K=Math.exp,tt=Math.ceil,et=Math.floor,st=Math.asin,it=Math.max,rt=Math.atan2,nt=Math.PI,ot=Math.round,at=(t,e,s)=>t<e?e:t>s?s:t,ht={},lt=(t,e)=>{if(e<0)return t;if(!e)return ot(t);let s=ht[e];return s||(s=ht[e]=10**e),ot(t*s)/s},ct=(t,e)=>O(e)?e.reduce(((e,s)=>J(s-t)<J(e-t)?s:e)):e?ot(t/e)*e:t,dt=(t,e,s)=>t+(e-t)*s,ut=(t,e,s)=>{const i=10**(s||0);return et((Math.random()*(e-t+1/i)+t)*i)/i},pt=t=>{let e,s,i=t.length;for(;i;)s=ut(0,--i),e=t[i],t[i]=t[s],t[s]=e;return t},mt=t=>t===1/0?d:t===-1/0?-1e12:t,ft=t=>t<=c?c:mt(lt(t,11)),gt=t=>O(t)?[...t]:t,yt=(t,e)=>{const s={...t};for(let i in e){const r=t[i];s[i]=z(r)?e[i]:r}return s},_t=(t,e,s,i="_prev",r="_next")=>{let n=t._head,o=r;for(s&&(n=t._tail,o=i);n;){const t=n[o];e(n),n=t}},vt=(t,e,s="_prev",i="_next")=>{const r=e[s],n=e[i];r?r[i]=n:t._head=n,n?n[s]=r:t._tail=r,e[s]=null,e[i]=null},bt=(t,e,s,i="_prev",r="_next")=>{let n=t._tail;for(;n&&s&&s(n,e);)n=n[i];const o=n?n[r]:t._head;n?n[r]=e:t._head=e,o?o[i]=e:t._tail=e,e[i]=n,e[r]=o},xt=t=>{let e;return(...s)=>{let i,r,n,o;e&&(i=e.currentIteration,r=e.iterationProgress,n=e.reversed,o=e._alternate,e.revert());const a=t(...s);return a&&!I(a)&&a.revert&&(e=a),z(r)||(e.currentIteration=i,e.iterationProgress=(o&&i%2?!n:n)?1-r:r),a||y}};class Tt{constructor(t=0){this.deltaTime=0,this._currentTime=t,this._elapsedTime=t,this._startTime=t,this._lastTime=t,this._scheduledTime=0,this._frameDuration=lt(u/120,0),this._fps=120,this._speed=1,this._hasChildren=!1,this._head=null,this._tail=null}get fps(){return this._fps}set fps(t){const e=this._frameDuration,s=+t,i=s<c?c:s,r=lt(u/i,0);this._fps=i,this._frameDuration=r,this._scheduledTime+=r-e}get speed(){return this._speed}set speed(t){const e=+t;this._speed=e<c?c:e}requestTick(t){const e=this._scheduledTime,s=this._elapsedTime;if(this._elapsedTime+=t-s,s<e)return 0;const i=this._frameDuration,r=s-e;return this._scheduledTime+=r<i?i:r,1}computeDeltaTime(t){const e=t-this._lastTime;return this.deltaTime=e,this._lastTime=t,e}}const wt=(t,e,s,r,n)=>{const o=t.parent,h=t.duration,l=t.completed,d=t.iterationDuration,u=t.iterationCount,m=t._currentIteration,f=t._loopDelay,y=t._reversed,_=t._alternate,v=t._hasChildren,b=t._delay,x=t._currentTime,T=b+d,w=e-b,S=at(x,-b,h),k=at(w,-b,h),$=w-x,C=k>0,E=k>=h,B=h<=c,D=2===n;let A=0,N=w,F=0;if(u>1){const e=~~(k/(d+(E?0:f)));t._currentIteration=at(e,0,u),E&&t._currentIteration--,A=t._currentIteration%2,N=k%(d+f)||0}const O=y^(_&&A),P=t._ease;let R=E?O?0:h:O?d-N:N;P&&(R=d*P(R/d)||0);const M=(o?o.backwards:w<x)?!O:!!O;if(t._currentTime=w,t._iterationTime=R,t.backwards=M,C&&!t.began?(t.began=!0,s||o&&(M||!o.began)||t.onBegin(t)):w<=0&&(t.began=!1),s||v||!C||t._currentIteration===m||t.onLoop(t),D||1===n&&(e>=b&&e<=T||e<=b&&S>b||e>=T&&S!==h)||R>=T&&S!==h||R<=b&&S>0||e<=S&&S===h&&l||E&&!l&&B){if(C&&(t.computeDeltaTime(S),s||t.onBeforeUpdate(t)),!v){const e=D||(M?-1*$:$)>=L.tickThreshold,n=t._offset+(o?o._offset:0)+b+R;let h,l,c,d,u=t._head,m=0;for(;u;){const t=u._composition,s=u._currentTime,o=u._changeDuration,f=u._absoluteStartTime+u._changeDuration,y=u._nextRep,_=u._prevRep,v=t!==i.none;if((e||(s!==o||n<=f+(y?y._delay:0))&&(0!==s||n>=u._absoluteStartTime))&&(!v||!u._isOverridden&&(!u._isOverlapped||n<=f)&&(!y||y._isOverridden||n<=y._absoluteStartTime)&&(!_||_._isOverridden||n>=_._absoluteStartTime+_._changeDuration+u._delay))){const e=u._currentTime=at(R-u._startTime,0,o),s=u._ease(e/u._updateDuration),n=u._modifier,p=u._valueType,f=u._tweenType,g=0===f,y=0===p,_=y&&g||0===s||1===s?-1:L.precision;let b,x;if(y)b=x=n(lt(dt(u._fromNumber,u._toNumber,s),_));else if(1===p)x=n(lt(dt(u._fromNumber,u._toNumber,s),_)),b=`${x}${u._unit}`;else if(2===p){const t=u._fromNumbers,e=u._toNumbers,i=lt(at(n(dt(t[0],e[0],s)),0,255),0),r=lt(at(n(dt(t[1],e[1],s)),0,255),0),o=lt(at(n(dt(t[2],e[2],s)),0,255),0),a=at(n(lt(dt(t[3],e[3],s),_)),0,1);if(b=`rgba(${i},${r},${o},${a})`,v){const t=u._numbers;t[0]=i,t[1]=r,t[2]=o,t[3]=a}}else if(3===p){b=u._strings[0];for(let t=0,e=u._toNumbers.length;t<e;t++){const e=n(lt(dt(u._fromNumbers[t],u._toNumbers[t],s),_)),i=u._strings[t+1];b+=`${i?e+i:e}`,v&&(u._numbers[t]=e)}}if(v&&(u._number=x),r||t===i.blend)u._value=b;else{const t=u.property;h=u.target,g?h[t]=b:1===f?h.setAttribute(t,b):(l=h.style,3===f?(h!==c&&(c=h,d=h[a]),d[t]=b,m=1):2===f?l[t]=b:4===f&&l.setProperty(t,b)),C&&(F=1)}}if(m&&u._renderTransforms){let t=p;for(let e in d)t+=`${g[e]}${d[e]}) `;l.transform=t,m=0}u=u._next}!s&&F&&t.onRender(t)}!s&&C&&t.onUpdate(t)}return o&&B?!s&&(o.began&&!M&&w>=h&&!l||M&&w<=c&&l)&&(t.onComplete(t),t.completed=!M):C&&E?u===1/0?t._startTime+=t.duration:t._currentIteration>=u-1&&(t.paused=!0,l||v||(t.completed=!0,s||o&&(M||!o.began)||(t.onComplete(t),t._resolve(t)))):t.completed=!1,F},St=(t,e,s,i,r)=>{const n=t._currentIteration;if(wt(t,e,s,i,r),t._hasChildren){const o=t,a=o.backwards,h=i?e:o._iterationTime,l=F();let d=0,u=!0;if(!i&&o._currentIteration!==n){const t=o.iterationDuration;_t(o,(e=>{if(a){const i=e.duration,r=e._offset+e._delay;s||!(i<=c)||r&&r+i!==t||e.onComplete(e)}else!e.completed&&!e.backwards&&e._currentTime<e.iterationDuration&&wt(e,t,s,1,2),e.began=!1,e.completed=!1})),s||o.onLoop(o)}_t(o,(t=>{const e=lt((h-t._offset)*t._speed,12),n=t._fps<o._fps?t.requestTick(l):r;d+=wt(t,e,s,i,n),!t.completed&&u&&(u=!1)}),a),!s&&d&&o.onRender(o),(u||a)&&o._currentTime>=o.duration&&(o.paused=!0,o.completed||(o.completed=!0,s||(o.onComplete(o),o._resolve(o))))}},kt={animation:null,update:y},$t=(()=>t?requestAnimationFrame:setImmediate)(),Ct=(()=>t?cancelAnimationFrame:clearImmediate)();class Et extends Tt{constructor(t){super(t),this.useDefaultMainLoop=!0,this.pauseOnDocumentHidden=!0,this.defaults=E,this.paused=!0,this.reqId=0}update(){const t=this._currentTime=F();if(this.requestTick(t)){this.computeDeltaTime(t);const e=this._speed,s=this._fps;let i=this._head;for(;i;){const r=i._next;i.paused?(vt(this,i),this._hasChildren=!!this._tail,i._running=!1,i.completed&&!i._cancelled&&i.cancel()):St(i,(t-i._startTime)*i._speed*e,0,0,i._fps<s?i.requestTick(t):1),i=r}kt.update()}}wake(){return this.useDefaultMainLoop&&!this.reqId&&(this.requestTick(F()),this.reqId=$t(Lt)),this}pause(){if(this.reqId)return this.paused=!0,Dt()}resume(){if(this.paused)return this.paused=!1,_t(this,(t=>t.resetTime())),this.wake()}get speed(){return this._speed*(1===L.timeScale?1:u)}set speed(t){this._speed=t*L.timeScale,_t(this,(t=>t.speed=t._speed))}get timeUnit(){return 1===L.timeScale?"ms":"s"}set timeUnit(t){const e="s"===t,s=e?.001:1;if(L.timeScale!==s){L.timeScale=s,L.tickThreshold=200*s;const t=e?.001:u;this.defaults.duration*=t,this._speed*=t}}get precision(){return L.precision}set precision(t){L.precision=t}}const Bt=(()=>{const e=new Et(F());return t&&(D.engine=e,s.addEventListener("visibilitychange",(()=>{e.pauseOnDocumentHidden&&(s.hidden?e.pause():e.resume())}))),e})(),Lt=()=>{Bt._head?(Bt.reqId=$t(Lt),Bt.update()):Bt.reqId=0},Dt=()=>(Ct(Bt.reqId),Bt.reqId=0,Bt);function At(t){const e=M(t)?B.root.querySelectorAll(t):t;if(e instanceof NodeList||e instanceof HTMLCollection)return e}function Nt(e){if(Y(e))return[];if(!t)return O(e)&&e.flat(1/0)||[e];if(O(e)){const t=e.flat(1/0),s=[];for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!Y(i)){const t=At(i);if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!Y(i)){let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}else{let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}}return s}const s=At(e);return s?Array.from(s):[e]}function Ft(t){const e=Nt(t),s=e.length;if(s)for(let t=0;t<s;t++){const s=e[t];if(!s[r]){s[r]=!0;const t=X(s);(s.nodeType||t)&&(s[n]=!0,s[o]=t,s[a]={})}}return e}const Ot=t=>{const e=Nt(t)[0];if(e&&X(e))return e},Pt=(t,e,s=0)=>t.getPointAtLength(e+s>=1?e+s:0),Rt=(t,e)=>s=>{const i=+t.getTotalLength(),r=s[o],n=t.getCTM();return{from:0,to:i,modifier:s=>{if("a"===e){const e=Pt(t,s,-1),i=Pt(t,s,1);return 180*rt(i.y-e.y,i.x-e.x)/nt}{const i=Pt(t,s,0);return"x"===e?r||!n?i.x:i.x*n.a+i.y*n.c+n.e:r||!n?i.y:i.x*n.b+i.y*n.d+n.f}}}},Mt=["opacity","rotate","overflow","color"],It={morphTo:(t,e=.33)=>s=>{const i=Ot(t);if(!i)return;const r="path"===s.tagName,n=r?" ":",",o=s[h];o&&s.setAttribute(r?"d":"points",o);let a="",l="";if(e){const t=s.getTotalLength(),o=i.getTotalLength(),h=Math.max(Math.ceil(t*e),Math.ceil(o*e));for(let e=0;e<h;e++){const c=e/(h-1),d=s.getPointAtLength(t*c),u=i.getPointAtLength(o*c),p=r?0===e?"M":"L":"";a+=p+lt(d.x,3)+n+d.y+" ",l+=p+lt(u.x,3)+n+u.y+" "}}else a=s.getAttribute(r?"d":"points"),l=i.getAttribute(r?"d":"points");return s[h]=l,[a,l]},createMotionPath:t=>{const e=Ot(t);if(e)return{translateX:Rt(e,"x"),translateY:Rt(e,"y"),rotate:Rt(e,"a")}},createDrawable:(t,e=0,s=0)=>Nt(t).map((t=>((t,e,s)=>{const i=u,r=getComputedStyle(t),n=r.strokeLinecap,o="non-scaling-stroke"===r.vectorEffect?t:null;let a=n;const h=new Proxy(t,{get(t,e){const s=t[e];return e===l?t:"setAttribute"===e?(...e)=>{if("draw"===e[0]){const s=e[1].split(" "),r=+s[0],h=+s[1],l=(t=>{let e=1;if(t&&t.getCTM){const s=t.getCTM();s&&(e=(j(s.a*s.a+s.b*s.b)+j(s.c*s.c+s.d*s.d))/2)}return e})(o),c=-1e3*r*l,d=h*i*l+c,u=i*l+(0===r&&1===h||1===r&&0===h?0:10*l)-d;if("butt"!==n){const e=r===h?"butt":n;a!==e&&(t.style.strokeLinecap=`${e}`,a=e)}t.setAttribute("stroke-dashoffset",`${c}`),t.setAttribute("stroke-dasharray",`${d} ${u}`)}return Reflect.apply(s,t,e)}:I(s)?(...e)=>Reflect.apply(s,t,e):s}});return"1000"!==t.getAttribute("pathLength")&&(t.setAttribute("pathLength","1000"),h.setAttribute("draw",`${e} ${s}`)),h})(t,e,s)))},zt=(t,e,s)=>(s<0&&(s+=1),s>1&&(s-=1),s<1/6?t+6*(e-t)*s:s<.5?e:s<2/3?t+(e-t)*(2/3-s)*6:t),Yt=(t,e)=>z(t)?e:t,Xt=(t,e,s,i,r)=>{if(I(t)){const n=()=>{const r=t(e,s,i);return isNaN(+r)?r||0:+r};return r&&(r.func=n),n()}return t},Wt=(t,e)=>t[n]?t[o]&&((t,e)=>{if(Mt.includes(e))return!1;if(t.getAttribute(e)||e in t){if("scale"===e){const e=t.parentNode;return e&&"filter"===e.tagName}return!0}})(t,e)?1:f.includes(e)||m.get(e)?3:N(e,"--")?4:e in t.style?2:e in t?0:1:0,Vt=(t,e,s)=>{const i=t.style[e];i&&s&&(s[e]=i);const r=i||getComputedStyle(t[l]||t).getPropertyValue(e);return"auto"===r?"0":r},Ht=(t,e,s,i)=>{const r=z(s)?Wt(t,e):s;return 0===r?t[e]||0:1===r?t.getAttribute(e):3===r?((t,e,s)=>{const i=t.style.transform;let r;if(i){const n=t[a];let o;for(;o=$.exec(i);){const t=o[1],i=o[2].slice(1,-1);n[t]=i,t===e&&(r=i,s&&(s[e]=i))}}return i&&!z(r)?r:N(e,"scale")?"1":N(e,"rotate")||N(e,"skew")?"0deg":"0px"})(t,e,i):4===r?Vt(t,e,i).trimStart():Vt(t,e,i)},Ut=(t,e,s)=>"-"===s?t-e:"+"===s?t+e:t*e,qt=(t,e)=>{if(e.t=0,e.n=0,e.u=null,e.o=null,e.d=null,e.s=null,!t)return e;const s=+t;if(isNaN(s)){let s=t;"="===s[1]&&(e.o=s[0],s=s.slice(2));const n=!s.includes(" ")&&S.exec(s);if(n)return e.t=1,e.n=+n[1],e.u=n[2],e;if(e.o)return e.n=+s,e;if(W(r=s)||V(r)||H(r))return e.t=2,e.d=V(i=s)?(t=>{const e=v.exec(t)||b.exec(t),s=z(e[4])?1:+e[4];return[+e[1],+e[2],+e[3],s]})(i):W(i)?(t=>{const e=t.length,s=4===e||5===e;return[+("0x"+t[1]+t[s?1:2]),+("0x"+t[s?2:3]+t[s?2:4]),+("0x"+t[s?3:5]+t[s?3:6]),5===e||9===e?+(+("0x"+t[s?4:7]+t[s?4:8])/255).toFixed(3):1]})(i):H(i)?(t=>{const e=x.exec(t)||T.exec(t),s=+e[1]/360,i=+e[2]/100,r=+e[3]/100,n=z(e[4])?1:+e[4];let o,a,h;if(0===i)o=a=h=r;else{const t=r<.5?r*(1+i):r+i-r*i,e=2*r-t;o=lt(255*zt(e,t,s+1/3),0),a=lt(255*zt(e,t,s),0),h=lt(255*zt(e,t,s-1/3),0)}return[o,a,h,n]})(i):[0,0,0,1],e;{const t=s.match(w);return e.t=3,e.d=t?t.map(Number):[],e.s=s.split(w)||[],e}}var i,r;return e.n=s,e},Qt=(t,e)=>(e.t=t._valueType,e.n=t._toNumber,e.u=t._unit,e.o=null,e.d=gt(t._toNumbers),e.s=gt(t._strings),e),jt={t:0,n:0,u:null,o:null,d:null,s:null},Gt={_rep:new WeakMap,_add:new Map},Zt=(t,e,s="_rep")=>{const i=Gt[s];let r=i.get(t);return r||(r={},i.set(t,r)),r[e]?r[e]:r[e]={_head:null,_tail:null}},Jt=(t,e)=>t._isOverridden||t._absoluteStartTime>e._absoluteStartTime,Kt=t=>{t._isOverlapped=1,t._isOverridden=1,t._changeDuration=c,t._currentTime=c},te=(t,e)=>{const s=t._composition;if(s===i.replace){const s=t._absoluteStartTime;bt(e,t,Jt,"_prevRep","_nextRep");const i=t._prevRep;if(i){const e=i.parent,r=i._absoluteStartTime+i._changeDuration;if(t.parent.id!==e.id&&e.iterationCount>1&&r+(e.duration-e.iterationDuration)>s){Kt(i);let t=i._prevRep;for(;t&&t.parent.id===e.id;)Kt(t),t=t._prevRep}const n=s-t._delay;if(r>n){const t=i._startTime,e=r-(t+i._updateDuration),s=lt(n-e-t,12);i._changeDuration=s,i._currentTime=s,i._isOverlapped=1,s<c&&Kt(i)}let o=!0;if(_t(e,(t=>{t._isOverlapped||(o=!1)})),o){const t=e.parent;if(t){let s=!0;_t(t,(t=>{t!==e&&_t(t,(t=>{t._isOverlapped||(s=!1)}))})),s&&t.cancel()}else e.cancel()}}}else if(s===i.blend){const e=Zt(t.target,t.property,"_add"),s=(t=>{let e=kt.animation;return e||(e={duration:c,computeDeltaTime:y,_offset:0,_delay:0,_head:null,_tail:null},kt.animation=e,kt.update=()=>{t.forEach((t=>{for(let e in t){const s=t[e],i=s._head;if(i){const t=i._valueType,e=3===t||2===t?gt(i._fromNumbers):null;let r=i._fromNumber,n=s._tail;for(;n&&n!==i;){if(e)for(let t=0,s=n._numbers.length;t<s;t++)e[t]+=n._numbers[t];else r+=n._number;n=n._prevAdd}i._toNumber=r,i._toNumbers=e}}})),wt(e,1,1,0,2)}),e})(Gt._add);let r=e._head;r||(r={...t},r._composition=i.replace,r._updateDuration=c,r._startTime=0,r._numbers=gt(t._fromNumbers),r._number=0,r._next=null,r._prev=null,bt(e,r),bt(s,r));const n=t._toNumber;if(t._fromNumber=r._fromNumber-n,t._toNumber=0,t._numbers=gt(t._fromNumbers),t._number=0,r._fromNumber=n,t._toNumbers){const e=gt(t._toNumbers);e&&e.forEach(((e,s)=>{t._fromNumbers[s]=r._fromNumbers[s]-e,t._toNumbers[s]=0})),r._fromNumbers=e}bt(e,t,null,"_prevAdd","_nextAdd")}return t},ee=t=>{const e=t._composition;if(e!==i.none){const s=t.target,r=t.property,n=Gt._rep.get(s)[r];if(vt(n,t,"_prevRep","_nextRep"),e===i.blend){const e=Gt._add,i=e.get(s);if(!i)return;const n=i[r],o=kt.animation;vt(n,t,"_prevAdd","_nextAdd");const a=n._head;if(a&&a===n._tail){vt(n,a,"_prevAdd","_nextAdd"),vt(o,a);let t=!0;for(let e in i)if(i[e]._head){t=!1;break}t&&e.delete(s)}}}return t},se=t=>(t.paused=!0,t.began=!1,t.completed=!1,t),ie=t=>t._cancelled?(t._hasChildren?_t(t,ie):_t(t,(t=>{t._composition!==i.none&&te(t,Zt(t.target,t.property))})),t._cancelled=0,t):t;let re=0;class ne extends Tt{constructor(t={},e=null,s=0){super(0);const{id:i,delay:r,duration:n,reversed:o,alternate:a,loop:h,loopDelay:l,autoplay:d,frameRate:u,playbackRate:p,onComplete:m,onLoop:f,onPause:g,onBegin:_,onBeforeUpdate:v,onUpdate:b}=t;B.current&&B.current.register(this);const x=e?0:Bt._elapsedTime,T=e?e.defaults:L.defaults,w=I(r)||z(r)?T.delay:+r,S=I(n)||z(n)?1/0:+n,k=Yt(h,T.loop),$=Yt(l,T.loopDelay),C=!0===k||k===1/0||k<0?1/0:k+1;let E=0;e?E=s:(Bt.reqId||Bt.requestTick(F()),E=(Bt._elapsedTime-Bt._startTime)*L.timeScale),this.id=z(i)?++re:i,this.parent=e,this.duration=mt((S+$)*C-$)||c,this.backwards=!1,this.paused=!0,this.began=!1,this.completed=!1,this.onBegin=_||T.onBegin,this.onBeforeUpdate=v||T.onBeforeUpdate,this.onUpdate=b||T.onUpdate,this.onLoop=f||T.onLoop,this.onPause=g||T.onPause,this.onComplete=m||T.onComplete,this.iterationDuration=S,this.iterationCount=C,this._autoplay=!e&&Yt(d,T.autoplay),this._offset=E,this._delay=w,this._loopDelay=$,this._iterationTime=0,this._currentIteration=0,this._resolve=y,this._running=!1,this._reversed=+Yt(o,T.reversed),this._reverse=this._reversed,this._cancelled=0,this._alternate=Yt(a,T.alternate),this._prev=null,this._next=null,this._elapsedTime=x,this._startTime=x,this._lastTime=x,this._fps=Yt(u,T.frameRate),this._speed=Yt(p,T.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(t){t?this.cancel():this.reset(1).play()}get currentTime(){return at(lt(this._currentTime,L.precision),-this._delay,this.duration)}set currentTime(t){const e=this.paused;this.pause().seek(+t),e||this.resume()}get iterationCurrentTime(){return lt(this._iterationTime,L.precision)}set iterationCurrentTime(t){this.currentTime=this.iterationDuration*this._currentIteration+t}get progress(){return at(lt(this._currentTime/this.duration,10),0,1)}set progress(t){this.currentTime=this.duration*t}get iterationProgress(){return at(lt(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(t){const e=this.iterationDuration;this.currentTime=e*this._currentIteration+e*t}get currentIteration(){return this._currentIteration}set currentIteration(t){this.currentTime=this.iterationDuration*at(+t,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(t){t?this.reverse():this.play()}get speed(){return super.speed}set speed(t){super.speed=t,this.resetTime()}reset(t=0){return ie(this),this._reversed&&!this._reverse&&(this.reversed=!1),this._iterationTime=this.iterationDuration,St(this,0,1,t,2),se(this),this._hasChildren&&_t(this,se),this}init(t=0){this.fps=this._fps,this.speed=this._speed,!t&&this._hasChildren&&St(this,this.duration,1,t,2),this.reset(t);const e=this._autoplay;return!0===e?this.resume():e&&!z(e.linked)&&e.link(this),this}resetTime(){const t=1/(this._speed*Bt._speed);return this._startTime=F()-(this._currentTime+this._delay)*t,this}pause(){return this.paused||(this.paused=!0,this.onPause(this)),this}resume(){return this.paused?(this.paused=!1,this.duration<=c&&!this._hasChildren?St(this,c,0,0,2):(this._running||(bt(Bt,this),Bt._hasChildren=!0,this._running=!0),this.resetTime(),this._startTime-=12,Bt.wake()),this):this}restart(){return this.reset(0).resume()}seek(t,e=0,s=0){ie(this),this.completed=!1;const i=this.paused;return this.paused=!0,St(this,t+this._delay,~~e,~~s,1),i?this:this.resume()}alternate(){const t=this._reversed,e=this.iterationCount,s=this.iterationDuration,i=e===1/0?et(d/s):e;return this._reversed=+(!this._alternate||i%2?!t:t),e===1/0?this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress:this.seek(s*i-this._currentTime),this.resetTime(),this}play(){return this._reversed&&this.alternate(),this.resume()}reverse(){return this._reversed||this.alternate(),this.resume()}cancel(){return this._hasChildren?_t(this,(t=>t.cancel()),!0):_t(this,ee),this._cancelled=1,this.pause()}stretch(t){const e=this.duration,s=ft(t);if(e===s)return this;const i=t/e,r=t<=c;return this.duration=r?c:s,this.iterationDuration=r?c:ft(this.iterationDuration*i),this._offset*=i,this._delay*=i,this._loopDelay*=i,this}revert(){St(this,0,1,0,1);const t=this._autoplay;return t&&t.linked&&t.linked===this&&t.revert(),this.cancel()}complete(){return this.seek(this.duration).cancel()}then(t=y){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=y};return new Promise((t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this)))}}const oe=t=>t,ae=(t,e,s)=>(((1-3*s+3*e)*t+(3*s-6*e))*t+3*e)*t,he=(t=.5,e=0,s=.5,i=1)=>t===e&&s===i?oe:r=>0===r||1===r?r:ae(((t,e,s)=>{let i,r,n=0,o=1,a=0;do{r=n+(o-n)/2,i=ae(r,e,s)-t,i>0?o=r:n=r}while(J(i)>1e-7&&++a<100);return r})(r,t,s),e,i),le=(t=10,e)=>{const s=e?tt:et;return e=>s(at(e,0,1)*t)*(1/t)},ce=(...t)=>{const e=t.length;if(!e)return oe;const s=e-1,i=t[0],r=t[s],n=[0],o=[q(i)];for(let e=1;e<s;e++){const i=t[e],r=M(i)?i.trim().split(" "):[i],a=r[0],h=r[1];n.push(z(h)?e/s:q(h)/100),o.push(q(a))}return o.push(q(r)),n.push(1),function(t){for(let e=1,s=n.length;e<s;e++){const s=n[e];if(t<=s){const i=n[e-1],r=o[e-1];return r+(o[e]-r)*(t-i)/(s-i)}}return o[o.length-1]}},de=(t=10,e=1)=>{const s=[0],i=t-1;for(let t=1;t<i;t++){const r=s[t-1],n=t/i,o=n*(1-e)+(n+((t+1)/i-n)*Math.random())*e;s.push(at(o,r,1))}return s.push(1),ce(...s)},ue=nt/2,pe=2*nt,me=(t=1.68)=>e=>Q(e,+t),fe={[p]:me,Quad:me(2),Cubic:me(3),Quart:me(4),Quint:me(5),Sine:t=>1-Z(t*ue),Circ:t=>1-j(1-t*t),Expo:t=>t?Q(2,10*t-10):0,Bounce:t=>{let e,s=4;for(;t<((e=Q(2,--s))-1)/11;);return 1/Q(4,3-s)-7.5625*Q((3*e-2)/22-t,2)},Back:(t=1.70158)=>e=>(+t+1)*e*e*e-+t*e*e,Elastic:(t=1,e=.3)=>{const s=at(+t,1,10),i=at(+e,c,2),r=i/pe*st(1/s),n=pe/i;return t=>0===t||1===t?t:-s*Q(2,-10*(1-t))*G((1-t-r)*n)}},ge={in:t=>e=>t(e),out:t=>e=>1-t(1-e),inOut:t=>e=>e<.5?t(2*e)/2:1-t(-2*e+2)/2,outIn:t=>e=>e<.5?(1-t(1-2*e))/2:(t(2*e-1)+1)/2},ye=(t,e,s)=>{if(s[t])return s[t];if(t.indexOf("(")<=-1){const i=ge[t]||t.includes("Back")||t.includes("Elastic")?e[t]():e[t];return i?s[t]=i:oe}{const i=t.slice(0,-1).split("("),r=e[i[0]];return r?s[t]=r(...i[1].split(",")):oe}},_e=(()=>{const t={linear:ce,irregular:de,steps:le,cubicBezier:he};for(let e in ge)for(let s in fe){const i=fe[s],r=ge[e];t[e+s]=s===p||"Back"===s||"Elastic"===s?(t,e)=>r(i(t,e)):r(i)}return t})(),ve={linear:oe},be=t=>I(t)?t:M(t)?ye(t,_e,ve):oe,xe={},Te=(t,e,s)=>{if(3===s)return m.get(t)||t;if(2===s||1===s&&X(e)&&t in e.style){const e=xe[t];if(e)return e;{const e=t?A(t):t;return xe[t]=e,e}}return t},we={deg:1,rad:180/nt,turn:360},Se={},ke=(t,e,i,r=!1)=>{const n=e.u,o=e.n;if(1===e.t&&n===i)return e;const a=o+n+i,h=Se[a];if(z(h)||r){let r;if(n in we)r=o*we[n]/we[i];else{const e=100,a=t.cloneNode(),h=t.parentNode,l=h&&h!==s?h:s.body;l.appendChild(a);const c=a.style;c.width=e+n;const d=a.offsetWidth||e;c.width=e+i;const u=d/(a.offsetWidth||e);l.removeChild(a),r=u*o}e.n=r,Se[a]=r}else e.n=h;return e.t,e.u=i,e},$e=t=>{if(t._hasChildren)_t(t,$e,!0);else{const e=t;e.pause(),_t(e,(t=>{const s=t.property,i=t.target;if(i[n]){const r=i.style,n=e._inlineStyles[s];if(3===t._tweenType){const e=i[a];if(z(n)||n===p?delete e[s]:e[s]=n,t._renderTransforms)if(Object.keys(e).length){let t=p;for(let s in e)t+=g[s]+e[s]+") ";r.transform=t}else r.removeProperty("transform")}else z(n)||n===p?r.removeProperty(s):r[s]=n;e._tail===t&&e.targets.forEach((t=>{t.getAttribute&&t.getAttribute("style")===p&&t.removeAttribute("style")}))}}))}return t},Ce={t:0,n:0,u:null,o:null,d:null,s:null},Ee={t:0,n:0,u:null,o:null,d:null,s:null},Be={func:null},Le=[null],De=[null,null],Ae={to:null};let Ne,Fe,Oe=0;class Pe extends ne{constructor(t,e,s,r,n=!1,o=0,a=0){super(e,s,r);const h=Ft(t),l=h.length,d=e.keyframes,p=d?yt(((t,e)=>{const s={};if(O(t)){const e=[].concat(...t.map((t=>Object.keys(t)))).filter(U);for(let i=0,r=e.length;i<r;i++){const r=e[i],n=t.map((t=>{const e={};for(let s in t){const i=t[s];U(s)?s===r&&(e.to=i):e[s]=i}return e}));s[r]=n}}else{const i=Yt(e.duration,L.defaults.duration),r=Object.keys(t).map((e=>({o:parseFloat(e)/100,p:t[e]}))).sort(((t,e)=>t.o-e.o));r.forEach((t=>{const e=t.o,r=t.p;for(let t in r)if(U(t)){let n=s[t];n||(n=s[t]=[]);const o=e*i;let a=n.length,h=n[a-1];const l={to:r[t]};let c=0;for(let t=0;t<a;t++)c+=n[t].duration;1===a&&(l.from=h.to),r.ease&&(l.ease=r.ease),l.duration=o-(a?c:0),n.push(l)}return t}));for(let t in s){const e=s[t];let i;for(let t=0,s=e.length;t<s;t++){const s=e[t],r=s.ease;s.ease=i||void 0,i=r}e[0].duration||e.shift()}}return s})(d,e),e):e,{delay:m,duration:f,ease:g,playbackEase:y,modifier:_,composition:v,onRender:b}=p,x=s?s.defaults:L.defaults,T=Yt(y,x.playbackEase),w=T?be(T):null,S=!z(g)&&!z(g.ease),k=S?g.ease:Yt(g,w?"linear":x.ease),$=S?g.duration:Yt(f,x.duration),C=Yt(m,x.delay),E=_||x.modifier,B=z(v)&&l>=u?i.none:z(v)?x.composition:v,D={},A=this._offset+(s?s._offset:0);let N=NaN,F=NaN,M=0,I=0;for(let t=0;t<l;t++){const e=h[t],r=o||t,d=a||l;let u=NaN,m=NaN;for(let t in p)if(U(t)){const o=Wt(e,t),a=Te(t,e,o);let h=p[t];const l=O(h);if(n&&!l&&(De[0]=h,De[1]=h,h=De),l){const t=h.length,e=!P(h[0]);2===t&&e?(Ae.to=h,Le[0]=Ae,Ne=Le):t>2&&e?(Ne=[],h.forEach(((t,e)=>{e?1===e?(De[1]=t,Ne.push(De)):Ne.push(t):De[0]=t}))):Ne=h}else Le[0]=h,Ne=Le;let f=null,g=null,y=NaN,_=0,v=0;for(let t=Ne.length;v<t;v++){const n=Ne[v];P(n)?Fe=n:(Ae.to=n,Fe=Ae),Be.func=null;const h=Xt(Fe.to,e,r,d,Be);let l;P(h)&&!z(h.to)?(Fe=h,l=h.to):l=h;const u=Xt(Fe.from,e,r,d),p=Fe.ease,m=!z(p)&&!z(p.ease),b=m?p.ease:p||k,x=m?p.duration:Xt(Yt(Fe.duration,t>1?Xt($,e,r,d)/t:$),e,r,d),T=Xt(Yt(Fe.delay,v?0:C),e,r,d),w=Xt(Yt(Fe.composition,B),e,r,d),S=R(w)?w:i[w],L=Fe.modifier||E,N=!z(u),F=!z(l),Y=O(l),X=Y||N&&F,W=g?_+T:T,V=lt(A+W,12);I||!N&&!Y||(I=1);let H=g;if(S!==i.none){f||(f=Zt(e,a));let t=f._head;for(;t&&!t._isOverridden&&t._absoluteStartTime<=V;)if(H=t,t=t._nextRep,t&&t._absoluteStartTime>=V)for(;t;)Kt(t),t=t._nextRep}if(X?(qt(Y?Xt(l[0],e,r,d):u,Ce),qt(Y?Xt(l[1],e,r,d,Be):l,Ee),0===Ce.t&&(H?1===H._valueType&&(Ce.t=1,Ce.u=H._unit):(qt(Ht(e,a,o,D),jt),1===jt.t&&(Ce.t=1,Ce.u=jt.u)))):(F?qt(l,Ee):g?Qt(g,Ee):qt(s&&H&&H.parent.parent===s?H._value:Ht(e,a,o,D),Ee),N?qt(u,Ce):g?Qt(g,Ce):qt(s&&H&&H.parent.parent===s?H._value:Ht(e,a,o,D),Ce)),Ce.o&&(Ce.n=Ut(H?H._toNumber:qt(Ht(e,a,o,D),jt).n,Ce.n,Ce.o)),Ee.o&&(Ee.n=Ut(Ce.n,Ee.n,Ee.o)),Ce.t!==Ee.t)if(3===Ce.t||3===Ee.t){const t=3===Ce.t?Ce:Ee,e=3===Ce.t?Ee:Ce;e.t=3,e.s=gt(t.s),e.d=t.d.map((()=>e.n))}else if(1===Ce.t||1===Ee.t){const t=1===Ce.t?Ce:Ee,e=1===Ce.t?Ee:Ce;e.t=1,e.u=t.u}else if(2===Ce.t||2===Ee.t){const t=2===Ce.t?Ce:Ee,e=2===Ce.t?Ee:Ce;e.t=2,e.s=t.s,e.d=[0,0,0,1]}if(Ce.u!==Ee.u){let t=Ee.u?Ce:Ee;t=ke(e,t,Ee.u?Ee.u:Ce.u,!1)}if(Ee.d&&Ce.d&&Ee.d.length!==Ce.d.length){const t=Ce.d.length>Ee.d.length?Ce:Ee,e=t===Ce?Ee:Ce;e.d=t.d.map(((t,s)=>z(e.d[s])?0:e.d[s])),e.s=gt(t.s)}const U=lt(+x||c,12),q={parent:this,id:Oe++,property:a,target:e,_value:null,_func:Be.func,_ease:be(b),_fromNumbers:gt(Ce.d),_toNumbers:gt(Ee.d),_strings:gt(Ee.s),_fromNumber:Ce.n,_toNumber:Ee.n,_numbers:gt(Ce.d),_number:Ce.n,_unit:Ee.u,_modifier:L,_currentTime:0,_startTime:W,_delay:+T,_updateDuration:U,_changeDuration:U,_absoluteStartTime:V,_tweenType:o,_valueType:Ee.t,_composition:S,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};S!==i.none&&te(q,f),isNaN(y)&&(y=q._startTime),_=lt(W+U,12),g=q,M++,bt(this,q)}(isNaN(F)||y<F)&&(F=y),(isNaN(N)||_>N)&&(N=_),3===o&&(u=M-v,m=M)}if(!isNaN(u)){let t=0;_t(this,(e=>{t>=u&&t<m&&(e._renderTransforms=1,e._composition===i.blend&&_t(kt.animation,(t=>{t.id===e.id&&(t._renderTransforms=1)}))),t++}))}}l||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation."),F?(_t(this,(t=>{t._startTime-t._delay||(t._delay-=F),t._startTime-=F})),N-=F):F=0,N||(N=c,this.iterationCount=0),this.targets=h,this.duration=N===c?c:mt((N+this._loopDelay)*this.iterationCount-this._loopDelay)||c,this.onRender=b||x.onRender,this._ease=w,this._delay=F,this.iterationDuration=N,this._inlineStyles=D,!this._autoplay&&I&&this.onRender(this)}stretch(t){const e=this.duration;if(e===ft(t))return this;const s=t/e;return _t(this,(t=>{t._updateDuration=ft(t._updateDuration*s),t._changeDuration=ft(t._changeDuration*s),t._currentTime*=s,t._startTime*=s,t._absoluteStartTime*=s})),super.stretch(t)}refresh(){return _t(this,(t=>{const e=t._func;if(e){const s=Ht(t.target,t.property,t._tweenType);qt(s,jt),qt(e(),Ee),t._fromNumbers=gt(jt.d),t._fromNumber=jt.n,t._toNumbers=gt(Ee.d),t._strings=gt(Ee.s),t._toNumber=Ee.o?Ut(jt.n,Ee.n,Ee.o):Ee.n}})),this}revert(){return super.revert(),$e(this)}then(t){return super.then(t)}}const Re=(t,e=100)=>{const s=[];for(let i=0;i<=e;i++)s.push(t(i/e));return`linear(${s.join(", ")})`},Me={in:"ease-in",out:"ease-out",inOut:"ease-in-out"},Ie=(()=>{const t={};for(let e in ge)t[e]=t=>ge[e](me(t));return t})(),ze=t=>{let e=Me[t];if(e)return e;if(e="linear",M(t)){if(N(t,"linear")||N(t,"cubic-")||N(t,"steps")||N(t,"ease"))e=t;else if(N(t,"cubicB"))e=A(t);else{const s=ye(t,Ie,Me);I(s)&&(e=s===oe?"linear":Re(s))}Me[t]=e}else if(I(t)){const s=Re(t);s&&(e=s)}else t.ease&&(e=Re(t.ease));return e},Ye=["x","y","z"],Xe=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",...Ye],We=(()=>[...Ye,...f.filter((t=>["X","Y","Z"].some((e=>t.endsWith(e)))))])();let Ve=null;const He={_head:null,_tail:null},Ue=(t,e,s)=>{let i=He._head;for(;i;){const r=i._next,n=i.$el===t,o=!e||i.property===e,a=!s||i.parent===s;if(n&&o&&a){const t=i.animation;try{t.commitStyles()}catch{}t.cancel(),vt(He,i);const e=i.parent;e&&(e._completed++,e.animations.length===e._completed&&(e.completed=!0,e.muteCallbacks||(e.paused=!0,e.onComplete(e),e._resolve(e))))}i=r}},qe=(t,e,s,i,r)=>{const n=e.animate(i,r),o=r.delay+ +r.duration*r.iterations;n.playbackRate=t._speed,t.paused&&n.pause(),t.duration<o&&(t.duration=o,t.controlAnimation=n),t.animations.push(n),Ue(e,s),bt(He,{parent:t,animation:n,$el:e,property:s,_next:null,_prev:null});const a=()=>{Ue(e,s,t)};return n.onremove=a,n.onfinish=a,n},Qe=(t,e,s,i,r)=>{let n=Xt(e,s,i,r);return R(n)?Xe.includes(t)||N(t,"translate")?`${n}px`:N(t,"rotate")||N(t,"skew")?`${n}deg`:`${n}`:n},je=(t,e,s,i,r,n)=>{let o="0";const a=z(i)?getComputedStyle(t)[e]:Qe(e,i,t,r,n);return o=z(s)?O(i)?i.map((s=>Qe(e,s,t,r,n))):a:[Qe(e,s,t,r,n),a],o};class Ge{constructor(e,s){B.current&&B.current.register(this),Y(Ve)&&(!t||!z(CSS)&&Object.hasOwnProperty.call(CSS,"registerProperty")?(f.forEach((t=>{const e=N(t,"skew"),s=N(t,"scale"),i=N(t,"rotate"),r=N(t,"translate"),n=i||e,o=n?"<angle>":s?"<number>":r?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:o,inherits:!1,initialValue:r?"0px":n?"0deg":s?"1":"0"})}catch{}})),Ve=!0):Ve=!1);const i=Ft(e),r=i.length;r||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation.");const n=Yt(s.ease,ze(L.defaults.ease)),o=n.ease&&n,h=Yt(s.autoplay,L.defaults.autoplay),l=!(!h||!h.link)&&h,c=s.alternate&&!0===s.alternate,d=s.reversed&&!0===s.reversed,_=Yt(s.loop,L.defaults.loop),v=!0===_||_===1/0?1/0:R(_)?_+1:1,b=c?d?"alternate-reverse":"alternate":d?"reverse":"normal",x=ze(n),T=1===L.timeScale?1:u;this.targets=i,this.animations=[],this.controlAnimation=null,this.onComplete=s.onComplete||y,this.duration=0,this.muteCallbacks=!1,this.completed=!1,this.paused=!h||!1!==l,this.reversed=d,this.autoplay=h,this._speed=Yt(s.playbackRate,L.defaults.playbackRate),this._resolve=y,this._completed=0,this._inlineStyles=i.map((t=>t.getAttribute("style"))),i.forEach(((t,e)=>{const i=t[a],h=We.some((t=>s.hasOwnProperty(t))),l=(o?o.duration:Xt(Yt(s.duration,L.defaults.duration),t,e,r))*T,c=Xt(Yt(s.delay,L.defaults.delay),t,e,r)*T,d=Yt(s.composition,"replace");for(let o in s){if(!U(o))continue;const a={},u={iterations:v,direction:b,fill:"forwards",easing:x,duration:l,delay:c,composite:d},p=s[o],g=!!h&&(f.includes(o)?o:m.get(o));let y;if(P(p)){const s=p,h=Yt(s.ease,n),m=h.ease&&h,f=s.to,_=s.from;if(u.duration=(m?m.duration:Xt(Yt(s.duration,l),t,e,r))*T,u.delay=Xt(Yt(s.delay,c),t,e,r)*T,u.composite=Yt(s.composition,d),u.easing=ze(h),y=je(t,o,_,f,e,r),g?(a[`--${g}`]=y,i[g]=y):a[o]=je(t,o,_,f,e,r),qe(this,t,o,a,u),!z(_))if(g){const e=`--${g}`;t.style.setProperty(e,a[e][0])}else t.style[o]=a[o][0]}else y=O(p)?p.map((s=>Qe(o,s,t,e,r))):Qe(o,p,t,e,r),g?(a[`--${g}`]=y,i[g]=y):a[o]=y,qe(this,t,o,a,u)}if(h){let e=p;for(let t in i)e+=`${g[t]}var(--${t})) `;t.style.transform=e}})),l&&this.autoplay.link(this)}forEach(t){const e=M(t)?e=>e[t]():t;return this.animations.forEach(e),this}get speed(){return this._speed}set speed(t){this._speed=+t,this.forEach((e=>e.playbackRate=t))}get currentTime(){const t=this.controlAnimation,e=L.timeScale;return this.completed?this.duration:t?+t.currentTime*(1===e?1:e):0}set currentTime(t){const e=t*(1===L.timeScale?1:u);this.forEach((t=>{e>=this.duration&&t.play(),t.currentTime=e}))}get progress(){return this.currentTime/this.duration}set progress(t){this.forEach((e=>e.currentTime=t*this.duration||0))}resume(){return this.paused?(this.paused=!1,this.forEach("play")):this}pause(){return this.paused?this:(this.paused=!0,this.forEach("pause"))}alternate(){return this.reversed=!this.reversed,this.forEach("reverse"),this.paused&&this.forEach("pause"),this}play(){return this.reversed&&this.alternate(),this.resume()}reverse(){return this.reversed||this.alternate(),this.resume()}seek(t,e=!1){return e&&(this.muteCallbacks=!0),t<this.duration&&(this.completed=!1),this.currentTime=t,this.muteCallbacks=!1,this.paused&&this.pause(),this}restart(){return this.completed=!1,this.seek(0,!0).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){return this.forEach("cancel"),this.pause()}revert(){return this.cancel(),this.targets.forEach(((t,e)=>t.setAttribute("style",this._inlineStyles[e]))),this}then(t=y){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=y};return new Promise((t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this)))}}const Ze={animate:(t,e)=>new Ge(t,e),convertEase:Re},Je=(t=y)=>new ne({duration:1*L.timeScale,onComplete:t},null,0).resume();function Ke(t,e,s){const i=Ft(t);if(!i.length)return;const[r]=i,n=Wt(r,e),o=Te(e,r,n);let a=Ht(r,o);if(z(s))return a;if(qt(a,jt),0===jt.t||1===jt.t){if(!1===s)return jt.n;{const t=ke(r,jt,s,!1);return`${lt(t.n,L.precision)}${t.u}`}}}const ts=(t,e)=>{if(!z(e))return e.duration=c,e.composition=Yt(e.composition,i.none),new Pe(t,e,null,0,!0).resume()},es=(t,e,s)=>{let i=!1;return _t(e,(r=>{const n=r.target;if(t.includes(n)){const t=r.property,o=r._tweenType,a=Te(s,n,o);(!a||a&&a===t)&&(r.parent._tail===r&&3===r._tweenType&&r._prev&&3===r._prev._tweenType&&(r._prev._renderTransforms=1),vt(e,r),ee(r),i=!0)}}),!0),i},ss=(t,e,s)=>{const i=Nt(t),r=e||Bt,n=e&&e.controlAnimation&&e;for(let t=0,e=i.length;t<e;t++){const e=i[t];Ue(e,s,n)}let o;if(r._hasChildren){let e=0;_t(r,(n=>{if(!n._hasChildren)if(o=es(i,n,s),o&&!n._head)n.cancel(),vt(r,n);else{const t=n._offset+n._delay+n.duration;t>e&&(e=t)}n._head?ss(t,n,s):n._hasChildren=!1}),!0),z(r.iterationDuration)||(r.iterationDuration=e)}else o=es(i,r,s);return o&&!r._head&&(r._hasChildren=!1,r.cancel&&r.cancel()),i},is=(t,e,s,i,r)=>i+(t-e)/(s-e)*(r-i),rs=(t,e,s,i)=>{let r=u/L.defaults.frameRate;if(!1!==i){const t=i||Bt._hasChildren&&Bt;t&&t.deltaTime&&(r=t.deltaTime)}const n=1-Math.exp(-s*r*.1);return s?1===s?e:(1-n)*t+n*e:t},ns=t=>(...e)=>{const s=t(...e);return new Proxy(y,{apply:(t,e,[i])=>s(i),get:(t,e)=>ns(((...t)=>{const i=as[e](...t);return t=>i(s(t))}))})},os=(t,e=0)=>(...s)=>(s.length<t.length?ns(((t,e=0)=>(...s)=>e?e=>t(...s,e):e=>t(e,...s))(t,e)):t)(...s),as={$:Ft,get:Ke,set:ts,remove:ss,cleanInlineStyles:$e,random:ut,randomPick:t=>t[ut(0,t.length-1)],shuffle:pt,lerp:rs,sync:Je,keepTime:xt,clamp:os(at),round:os(lt),snap:os(ct),wrap:os(((t,e,s)=>((t-e)%(s-e)+(s-e))%(s-e)+e)),interpolate:os(dt,1),mapRange:os(is),roundPad:os(((t,e)=>(+t).toFixed(e))),padStart:os(((t,e,s)=>`${t}`.padStart(e,s))),padEnd:os(((t,e,s)=>`${t}`.padEnd(e,s))),degToRad:os((t=>t*nt/180)),radToDeg:os((t=>180*t/nt))},hs=(t,e)=>{let s=t.iterationDuration;if(s===c&&(s=0),z(e))return s;if(R(+e))return+e;const i=e,r=t?t.labels:null,n=!Y(r),o=((t,e)=>{if(N(e,"<")){const s="<"===e[1],i=t._tail,r=i?i._offset+i._delay:0;return s?r:r+i.duration}})(t,i),a=!z(o),h=C.exec(i);if(h){const t=h[0],e=i.split(t),l=n&&e[0]?r[e[0]]:s,c=a?o:n?l:s,d=+e[1];return Ut(c,d,t[0])}return a?o:n?z(r[i])?s:r[i]:s};function ls(t,e,s,i,r,n){const o=R(t.duration)&&t.duration<=c?s-c:s;St(e,o,1,1,1);const a=i?new Pe(i,t,e,o,!1,r,n):new ne(t,e,o);return a.init(1),bt(e,a),_t(e,(t=>{const s=t._offset+t._delay+t.duration;s>e.iterationDuration&&(e.iterationDuration=s)})),e.duration=function(t){return mt((t.iterationDuration+t._loopDelay)*t.iterationCount-t._loopDelay)||c}(e),e}class cs extends ne{constructor(t={}){super(t,null,0),this.duration=0,this.labels={};const e=t.defaults,s=L.defaults;this.defaults=e?yt(e,s):s,this.onRender=t.onRender||s.onRender;const i=Yt(t.playbackEase,s.playbackEase);this._ease=i?be(i):null,this.iterationDuration=0}add(t,e,s){const i=P(e),r=P(t);if(i||r){if(this._hasChildren=!0,i){const i=e;if(I(s)){const e=s,r=Nt(t),n=this.duration,o=this.iterationDuration,a=i.id;let h=0;const l=r.length;r.forEach((t=>{const s={...i};this.duration=n,this.iterationDuration=o,z(a)||(s.id=a+"-"+h),ls(s,this,hs(this,e(t,h,l,this)),t,h,l),h++}))}else ls(i,this,hs(this,s),t)}else ls(t,this,hs(this,e));return this.init(1)}}sync(t,e){if(z(t)||t&&z(t.pause))return this;t.pause();const s=+(t.effect?t.effect.getTiming().duration:t.duration);return this.add(t,{currentTime:[0,s],duration:s,ease:"linear"},e)}set(t,e,s){return z(e)?this:(e.duration=c,e.composition=i.replace,this.add(t,e,s))}call(t,e){return z(t)||t&&!I(t)?this:this.add({duration:0,onComplete:()=>t(this)},e)}label(t,e){return z(t)||t&&!M(t)||(this.labels[t]=hs(this,e)),this}remove(t,e){return ss(t,this,e),this}stretch(t){const e=this.duration;if(e===ft(t))return this;const s=t/e,i=this.labels;_t(this,(t=>t.stretch(t.duration*s)));for(let t in i)i[t]*=s;return super.stretch(t)}refresh(){return _t(this,(t=>{t.refresh&&t.refresh()})),this}revert(){return super.revert(),_t(this,(t=>t.revert),!0),$e(this)}then(t){return super.then(t)}}class ds{constructor(t,e){B.current&&B.current.register(this);const s=()=>{if(this.callbacks.completed)return;let t=!0;for(let e in this.animations)if(!this.animations[e].paused&&t){t=!1;break}t&&this.callbacks.complete()},r={onBegin:()=>{this.callbacks.completed&&this.callbacks.reset(),this.callbacks.play()},onComplete:s,onPause:s},n={v:1,autoplay:!1},o={};if(this.targets=[],this.animations={},this.callbacks=null,!z(t)&&!z(e)){for(let t in e){const s=e[t];U(t)?o[t]=s:N(t,"on")?n[t]=s:r[t]=s}this.callbacks=new Pe({v:0},n);for(let e in o){const s=o[e],n=P(s);let a={},h="+=0";if(n){const t=s.unit;M(t)&&(h+=t)}else a.duration=s;a[e]=n?yt({to:h},s):h;const l=yt(r,a);l.composition=i.replace,l.autoplay=!1;const c=this.animations[e]=new Pe(t,l,null,0,!1).init();this.targets.length||this.targets.push(...c.targets),this[e]=(t,e,s)=>{const i=c._head;if(z(t)&&i){const t=i._numbers;return t&&t.length?t:i._modifier(i._number)}return _t(c,(e=>{if(O(t))for(let s=0,i=t.length;s<i;s++)z(e._numbers[s])||(e._fromNumbers[s]=e._modifier(e._numbers[s]),e._toNumbers[s]=t[s]);else e._fromNumber=e._modifier(e._number),e._toNumber=t;z(s)||(e._ease=be(s)),e._currentTime=0})),z(e)||c.stretch(e),c.reset(1).resume(),this}}}}revert(){for(let t in this.animations)this[t]=y,this.animations[t].revert();return this.animations={},this.targets.length=0,this.callbacks&&this.callbacks.revert(),this}}const us=10*u;class ps{constructor(t={}){this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/u,this.maxIterations=this.maxDuration/this.timeStep/u,this.m=at(Yt(t.mass,1),0,us),this.s=at(Yt(t.stiffness,100),1,us),this.d=at(Yt(t.damping,10),.1,us),this.v=at(Yt(t.velocity,0),-1e4,us),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.solverDuration=0,this.duration=0,this.compute(),this.ease=t=>0===t||1===t?t:this.solve(t*this.solverDuration)}solve(t){const{zeta:e,w0:s,wd:i,b:r}=this;let n=t;return n=e<1?K(-n*e*s)*(1*Z(i*n)+r*G(i*n)):(1+r*n)*K(-n*s),1-n}compute(){const{maxRestSteps:t,maxIterations:e,restThreshold:s,timeStep:i,m:r,d:n,s:o,v:a}=this,h=this.w0=at(j(o/r),c,u),l=this.zeta=n/(2*j(o*r)),d=this.wd=l<1?h*j(1-l*l):0;this.b=l<1?(l*h-a)/d:-a+h;let p=0,m=0,f=0;for(;m<t&&f<e;)J(1-this.solve(p))<s?m++:m=0,this.solverDuration=p,p+=i,f++;this.duration=lt(this.solverDuration*u,0)*L.timeScale}get mass(){return this.m}set mass(t){this.m=at(Yt(t,1),0,us),this.compute()}get stiffness(){return this.s}set stiffness(t){this.s=at(Yt(t,100),1,us),this.compute()}get damping(){return this.d}set damping(t){this.d=at(Yt(t,10),.1,us),this.compute()}get velocity(){return this.v}set velocity(t){this.v=at(Yt(t,0),-1e4,us),this.compute()}}const ms=t=>new ps(t),fs=t=>{t.cancelable&&t.preventDefault()};class gs{constructor(t){this.el=t,this.zIndex=0,this.parentElement=null,this.classList={add:y,remove:y}}get x(){return this.el.x||0}set x(t){this.el.x=t}get y(){return this.el.y||0}set y(t){this.el.y=t}get width(){return this.el.width||0}set width(t){this.el.width=t}get height(){return this.el.height||0}set height(t){this.el.height=t}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class ys{constructor(t){this.$el=t,this.inlineTransforms=[],this.point=new DOMPoint,this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(t,e){return this.point.x=t,this.point.y=e,this.point.matrixTransform(this.inversedMatrix)}traverseUp(t){let e=this.$el.parentElement,i=0;for(;e&&e!==s;)t(e,i),e=e.parentElement,i++}getMatrix(){const t=new DOMMatrix;return this.traverseUp((e=>{const s=getComputedStyle(e).transform;if(s){const e=new DOMMatrix(s);t.preMultiplySelf(e)}})),t}remove(){this.traverseUp(((t,e)=>{this.inlineTransforms[e]=t.style.transform,t.style.transform="none"}))}revert(){this.traverseUp(((t,e)=>{const s=this.inlineTransforms[e];""===s?t.style.removeProperty("transform"):t.style.transform=s}))}}const _s=(t,e)=>t&&I(t)?t(e):t;let vs=0;class bs{constructor(t,i={}){if(!t)return;B.current&&B.current.register(this);const r=i.x,n=i.y,o=i.trigger,a=i.modifier,h=i.releaseEase,l=h&&be(h),c=!z(h)&&!z(h.ease),u=P(r)&&!z(r.mapTo)?r.mapTo:"translateX",p=P(n)&&!z(n.mapTo)?n.mapTo:"translateY",m=_s(i.container,this);this.containerArray=O(m)?m:null,this.$container=m&&!this.containerArray?Nt(m)[0]:s.body,this.useWin=this.$container===s.body,this.$scrollContainer=this.useWin?e:this.$container,this.$target=P(t)?new gs(t):Nt(t)[0],this.$trigger=Nt(o||t)[0],this.fixed="fixed"===Ke(this.$target,"position"),this.isFinePointer=!0,this.containerPadding=[0,0,0,0],this.containerFriction=0,this.releaseContainerFriction=0,this.snapX=0,this.snapY=0,this.scrollSpeed=0,this.scrollThreshold=0,this.dragSpeed=0,this.maxVelocity=0,this.minVelocity=0,this.velocityMultiplier=0,this.cursor=!1,this.releaseXSpring=c?h:ms({mass:Yt(i.releaseMass,1),stiffness:Yt(i.releaseStiffness,80),damping:Yt(i.releaseDamping,20)}),this.releaseYSpring=c?h:ms({mass:Yt(i.releaseMass,1),stiffness:Yt(i.releaseStiffness,80),damping:Yt(i.releaseDamping,20)}),this.releaseEase=l||_e.outQuint,this.hasReleaseSpring=c,this.onGrab=i.onGrab||y,this.onDrag=i.onDrag||y,this.onRelease=i.onRelease||y,this.onUpdate=i.onUpdate||y,this.onSettle=i.onSettle||y,this.onSnap=i.onSnap||y,this.onResize=i.onResize||y,this.onAfterResize=i.onAfterResize||y,this.disabled=[0,0];const f={};if(a&&(f.modifier=a),z(r)||!0===r)f[u]=0;else if(P(r)){const t=r,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[u]=e}else!1===r&&(f[u]=0,this.disabled[0]=1);if(z(n)||!0===n)f[p]=0;else if(P(n)){const t=n,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[p]=e}else!1===n&&(f[p]=0,this.disabled[1]=1);this.animate=new ds(this.$target,f),this.xProp=u,this.yProp=p,this.destX=0,this.destY=0,this.deltaX=0,this.deltaY=0,this.scroll={x:0,y:0},this.coords=[this.x,this.y,0,0],this.snapped=[0,0],this.pointer=[0,0,0,0,0,0,0,0],this.scrollView=[0,0],this.dragArea=[0,0,0,0],this.containerBounds=[-1e12,d,d,-1e12],this.scrollBounds=[0,0,0,0],this.targetBounds=[0,0,0,0],this.window=[0,0],this.velocityStack=[0,0,0],this.velocityStackIndex=0,this.velocityTime=F(),this.velocity=0,this.angle=0,this.cursorStyles=null,this.triggerStyles=null,this.bodyStyles=null,this.targetStyles=null,this.touchActionStyles=null,this.transforms=new ys(this.$target),this.overshootCoords={x:0,y:0},this.overshootTicker=new ne({autoplay:!1,onUpdate:()=>{this.updated=!0,this.manual=!0,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,1),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=!1,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,0),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init(),this.updateTicker=new ne({autoplay:!1,onUpdate:()=>this.update()},null,0).init(),this.contained=!z(m),this.manual=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.enabled=!1,this.initialized=!1,this.activeProp=this.disabled[1]?u:p,this.animate.callbacks.onRender=()=>{const t=this.updated,e=!(this.grabbed&&t)&&this.released,s=this.x,i=this.y,r=s-this.coords[2],n=i-this.coords[3];this.deltaX=r,this.deltaY=n,this.coords[2]=s,this.coords[3]=i,t&&(r||n)&&this.onUpdate(this),e?(this.computeVelocity(r,n),this.angle=rt(n,r)):this.updated=!1},this.animate.callbacks.onComplete=()=>{!this.grabbed&&this.released&&(this.released=!1),this.manual||(this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.onSettle(this))},this.resizeTicker=new ne({autoplay:!1,duration:150*L.timeScale,onComplete:()=>{this.onResize(this),this.refresh(),this.onAfterResize(this)}}).init(),this.parameters=i,this.resizeObserver=new ResizeObserver((()=>{this.initialized?this.resizeTicker.restart():this.initialized=!0})),this.enable(),this.refresh(),this.resizeObserver.observe(this.$container),P(t)||this.resizeObserver.observe(this.$target)}computeVelocity(t,e){const s=this.velocityTime,i=F(),r=i-s;if(r<17)return this.velocity;this.velocityTime=i;const n=this.velocityStack,o=this.velocityMultiplier,a=this.minVelocity,h=this.maxVelocity,l=this.velocityStackIndex;n[l]=lt(at(j(t*t+e*e)/r*o,a,h),5);const c=it(n[0],n[1],n[2]);return this.velocity=c,this.velocityStackIndex=(l+1)%3,c}setX(t,e=!1){if(this.disabled[0])return;const s=lt(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destX=s,this.snapped[0]=ct(s,this.snapX),this.animate[this.xProp](s,0),this.manual=!1,this}setY(t,e=!1){if(this.disabled[1])return;const s=lt(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destY=s,this.snapped[1]=ct(s,this.snapY),this.animate[this.yProp](s,0),this.manual=!1,this}get x(){return lt(this.animate[this.xProp](),L.precision)}set x(t){this.setX(t,!1)}get y(){return lt(this.animate[this.yProp](),L.precision)}set y(t){this.setY(t,!1)}get progressX(){return is(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(t){this.setX(is(t,0,1,this.containerBounds[3],this.containerBounds[1]),!1)}get progressY(){return is(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(t){this.setY(is(t,0,1,this.containerBounds[0],this.containerBounds[2]),!1)}updateScrollCoords(){const t=lt(this.useWin?e.scrollX:this.$container.scrollLeft,0),s=lt(this.useWin?e.scrollY:this.$container.scrollTop,0),[i,r,n,o]=this.containerPadding,a=this.scrollThreshold;this.scroll.x=t,this.scroll.y=s,this.scrollBounds[0]=s-this.targetBounds[0]+i-a,this.scrollBounds[1]=t-this.targetBounds[1]-r+a,this.scrollBounds[2]=s-this.targetBounds[2]-n+a,this.scrollBounds[3]=t-this.targetBounds[3]+o-a}updateBoundingValues(){const t=this.$container;if(!t)return;const i=this.x,r=this.y,n=this.coords[2],o=this.coords[3];this.coords[2]=0,this.coords[3]=0,this.setX(0,!0),this.setY(0,!0),this.transforms.remove();const a=this.window[0]=e.innerWidth,h=this.window[1]=e.innerHeight,l=this.useWin,c=t.scrollWidth,d=t.scrollHeight,u=this.fixed,p=t.getBoundingClientRect(),[m,f,g,y]=this.containerPadding;this.dragArea[0]=l?0:p.left,this.dragArea[1]=l?0:p.top,this.scrollView[0]=l?at(c,a,c):c,this.scrollView[1]=l?at(d,h,d):d,this.updateScrollCoords();const{width:_,height:v,left:b,top:x,right:T,bottom:w}=t.getBoundingClientRect();this.dragArea[2]=lt(l?at(_,a,a):_,0),this.dragArea[3]=lt(l?at(v,h,h):v,0);const S=Ke(t,"overflow"),k="visible"===S,$="hidden"===S;if(this.canScroll=!u&&this.contained&&(t===s.body&&k||!$&&!k)&&(c>this.dragArea[2]+y-f||d>this.dragArea[3]+m-g)&&(!this.containerArray||this.containerArray&&!O(this.containerArray)),this.contained){const e=this.scroll.x,s=this.scroll.y,i=this.canScroll,r=this.$target.getBoundingClientRect(),n=i?l?0:t.scrollLeft:0,o=i?l?0:t.scrollTop:0,c=i?this.scrollView[0]-n-_:0,d=i?this.scrollView[1]-o-v:0;this.targetBounds[0]=lt(r.top+s-(l?0:x),0),this.targetBounds[1]=lt(r.right+e-(l?a:T),0),this.targetBounds[2]=lt(r.bottom+s-(l?h:w),0),this.targetBounds[3]=lt(r.left+e-(l?0:b),0),this.containerArray?(this.containerBounds[0]=this.containerArray[0]+m,this.containerBounds[1]=this.containerArray[1]-f,this.containerBounds[2]=this.containerArray[2]-g,this.containerBounds[3]=this.containerArray[3]+y):(this.containerBounds[0]=-lt(r.top-(u?at(x,0,h):x)+o-m,0),this.containerBounds[1]=-lt(r.right-(u?at(T,0,a):T)-c+f,0),this.containerBounds[2]=-lt(r.bottom-(u?at(w,0,h):w)-d+g,0),this.containerBounds[3]=-lt(r.left-(u?at(b,0,a):b)+n-y,0))}this.transforms.revert(),this.coords[2]=n,this.coords[3]=o,this.setX(i,!0),this.setY(r,!0)}isOutOfBounds(t,e,s){if(!this.contained)return 0;const[i,r,n,o]=t,[a,h]=this.disabled,l=!a&&e<o||!a&&e>r,c=!h&&s<i||!h&&s>n;return l&&!c?1:!l&&c?2:l&&c?3:0}refresh(){const t=this.parameters,i=t.x,r=t.y,n=_s(t.container,this),o=_s(t.containerPadding,this)||0,a=O(o)?o:[o,o,o,o],h=this.x,l=this.y,c=_s(t.cursor,this),d={onHover:"grab",onGrab:"grabbing"};if(c){const{onHover:t,onGrab:e}=c;t&&(d.onHover=t),e&&(d.onGrab=e)}this.containerArray=O(n)?n:null,this.$container=n&&!this.containerArray?Nt(n)[0]:s.body,this.useWin=this.$container===s.body,this.$scrollContainer=this.useWin?e:this.$container,this.isFinePointer=matchMedia("(pointer:fine)").matches,this.containerPadding=Yt(a,[0,0,0,0]),this.containerFriction=at(Yt(_s(t.containerFriction,this),.8),0,1),this.releaseContainerFriction=at(Yt(_s(t.releaseContainerFriction,this),this.containerFriction),0,1),this.snapX=_s(P(i)&&!z(i.snap)?i.snap:t.snap,this),this.snapY=_s(P(r)&&!z(r.snap)?r.snap:t.snap,this),this.scrollSpeed=Yt(_s(t.scrollSpeed,this),1.5),this.scrollThreshold=Yt(_s(t.scrollThreshold,this),20),this.dragSpeed=Yt(_s(t.dragSpeed,this),1),this.minVelocity=Yt(_s(t.minVelocity,this),0),this.maxVelocity=Yt(_s(t.maxVelocity,this),50),this.velocityMultiplier=Yt(_s(t.velocityMultiplier,this),1),this.cursor=!1!==c&&d,this.updateBoundingValues();const[u,p,m,f]=this.containerBounds;this.setX(at(h,f,p),!0),this.setY(at(l,u,m),!0)}update(){if(this.updateScrollCoords(),this.canScroll){const[t,e,s,i]=this.containerPadding,[r,n]=this.scrollView,o=this.dragArea[2],a=this.dragArea[3],h=this.scroll.x,l=this.scroll.y,c=this.$container.scrollWidth,d=this.$container.scrollHeight,u=this.useWin?at(c,this.window[0],c):c,p=this.useWin?at(d,this.window[1],d):d,m=r-u,f=n-p;this.dragged&&m>0&&(this.coords[0]-=m,this.scrollView[0]=u),this.dragged&&f>0&&(this.coords[1]-=f,this.scrollView[1]=p);const g=10*this.scrollSpeed,y=this.scrollThreshold,[_,v]=this.coords,[b,x,T,w]=this.scrollBounds,S=lt(at((v-b+t)/y,-1,0)*g,0),k=lt(at((_-x-e)/y,0,1)*g,0),$=lt(at((v-T-s)/y,0,1)*g,0),C=lt(at((_-w+i)/y,-1,0)*g,0);if(S||$||C||k){const[t,e]=this.disabled;let s=h,i=l;t||(s=lt(at(h+(C||k),0,r-o),0),this.coords[0]-=h-s),e||(i=lt(at(l+(S||$),0,n-a),0),this.coords[1]-=l-i),this.useWin?this.$scrollContainer.scrollBy(-(h-s),-(l-i)):this.$scrollContainer.scrollTo(s,i)}}const[t,e,s,i]=this.containerBounds,[r,n,o,a,h,l]=this.pointer;this.coords[0]+=(r-h)*this.dragSpeed,this.coords[1]+=(n-l)*this.dragSpeed,this.pointer[4]=r,this.pointer[5]=n;const[c,d]=this.coords,[u,p]=this.snapped,m=(1-this.containerFriction)*this.dragSpeed;this.setX(c>e?e+(c-e)*m:c<i?i+(c-i)*m:c,!1),this.setY(d>s?s+(d-s)*m:d<t?t+(d-t)*m:d,!1),this.computeVelocity(r-h,n-l),this.angle=rt(n-a,r-o);const[f,g]=this.snapped;(f!==u&&this.snapX||g!==p&&this.snapY)&&this.onSnap(this)}stop(){this.updateTicker.pause(),this.overshootTicker.pause();for(let t in this.animate.animations)this.animate.animations[t].pause();return ss(this,null,"x"),ss(this,null,"y"),ss(this,null,"progressX"),ss(this,null,"progressY"),ss(this.scroll),ss(this.overshootCoords),this}scrollInView(t,e=0,s=_e.inOutQuad){this.updateScrollCoords();const i=this.destX,r=this.destY,n=this.scroll,o=this.scrollBounds,a=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(o,i,r)){const[h,l,c,u]=o,p=lt(at(r-h,-1e12,0),0),m=lt(at(i-l,0,d),0),f=lt(at(r-c,0,d),0),g=lt(at(i-u,-1e12,0),0);new Pe(n,{x:lt(n.x+(g?g-e:m?m+e:0),0),y:lt(n.y+(p?p-e:f?f+e:0),0),duration:z(t)?350*L.timeScale:t,ease:s,onUpdate:()=>{this.canScroll=!1,this.$scrollContainer.scrollTo(n.x,n.y)}}).init().then((()=>{this.canScroll=a}))}return this}handleHover(){this.isFinePointer&&this.cursor&&!this.cursorStyles&&(this.cursorStyles=ts(this.$trigger,{cursor:this.cursor.onHover}))}animateInView(t,e=0,s=_e.inOutQuad){this.stop(),this.updateBoundingValues();const i=this.x,r=this.y,[n,o,a,h]=this.containerPadding,l=this.scroll.y-this.targetBounds[0]+n+e,c=this.scroll.x-this.targetBounds[1]-o-e,d=this.scroll.y-this.targetBounds[2]-a-e,u=this.scroll.x-this.targetBounds[3]+h+e,p=this.isOutOfBounds([l,c,d,u],i,r);if(p){const[e,n]=this.disabled,o=at(ct(i,this.snapX),u,c),a=at(ct(r,this.snapY),l,d),h=z(t)?350*L.timeScale:t;e||1!==p&&3!==p||this.animate[this.xProp](o,h,s),n||2!==p&&3!==p||this.animate[this.yProp](a,h,s)}return this}handleDown(t){const e=t.target;if(this.grabbed||"range"===e.type)return;t.stopPropagation(),this.grabbed=!0,this.released=!1,this.stop(),this.updateBoundingValues();const i=t.changedTouches,r=i?i[0].clientX:t.clientX,n=i?i[0].clientY:t.clientY,{x:o,y:a}=this.transforms.normalizePoint(r,n),[h,l,c,d]=this.containerBounds,u=(1-this.containerFriction)*this.dragSpeed,p=this.x,m=this.y;this.coords[0]=this.coords[2]=u?p>l?l+(p-l)/u:p<d?d+(p-d)/u:p:p,this.coords[1]=this.coords[3]=u?m>c?c+(m-c)/u:m<h?h+(m-h)/u:m:m,this.pointer[0]=o,this.pointer[1]=a,this.pointer[2]=o,this.pointer[3]=a,this.pointer[4]=o,this.pointer[5]=a,this.pointer[6]=o,this.pointer[7]=a,this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null);const f=Ke(this.$target,"zIndex",!1);vs=(f>vs?f:vs)+1,this.targetStyles=ts(this.$target,{zIndex:vs}),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.isFinePointer&&this.cursor&&(this.bodyStyles=ts(s.body,{cursor:this.cursor.onGrab})),this.scrollInView(100,0,_e.out(3)),this.onGrab(this),s.addEventListener("touchmove",this),s.addEventListener("touchend",this),s.addEventListener("touchcancel",this),s.addEventListener("mousemove",this),s.addEventListener("mouseup",this),s.addEventListener("selectstart",this)}handleMove(t){if(!this.grabbed)return;const e=t.changedTouches,s=e?e[0].clientX:t.clientX,i=e?e[0].clientY:t.clientY,{x:r,y:n}=this.transforms.normalizePoint(s,i),o=r-this.pointer[6],a=n-this.pointer[7];let h=t.target,l=!1,c=!1,d=!1;for(;e&&h&&h!==this.$trigger;){const t=Ke(h,"overflow-y");if("hidden"!==t&&"visible"!==t){const{scrollTop:t,scrollHeight:e,clientHeight:s}=h;if(e>s){d=!0,l=t<=3,c=t>=e-s-3;break}}h=h.parentNode}d&&(!l&&!c||l&&a<0||c&&a>0)?(this.pointer[0]=r,this.pointer[1]=n,this.pointer[2]=r,this.pointer[3]=n,this.pointer[4]=r,this.pointer[5]=n,this.pointer[6]=r,this.pointer[7]=n):(fs(t),this.triggerStyles||(this.triggerStyles=ts(this.$trigger,{pointerEvents:"none"})),this.$trigger.addEventListener("touchstart",fs,{passive:!1}),this.$trigger.addEventListener("touchmove",fs,{passive:!1}),this.$trigger.addEventListener("touchend",fs),(!this.disabled[0]&&J(o)>3||!this.disabled[1]&&J(a)>3)&&(this.updateTicker.resume(),this.pointer[2]=this.pointer[0],this.pointer[3]=this.pointer[1],this.pointer[0]=r,this.pointer[1]=n,this.dragged=!0,this.released=!1,this.onDrag(this)))}handleUp(){if(!this.grabbed)return;this.updateTicker.pause(),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null);const[t,e]=this.disabled,[r,n,o,a,h,l]=this.pointer,[c,d,u,p]=this.containerBounds,[m,f]=this.snapped,g=this.releaseXSpring,y=this.releaseYSpring,_=this.releaseEase,v=this.hasReleaseSpring,b=this.overshootCoords,x=this.x,T=this.y,w=this.computeVelocity(r-h,n-l),S=this.angle=rt(n-a,r-o),k=150*w,$=(1-this.releaseContainerFriction)*this.dragSpeed,C=x+Z(S)*k,E=T+G(S)*k,B=C>d?d+(C-d)*$:C<p?p+(C-p)*$:C,D=E>u?u+(E-u)*$:E<c?c+(E-c)*$:E,A=this.destX=at(lt(ct(B,this.snapX),5),p,d),N=this.destY=at(lt(ct(D,this.snapY),5),c,u),F=this.isOutOfBounds(this.containerBounds,C,E);let O=0,P=0,R=_,M=_,I=0;if(b.x=x,b.y=T,!t){const t=A===d?x>d?-1:1:x<p?-1:1,s=lt(x-A,0);g.velocity=e&&v?s?k*t/J(s):0:w;const{ease:i,duration:r,restDuration:n}=g;O=x===A?0:v?r:r-n*L.timeScale,v&&(R=i),O>I&&(I=O)}if(!e){const e=N===u?T>u?-1:1:T<c?-1:1,s=lt(T-N,0);y.velocity=t&&v?s?k*e/J(s):0:w;const{ease:i,duration:r,restDuration:n}=y;P=T===N?0:v?r:r-n*L.timeScale,v&&(M=i),P>I&&(I=P)}if(!v&&F&&$&&(O||P)){const t=i.blend;new Pe(b,{x:{to:B,duration:.65*O},y:{to:D,duration:.65*P},ease:_,composition:t}).init(),new Pe(b,{x:{to:A,duration:O},y:{to:N,duration:P},ease:_,composition:t}).init(),this.overshootTicker.stretch(it(O,P)).restart()}else t||this.animate[this.xProp](A,O,R),e||this.animate[this.yProp](N,P,M);this.scrollInView(I,this.scrollThreshold,_);let z=!1;A!==m&&(this.snapped[0]=A,this.snapX&&(z=!0)),N!==f&&this.snapY&&(this.snapped[1]=N,this.snapY&&(z=!0)),z&&this.onSnap(this),this.grabbed=!1,this.dragged=!1,this.updated=!0,this.released=!0,this.onRelease(this),this.$trigger.removeEventListener("touchstart",fs),this.$trigger.removeEventListener("touchmove",fs),this.$trigger.removeEventListener("touchend",fs),s.removeEventListener("touchmove",this),s.removeEventListener("touchend",this),s.removeEventListener("touchcancel",this),s.removeEventListener("mousemove",this),s.removeEventListener("mouseup",this),s.removeEventListener("selectstart",this)}reset(){return this.stop(),this.resizeTicker.pause(),this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.setX(0,!0),this.setY(0,!0),this.coords[0]=0,this.coords[1]=0,this.pointer[0]=0,this.pointer[1]=0,this.pointer[2]=0,this.pointer[3]=0,this.pointer[4]=0,this.pointer[5]=0,this.pointer[6]=0,this.pointer[7]=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this}enable(){return this.enabled||(this.enabled=!0,this.$target.classList.remove("is-disabled"),this.touchActionStyles=ts(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"}),this.$trigger.addEventListener("touchstart",this,{passive:!0}),this.$trigger.addEventListener("mousedown",this,{passive:!0}),this.$trigger.addEventListener("mouseenter",this)),this}disable(){return this.enabled=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.touchActionStyles.revert(),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null),this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null),this.$target.classList.add("is-disabled"),this.$trigger.removeEventListener("touchstart",this),this.$trigger.removeEventListener("mousedown",this),this.$trigger.removeEventListener("mouseenter",this),s.removeEventListener("touchmove",this),s.removeEventListener("touchend",this),s.removeEventListener("touchcancel",this),s.removeEventListener("mousemove",this),s.removeEventListener("mouseup",this),s.removeEventListener("selectstart",this),this}revert(){return this.reset(),this.disable(),this.$target.classList.remove("is-disabled"),this.updateTicker.revert(),this.overshootTicker.revert(),this.resizeTicker.revert(),this.animate.revert(),this.resizeObserver.disconnect(),this}handleEvent(t){switch(t.type){case"mousedown":case"touchstart":this.handleDown(t);break;case"mousemove":case"touchmove":this.handleMove(t);break;case"mouseup":case"touchend":case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":fs(t)}}}class xs{constructor(t={}){B.current&&B.current.register(this);const i=t.root;let r=s;i&&(r=i.current||i.nativeElement||Nt(i)[0]||s);const n=t.defaults,o=L.defaults,a=t.mediaQueries;if(this.defaults=n?yt(n,o):o,this.root=r,this.constructors=[],this.revertConstructors=[],this.revertibles=[],this.constructorsOnce=[],this.revertConstructorsOnce=[],this.revertiblesOnce=[],this.once=!1,this.onceIndex=0,this.methods={},this.matches={},this.mediaQueryLists={},this.data={},a)for(let t in a){const s=e.matchMedia(a[t]);this.mediaQueryLists[t]=s,s.addEventListener("change",this)}}register(t){(this.once?this.revertiblesOnce:this.revertibles).push(t)}execute(t){let e=B.current,s=B.root,i=L.defaults;B.current=this,B.root=this.root,L.defaults=this.defaults;const r=this.mediaQueryLists;for(let t in r)this.matches[t]=r[t].matches;const n=t(this);return B.current=e,B.root=s,L.defaults=i,n}refresh(){return this.onceIndex=0,this.execute((()=>{let t=this.revertibles.length,e=this.revertConstructors.length;for(;t--;)this.revertibles[t].revert();for(;e--;)this.revertConstructors[e](this);this.revertibles.length=0,this.revertConstructors.length=0,this.constructors.forEach((t=>{const e=t(this);I(e)&&this.revertConstructors.push(e)}))})),this}add(t,e){if(this.once=!1,I(t)){const e=t;this.constructors.push(e),this.execute((()=>{const t=e(this);I(t)&&this.revertConstructors.push(t)}))}else this.methods[t]=(...t)=>this.execute((()=>e(...t)));return this}addOnce(t){if(this.once=!0,I(t)){const e=this.onceIndex++;if(this.constructorsOnce[e])return this;const s=t;this.constructorsOnce[e]=s,this.execute((()=>{const t=s(this);I(t)&&this.revertConstructorsOnce.push(t)}))}return this}keepTime(t){this.once=!0;const e=this.onceIndex++,s=this.constructorsOnce[e];if(I(s))return s(this);const i=xt(t);let r;return this.constructorsOnce[e]=i,this.execute((()=>{r=i(this)})),r}handleEvent(t){"change"===t.type&&this.refresh()}revert(){const t=this.revertibles,e=this.revertConstructors,s=this.revertiblesOnce,i=this.revertConstructorsOnce,r=this.mediaQueryLists;let n=t.length,o=e.length,a=s.length,h=i.length;for(;n--;)t[n].revert();for(;o--;)e[o](this);for(;a--;)s[a].revert();for(;h--;)i[h](this);for(let t in r)r[t].removeEventListener("change",this);t.length=0,e.length=0,this.constructors.length=0,s.length=0,i.length=0,this.constructorsOnce.length=0,this.onceIndex=0,this.matches={},this.methods={},this.mediaQueryLists={},this.data={}}}const Ts=(t,e)=>t&&I(t)?t(e):t,ws=new Map;class Ss{constructor(t){this.element=t,this.useWin=this.element===s.body,this.winWidth=0,this.winHeight=0,this.width=0,this.height=0,this.left=0,this.top=0,this.zIndex=0,this.scrollX=0,this.scrollY=0,this.prevScrollX=0,this.prevScrollY=0,this.scrollWidth=0,this.scrollHeight=0,this.velocity=0,this.backwardX=!1,this.backwardY=!1,this.scrollTicker=new ne({autoplay:!1,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const t=this.backwardX||this.backwardY;_t(this,(t=>t.handleScroll()),t)},onComplete:()=>this.dataTimer.pause()}).init(),this.dataTimer=new ne({autoplay:!1,frameRate:30,onUpdate:t=>{const e=t.deltaTime,s=this.prevScrollX,i=this.prevScrollY,r=this.scrollX,n=this.scrollY,o=s-r,a=i-n;this.prevScrollX=r,this.prevScrollY=n,o&&(this.backwardX=s>r),a&&(this.backwardY=i>n),this.velocity=lt(e>0?Math.sqrt(o*o+a*a)/e:0,5)}}).init(),this.resizeTicker=new ne({autoplay:!1,duration:250*L.timeScale,onComplete:()=>{this.updateWindowBounds(),this.refreshScrollObservers(),this.handleScroll()}}).init(),this.wakeTicker=new ne({autoplay:!1,duration:500*L.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init(),this._head=null,this._tail=null,this.updateScrollCoords(),this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll(),this.resizeObserver=new ResizeObserver((()=>this.resizeTicker.restart())),this.resizeObserver.observe(this.element),(this.useWin?e:this.element).addEventListener("scroll",this,!1)}updateScrollCoords(){const t=this.useWin,s=this.element;this.scrollX=lt(t?e.scrollX:s.scrollLeft,0),this.scrollY=lt(t?e.scrollY:s.scrollTop,0)}updateWindowBounds(){this.winWidth=e.innerWidth,this.winHeight=(()=>{const t=s.createElement("div");s.body.appendChild(t),t.style.height="100lvh";const e=t.offsetHeight;return s.body.removeChild(t),e})()}updateBounds(){const t=getComputedStyle(this.element),e=this.element;let s,i;if(this.scrollWidth=e.scrollWidth+parseFloat(t.marginLeft)+parseFloat(t.marginRight),this.scrollHeight=e.scrollHeight+parseFloat(t.marginTop)+parseFloat(t.marginBottom),this.updateWindowBounds(),this.useWin)s=this.winWidth,i=this.winHeight;else{const t=e.getBoundingClientRect();s=e.clientWidth,i=e.clientHeight,this.top=t.top,this.left=t.left}this.width=s,this.height=i}refreshScrollObservers(){_t(this,(t=>{t._debug&&t.removeDebug()})),this.updateBounds(),_t(this,(t=>{t.refresh(),t._debug&&t.debug()}))}refresh(){this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll()}handleScroll(){this.updateScrollCoords(),this.wakeTicker.restart()}handleEvent(t){"scroll"===t.type&&this.handleScroll()}revert(){this.scrollTicker.cancel(),this.dataTimer.cancel(),this.resizeTicker.cancel(),this.wakeTicker.cancel(),this.resizeObserver.disconnect(),(this.useWin?e:this.element).removeEventListener("scroll",this),ws.delete(this.element)}}const ks=(t,e,s,i,r)=>{const n="min"===e,o="max"===e,a="top"===e||"left"===e||"start"===e||n?0:"bottom"===e||"right"===e||"end"===e||o?"100%":"center"===e?"50%":e,{n:h,u:l}=qt(a,jt);let c=h;return"%"===l?c=h/100*s:l&&(c=ke(t,jt,"px",!0).n),o&&i<0&&(c+=i),n&&r>0&&(c+=r),c},$s=(t,e,s,i,r)=>{let n;if(M(e)){const o=C.exec(e);if(o){const a=o[0],h=a[0],l=e.split(a),c="min"===l[0],d="max"===l[0],u=ks(t,l[0],s,i,r),p=ks(t,l[1],s,i,r);if(c){const e=Ut(ks(t,"min",s),p,h);n=e<u?u:e}else if(d){const e=Ut(ks(t,"max",s),p,h);n=e>u?u:e}else n=Ut(u,p,h)}else n=ks(t,e,s,i,r)}else n=e;return lt(n,0)},Cs=t=>{let e;const s=t.targets;for(let t=0,i=s.length;t<i;t++){const i=s[t];if(i[n]){e=i;break}}return e};let Es=0;const Bs=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class Ls{constructor(t={}){B.current&&B.current.register(this);const e=Yt(t.sync,"play pause"),i=e?be(e):null,r=e&&("linear"===e||e===oe),n=e&&!(i===oe&&!r),o=e&&(R(e)||!0===e||r),a=e&&M(e)&&!n&&!o,h=a?e.split(" ").map((t=>()=>{const e=this.linked;return e&&e[t]?e[t]():null})):null,l=a&&h.length>2;this.index=Es++,this.id=z(t.id)?this.index:t.id,this.container=(t=>{const e=t&&Nt(t)[0]||s.body;let i=ws.get(e);return i||(i=new Ss(e),ws.set(e,i)),i})(t.container),this.target=null,this.linked=null,this.repeat=null,this.horizontal=null,this.enter=null,this.leave=null,this.sync=n||o||!!h,this.syncEase=n?i:null,this.syncSmooth=o?!0===e||r?1:e:null,this.onSyncEnter=h&&!l&&h[0]?h[0]:y,this.onSyncLeave=h&&!l&&h[1]?h[1]:y,this.onSyncEnterForward=h&&l&&h[0]?h[0]:y,this.onSyncLeaveForward=h&&l&&h[1]?h[1]:y,this.onSyncEnterBackward=h&&l&&h[2]?h[2]:y,this.onSyncLeaveBackward=h&&l&&h[3]?h[3]:y,this.onEnter=t.onEnter||y,this.onLeave=t.onLeave||y,this.onEnterForward=t.onEnterForward||y,this.onLeaveForward=t.onLeaveForward||y,this.onEnterBackward=t.onEnterBackward||y,this.onLeaveBackward=t.onLeaveBackward||y,this.onUpdate=t.onUpdate||y,this.onSyncComplete=t.onSyncComplete||y,this.reverted=!1,this.completed=!1,this.began=!1,this.isInView=!1,this.forceEnter=!1,this.hasEntered=!1,this.offset=0,this.offsetStart=0,this.offsetEnd=0,this.distance=0,this.prevProgress=0,this.thresholds=["start","end","end","start"],this.coords=[0,0,0,0],this.debugStyles=null,this.$debug=null,this._params=t,this._debug=Yt(t.debug,!1),this._next=null,this._prev=null,bt(this.container,this),Je((()=>{if(!this.reverted){if(!this.target){const e=Nt(t.target)[0];this.target=e||s.body,this.refresh()}this._debug&&this.debug()}}))}link(t){if(t&&(t.pause(),this.linked=t,!this._params.target)){let e;z(t.targets)?_t(t,(t=>{t.targets&&!e&&(e=Cs(t))})):e=Cs(t),this.target=e||s.body,this.refresh()}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const t=(this.scroll-this.offsetStart)/this.distance;return t===1/0||isNaN(t)?0:lt(at(t,0,1),6)}refresh(){this.reverted=!1;const t=this._params;return this.repeat=Yt(Ts(t.repeat,this),!0),this.horizontal="x"===Yt(Ts(t.axis,this),"y"),this.enter=Yt(Ts(t.enter,this),"end start"),this.leave=Yt(Ts(t.leave,this),"start end"),this.updateBounds(),this.handleScroll(),this}removeDebug(){return this.$debug&&(this.$debug.parentNode.removeChild(this.$debug),this.$debug=null),this.debugStyles&&(this.debugStyles.revert(),this.$debug=null),this}debug(){this.removeDebug();const t=this.container,e=this.horizontal,i=t.element.querySelector(":scope > .animejs-onscroll-debug"),r=s.createElement("div"),n=s.createElement("div"),o=s.createElement("div"),a=Bs[this.index%Bs.length],h=t.useWin,l=h?t.winWidth:t.width,c=h?t.winHeight:t.height,d=t.scrollWidth,u=t.scrollHeight,p=this.container.width>360?320:260,m=e?0:10,f=e?10:0,g=e?24:p/2,y=e?g:15,_=e?60:g,v=e?_:y,b=e?"repeat-x":"repeat-y",x=t=>e?"0px "+t+"px":t+"px 2px",T=t=>`linear-gradient(${e?90:0}deg, ${t} 2px, transparent 1px)`,w=(t,e,s,i,r)=>`position:${t};left:${e}px;top:${s}px;width:${i}px;height:${r}px;`;r.style.cssText=`${w("absolute",m,f,e?d:p,e?p:u)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${e?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `,n.style.cssText=`${w("sticky",0,0,e?l:g,e?g:c)}`,i||(n.style.cssText+=`background:\n ${T("#FFFF")}${x(g-10)} / 100px 100px ${b},\n ${T("#FFF8")}${x(g-10)} / 10px 10px ${b};\n `),o.style.cssText=`${w("relative",0,0,e?d:g,e?g:u)}`,i||(o.style.cssText+=`background:\n ${T("#FFFF")}${x(0)} / ${e?"100px 10px":"10px 100px"} ${b},\n ${T("#FFF8")}${x(0)} / ${e?"10px 0px":"0px 10px"} ${b};\n `);const S=[" enter: "," leave: "];this.coords.forEach(((t,i)=>{const r=i>1,h=(r?0:this.offset)+t,m=i%2,f=h<v,g=h>(r?e?l:c:e?d:u)-v,b=(r?m&&!f:!m&&!f)||g,x=s.createElement("div"),T=s.createElement("div"),k=e?b?"right":"left":b?"bottom":"top",$=b?(e?_:y)+(r?e?-1:g?0:-2:e?-1:-2):e?1:0;T.innerHTML=`${this.id}${S[m]}${this.thresholds[i]}`,x.style.cssText=`${w("absolute",0,0,_,y)}\n display: flex;\n flex-direction: ${e?"column":"row"};\n justify-content: flex-${r?"start":"end"};\n align-items: flex-${b?"end":"start"};\n border-${k}: 2px solid ${a};\n `,T.style.cssText=`\n overflow: hidden;\n max-width: ${p/2-10}px;\n height: ${y};\n margin-${e?b?"right":"left":b?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${e&&b||!e&&!r?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${m?a:"rgba(0,0,0,.75)"};\n background-color: ${m?"rgba(0,0,0,.65)":a};\n border: 2px solid ${m?a:"transparent"};\n border-${e?b?"top-left":"top-right":b?"top-left":"bottom-left"}-radius: 5px;\n border-${e?b?"bottom-left":"bottom-right":b?"top-right":"bottom-right"}-radius: 5px;\n `,x.appendChild(T);let C=h-$+(e?1:0);x.style[e?"left":"top"]=`${C}px`,(r?n:o).appendChild(x)})),r.appendChild(n),r.appendChild(o),t.element.appendChild(r),i||r.classList.add("animejs-onscroll-debug"),this.$debug=r,"static"===Ke(t.element,"position")&&(this.debugStyles=ts(t.element,{position:"relative "}))}updateBounds(){let t;this._debug&&this.removeDebug();const e=this.target,i=this.container,r=this.horizontal,n=this.linked;let o,a=e;for(n&&(o=n.currentTime,n.seek(0,!0)),a.parentElement;a&&a!==i.element&&a!==s.body;){const e="sticky"===Ke(a,"position")&&ts(a,{position:"static"});a=a.parentElement,e&&(t||(t=[]),t.push(e))}const h=e.getBoundingClientRect(),l=r?h.left+i.scrollX-i.left:h.top+i.scrollY-i.top,c=r?h.width:h.height,d=r?i.width:i.height,u=(r?i.scrollWidth:i.scrollHeight)-d,p=this.enter,m=this.leave;let f="start",g="end",y="end",_="start";if(M(p)){const t=p.split(" ");y=t[0],f=t.length>1?t[1]:f}else if(P(p)){const t=p;z(t.container)||(y=t.container),z(t.target)||(f=t.target)}else R(p)&&(y=p);if(M(m)){const t=m.split(" ");_=t[0],g=t.length>1?t[1]:g}else if(P(m)){const t=m;z(t.container)||(_=t.container),z(t.target)||(g=t.target)}else R(m)&&(_=m);const v=$s(e,f,c),b=$s(e,g,c),x=v+l-d,T=b+l-u,w=$s(e,y,d,x,T),S=$s(e,_,d,x,T),k=v+l-w,$=b+l-S,C=$-k;this.offset=l,this.offsetStart=k,this.offsetEnd=$,this.distance=C<=0?0:C,this.thresholds=[f,g,y,_],this.coords=[v,b,w,S],t&&t.forEach((t=>t.revert())),n&&n.seek(o,!0),this._debug&&this.debug()}handleScroll(){const t=this.linked,e=this.sync,s=this.syncEase,i=this.syncSmooth,r=t&&(s||i),n=this.horizontal,o=this.container,a=this.scroll,h=a<=this.offsetStart,l=a>=this.offsetEnd,c=!h&&!l,d=a===this.offsetStart||a===this.offsetEnd,u=!this.hasEntered&&d,p=this._debug&&this.$debug;let m=!1,f=!1,g=this.progress;if(h&&this.began&&(this.began=!1),g>0&&!this.began&&(this.began=!0),r){const e=t.progress;if(i&&R(i)){if(i<1){const t=e<g&&1===g?1e-4:e>g&&!g?-1e-4:0;g=lt(rs(e,g,dt(.01,.2,i),!1)+t,6)}}else s&&(g=s(g));m=g!==this.prevProgress,f=1===e,m&&!f&&i&&e&&o.wakeTicker.restart()}if(p){const t=n?o.scrollY:o.scrollX;p.style[n?"top":"left"]=t+10+"px"}(c&&!this.isInView||u&&!this.forceEnter&&!this.hasEntered)&&(c&&(this.isInView=!0),this.forceEnter&&this.hasEntered?c&&(this.forceEnter=!1):(p&&c&&(p.style.zIndex=""+this.container.zIndex++),this.onSyncEnter(this),this.onEnter(this),this.backward?(this.onSyncEnterBackward(this),this.onEnterBackward(this)):(this.onSyncEnterForward(this),this.onEnterForward(this)),this.hasEntered=!0,u&&(this.forceEnter=!0))),(c||!c&&this.isInView)&&(m=!0),m&&(r&&t.seek(t.duration*g),this.onUpdate(this)),!c&&this.isInView&&(this.isInView=!1,this.onSyncLeave(this),this.onLeave(this),this.backward?(this.onSyncLeaveBackward(this),this.onLeaveBackward(this)):(this.onSyncLeaveForward(this),this.onLeaveForward(this)),e&&!i&&(f=!0)),g>=1&&this.began&&!this.completed&&(e&&f||!e)&&(e&&this.onSyncComplete(this),this.completed=!0,(!this.repeat&&!t||!this.repeat&&t&&t.completed)&&this.revert()),g<1&&this.completed&&(this.completed=!1),this.prevProgress=g}revert(){if(this.reverted)return;const t=this.container;return vt(t,this),t._head||t.revert(),this._debug&&this.removeDebug(),this.reverted=!0,this}}const Ds="undefined"!=typeof Intl&&Intl.Segmenter,As=/\{value\}/g,Ns=/\{i\}/g,Fs=/(\s+)/,Os=/^\s+$/,Ps="line",Rs="word",Ms="char",Is="data-line";let zs=null,Ys=null,Xs=null;const Ws=t=>t.isWordLike||" "===t.segment||R(+t.segment),Vs=t=>t.setAttribute("aria-hidden","true"),Hs=(t,e)=>[...t.querySelectorAll(`[data-${e}]:not([data-${e}] [data-${e}])`)],Us={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"},qs=t=>{if(!t.childElementCount&&!t.textContent.trim()){const e=t.parentElement;t.remove(),e&&qs(e)}},Qs=(t,e,s)=>{const i=t.getAttribute(Is);(null!==i&&+i!==e||"BR"===t.tagName)&&s.add(t);let r=t.childElementCount;for(;r--;)Qs(t.children[r],e,s);return s},js=(t,e={})=>{let s="";const i=M(e.class)?` class="${e.class}"`:"",r=Yt(e.clone,!1),n=Yt(e.wrap,!1),o=n?!0===n?"clip":n:!!r&&"clip";return n&&(s+=`<span${o?` style="overflow:${o};"`:""}>`),s+=`<span${i}${r?' style="position:relative;"':""} data-${t}="{i}">`,r?(s+="<span>{value}</span>",s+=`<span inert style="position:absolute;top:${"top"===r?"-100%":"bottom"===r?"100%":"0"};left:${"left"===r?"-100%":"right"===r?"100%":"0"};white-space:nowrap;">{value}</span>`):s+="{value}",s+="</span>",n&&(s+="</span>"),s},Gs=(t,e,s,i,r,n,o,a,h)=>{const l=r===Ps,c=r===Ms,d=`_${r}_`,u=I(t)?t(s):t,p=l?"block":"inline-block";Xs.innerHTML=u.replace(As,`<i class="${d}"></i>`).replace(Ns,`${c?h:l?o:a}`);const m=Xs.content,f=m.firstElementChild,g=m.querySelector(`[data-${r}]`)||f,y=m.querySelectorAll(`i.${d}`),_=y.length;if(_){f.style.display=p,g.style.display=p,g.setAttribute(Is,`${o}`),l||(g.setAttribute("data-word",`${a}`),c&&g.setAttribute("data-char",`${h}`));let t=_;for(;t--;){const e=y[t],i=e.parentElement;i.style.display=p,l?i.innerHTML=s.innerHTML:i.replaceChild(s.cloneNode(!0),e)}e.push(g),i.appendChild(m)}else console.warn('The expression "{value}" is missing from the provided template.');return n&&(f.style.outline=`1px dotted ${Us[r]}`),f};class Zs{constructor(e,i={}){zs||(zs=Ds?new Ds([],{granularity:Rs}):{segment:t=>{const e=[],s=t.split(Fs);for(let t=0,i=s.length;t<i;t++){const i=s[t];e.push({segment:i,isWordLike:!Os.test(i)})}return e}}),Ys||(Ys=Ds?new Ds([],{granularity:"grapheme"}):{segment:t=>[...t].map((t=>({segment:t})))}),!Xs&&t&&(Xs=s.createElement("template")),B.current&&B.current.register(this);const{words:r,chars:n,lines:o,accessible:a,includeSpaces:h,debug:l}=i,c=(e=O(e)?e[0]:e)&&e.nodeType?e:(At(e)||[])[0],d=!0===o?{}:o,u=!0===r||z(r)?{}:r,p=!0===n?{}:n;this.debug=Yt(l,!1),this.includeSpaces=Yt(h,!1),this.accessible=Yt(a,!0),this.linesOnly=d&&!u&&!p,this.lineTemplate=P(d)?js(Ps,d):d,this.wordTemplate=P(u)||this.linesOnly?js(Rs,u):u,this.charTemplate=P(p)?js(Ms,p):p,this.$target=c,this.html=c&&c.innerHTML,this.lines=[],this.words=[],this.chars=[],this.effects=[],this.effectsCleanups=[],this.cache=null,this.ready=!1,this.width=0,this.resizeTimeout=null;const m=()=>this.html&&(d||u||p)&&this.split();this.resizeObserver=new ResizeObserver((()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout((()=>{const t=c.offsetWidth;t!==this.width&&(this.width=t,m())}),150)})),this.lineTemplate&&!this.ready?s.fonts.ready.then(m):m(),c?this.resizeObserver.observe(c):console.warn("No Text Splitter target found.")}addEffect(t){if(!I(t))return console.warn("Effect must return a function.");const e=xt(t);return this.effects.push(e),this.ready&&(this.effectsCleanups[this.effects.length-1]=e(this)),this}revert(){return clearTimeout(this.resizeTimeout),this.lines.length=this.words.length=this.chars.length=0,this.resizeObserver.disconnect(),this.effectsCleanups.forEach((t=>I(t)?t(this):t.revert&&t.revert())),this.$target.innerHTML=this.html,this}splitNode(t){const e=this.wordTemplate,i=this.charTemplate,r=this.includeSpaces,n=this.debug,o=t.nodeType;if(3===o){const o=t.nodeValue;if(o.trim()){const a=[],h=this.words,l=this.chars,c=zs.segment(o),d=s.createDocumentFragment();let u=null;for(const t of c){const e=t.segment,s=Ws(t);if(!u||s&&u&&Ws(u))a.push(e);else{const t=a.length-1;a[t].includes(" ")||e.includes(" ")?a.push(e):a[t]+=e}u=t}for(let t=0,o=a.length;t<o;t++){const o=a[t];if(o.trim()){const c=a[t+1],u=r&&c&&!c.trim(),p=o,m=i?Ys.segment(p):null,f=i?s.createDocumentFragment():s.createTextNode(u?o+" ":o);if(i){const t=[...m];for(let e=0,r=t.length;e<r;e++){const o=t[e],a=e===r-1&&u?o.segment+" ":o.segment,c=s.createTextNode(a);Gs(i,l,c,f,Ms,n,-1,h.length,l.length)}}e?Gs(e,h,f,d,Rs,n,-1,h.length,l.length):i?d.appendChild(f):d.appendChild(s.createTextNode(o)),u&&t++}else{if(t&&r)continue;d.appendChild(s.createTextNode(o))}}t.parentNode.replaceChild(d,t)}}else if(1===o){const e=[...t.childNodes];for(let t=0,s=e.length;t<s;t++)this.splitNode(e[t])}}split(t=!1){const e=this.$target,i=!!this.cache&&!t,r=this.lineTemplate,n=this.wordTemplate,o=this.charTemplate,a="loading"!==s.fonts.status,h=r&&a;this.ready=!r||a,(h||t)&&this.effectsCleanups.forEach((t=>I(t)&&t(this))),i||(t&&(e.innerHTML=this.html,this.words.length=this.chars.length=0),this.splitNode(e),this.cache=e.innerHTML),h&&(i&&(e.innerHTML=this.cache),this.lines.length=0,n&&(this.words=Hs(e,Rs))),o&&(h||n)&&(this.chars=Hs(e,Ms));const l=this.words.length?this.words:this.chars;let c,d=0;for(let t=0,e=l.length;t<e;t++){const e=l[t],{top:s,height:i}=e.getBoundingClientRect();c&&s-c>.5*i&&d++,e.setAttribute(Is,`${d}`);const r=e.querySelectorAll(`[${Is}]`);let n=r.length;for(;n--;)r[n].setAttribute(Is,`${d}`);c=s}if(h){const t=s.createDocumentFragment(),i=new Set,a=[];for(let t=0;t<d+1;t++){const s=e.cloneNode(!0);Qs(s,t,new Set).forEach((t=>{const e=t.parentElement;e&&i.add(e),t.remove()})),a.push(s)}i.forEach(qs);for(let e=0,s=a.length;e<s;e++)Gs(r,this.lines,a[e],t,Ps,this.debug,e);e.innerHTML="",e.appendChild(t),n&&(this.words=Hs(e,Rs)),o&&(this.chars=Hs(e,Ms))}if(this.linesOnly){const t=this.words;let e=t.length;for(;e--;){const s=t[e];s.replaceWith(s.textContent)}t.length=0}if(this.accessible&&(h||!i)){const t=s.createElement("span");t.style.cssText="position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;",t.innerHTML=this.html,e.insertBefore(t,e.firstChild),this.lines.forEach(Vs),this.words.forEach(Vs),this.chars.forEach(Vs)}return this.width=e.offsetWidth,(h||t)&&this.effects.forEach(((t,e)=>this.effectsCleanups[e]=t(this))),this}refresh(){this.split(!0)}}const Js={split:(t,e)=>new Zs(t,e)};exports.Animatable=ds,exports.Draggable=bs,exports.JSAnimation=Pe,exports.Scope=xs,exports.ScrollObserver=Ls,exports.Spring=ps,exports.TextSplitter=Zs,exports.Timeline=cs,exports.Timer=ne,exports.WAAPIAnimation=Ge,exports.animate=(t,e)=>new Pe(t,e,null,0,!1).init(),exports.createAnimatable=(t,e)=>new ds(t,e),exports.createDraggable=(t,e)=>new bs(t,e),exports.createScope=t=>new xs(t),exports.createSpring=ms,exports.createTimeline=t=>new cs(t).init(),exports.createTimer=t=>new ne(t,null,0).init(),exports.eases=_e,exports.engine=Bt,exports.onScroll=(t={})=>new Ls(t),exports.scrollContainers=ws,exports.stagger=(t,e={})=>{let s=[],i=0;const r=e.from,n=e.reversed,o=e.ease,a=!z(o),h=a&&!z(o.ease)?o.ease:a?be(o):null,l=e.grid,c=e.axis,d=e.total,u=z(r)||0===r||"first"===r,m="center"===r,f="last"===r,g="random"===r,y=O(t),_=e.use,v=q(y?t[0]:t),b=y?q(t[1]):0,x=S.exec((y?t[1]:t)+p),T=e.start||0+(y?v:0);let w=u?0:R(r)?r:0;return(t,r,o,a)=>{const[u]=Ft(t),p=z(d)?o:d,S=!z(_)&&(I(_)?_(u,r,p):Ht(u,_)),k=R(S)||M(S)&&R(+S)?+S:r;if(m&&(w=(p-1)/2),f&&(w=p-1),!s.length){for(let t=0;t<p;t++){if(l){const e=m?(l[0]-1)/2:w%l[0],i=m?(l[1]-1)/2:et(w/l[0]),r=e-t%l[0],n=i-et(t/l[0]);let o=j(r*r+n*n);"x"===c&&(o=-r),"y"===c&&(o=-n),s.push(o)}else s.push(J(w-t));i=it(...s)}h&&(s=s.map((t=>h(t/i)*i))),n&&(s=s.map((t=>c?t<0?-1*t:-t:J(i-t)))),g&&(s=pt(s))}const $=y?(b-v)/i:v;let C=(a?hs(a,z(e.start)?a.iterationDuration:T):T)+($*lt(s[k],2)||0);return e.modifier&&(C=e.modifier(C)),x&&(C=`${C}${x[2]}`),C}},exports.svg=It,exports.text=Js,exports.utils=as,exports.waapi=Ze;
diff --git a/lib/anime.umd.js b/lib/anime.umd.js
deleted file mode 100644
index f97baac7..00000000
--- a/lib/anime.umd.js
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * anime.js - UMD
- * @version v4.1.3
- * @author Julian Garnier
- * @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
- */
-(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):(global=typeof globalThis!=="undefined"?globalThis:global||self,factory(global.anime={}))})(this,(function(exports){"use strict";const isBrowser=typeof window!=="undefined";const win=isBrowser?window:null;const doc=isBrowser?document:null;const tweenTypes={OBJECT:0,ATTRIBUTE:1,CSS:2,TRANSFORM:3,CSS_VAR:4};const valueTypes={NUMBER:0,UNIT:1,COLOR:2,COMPLEX:3};const tickModes={NONE:0,AUTO:1,FORCE:2};const compositionTypes={replace:0,none:1,blend:2};const isRegisteredTargetSymbol=Symbol();const isDomSymbol=Symbol();const isSvgSymbol=Symbol();const transformsSymbol=Symbol();const morphPointsSymbol=Symbol();const proxyTargetSymbol=Symbol();const minValue=1e-11;const maxValue=1e12;const K=1e3;const maxFps=120;const emptyString="";const shortTransforms=(()=>{const map=new Map;map.set("x","translateX");map.set("y","translateY");map.set("z","translateZ");return map})();const validTransforms=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"];const transformsFragmentStrings=validTransforms.reduce(((a,v)=>({...a,[v]:v+"("})),{});const noop=()=>{};const hexTestRgx=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;const rgbExecRgx=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;const rgbaExecRgx=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;const hslExecRgx=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;const hslaExecRgx=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;const digitWithExponentRgx=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;const unitsExecRgx=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;const lowerCaseRgx=/([a-z])([A-Z])/g;const transformsExecRgx=/(\w+)(\([^)]+\)+)/g;const relativeValuesExecRgx=/(\*=|\+=|-=)/;const defaults={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:maxFps,loop:0,reversed:false,alternate:false,autoplay:true,duration:K,delay:0,loopDelay:0,ease:"out(2)",composition:compositionTypes.replace,modifier:v=>v,onBegin:noop,onBeforeUpdate:noop,onUpdate:noop,onLoop:noop,onPause:noop,onComplete:noop,onRender:noop};const scope={current:null,root:doc};const globals={defaults:defaults,precision:4,timeScale:1,tickThreshold:200};const globalVersions={version:"4.1.3",engine:null};if(isBrowser){if(!win.AnimeJS)win.AnimeJS=[];win.AnimeJS.push(globalVersions)}const toLowerCase=str=>str.replace(lowerCaseRgx,"$1-$2").toLowerCase();const stringStartsWith=(str,sub)=>str.indexOf(sub)===0;const now=Date.now;const isArr=Array.isArray;const isObj=a=>a&&a.constructor===Object;const isNum=a=>typeof a==="number"&&!isNaN(a);const isStr=a=>typeof a==="string";const isFnc=a=>typeof a==="function";const isUnd=a=>typeof a==="undefined";const isNil=a=>isUnd(a)||a===null;const isSvg=a=>isBrowser&&a instanceof SVGElement;const isHex=a=>hexTestRgx.test(a);const isRgb=a=>stringStartsWith(a,"rgb");const isHsl=a=>stringStartsWith(a,"hsl");const isCol=a=>isHex(a)||isRgb(a)||isHsl(a);const isKey=a=>!globals.defaults.hasOwnProperty(a);const parseNumber=str=>isStr(str)?parseFloat(str):str;const pow=Math.pow;const sqrt=Math.sqrt;const sin=Math.sin;const cos=Math.cos;const abs=Math.abs;const exp=Math.exp;const ceil=Math.ceil;const floor=Math.floor;const asin=Math.asin;const max=Math.max;const atan2=Math.atan2;const PI=Math.PI;const _round=Math.round;const clamp=(v,min,max)=>v<min?min:v>max?max:v;const powCache={};const round=(v,decimalLength)=>{if(decimalLength<0)return v;if(!decimalLength)return _round(v);let p=powCache[decimalLength];if(!p)p=powCache[decimalLength]=10**decimalLength;return _round(v*p)/p};const snap=(v,increment)=>isArr(increment)?increment.reduce(((closest,cv)=>abs(cv-v)<abs(closest-v)?cv:closest)):increment?_round(v/increment)*increment:v;const interpolate=(start,end,progress)=>start+(end-start)*progress;const random=(min,max,decimalLength)=>{const m=10**(decimalLength||0);return floor((Math.random()*(max-min+1/m)+min)*m)/m};const shuffle=items=>{let m=items.length,t,i;while(m){i=random(0,--m);t=items[m];items[m]=items[i];items[i]=t}return items};const clampInfinity=v=>v===Infinity?maxValue:v===-Infinity?-1e12:v;const normalizeTime=v=>v<=minValue?minValue:clampInfinity(round(v,11));const cloneArray=a=>isArr(a)?[...a]:a;const mergeObjects=(o1,o2)=>{const merged={...o1};for(let p in o2){const o1p=o1[p];merged[p]=isUnd(o1p)?o2[p]:o1p}return merged};const forEachChildren=(parent,callback,reverse,prevProp="_prev",nextProp="_next")=>{let next=parent._head;let adjustedNextProp=nextProp;if(reverse){next=parent._tail;adjustedNextProp=prevProp}while(next){const currentNext=next[adjustedNextProp];callback(next);next=currentNext}};const removeChild=(parent,child,prevProp="_prev",nextProp="_next")=>{const prev=child[prevProp];const next=child[nextProp];prev?prev[nextProp]=next:parent._head=next;next?next[prevProp]=prev:parent._tail=prev;child[prevProp]=null;child[nextProp]=null};const addChild=(parent,child,sortMethod,prevProp="_prev",nextProp="_next")=>{let prev=parent._tail;while(prev&&sortMethod&&sortMethod(prev,child))prev=prev[prevProp];const next=prev?prev[nextProp]:parent._head;prev?prev[nextProp]=child:parent._head=child;next?next[prevProp]=child:parent._tail=child;child[prevProp]=prev;child[nextProp]=next};const createRefreshable=constructor=>{let tracked;return(...args)=>{let currentIteration,currentIterationProgress,reversed,alternate;if(tracked){currentIteration=tracked.currentIteration;currentIterationProgress=tracked.iterationProgress;reversed=tracked.reversed;alternate=tracked._alternate;tracked.revert()}const cleanup=constructor(...args);if(cleanup&&!isFnc(cleanup)&&cleanup.revert)tracked=cleanup;if(!isUnd(currentIterationProgress)){tracked.currentIteration=currentIteration;tracked.iterationProgress=(alternate?!(currentIteration%2)?reversed:!reversed:reversed)?1-currentIterationProgress:currentIterationProgress}return cleanup||noop}};class Clock{constructor(initTime=0){this.deltaTime=0;this._currentTime=initTime;this._elapsedTime=initTime;this._startTime=initTime;this._lastTime=initTime;this._scheduledTime=0;this._frameDuration=round(K/maxFps,0);this._fps=maxFps;this._speed=1;this._hasChildren=false;this._head=null;this._tail=null}get fps(){return this._fps}set fps(frameRate){const previousFrameDuration=this._frameDuration;const fr=+frameRate;const fps=fr<minValue?minValue:fr;const frameDuration=round(K/fps,0);this._fps=fps;this._frameDuration=frameDuration;this._scheduledTime+=frameDuration-previousFrameDuration}get speed(){return this._speed}set speed(playbackRate){const pbr=+playbackRate;this._speed=pbr<minValue?minValue:pbr}requestTick(time){const scheduledTime=this._scheduledTime;const elapsedTime=this._elapsedTime;this._elapsedTime+=time-elapsedTime;if(elapsedTime<scheduledTime)return tickModes.NONE;const frameDuration=this._frameDuration;const frameDelta=elapsedTime-scheduledTime;this._scheduledTime+=frameDelta<frameDuration?frameDuration:frameDelta;return tickModes.AUTO}computeDeltaTime(time){const delta=time-this._lastTime;this.deltaTime=delta;this._lastTime=time;return delta}}const render=(tickable,time,muteCallbacks,internalRender,tickMode)=>{const parent=tickable.parent;const duration=tickable.duration;const completed=tickable.completed;const iterationDuration=tickable.iterationDuration;const iterationCount=tickable.iterationCount;const _currentIteration=tickable._currentIteration;const _loopDelay=tickable._loopDelay;const _reversed=tickable._reversed;const _alternate=tickable._alternate;const _hasChildren=tickable._hasChildren;const tickableDelay=tickable._delay;const tickablePrevAbsoluteTime=tickable._currentTime;const tickableEndTime=tickableDelay+iterationDuration;const tickableAbsoluteTime=time-tickableDelay;const tickablePrevTime=clamp(tickablePrevAbsoluteTime,-tickableDelay,duration);const tickableCurrentTime=clamp(tickableAbsoluteTime,-tickableDelay,duration);const deltaTime=tickableAbsoluteTime-tickablePrevAbsoluteTime;const isCurrentTimeAboveZero=tickableCurrentTime>0;const isCurrentTimeEqualOrAboveDuration=tickableCurrentTime>=duration;const isSetter=duration<=minValue;const forcedTick=tickMode===tickModes.FORCE;let isOdd=0;let iterationElapsedTime=tickableAbsoluteTime;let hasRendered=0;if(iterationCount>1){const currentIteration=~~(tickableCurrentTime/(iterationDuration+(isCurrentTimeEqualOrAboveDuration?0:_loopDelay)));tickable._currentIteration=clamp(currentIteration,0,iterationCount);if(isCurrentTimeEqualOrAboveDuration)tickable._currentIteration--;isOdd=tickable._currentIteration%2;iterationElapsedTime=tickableCurrentTime%(iterationDuration+_loopDelay)||0}const isReversed=_reversed^(_alternate&&isOdd);const _ease=tickable._ease;let iterationTime=isCurrentTimeEqualOrAboveDuration?isReversed?0:duration:isReversed?iterationDuration-iterationElapsedTime:iterationElapsedTime;if(_ease)iterationTime=iterationDuration*_ease(iterationTime/iterationDuration)||0;const isRunningBackwards=(parent?parent.backwards:tickableAbsoluteTime<tickablePrevAbsoluteTime)?!isReversed:!!isReversed;tickable._currentTime=tickableAbsoluteTime;tickable._iterationTime=iterationTime;tickable.backwards=isRunningBackwards;if(isCurrentTimeAboveZero&&!tickable.began){tickable.began=true;if(!muteCallbacks&&!(parent&&(isRunningBackwards||!parent.began))){tickable.onBegin(tickable)}}else if(tickableAbsoluteTime<=0){tickable.began=false}if(!muteCallbacks&&!_hasChildren&&isCurrentTimeAboveZero&&tickable._currentIteration!==_currentIteration){tickable.onLoop(tickable)}if(forcedTick||tickMode===tickModes.AUTO&&(time>=tickableDelay&&time<=tickableEndTime||time<=tickableDelay&&tickablePrevTime>tickableDelay||time>=tickableEndTime&&tickablePrevTime!==duration)||iterationTime>=tickableEndTime&&tickablePrevTime!==duration||iterationTime<=tickableDelay&&tickablePrevTime>0||time<=tickablePrevTime&&tickablePrevTime===duration&&completed||isCurrentTimeEqualOrAboveDuration&&!completed&&isSetter){if(isCurrentTimeAboveZero){tickable.computeDeltaTime(tickablePrevTime);if(!muteCallbacks)tickable.onBeforeUpdate(tickable)}if(!_hasChildren){const forcedRender=forcedTick||(isRunningBackwards?deltaTime*-1:deltaTime)>=globals.tickThreshold;const absoluteTime=tickable._offset+(parent?parent._offset:0)+tickableDelay+iterationTime;let tween=tickable._head;let tweenTarget;let tweenStyle;let tweenTargetTransforms;let tweenTargetTransformsProperties;let tweenTransformsNeedUpdate=0;while(tween){const tweenComposition=tween._composition;const tweenCurrentTime=tween._currentTime;const tweenChangeDuration=tween._changeDuration;const tweenAbsEndTime=tween._absoluteStartTime+tween._changeDuration;const tweenNextRep=tween._nextRep;const tweenPrevRep=tween._prevRep;const tweenHasComposition=tweenComposition!==compositionTypes.none;if((forcedRender||(tweenCurrentTime!==tweenChangeDuration||absoluteTime<=tweenAbsEndTime+(tweenNextRep?tweenNextRep._delay:0))&&(tweenCurrentTime!==0||absoluteTime>=tween._absoluteStartTime))&&(!tweenHasComposition||!tween._isOverridden&&(!tween._isOverlapped||absoluteTime<=tweenAbsEndTime)&&(!tweenNextRep||(tweenNextRep._isOverridden||absoluteTime<=tweenNextRep._absoluteStartTime))&&(!tweenPrevRep||(tweenPrevRep._isOverridden||absoluteTime>=tweenPrevRep._absoluteStartTime+tweenPrevRep._changeDuration+tween._delay)))){const tweenNewTime=tween._currentTime=clamp(iterationTime-tween._startTime,0,tweenChangeDuration);const tweenProgress=tween._ease(tweenNewTime/tween._updateDuration);const tweenModifier=tween._modifier;const tweenValueType=tween._valueType;const tweenType=tween._tweenType;const tweenIsObject=tweenType===tweenTypes.OBJECT;const tweenIsNumber=tweenValueType===valueTypes.NUMBER;const tweenPrecision=tweenIsNumber&&tweenIsObject||tweenProgress===0||tweenProgress===1?-1:globals.precision;let value;let number;if(tweenIsNumber){value=number=tweenModifier(round(interpolate(tween._fromNumber,tween._toNumber,tweenProgress),tweenPrecision))}else if(tweenValueType===valueTypes.UNIT){number=tweenModifier(round(interpolate(tween._fromNumber,tween._toNumber,tweenProgress),tweenPrecision));value=`${number}${tween._unit}`}else if(tweenValueType===valueTypes.COLOR){const fn=tween._fromNumbers;const tn=tween._toNumbers;const r=round(clamp(tweenModifier(interpolate(fn[0],tn[0],tweenProgress)),0,255),0);const g=round(clamp(tweenModifier(interpolate(fn[1],tn[1],tweenProgress)),0,255),0);const b=round(clamp(tweenModifier(interpolate(fn[2],tn[2],tweenProgress)),0,255),0);const a=clamp(tweenModifier(round(interpolate(fn[3],tn[3],tweenProgress),tweenPrecision)),0,1);value=`rgba(${r},${g},${b},${a})`;if(tweenHasComposition){const ns=tween._numbers;ns[0]=r;ns[1]=g;ns[2]=b;ns[3]=a}}else if(tweenValueType===valueTypes.COMPLEX){value=tween._strings[0];for(let j=0,l=tween._toNumbers.length;j<l;j++){const n=tweenModifier(round(interpolate(tween._fromNumbers[j],tween._toNumbers[j],tweenProgress),tweenPrecision));const s=tween._strings[j+1];value+=`${s?n+s:n}`;if(tweenHasComposition){tween._numbers[j]=n}}}if(tweenHasComposition){tween._number=number}if(!internalRender&&tweenComposition!==compositionTypes.blend){const tweenProperty=tween.property;tweenTarget=tween.target;if(tweenIsObject){tweenTarget[tweenProperty]=value}else if(tweenType===tweenTypes.ATTRIBUTE){tweenTarget.setAttribute(tweenProperty,value)}else{tweenStyle=tweenTarget.style;if(tweenType===tweenTypes.TRANSFORM){if(tweenTarget!==tweenTargetTransforms){tweenTargetTransforms=tweenTarget;tweenTargetTransformsProperties=tweenTarget[transformsSymbol]}tweenTargetTransformsProperties[tweenProperty]=value;tweenTransformsNeedUpdate=1}else if(tweenType===tweenTypes.CSS){tweenStyle[tweenProperty]=value}else if(tweenType===tweenTypes.CSS_VAR){tweenStyle.setProperty(tweenProperty,value)}}if(isCurrentTimeAboveZero)hasRendered=1}else{tween._value=value}}if(tweenTransformsNeedUpdate&&tween._renderTransforms){let str=emptyString;for(let key in tweenTargetTransformsProperties){str+=`${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `}tweenStyle.transform=str;tweenTransformsNeedUpdate=0}tween=tween._next}if(!muteCallbacks&&hasRendered){tickable.onRender(tickable)}}if(!muteCallbacks&&isCurrentTimeAboveZero){tickable.onUpdate(tickable)}}if(parent&&isSetter){if(!muteCallbacks&&(parent.began&&!isRunningBackwards&&tickableAbsoluteTime>=duration&&!completed||isRunningBackwards&&tickableAbsoluteTime<=minValue&&completed)){tickable.onComplete(tickable);tickable.completed=!isRunningBackwards}}else if(isCurrentTimeAboveZero&&isCurrentTimeEqualOrAboveDuration){if(iterationCount===Infinity){tickable._startTime+=tickable.duration}else if(tickable._currentIteration>=iterationCount-1){tickable.paused=true;if(!completed&&!_hasChildren){tickable.completed=true;if(!muteCallbacks&&!(parent&&(isRunningBackwards||!parent.began))){tickable.onComplete(tickable);tickable._resolve(tickable)}}}}else{tickable.completed=false}return hasRendered};const tick=(tickable,time,muteCallbacks,internalRender,tickMode)=>{const _currentIteration=tickable._currentIteration;render(tickable,time,muteCallbacks,internalRender,tickMode);if(tickable._hasChildren){const tl=tickable;const tlIsRunningBackwards=tl.backwards;const tlChildrenTime=internalRender?time:tl._iterationTime;const tlCildrenTickTime=now();let tlChildrenHasRendered=0;let tlChildrenHaveCompleted=true;if(!internalRender&&tl._currentIteration!==_currentIteration){const tlIterationDuration=tl.iterationDuration;forEachChildren(tl,(child=>{if(!tlIsRunningBackwards){if(!child.completed&&!child.backwards&&child._currentTime<child.iterationDuration){render(child,tlIterationDuration,muteCallbacks,1,tickModes.FORCE)}child.began=false;child.completed=false}else{const childDuration=child.duration;const childStartTime=child._offset+child._delay;const childEndTime=childStartTime+childDuration;if(!muteCallbacks&&childDuration<=minValue&&(!childStartTime||childEndTime===tlIterationDuration)){child.onComplete(child)}}}));if(!muteCallbacks)tl.onLoop(tl)}forEachChildren(tl,(child=>{const childTime=round((tlChildrenTime-child._offset)*child._speed,12);const childTickMode=child._fps<tl._fps?child.requestTick(tlCildrenTickTime):tickMode;tlChildrenHasRendered+=render(child,childTime,muteCallbacks,internalRender,childTickMode);if(!child.completed&&tlChildrenHaveCompleted)tlChildrenHaveCompleted=false}),tlIsRunningBackwards);if(!muteCallbacks&&tlChildrenHasRendered)tl.onRender(tl);if((tlChildrenHaveCompleted||tlIsRunningBackwards)&&tl._currentTime>=tl.duration){tl.paused=true;if(!tl.completed){tl.completed=true;if(!muteCallbacks){tl.onComplete(tl);tl._resolve(tl)}}}}};const additive={animation:null,update:noop};const addAdditiveAnimation=lookups=>{let animation=additive.animation;if(!animation){animation={duration:minValue,computeDeltaTime:noop,_offset:0,_delay:0,_head:null,_tail:null};additive.animation=animation;additive.update=()=>{lookups.forEach((propertyAnimation=>{for(let propertyName in propertyAnimation){const tweens=propertyAnimation[propertyName];const lookupTween=tweens._head;if(lookupTween){const valueType=lookupTween._valueType;const additiveValues=valueType===valueTypes.COMPLEX||valueType===valueTypes.COLOR?cloneArray(lookupTween._fromNumbers):null;let additiveValue=lookupTween._fromNumber;let tween=tweens._tail;while(tween&&tween!==lookupTween){if(additiveValues){for(let i=0,l=tween._numbers.length;i<l;i++)additiveValues[i]+=tween._numbers[i]}else{additiveValue+=tween._number}tween=tween._prevAdd}lookupTween._toNumber=additiveValue;lookupTween._toNumbers=additiveValues}}}));render(animation,1,1,0,tickModes.FORCE)}}return animation};const engineTickMethod=(()=>isBrowser?requestAnimationFrame:setImmediate)();const engineCancelMethod=(()=>isBrowser?cancelAnimationFrame:clearImmediate)();class Engine extends Clock{constructor(initTime){super(initTime);this.useDefaultMainLoop=true;this.pauseOnDocumentHidden=true;this.defaults=defaults;this.paused=true;this.reqId=0}update(){const time=this._currentTime=now();if(this.requestTick(time)){this.computeDeltaTime(time);const engineSpeed=this._speed;const engineFps=this._fps;let activeTickable=this._head;while(activeTickable){const nextTickable=activeTickable._next;if(!activeTickable.paused){tick(activeTickable,(time-activeTickable._startTime)*activeTickable._speed*engineSpeed,0,0,activeTickable._fps<engineFps?activeTickable.requestTick(time):tickModes.AUTO)}else{removeChild(this,activeTickable);this._hasChildren=!!this._tail;activeTickable._running=false;if(activeTickable.completed&&!activeTickable._cancelled){activeTickable.cancel()}}activeTickable=nextTickable}additive.update()}}wake(){if(this.useDefaultMainLoop&&!this.reqId){this.requestTick(now());this.reqId=engineTickMethod(tickEngine)}return this}pause(){if(!this.reqId)return;this.paused=true;return killEngine()}resume(){if(!this.paused)return;this.paused=false;forEachChildren(this,(child=>child.resetTime()));return this.wake()}get speed(){return this._speed*(globals.timeScale===1?1:K)}set speed(playbackRate){this._speed=playbackRate*globals.timeScale;forEachChildren(this,(child=>child.speed=child._speed))}get timeUnit(){return globals.timeScale===1?"ms":"s"}set timeUnit(unit){const secondsScale=.001;const isSecond=unit==="s";const newScale=isSecond?secondsScale:1;if(globals.timeScale!==newScale){globals.timeScale=newScale;globals.tickThreshold=200*newScale;const scaleFactor=isSecond?secondsScale:K;this.defaults.duration*=scaleFactor;this._speed*=scaleFactor}}get precision(){return globals.precision}set precision(precision){globals.precision=precision}}const engine=(()=>{const engine=new Engine(now());if(isBrowser){globalVersions.engine=engine;doc.addEventListener("visibilitychange",(()=>{if(!engine.pauseOnDocumentHidden)return;doc.hidden?engine.pause():engine.resume()}))}return engine})();const tickEngine=()=>{if(engine._head){engine.reqId=engineTickMethod(tickEngine);engine.update()}else{engine.reqId=0}};const killEngine=()=>{engineCancelMethod(engine.reqId);engine.reqId=0;return engine};const parseInlineTransforms=(target,propName,animationInlineStyles)=>{const inlineTransforms=target.style.transform;let inlinedStylesPropertyValue;if(inlineTransforms){const cachedTransforms=target[transformsSymbol];let t;while(t=transformsExecRgx.exec(inlineTransforms)){const inlinePropertyName=t[1];const inlinePropertyValue=t[2].slice(1,-1);cachedTransforms[inlinePropertyName]=inlinePropertyValue;if(inlinePropertyName===propName){inlinedStylesPropertyValue=inlinePropertyValue;if(animationInlineStyles){animationInlineStyles[propName]=inlinePropertyValue}}}}return inlineTransforms&&!isUnd(inlinedStylesPropertyValue)?inlinedStylesPropertyValue:stringStartsWith(propName,"scale")?"1":stringStartsWith(propName,"rotate")||stringStartsWith(propName,"skew")?"0deg":"0px"};function getNodeList(v){const n=isStr(v)?scope.root.querySelectorAll(v):v;if(n instanceof NodeList||n instanceof HTMLCollection)return n}function parseTargets(targets){if(isNil(targets))return[];if(!isBrowser)return isArr(targets)&&targets.flat(Infinity)||[targets];if(isArr(targets)){const flattened=targets.flat(Infinity);const parsed=[];for(let i=0,l=flattened.length;i<l;i++){const item=flattened[i];if(!isNil(item)){const nodeList=getNodeList(item);if(nodeList){for(let j=0,jl=nodeList.length;j<jl;j++){const subItem=nodeList[j];if(!isNil(subItem)){let isDuplicate=false;for(let k=0,kl=parsed.length;k<kl;k++){if(parsed[k]===subItem){isDuplicate=true;break}}if(!isDuplicate){parsed.push(subItem)}}}}else{let isDuplicate=false;for(let j=0,jl=parsed.length;j<jl;j++){if(parsed[j]===item){isDuplicate=true;break}}if(!isDuplicate){parsed.push(item)}}}}return parsed}const nodeList=getNodeList(targets);if(nodeList)return Array.from(nodeList);return[targets]}function registerTargets(targets){const parsedTargetsArray=parseTargets(targets);const parsedTargetsLength=parsedTargetsArray.length;if(parsedTargetsLength){for(let i=0;i<parsedTargetsLength;i++){const target=parsedTargetsArray[i];if(!target[isRegisteredTargetSymbol]){target[isRegisteredTargetSymbol]=true;const isSvgType=isSvg(target);const isDom=target.nodeType||isSvgType;if(isDom){target[isDomSymbol]=true;target[isSvgSymbol]=isSvgType;target[transformsSymbol]={}}}}}return parsedTargetsArray}const getPath=path=>{const parsedTargets=parseTargets(path);const $parsedSvg=parsedTargets[0];if(!$parsedSvg||!isSvg($parsedSvg))return;return $parsedSvg};const morphTo=(path2,precision=.33)=>$path1=>{const $path2=getPath(path2);if(!$path2)return;const isPath=$path1.tagName==="path";const separator=isPath?" ":",";const previousPoints=$path1[morphPointsSymbol];if(previousPoints)$path1.setAttribute(isPath?"d":"points",previousPoints);let v1="",v2="";if(!precision){v1=$path1.getAttribute(isPath?"d":"points");v2=$path2.getAttribute(isPath?"d":"points")}else{const length1=$path1.getTotalLength();const length2=$path2.getTotalLength();const maxPoints=Math.max(Math.ceil(length1*precision),Math.ceil(length2*precision));for(let i=0;i<maxPoints;i++){const t=i/(maxPoints-1);const pointOnPath1=$path1.getPointAtLength(length1*t);const pointOnPath2=$path2.getPointAtLength(length2*t);const prefix=isPath?i===0?"M":"L":"";v1+=prefix+round(pointOnPath1.x,3)+separator+pointOnPath1.y+" ";v2+=prefix+round(pointOnPath2.x,3)+separator+pointOnPath2.y+" "}}$path1[morphPointsSymbol]=v2;return[v1,v2]};const getScaleFactor=$el=>{let scaleFactor=1;if($el&&$el.getCTM){const ctm=$el.getCTM();if(ctm){const scaleX=sqrt(ctm.a*ctm.a+ctm.b*ctm.b);const scaleY=sqrt(ctm.c*ctm.c+ctm.d*ctm.d);scaleFactor=(scaleX+scaleY)/2}}return scaleFactor};const createDrawableProxy=($el,start,end)=>{const pathLength=K;const computedStyles=getComputedStyle($el);const strokeLineCap=computedStyles.strokeLinecap;const $scalled=computedStyles.vectorEffect==="non-scaling-stroke"?$el:null;let currentCap=strokeLineCap;const proxy=new Proxy($el,{get(target,property){const value=target[property];if(property===proxyTargetSymbol)return target;if(property==="setAttribute"){return(...args)=>{if(args[0]==="draw"){const value=args[1];const values=value.split(" ");const v1=+values[0];const v2=+values[1];const scaleFactor=getScaleFactor($scalled);const os=v1*-1e3*scaleFactor;const d1=v2*pathLength*scaleFactor+os;const d2=pathLength*scaleFactor+(v1===0&&v2===1||v1===1&&v2===0?0:10*scaleFactor)-d1;if(strokeLineCap!=="butt"){const newCap=v1===v2?"butt":strokeLineCap;if(currentCap!==newCap){target.style.strokeLinecap=`${newCap}`;currentCap=newCap}}target.setAttribute("stroke-dashoffset",`${os}`);target.setAttribute("stroke-dasharray",`${d1} ${d2}`)}return Reflect.apply(value,target,args)}}if(isFnc(value)){return(...args)=>Reflect.apply(value,target,args)}else{return value}}});if($el.getAttribute("pathLength")!==`${pathLength}`){$el.setAttribute("pathLength",`${pathLength}`);proxy.setAttribute("draw",`${start} ${end}`)}return proxy};const createDrawable=(selector,start=0,end=0)=>{const els=parseTargets(selector);return els.map(($el=>createDrawableProxy($el,start,end)))};const getPathPoint=($path,progress,lookup=0)=>$path.getPointAtLength(progress+lookup>=1?progress+lookup:0);const getPathProgess=($path,pathProperty)=>$el=>{const totalLength=+$path.getTotalLength();const inSvg=$el[isSvgSymbol];const ctm=$path.getCTM();return{from:0,to:totalLength,modifier:progress=>{if(pathProperty==="a"){const p0=getPathPoint($path,progress,-1);const p1=getPathPoint($path,progress,1);return atan2(p1.y-p0.y,p1.x-p0.x)*180/PI}else{const p=getPathPoint($path,progress,0);return pathProperty==="x"?inSvg||!ctm?p.x:p.x*ctm.a+p.y*ctm.c+ctm.e:inSvg||!ctm?p.y:p.x*ctm.b+p.y*ctm.d+ctm.f}}}};const createMotionPath=path=>{const $path=getPath(path);if(!$path)return;return{translateX:getPathProgess($path,"x"),translateY:getPathProgess($path,"y"),rotate:getPathProgess($path,"a")}};const cssReservedProperties=["opacity","rotate","overflow","color"];const isValidSVGAttribute=(el,propertyName)=>{if(cssReservedProperties.includes(propertyName))return false;if(el.getAttribute(propertyName)||propertyName in el){if(propertyName==="scale"){const elParentNode=el.parentNode;return elParentNode&&elParentNode.tagName==="filter"}return true}};const svg={morphTo:morphTo,createMotionPath:createMotionPath,createDrawable:createDrawable};const rgbToRgba=rgbValue=>{const rgba=rgbExecRgx.exec(rgbValue)||rgbaExecRgx.exec(rgbValue);const a=!isUnd(rgba[4])?+rgba[4]:1;return[+rgba[1],+rgba[2],+rgba[3],a]};const hexToRgba=hexValue=>{const hexLength=hexValue.length;const isShort=hexLength===4||hexLength===5;return[+("0x"+hexValue[1]+hexValue[isShort?1:2]),+("0x"+hexValue[isShort?2:3]+hexValue[isShort?2:4]),+("0x"+hexValue[isShort?3:5]+hexValue[isShort?3:6]),hexLength===5||hexLength===9?+(+("0x"+hexValue[isShort?4:7]+hexValue[isShort?4:8])/255).toFixed(3):1]};const hue2rgb=(p,q,t)=>{if(t<0)t+=1;if(t>1)t-=1;return t<1/6?p+(q-p)*6*t:t<1/2?q:t<2/3?p+(q-p)*(2/3-t)*6:p};const hslToRgba=hslValue=>{const hsla=hslExecRgx.exec(hslValue)||hslaExecRgx.exec(hslValue);const h=+hsla[1]/360;const s=+hsla[2]/100;const l=+hsla[3]/100;const a=!isUnd(hsla[4])?+hsla[4]:1;let r,g,b;if(s===0){r=g=b=l}else{const q=l<.5?l*(1+s):l+s-l*s;const p=2*l-q;r=round(hue2rgb(p,q,h+1/3)*255,0);g=round(hue2rgb(p,q,h)*255,0);b=round(hue2rgb(p,q,h-1/3)*255,0)}return[r,g,b,a]};const convertColorStringValuesToRgbaArray=colorString=>isRgb(colorString)?rgbToRgba(colorString):isHex(colorString)?hexToRgba(colorString):isHsl(colorString)?hslToRgba(colorString):[0,0,0,1];const setValue=(targetValue,defaultValue)=>isUnd(targetValue)?defaultValue:targetValue;const getFunctionValue=(value,target,index,total,store)=>{if(isFnc(value)){const func=()=>{const computed=value(target,index,total);return!isNaN(+computed)?+computed:computed||0};if(store){store.func=func}return func()}else{return value}};const getTweenType=(target,prop)=>!target[isDomSymbol]?tweenTypes.OBJECT:target[isSvgSymbol]&&isValidSVGAttribute(target,prop)?tweenTypes.ATTRIBUTE:validTransforms.includes(prop)||shortTransforms.get(prop)?tweenTypes.TRANSFORM:stringStartsWith(prop,"--")?tweenTypes.CSS_VAR:prop in target.style?tweenTypes.CSS:prop in target?tweenTypes.OBJECT:tweenTypes.ATTRIBUTE;const getCSSValue=(target,propName,animationInlineStyles)=>{const inlineStyles=target.style[propName];if(inlineStyles&&animationInlineStyles){animationInlineStyles[propName]=inlineStyles}const value=inlineStyles||getComputedStyle(target[proxyTargetSymbol]||target).getPropertyValue(propName);return value==="auto"?"0":value};const getOriginalAnimatableValue=(target,propName,tweenType,animationInlineStyles)=>{const type=!isUnd(tweenType)?tweenType:getTweenType(target,propName);return type===tweenTypes.OBJECT?target[propName]||0:type===tweenTypes.ATTRIBUTE?target.getAttribute(propName):type===tweenTypes.TRANSFORM?parseInlineTransforms(target,propName,animationInlineStyles):type===tweenTypes.CSS_VAR?getCSSValue(target,propName,animationInlineStyles).trimStart():getCSSValue(target,propName,animationInlineStyles)};const getRelativeValue=(x,y,operator)=>operator==="-"?x-y:operator==="+"?x+y:x*y;const createDecomposedValueTargetObject=()=>({t:valueTypes.NUMBER,n:0,u:null,o:null,d:null,s:null});const decomposeRawValue=(rawValue,targetObject)=>{targetObject.t=valueTypes.NUMBER;targetObject.n=0;targetObject.u=null;targetObject.o=null;targetObject.d=null;targetObject.s=null;if(!rawValue)return targetObject;const num=+rawValue;if(!isNaN(num)){targetObject.n=num;return targetObject}else{let str=rawValue;if(str[1]==="="){targetObject.o=str[0];str=str.slice(2)}const unitMatch=str.includes(" ")?false:unitsExecRgx.exec(str);if(unitMatch){targetObject.t=valueTypes.UNIT;targetObject.n=+unitMatch[1];targetObject.u=unitMatch[2];return targetObject}else if(targetObject.o){targetObject.n=+str;return targetObject}else if(isCol(str)){targetObject.t=valueTypes.COLOR;targetObject.d=convertColorStringValuesToRgbaArray(str);return targetObject}else{const matchedNumbers=str.match(digitWithExponentRgx);targetObject.t=valueTypes.COMPLEX;targetObject.d=matchedNumbers?matchedNumbers.map(Number):[];targetObject.s=str.split(digitWithExponentRgx)||[];return targetObject}}};const decomposeTweenValue=(tween,targetObject)=>{targetObject.t=tween._valueType;targetObject.n=tween._toNumber;targetObject.u=tween._unit;targetObject.o=null;targetObject.d=cloneArray(tween._toNumbers);targetObject.s=cloneArray(tween._strings);return targetObject};const decomposedOriginalValue=createDecomposedValueTargetObject();const lookups={_rep:new WeakMap,_add:new Map};const getTweenSiblings=(target,property,lookup="_rep")=>{const lookupMap=lookups[lookup];let targetLookup=lookupMap.get(target);if(!targetLookup){targetLookup={};lookupMap.set(target,targetLookup)}return targetLookup[property]?targetLookup[property]:targetLookup[property]={_head:null,_tail:null}};const addTweenSortMethod=(p,c)=>p._isOverridden||p._absoluteStartTime>c._absoluteStartTime;const overrideTween=tween=>{tween._isOverlapped=1;tween._isOverridden=1;tween._changeDuration=minValue;tween._currentTime=minValue};const composeTween=(tween,siblings)=>{const tweenCompositionType=tween._composition;if(tweenCompositionType===compositionTypes.replace){const tweenAbsStartTime=tween._absoluteStartTime;addChild(siblings,tween,addTweenSortMethod,"_prevRep","_nextRep");const prevSibling=tween._prevRep;if(prevSibling){const prevParent=prevSibling.parent;const prevAbsEndTime=prevSibling._absoluteStartTime+prevSibling._changeDuration;if(tween.parent.id!==prevParent.id&&prevParent.iterationCount>1&&prevAbsEndTime+(prevParent.duration-prevParent.iterationDuration)>tweenAbsStartTime){overrideTween(prevSibling);let prevPrevSibling=prevSibling._prevRep;while(prevPrevSibling&&prevPrevSibling.parent.id===prevParent.id){overrideTween(prevPrevSibling);prevPrevSibling=prevPrevSibling._prevRep}}const absoluteUpdateStartTime=tweenAbsStartTime-tween._delay;if(prevAbsEndTime>absoluteUpdateStartTime){const prevChangeStartTime=prevSibling._startTime;const prevTLOffset=prevAbsEndTime-(prevChangeStartTime+prevSibling._updateDuration);const updatedPrevChangeDuration=round(absoluteUpdateStartTime-prevTLOffset-prevChangeStartTime,12);prevSibling._changeDuration=updatedPrevChangeDuration;prevSibling._currentTime=updatedPrevChangeDuration;prevSibling._isOverlapped=1;if(updatedPrevChangeDuration<minValue){overrideTween(prevSibling)}}let pausePrevParentAnimation=true;forEachChildren(prevParent,(t=>{if(!t._isOverlapped)pausePrevParentAnimation=false}));if(pausePrevParentAnimation){const prevParentTL=prevParent.parent;if(prevParentTL){let pausePrevParentTL=true;forEachChildren(prevParentTL,(a=>{if(a!==prevParent){forEachChildren(a,(t=>{if(!t._isOverlapped)pausePrevParentTL=false}))}}));if(pausePrevParentTL){prevParentTL.cancel()}}else{prevParent.cancel()}}}}else if(tweenCompositionType===compositionTypes.blend){const additiveTweenSiblings=getTweenSiblings(tween.target,tween.property,"_add");const additiveAnimation=addAdditiveAnimation(lookups._add);let lookupTween=additiveTweenSiblings._head;if(!lookupTween){lookupTween={...tween};lookupTween._composition=compositionTypes.replace;lookupTween._updateDuration=minValue;lookupTween._startTime=0;lookupTween._numbers=cloneArray(tween._fromNumbers);lookupTween._number=0;lookupTween._next=null;lookupTween._prev=null;addChild(additiveTweenSiblings,lookupTween);addChild(additiveAnimation,lookupTween)}const toNumber=tween._toNumber;tween._fromNumber=lookupTween._fromNumber-toNumber;tween._toNumber=0;tween._numbers=cloneArray(tween._fromNumbers);tween._number=0;lookupTween._fromNumber=toNumber;if(tween._toNumbers){const toNumbers=cloneArray(tween._toNumbers);if(toNumbers){toNumbers.forEach(((value,i)=>{tween._fromNumbers[i]=lookupTween._fromNumbers[i]-value;tween._toNumbers[i]=0}))}lookupTween._fromNumbers=toNumbers}addChild(additiveTweenSiblings,tween,null,"_prevAdd","_nextAdd")}return tween};const removeTweenSliblings=tween=>{const tweenComposition=tween._composition;if(tweenComposition!==compositionTypes.none){const tweenTarget=tween.target;const tweenProperty=tween.property;const replaceTweensLookup=lookups._rep;const replaceTargetProps=replaceTweensLookup.get(tweenTarget);const tweenReplaceSiblings=replaceTargetProps[tweenProperty];removeChild(tweenReplaceSiblings,tween,"_prevRep","_nextRep");if(tweenComposition===compositionTypes.blend){const addTweensLookup=lookups._add;const addTargetProps=addTweensLookup.get(tweenTarget);if(!addTargetProps)return;const additiveTweenSiblings=addTargetProps[tweenProperty];const additiveAnimation=additive.animation;removeChild(additiveTweenSiblings,tween,"_prevAdd","_nextAdd");const lookupTween=additiveTweenSiblings._head;if(lookupTween&&lookupTween===additiveTweenSiblings._tail){removeChild(additiveTweenSiblings,lookupTween,"_prevAdd","_nextAdd");removeChild(additiveAnimation,lookupTween);let shouldClean=true;for(let prop in addTargetProps){if(addTargetProps[prop]._head){shouldClean=false;break}}if(shouldClean){addTweensLookup.delete(tweenTarget)}}}}return tween};const resetTimerProperties=timer=>{timer.paused=true;timer.began=false;timer.completed=false;return timer};const reviveTimer=timer=>{if(!timer._cancelled)return timer;if(timer._hasChildren){forEachChildren(timer,reviveTimer)}else{forEachChildren(timer,(tween=>{if(tween._composition!==compositionTypes.none){composeTween(tween,getTweenSiblings(tween.target,tween.property))}}))}timer._cancelled=0;return timer};let timerId=0;class Timer extends Clock{constructor(parameters={},parent=null,parentPosition=0){super(0);const{id:id,delay:delay,duration:duration,reversed:reversed,alternate:alternate,loop:loop,loopDelay:loopDelay,autoplay:autoplay,frameRate:frameRate,playbackRate:playbackRate,onComplete:onComplete,onLoop:onLoop,onPause:onPause,onBegin:onBegin,onBeforeUpdate:onBeforeUpdate,onUpdate:onUpdate}=parameters;if(scope.current)scope.current.register(this);const timerInitTime=parent?0:engine._elapsedTime;const timerDefaults=parent?parent.defaults:globals.defaults;const timerDelay=isFnc(delay)||isUnd(delay)?timerDefaults.delay:+delay;const timerDuration=isFnc(duration)||isUnd(duration)?Infinity:+duration;const timerLoop=setValue(loop,timerDefaults.loop);const timerLoopDelay=setValue(loopDelay,timerDefaults.loopDelay);const timerIterationCount=timerLoop===true||timerLoop===Infinity||timerLoop<0?Infinity:timerLoop+1;let offsetPosition=0;if(parent){offsetPosition=parentPosition}else{if(!engine.reqId)engine.requestTick(now());offsetPosition=(engine._elapsedTime-engine._startTime)*globals.timeScale}this.id=!isUnd(id)?id:++timerId;this.parent=parent;this.duration=clampInfinity((timerDuration+timerLoopDelay)*timerIterationCount-timerLoopDelay)||minValue;this.backwards=false;this.paused=true;this.began=false;this.completed=false;this.onBegin=onBegin||timerDefaults.onBegin;this.onBeforeUpdate=onBeforeUpdate||timerDefaults.onBeforeUpdate;this.onUpdate=onUpdate||timerDefaults.onUpdate;this.onLoop=onLoop||timerDefaults.onLoop;this.onPause=onPause||timerDefaults.onPause;this.onComplete=onComplete||timerDefaults.onComplete;this.iterationDuration=timerDuration;this.iterationCount=timerIterationCount;this._autoplay=parent?false:setValue(autoplay,timerDefaults.autoplay);this._offset=offsetPosition;this._delay=timerDelay;this._loopDelay=timerLoopDelay;this._iterationTime=0;this._currentIteration=0;this._resolve=noop;this._running=false;this._reversed=+setValue(reversed,timerDefaults.reversed);this._reverse=this._reversed;this._cancelled=0;this._alternate=setValue(alternate,timerDefaults.alternate);this._prev=null;this._next=null;this._elapsedTime=timerInitTime;this._startTime=timerInitTime;this._lastTime=timerInitTime;this._fps=setValue(frameRate,timerDefaults.frameRate);this._speed=setValue(playbackRate,timerDefaults.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(cancelled){cancelled?this.cancel():this.reset(1).play()}get currentTime(){return clamp(round(this._currentTime,globals.precision),-this._delay,this.duration)}set currentTime(time){const paused=this.paused;this.pause().seek(+time);if(!paused)this.resume()}get iterationCurrentTime(){return round(this._iterationTime,globals.precision)}set iterationCurrentTime(time){this.currentTime=this.iterationDuration*this._currentIteration+time}get progress(){return clamp(round(this._currentTime/this.duration,10),0,1)}set progress(progress){this.currentTime=this.duration*progress}get iterationProgress(){return clamp(round(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(progress){const iterationDuration=this.iterationDuration;this.currentTime=iterationDuration*this._currentIteration+iterationDuration*progress}get currentIteration(){return this._currentIteration}set currentIteration(iterationCount){this.currentTime=this.iterationDuration*clamp(+iterationCount,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(reverse){reverse?this.reverse():this.play()}get speed(){return super.speed}set speed(playbackRate){super.speed=playbackRate;this.resetTime()}reset(internalRender=0){reviveTimer(this);if(this._reversed&&!this._reverse)this.reversed=false;this._iterationTime=this.iterationDuration;tick(this,0,1,internalRender,tickModes.FORCE);resetTimerProperties(this);if(this._hasChildren){forEachChildren(this,resetTimerProperties)}return this}init(internalRender=0){this.fps=this._fps;this.speed=this._speed;if(!internalRender&&this._hasChildren){tick(this,this.duration,1,internalRender,tickModes.FORCE)}this.reset(internalRender);const autoplay=this._autoplay;if(autoplay===true){this.resume()}else if(autoplay&&!isUnd(autoplay.linked)){autoplay.link(this)}return this}resetTime(){const timeScale=1/(this._speed*engine._speed);this._startTime=now()-(this._currentTime+this._delay)*timeScale;return this}pause(){if(this.paused)return this;this.paused=true;this.onPause(this);return this}resume(){if(!this.paused)return this;this.paused=false;if(this.duration<=minValue&&!this._hasChildren){tick(this,minValue,0,0,tickModes.FORCE)}else{if(!this._running){addChild(engine,this);engine._hasChildren=true;this._running=true}this.resetTime();this._startTime-=12;engine.wake()}return this}restart(){return this.reset(0).resume()}seek(time,muteCallbacks=0,internalRender=0){reviveTimer(this);this.completed=false;const isPaused=this.paused;this.paused=true;tick(this,time+this._delay,~~muteCallbacks,~~internalRender,tickModes.AUTO);return isPaused?this:this.resume()}alternate(){const reversed=this._reversed;const count=this.iterationCount;const duration=this.iterationDuration;const iterations=count===Infinity?floor(maxValue/duration):count;this._reversed=+(this._alternate&&!(iterations%2)?reversed:!reversed);if(count===Infinity){this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress}else{this.seek(duration*iterations-this._currentTime)}this.resetTime();return this}play(){if(this._reversed)this.alternate();return this.resume()}reverse(){if(!this._reversed)this.alternate();return this.resume()}cancel(){if(this._hasChildren){forEachChildren(this,(child=>child.cancel()),true)}else{forEachChildren(this,removeTweenSliblings)}this._cancelled=1;return this.pause()}stretch(newDuration){const currentDuration=this.duration;const normlizedDuration=normalizeTime(newDuration);if(currentDuration===normlizedDuration)return this;const timeScale=newDuration/currentDuration;const isSetter=newDuration<=minValue;this.duration=isSetter?minValue:normlizedDuration;this.iterationDuration=isSetter?minValue:normalizeTime(this.iterationDuration*timeScale);this._offset*=timeScale;this._delay*=timeScale;this._loopDelay*=timeScale;return this}revert(){tick(this,0,1,0,tickModes.AUTO);const ap=this._autoplay;if(ap&&ap.linked&&ap.linked===this)ap.revert();return this.cancel()}complete(){return this.seek(this.duration).cancel()}then(callback=noop){const then=this.then;const onResolve=()=>{this.then=null;callback(this);this.then=then;this._resolve=noop};return new Promise((r=>{this._resolve=()=>r(onResolve());if(this.completed)this._resolve();return this}))}}const createTimer=parameters=>new Timer(parameters,null,0).init();const none=t=>t;const calcBezier=(aT,aA1,aA2)=>(((1-3*aA2+3*aA1)*aT+(3*aA2-6*aA1))*aT+3*aA1)*aT;const binarySubdivide=(aX,mX1,mX2)=>{let aA=0,aB=1,currentX,currentT,i=0;do{currentT=aA+(aB-aA)/2;currentX=calcBezier(currentT,mX1,mX2)-aX;if(currentX>0){aB=currentT}else{aA=currentT}}while(abs(currentX)>1e-7&&++i<100);return currentT};const cubicBezier=(mX1=.5,mY1=0,mX2=.5,mY2=1)=>mX1===mY1&&mX2===mY2?none:t=>t===0||t===1?t:calcBezier(binarySubdivide(t,mX1,mX2),mY1,mY2);const steps=(steps=10,fromStart)=>{const roundMethod=fromStart?ceil:floor;return t=>roundMethod(clamp(t,0,1)*steps)*(1/steps)};const linear=(...args)=>{const argsLength=args.length;if(!argsLength)return none;const totalPoints=argsLength-1;const firstArg=args[0];const lastArg=args[totalPoints];const xPoints=[0];const yPoints=[parseNumber(firstArg)];for(let i=1;i<totalPoints;i++){const arg=args[i];const splitValue=isStr(arg)?arg.trim().split(" "):[arg];const value=splitValue[0];const percent=splitValue[1];xPoints.push(!isUnd(percent)?parseNumber(percent)/100:i/totalPoints);yPoints.push(parseNumber(value))}yPoints.push(parseNumber(lastArg));xPoints.push(1);return function easeLinear(t){for(let i=1,l=xPoints.length;i<l;i++){const currentX=xPoints[i];if(t<=currentX){const prevX=xPoints[i-1];const prevY=yPoints[i-1];return prevY+(yPoints[i]-prevY)*(t-prevX)/(currentX-prevX)}}return yPoints[yPoints.length-1]}};const irregular=(length=10,randomness=1)=>{const values=[0];const total=length-1;for(let i=1;i<total;i++){const previousValue=values[i-1];const spacing=i/total;const segmentEnd=(i+1)/total;const randomVariation=spacing+(segmentEnd-spacing)*Math.random();const randomValue=spacing*(1-randomness)+randomVariation*randomness;values.push(clamp(randomValue,previousValue,1))}values.push(1);return linear(...values)};const halfPI=PI/2;const doublePI=PI*2;const easeInPower=(p=1.68)=>t=>pow(t,+p);const easeInFunctions={[emptyString]:easeInPower,Quad:easeInPower(2),Cubic:easeInPower(3),Quart:easeInPower(4),Quint:easeInPower(5),Sine:t=>1-cos(t*halfPI),Circ:t=>1-sqrt(1-t*t),Expo:t=>t?pow(2,10*t-10):0,Bounce:t=>{let pow2,b=4;while(t<((pow2=pow(2,--b))-1)/11);return 1/pow(4,3-b)-7.5625*pow((pow2*3-2)/22-t,2)},Back:(overshoot=1.70158)=>t=>(+overshoot+1)*t*t*t-+overshoot*t*t,Elastic:(amplitude=1,period=.3)=>{const a=clamp(+amplitude,1,10);const p=clamp(+period,minValue,2);const s=p/doublePI*asin(1/a);const e=doublePI/p;return t=>t===0||t===1?t:-a*pow(2,-10*(1-t))*sin((1-t-s)*e)}};const easeTypes={in:easeIn=>t=>easeIn(t),out:easeIn=>t=>1-easeIn(1-t),inOut:easeIn=>t=>t<.5?easeIn(t*2)/2:1-easeIn(t*-2+2)/2,outIn:easeIn=>t=>t<.5?(1-easeIn(1-t*2))/2:(easeIn(t*2-1)+1)/2};const parseEaseString=(string,easesFunctions,easesLookups)=>{if(easesLookups[string])return easesLookups[string];if(string.indexOf("(")<=-1){const hasParams=easeTypes[string]||string.includes("Back")||string.includes("Elastic");const parsedFn=hasParams?easesFunctions[string]():easesFunctions[string];return parsedFn?easesLookups[string]=parsedFn:none}else{const split=string.slice(0,-1).split("(");const parsedFn=easesFunctions[split[0]];return parsedFn?easesLookups[string]=parsedFn(...split[1].split(",")):none}};const eases=(()=>{const list={linear:linear,irregular:irregular,steps:steps,cubicBezier:cubicBezier};for(let type in easeTypes){for(let name in easeInFunctions){const easeIn=easeInFunctions[name];const easeType=easeTypes[type];list[type+name]=name===emptyString||name==="Back"||name==="Elastic"?(a,b)=>easeType(easeIn(a,b)):easeType(easeIn)}}return list})();const JSEasesLookups={linear:none};const parseEasings=ease=>isFnc(ease)?ease:isStr(ease)?parseEaseString(ease,eases,JSEasesLookups):none;const propertyNamesCache={};const sanitizePropertyName=(propertyName,target,tweenType)=>{if(tweenType===tweenTypes.TRANSFORM){const t=shortTransforms.get(propertyName);return t?t:propertyName}else if(tweenType===tweenTypes.CSS||tweenType===tweenTypes.ATTRIBUTE&&(isSvg(target)&&propertyName in target.style)){const cachedPropertyName=propertyNamesCache[propertyName];if(cachedPropertyName){return cachedPropertyName}else{const lowerCaseName=propertyName?toLowerCase(propertyName):propertyName;propertyNamesCache[propertyName]=lowerCaseName;return lowerCaseName}}else{return propertyName}};const angleUnitsMap={deg:1,rad:180/PI,turn:360};const convertedValuesCache={};const convertValueUnit=(el,decomposedValue,unit,force=false)=>{const currentUnit=decomposedValue.u;const currentNumber=decomposedValue.n;if(decomposedValue.t===valueTypes.UNIT&&currentUnit===unit){return decomposedValue}const cachedKey=currentNumber+currentUnit+unit;const cached=convertedValuesCache[cachedKey];if(!isUnd(cached)&&!force){decomposedValue.n=cached}else{let convertedValue;if(currentUnit in angleUnitsMap){convertedValue=currentNumber*angleUnitsMap[currentUnit]/angleUnitsMap[unit]}else{const baseline=100;const tempEl=el.cloneNode();const parentNode=el.parentNode;const parentEl=parentNode&&parentNode!==doc?parentNode:doc.body;parentEl.appendChild(tempEl);const elStyle=tempEl.style;elStyle.width=baseline+currentUnit;const currentUnitWidth=tempEl.offsetWidth||baseline;elStyle.width=baseline+unit;const newUnitWidth=tempEl.offsetWidth||baseline;const factor=currentUnitWidth/newUnitWidth;parentEl.removeChild(tempEl);convertedValue=factor*currentNumber}decomposedValue.n=convertedValue;convertedValuesCache[cachedKey]=convertedValue}decomposedValue.t===valueTypes.UNIT;decomposedValue.u=unit;return decomposedValue};const cleanInlineStyles=renderable=>{if(renderable._hasChildren){forEachChildren(renderable,cleanInlineStyles,true)}else{const animation=renderable;animation.pause();forEachChildren(animation,(tween=>{const tweenProperty=tween.property;const tweenTarget=tween.target;if(tweenTarget[isDomSymbol]){const targetStyle=tweenTarget.style;const originalInlinedValue=animation._inlineStyles[tweenProperty];if(tween._tweenType===tweenTypes.TRANSFORM){const cachedTransforms=tweenTarget[transformsSymbol];if(isUnd(originalInlinedValue)||originalInlinedValue===emptyString){delete cachedTransforms[tweenProperty]}else{cachedTransforms[tweenProperty]=originalInlinedValue}if(tween._renderTransforms){if(!Object.keys(cachedTransforms).length){targetStyle.removeProperty("transform")}else{let str=emptyString;for(let key in cachedTransforms){str+=transformsFragmentStrings[key]+cachedTransforms[key]+") "}targetStyle.transform=str}}}else{if(isUnd(originalInlinedValue)||originalInlinedValue===emptyString){targetStyle.removeProperty(tweenProperty)}else{targetStyle[tweenProperty]=originalInlinedValue}}if(animation._tail===tween){animation.targets.forEach((t=>{if(t.getAttribute&&t.getAttribute("style")===emptyString){t.removeAttribute("style")}}))}}}))}return renderable};const fromTargetObject=createDecomposedValueTargetObject();const toTargetObject=createDecomposedValueTargetObject();const toFunctionStore={func:null};const keyframesTargetArray=[null];const fastSetValuesArray=[null,null];const keyObjectTarget={to:null};let tweenId=0;let keyframes;let key;const generateKeyframes=(keyframes,parameters)=>{const properties={};if(isArr(keyframes)){const propertyNames=[].concat(...keyframes.map((key=>Object.keys(key)))).filter(isKey);for(let i=0,l=propertyNames.length;i<l;i++){const propName=propertyNames[i];const propArray=keyframes.map((key=>{const newKey={};for(let p in key){const keyValue=key[p];if(isKey(p)){if(p===propName){newKey.to=keyValue}}else{newKey[p]=keyValue}}return newKey}));properties[propName]=propArray}}else{const totalDuration=setValue(parameters.duration,globals.defaults.duration);const keys=Object.keys(keyframes).map((key=>({o:parseFloat(key)/100,p:keyframes[key]}))).sort(((a,b)=>a.o-b.o));keys.forEach((key=>{const offset=key.o;const prop=key.p;for(let name in prop){if(isKey(name)){let propArray=properties[name];if(!propArray)propArray=properties[name]=[];const duration=offset*totalDuration;let length=propArray.length;let prevKey=propArray[length-1];const keyObj={to:prop[name]};let durProgress=0;for(let i=0;i<length;i++){durProgress+=propArray[i].duration}if(length===1){keyObj.from=prevKey.to}if(prop.ease){keyObj.ease=prop.ease}keyObj.duration=duration-(length?durProgress:0);propArray.push(keyObj)}}return key}));for(let name in properties){const propArray=properties[name];let prevEase;for(let i=0,l=propArray.length;i<l;i++){const prop=propArray[i];const currentEase=prop.ease;prop.ease=prevEase?prevEase:undefined;prevEase=currentEase}if(!propArray[0].duration){propArray.shift()}}}return properties};class JSAnimation extends Timer{constructor(targets,parameters,parent,parentPosition,fastSet=false,index=0,length=0){super(parameters,parent,parentPosition);const parsedTargets=registerTargets(targets);const targetsLength=parsedTargets.length;const kfParams=parameters.keyframes;const params=kfParams?mergeObjects(generateKeyframes(kfParams,parameters),parameters):parameters;const{delay:delay,duration:duration,ease:ease,playbackEase:playbackEase,modifier:modifier,composition:composition,onRender:onRender}=params;const animDefaults=parent?parent.defaults:globals.defaults;const animaPlaybackEase=setValue(playbackEase,animDefaults.playbackEase);const animEase=animaPlaybackEase?parseEasings(animaPlaybackEase):null;const hasSpring=!isUnd(ease)&&!isUnd(ease.ease);const tEasing=hasSpring?ease.ease:setValue(ease,animEase?"linear":animDefaults.ease);const tDuration=hasSpring?ease.duration:setValue(duration,animDefaults.duration);const tDelay=setValue(delay,animDefaults.delay);const tModifier=modifier||animDefaults.modifier;const tComposition=isUnd(composition)&&targetsLength>=K?compositionTypes.none:!isUnd(composition)?composition:animDefaults.composition;const animInlineStyles={};const absoluteOffsetTime=this._offset+(parent?parent._offset:0);let iterationDuration=NaN;let iterationDelay=NaN;let animationAnimationLength=0;let shouldTriggerRender=0;for(let targetIndex=0;targetIndex<targetsLength;targetIndex++){const target=parsedTargets[targetIndex];const ti=index||targetIndex;const tl=length||targetsLength;let lastTransformGroupIndex=NaN;let lastTransformGroupLength=NaN;for(let p in params){if(isKey(p)){const tweenType=getTweenType(target,p);const propName=sanitizePropertyName(p,target,tweenType);let propValue=params[p];const isPropValueArray=isArr(propValue);if(fastSet&&!isPropValueArray){fastSetValuesArray[0]=propValue;fastSetValuesArray[1]=propValue;propValue=fastSetValuesArray}if(isPropValueArray){const arrayLength=propValue.length;const isNotObjectValue=!isObj(propValue[0]);if(arrayLength===2&&isNotObjectValue){keyObjectTarget.to=propValue;keyframesTargetArray[0]=keyObjectTarget;keyframes=keyframesTargetArray}else if(arrayLength>2&&isNotObjectValue){keyframes=[];propValue.forEach(((v,i)=>{if(!i){fastSetValuesArray[0]=v}else if(i===1){fastSetValuesArray[1]=v;keyframes.push(fastSetValuesArray)}else{keyframes.push(v)}}))}else{keyframes=propValue}}else{keyframesTargetArray[0]=propValue;keyframes=keyframesTargetArray}let siblings=null;let prevTween=null;let firstTweenChangeStartTime=NaN;let lastTweenChangeEndTime=0;let tweenIndex=0;for(let l=keyframes.length;tweenIndex<l;tweenIndex++){const keyframe=keyframes[tweenIndex];if(isObj(keyframe)){key=keyframe}else{keyObjectTarget.to=keyframe;key=keyObjectTarget}toFunctionStore.func=null;const computedToValue=getFunctionValue(key.to,target,ti,tl,toFunctionStore);let tweenToValue;if(isObj(computedToValue)&&!isUnd(computedToValue.to)){key=computedToValue;tweenToValue=computedToValue.to}else{tweenToValue=computedToValue}const tweenFromValue=getFunctionValue(key.from,target,ti,tl);const keyEasing=key.ease;const hasSpring=!isUnd(keyEasing)&&!isUnd(keyEasing.ease);const tweenEasing=hasSpring?keyEasing.ease:keyEasing||tEasing;const tweenDuration=hasSpring?keyEasing.duration:getFunctionValue(setValue(key.duration,l>1?getFunctionValue(tDuration,target,ti,tl)/l:tDuration),target,ti,tl);const tweenDelay=getFunctionValue(setValue(key.delay,!tweenIndex?tDelay:0),target,ti,tl);const computedComposition=getFunctionValue(setValue(key.composition,tComposition),target,ti,tl);const tweenComposition=isNum(computedComposition)?computedComposition:compositionTypes[computedComposition];const tweenModifier=key.modifier||tModifier;const hasFromvalue=!isUnd(tweenFromValue);const hasToValue=!isUnd(tweenToValue);const isFromToArray=isArr(tweenToValue);const isFromToValue=isFromToArray||hasFromvalue&&hasToValue;const tweenStartTime=prevTween?lastTweenChangeEndTime+tweenDelay:tweenDelay;const absoluteStartTime=round(absoluteOffsetTime+tweenStartTime,12);if(!shouldTriggerRender&&(hasFromvalue||isFromToArray))shouldTriggerRender=1;let prevSibling=prevTween;if(tweenComposition!==compositionTypes.none){if(!siblings)siblings=getTweenSiblings(target,propName);let nextSibling=siblings._head;while(nextSibling&&!nextSibling._isOverridden&&nextSibling._absoluteStartTime<=absoluteStartTime){prevSibling=nextSibling;nextSibling=nextSibling._nextRep;if(nextSibling&&nextSibling._absoluteStartTime>=absoluteStartTime){while(nextSibling){overrideTween(nextSibling);nextSibling=nextSibling._nextRep}}}}if(isFromToValue){decomposeRawValue(isFromToArray?getFunctionValue(tweenToValue[0],target,ti,tl):tweenFromValue,fromTargetObject);decomposeRawValue(isFromToArray?getFunctionValue(tweenToValue[1],target,ti,tl,toFunctionStore):tweenToValue,toTargetObject);if(fromTargetObject.t===valueTypes.NUMBER){if(prevSibling){if(prevSibling._valueType===valueTypes.UNIT){fromTargetObject.t=valueTypes.UNIT;fromTargetObject.u=prevSibling._unit}}else{decomposeRawValue(getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),decomposedOriginalValue);if(decomposedOriginalValue.t===valueTypes.UNIT){fromTargetObject.t=valueTypes.UNIT;fromTargetObject.u=decomposedOriginalValue.u}}}}else{if(hasToValue){decomposeRawValue(tweenToValue,toTargetObject)}else{if(prevTween){decomposeTweenValue(prevTween,toTargetObject)}else{decomposeRawValue(parent&&prevSibling&&prevSibling.parent.parent===parent?prevSibling._value:getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),toTargetObject)}}if(hasFromvalue){decomposeRawValue(tweenFromValue,fromTargetObject)}else{if(prevTween){decomposeTweenValue(prevTween,fromTargetObject)}else{decomposeRawValue(parent&&prevSibling&&prevSibling.parent.parent===parent?prevSibling._value:getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),fromTargetObject)}}}if(fromTargetObject.o){fromTargetObject.n=getRelativeValue(!prevSibling?decomposeRawValue(getOriginalAnimatableValue(target,propName,tweenType,animInlineStyles),decomposedOriginalValue).n:prevSibling._toNumber,fromTargetObject.n,fromTargetObject.o)}if(toTargetObject.o){toTargetObject.n=getRelativeValue(fromTargetObject.n,toTargetObject.n,toTargetObject.o)}if(fromTargetObject.t!==toTargetObject.t){if(fromTargetObject.t===valueTypes.COMPLEX||toTargetObject.t===valueTypes.COMPLEX){const complexValue=fromTargetObject.t===valueTypes.COMPLEX?fromTargetObject:toTargetObject;const notComplexValue=fromTargetObject.t===valueTypes.COMPLEX?toTargetObject:fromTargetObject;notComplexValue.t=valueTypes.COMPLEX;notComplexValue.s=cloneArray(complexValue.s);notComplexValue.d=complexValue.d.map((()=>notComplexValue.n))}else if(fromTargetObject.t===valueTypes.UNIT||toTargetObject.t===valueTypes.UNIT){const unitValue=fromTargetObject.t===valueTypes.UNIT?fromTargetObject:toTargetObject;const notUnitValue=fromTargetObject.t===valueTypes.UNIT?toTargetObject:fromTargetObject;notUnitValue.t=valueTypes.UNIT;notUnitValue.u=unitValue.u}else if(fromTargetObject.t===valueTypes.COLOR||toTargetObject.t===valueTypes.COLOR){const colorValue=fromTargetObject.t===valueTypes.COLOR?fromTargetObject:toTargetObject;const notColorValue=fromTargetObject.t===valueTypes.COLOR?toTargetObject:fromTargetObject;notColorValue.t=valueTypes.COLOR;notColorValue.s=colorValue.s;notColorValue.d=[0,0,0,1]}}if(fromTargetObject.u!==toTargetObject.u){let valueToConvert=toTargetObject.u?fromTargetObject:toTargetObject;valueToConvert=convertValueUnit(target,valueToConvert,toTargetObject.u?toTargetObject.u:fromTargetObject.u,false)}if(toTargetObject.d&&fromTargetObject.d&&toTargetObject.d.length!==fromTargetObject.d.length){const longestValue=fromTargetObject.d.length>toTargetObject.d.length?fromTargetObject:toTargetObject;const shortestValue=longestValue===fromTargetObject?toTargetObject:fromTargetObject;shortestValue.d=longestValue.d.map(((_,i)=>isUnd(shortestValue.d[i])?0:shortestValue.d[i]));shortestValue.s=cloneArray(longestValue.s)}const tweenUpdateDuration=round(+tweenDuration||minValue,12);const tween={parent:this,id:tweenId++,property:propName,target:target,_value:null,_func:toFunctionStore.func,_ease:parseEasings(tweenEasing),_fromNumbers:cloneArray(fromTargetObject.d),_toNumbers:cloneArray(toTargetObject.d),_strings:cloneArray(toTargetObject.s),_fromNumber:fromTargetObject.n,_toNumber:toTargetObject.n,_numbers:cloneArray(fromTargetObject.d),_number:fromTargetObject.n,_unit:toTargetObject.u,_modifier:tweenModifier,_currentTime:0,_startTime:tweenStartTime,_delay:+tweenDelay,_updateDuration:tweenUpdateDuration,_changeDuration:tweenUpdateDuration,_absoluteStartTime:absoluteStartTime,_tweenType:tweenType,_valueType:toTargetObject.t,_composition:tweenComposition,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};if(tweenComposition!==compositionTypes.none){composeTween(tween,siblings)}if(isNaN(firstTweenChangeStartTime)){firstTweenChangeStartTime=tween._startTime}lastTweenChangeEndTime=round(tweenStartTime+tweenUpdateDuration,12);prevTween=tween;animationAnimationLength++;addChild(this,tween)}if(isNaN(iterationDelay)||firstTweenChangeStartTime<iterationDelay){iterationDelay=firstTweenChangeStartTime}if(isNaN(iterationDuration)||lastTweenChangeEndTime>iterationDuration){iterationDuration=lastTweenChangeEndTime}if(tweenType===tweenTypes.TRANSFORM){lastTransformGroupIndex=animationAnimationLength-tweenIndex;lastTransformGroupLength=animationAnimationLength}}}if(!isNaN(lastTransformGroupIndex)){let i=0;forEachChildren(this,(tween=>{if(i>=lastTransformGroupIndex&&i<lastTransformGroupLength){tween._renderTransforms=1;if(tween._composition===compositionTypes.blend){forEachChildren(additive.animation,(additiveTween=>{if(additiveTween.id===tween.id){additiveTween._renderTransforms=1}}))}}i++}))}}if(!targetsLength){console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`)}if(iterationDelay){forEachChildren(this,(tween=>{if(!(tween._startTime-tween._delay)){tween._delay-=iterationDelay}tween._startTime-=iterationDelay}));iterationDuration-=iterationDelay}else{iterationDelay=0}if(!iterationDuration){iterationDuration=minValue;this.iterationCount=0}this.targets=parsedTargets;this.duration=iterationDuration===minValue?minValue:clampInfinity((iterationDuration+this._loopDelay)*this.iterationCount-this._loopDelay)||minValue;this.onRender=onRender||animDefaults.onRender;this._ease=animEase;this._delay=iterationDelay;this.iterationDuration=iterationDuration;this._inlineStyles=animInlineStyles;if(!this._autoplay&&shouldTriggerRender)this.onRender(this)}stretch(newDuration){const currentDuration=this.duration;if(currentDuration===normalizeTime(newDuration))return this;const timeScale=newDuration/currentDuration;forEachChildren(this,(tween=>{tween._updateDuration=normalizeTime(tween._updateDuration*timeScale);tween._changeDuration=normalizeTime(tween._changeDuration*timeScale);tween._currentTime*=timeScale;tween._startTime*=timeScale;tween._absoluteStartTime*=timeScale}));return super.stretch(newDuration)}refresh(){forEachChildren(this,(tween=>{const tweenFunc=tween._func;if(tweenFunc){const ogValue=getOriginalAnimatableValue(tween.target,tween.property,tween._tweenType);decomposeRawValue(ogValue,decomposedOriginalValue);decomposeRawValue(tweenFunc(),toTargetObject);tween._fromNumbers=cloneArray(decomposedOriginalValue.d);tween._fromNumber=decomposedOriginalValue.n;tween._toNumbers=cloneArray(toTargetObject.d);tween._strings=cloneArray(toTargetObject.s);tween._toNumber=toTargetObject.o?getRelativeValue(decomposedOriginalValue.n,toTargetObject.n,toTargetObject.o):toTargetObject.n}}));return this}revert(){super.revert();return cleanInlineStyles(this)}then(callback){return super.then(callback)}}const animate=(targets,parameters)=>new JSAnimation(targets,parameters,null,0,false).init();const easingToLinear=(fn,samples=100)=>{const points=[];for(let i=0;i<=samples;i++)points.push(fn(i/samples));return`linear(${points.join(", ")})`};const WAAPIEasesLookups={in:"ease-in",out:"ease-out",inOut:"ease-in-out"};const WAAPIeases=(()=>{const list={};for(let type in easeTypes)list[type]=p=>easeTypes[type](easeInPower(p));return list})();const parseWAAPIEasing=ease=>{let parsedEase=WAAPIEasesLookups[ease];if(parsedEase)return parsedEase;parsedEase="linear";if(isStr(ease)){if(stringStartsWith(ease,"linear")||stringStartsWith(ease,"cubic-")||stringStartsWith(ease,"steps")||stringStartsWith(ease,"ease")){parsedEase=ease}else if(stringStartsWith(ease,"cubicB")){parsedEase=toLowerCase(ease)}else{const parsed=parseEaseString(ease,WAAPIeases,WAAPIEasesLookups);if(isFnc(parsed))parsedEase=parsed===none?"linear":easingToLinear(parsed)}WAAPIEasesLookups[ease]=parsedEase}else if(isFnc(ease)){const easing=easingToLinear(ease);if(easing)parsedEase=easing}else if(ease.ease){parsedEase=easingToLinear(ease.ease)}return parsedEase};const transformsShorthands=["x","y","z"];const commonDefaultPXProperties=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",...transformsShorthands];const validIndividualTransforms=(()=>[...transformsShorthands,...validTransforms.filter((t=>["X","Y","Z"].some((axis=>t.endsWith(axis)))))])();let transformsPropertiesRegistered=null;const WAAPIAnimationsLookups={_head:null,_tail:null};const removeWAAPIAnimation=($el,property,parent)=>{let nextLookup=WAAPIAnimationsLookups._head;while(nextLookup){const next=nextLookup._next;const matchTarget=nextLookup.$el===$el;const matchProperty=!property||nextLookup.property===property;const matchParent=!parent||nextLookup.parent===parent;if(matchTarget&&matchProperty&&matchParent){const anim=nextLookup.animation;try{anim.commitStyles()}catch{}anim.cancel();removeChild(WAAPIAnimationsLookups,nextLookup);const lookupParent=nextLookup.parent;if(lookupParent){lookupParent._completed++;if(lookupParent.animations.length===lookupParent._completed){lookupParent.completed=true;if(!lookupParent.muteCallbacks){lookupParent.paused=true;lookupParent.onComplete(lookupParent);lookupParent._resolve(lookupParent)}}}}nextLookup=next}};const addWAAPIAnimation=(parent,$el,property,keyframes,params)=>{const animation=$el.animate(keyframes,params);const animTotalDuration=params.delay+ +params.duration*params.iterations;animation.playbackRate=parent._speed;if(parent.paused)animation.pause();if(parent.duration<animTotalDuration){parent.duration=animTotalDuration;parent.controlAnimation=animation}parent.animations.push(animation);removeWAAPIAnimation($el,property);addChild(WAAPIAnimationsLookups,{parent:parent,animation:animation,$el:$el,property:property,_next:null,_prev:null});const handleRemove=()=>{removeWAAPIAnimation($el,property,parent)};animation.onremove=handleRemove;animation.onfinish=handleRemove;return animation};const normalizeTweenValue=(propName,value,$el,i,targetsLength)=>{let v=getFunctionValue(value,$el,i,targetsLength);if(!isNum(v))return v;if(commonDefaultPXProperties.includes(propName)||stringStartsWith(propName,"translate"))return`${v}px`;if(stringStartsWith(propName,"rotate")||stringStartsWith(propName,"skew"))return`${v}deg`;return`${v}`};const parseIndividualTweenValue=($el,propName,from,to,i,targetsLength)=>{let tweenValue="0";const computedTo=!isUnd(to)?normalizeTweenValue(propName,to,$el,i,targetsLength):getComputedStyle($el)[propName];if(!isUnd(from)){const computedFrom=normalizeTweenValue(propName,from,$el,i,targetsLength);tweenValue=[computedFrom,computedTo]}else{tweenValue=isArr(to)?to.map((v=>normalizeTweenValue(propName,v,$el,i,targetsLength))):computedTo}return tweenValue};class WAAPIAnimation{constructor(targets,params){if(scope.current)scope.current.register(this);if(isNil(transformsPropertiesRegistered)){if(isBrowser&&(isUnd(CSS)||!Object.hasOwnProperty.call(CSS,"registerProperty"))){transformsPropertiesRegistered=false}else{validTransforms.forEach((t=>{const isSkew=stringStartsWith(t,"skew");const isScale=stringStartsWith(t,"scale");const isRotate=stringStartsWith(t,"rotate");const isTranslate=stringStartsWith(t,"translate");const isAngle=isRotate||isSkew;const syntax=isAngle?"<angle>":isScale?"<number>":isTranslate?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:syntax,inherits:false,initialValue:isTranslate?"0px":isAngle?"0deg":isScale?"1":"0"})}catch{}}));transformsPropertiesRegistered=true}}const parsedTargets=registerTargets(targets);const targetsLength=parsedTargets.length;if(!targetsLength){console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`)}const ease=setValue(params.ease,parseWAAPIEasing(globals.defaults.ease));const spring=ease.ease&&ease;const autoplay=setValue(params.autoplay,globals.defaults.autoplay);const scroll=autoplay&&autoplay.link?autoplay:false;const alternate=params.alternate&&params.alternate===true;const reversed=params.reversed&&params.reversed===true;const loop=setValue(params.loop,globals.defaults.loop);const iterations=loop===true||loop===Infinity?Infinity:isNum(loop)?loop+1:1;const direction=alternate?reversed?"alternate-reverse":"alternate":reversed?"reverse":"normal";const fill="forwards";const easing=parseWAAPIEasing(ease);const timeScale=globals.timeScale===1?1:K;this.targets=parsedTargets;this.animations=[];this.controlAnimation=null;this.onComplete=params.onComplete||noop;this.duration=0;this.muteCallbacks=false;this.completed=false;this.paused=!autoplay||scroll!==false;this.reversed=reversed;this.autoplay=autoplay;this._speed=setValue(params.playbackRate,globals.defaults.playbackRate);this._resolve=noop;this._completed=0;this._inlineStyles=parsedTargets.map(($el=>$el.getAttribute("style")));parsedTargets.forEach((($el,i)=>{const cachedTransforms=$el[transformsSymbol];const hasIndividualTransforms=validIndividualTransforms.some((t=>params.hasOwnProperty(t)));const duration=(spring?spring.duration:getFunctionValue(setValue(params.duration,globals.defaults.duration),$el,i,targetsLength))*timeScale;const delay=getFunctionValue(setValue(params.delay,globals.defaults.delay),$el,i,targetsLength)*timeScale;const composite=setValue(params.composition,"replace");for(let name in params){if(!isKey(name))continue;const keyframes={};const tweenParams={iterations:iterations,direction:direction,fill:fill,easing:easing,duration:duration,delay:delay,composite:composite};const propertyValue=params[name];const individualTransformProperty=hasIndividualTransforms?validTransforms.includes(name)?name:shortTransforms.get(name):false;let parsedPropertyValue;if(isObj(propertyValue)){const tweenOptions=propertyValue;const tweenOptionsEase=setValue(tweenOptions.ease,ease);const tweenOptionsSpring=tweenOptionsEase.ease&&tweenOptionsEase;const to=tweenOptions.to;const from=tweenOptions.from;tweenParams.duration=(tweenOptionsSpring?tweenOptionsSpring.duration:getFunctionValue(setValue(tweenOptions.duration,duration),$el,i,targetsLength))*timeScale;tweenParams.delay=getFunctionValue(setValue(tweenOptions.delay,delay),$el,i,targetsLength)*timeScale;tweenParams.composite=setValue(tweenOptions.composition,composite);tweenParams.easing=parseWAAPIEasing(tweenOptionsEase);parsedPropertyValue=parseIndividualTweenValue($el,name,from,to,i,targetsLength);if(individualTransformProperty){keyframes[`--${individualTransformProperty}`]=parsedPropertyValue;cachedTransforms[individualTransformProperty]=parsedPropertyValue}else{keyframes[name]=parseIndividualTweenValue($el,name,from,to,i,targetsLength)}addWAAPIAnimation(this,$el,name,keyframes,tweenParams);if(!isUnd(from)){if(!individualTransformProperty){$el.style[name]=keyframes[name][0]}else{const key=`--${individualTransformProperty}`;$el.style.setProperty(key,keyframes[key][0])}}}else{parsedPropertyValue=isArr(propertyValue)?propertyValue.map((v=>normalizeTweenValue(name,v,$el,i,targetsLength))):normalizeTweenValue(name,propertyValue,$el,i,targetsLength);if(individualTransformProperty){keyframes[`--${individualTransformProperty}`]=parsedPropertyValue;cachedTransforms[individualTransformProperty]=parsedPropertyValue}else{keyframes[name]=parsedPropertyValue}addWAAPIAnimation(this,$el,name,keyframes,tweenParams)}}if(hasIndividualTransforms){let transforms=emptyString;for(let t in cachedTransforms){transforms+=`${transformsFragmentStrings[t]}var(--${t})) `}$el.style.transform=transforms}}));if(scroll){this.autoplay.link(this)}}forEach(callback){const cb=isStr(callback)?a=>a[callback]():callback;this.animations.forEach(cb);return this}get speed(){return this._speed}set speed(speed){this._speed=+speed;this.forEach((anim=>anim.playbackRate=speed))}get currentTime(){const controlAnimation=this.controlAnimation;const timeScale=globals.timeScale;return this.completed?this.duration:controlAnimation?+controlAnimation.currentTime*(timeScale===1?1:timeScale):0}set currentTime(time){const t=time*(globals.timeScale===1?1:K);this.forEach((anim=>{if(t>=this.duration)anim.play();anim.currentTime=t}))}get progress(){return this.currentTime/this.duration}set progress(progress){this.forEach((anim=>anim.currentTime=progress*this.duration||0))}resume(){if(!this.paused)return this;this.paused=false;return this.forEach("play")}pause(){if(this.paused)return this;this.paused=true;return this.forEach("pause")}alternate(){this.reversed=!this.reversed;this.forEach("reverse");if(this.paused)this.forEach("pause");return this}play(){if(this.reversed)this.alternate();return this.resume()}reverse(){if(!this.reversed)this.alternate();return this.resume()}seek(time,muteCallbacks=false){if(muteCallbacks)this.muteCallbacks=true;if(time<this.duration)this.completed=false;this.currentTime=time;this.muteCallbacks=false;if(this.paused)this.pause();return this}restart(){this.completed=false;return this.seek(0,true).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){this.forEach("cancel");return this.pause()}revert(){this.cancel();this.targets.forEach((($el,i)=>$el.setAttribute("style",this._inlineStyles[i])));return this}then(callback=noop){const then=this.then;const onResolve=()=>{this.then=null;callback(this);this.then=then;this._resolve=noop};return new Promise((r=>{this._resolve=()=>r(onResolve());if(this.completed)this._resolve();return this}))}}const waapi={animate:(targets,params)=>new WAAPIAnimation(targets,params),convertEase:easingToLinear};const sync=(callback=noop)=>new Timer({duration:1*globals.timeScale,onComplete:callback},null,0).resume();function getTargetValue(targetSelector,propName,unit){const targets=registerTargets(targetSelector);if(!targets.length)return;const[target]=targets;const tweenType=getTweenType(target,propName);const normalizePropName=sanitizePropertyName(propName,target,tweenType);let originalValue=getOriginalAnimatableValue(target,normalizePropName);if(isUnd(unit)){return originalValue}else{decomposeRawValue(originalValue,decomposedOriginalValue);if(decomposedOriginalValue.t===valueTypes.NUMBER||decomposedOriginalValue.t===valueTypes.UNIT){if(unit===false){return decomposedOriginalValue.n}else{const convertedValue=convertValueUnit(target,decomposedOriginalValue,unit,false);return`${round(convertedValue.n,globals.precision)}${convertedValue.u}`}}}}const setTargetValues=(targets,parameters)=>{if(isUnd(parameters))return;parameters.duration=minValue;parameters.composition=setValue(parameters.composition,compositionTypes.none);return new JSAnimation(targets,parameters,null,0,true).resume()};const removeTargetsFromAnimation=(targetsArray,animation,propertyName)=>{let tweensMatchesTargets=false;forEachChildren(animation,(tween=>{const tweenTarget=tween.target;if(targetsArray.includes(tweenTarget)){const tweenName=tween.property;const tweenType=tween._tweenType;const normalizePropName=sanitizePropertyName(propertyName,tweenTarget,tweenType);if(!normalizePropName||normalizePropName&&normalizePropName===tweenName){if(tween.parent._tail===tween&&tween._tweenType===tweenTypes.TRANSFORM&&tween._prev&&tween._prev._tweenType===tweenTypes.TRANSFORM){tween._prev._renderTransforms=1}removeChild(animation,tween);removeTweenSliblings(tween);tweensMatchesTargets=true}}}),true);return tweensMatchesTargets};const remove=(targets,renderable,propertyName)=>{const targetsArray=parseTargets(targets);const parent=renderable?renderable:engine;const waapiAnimation=renderable&&renderable.controlAnimation&&renderable;for(let i=0,l=targetsArray.length;i<l;i++){const $el=targetsArray[i];removeWAAPIAnimation($el,propertyName,waapiAnimation)}let removeMatches;if(parent._hasChildren){let iterationDuration=0;forEachChildren(parent,(child=>{if(!child._hasChildren){removeMatches=removeTargetsFromAnimation(targetsArray,child,propertyName);if(removeMatches&&!child._head){child.cancel();removeChild(parent,child)}else{const childTLOffset=child._offset+child._delay;const childDur=childTLOffset+child.duration;if(childDur>iterationDuration){iterationDuration=childDur}}}if(child._head){remove(targets,child,propertyName)}else{child._hasChildren=false}}),true);if(!isUnd(parent.iterationDuration)){parent.iterationDuration=iterationDuration}}else{removeMatches=removeTargetsFromAnimation(targetsArray,parent,propertyName)}if(removeMatches&&!parent._head){parent._hasChildren=false;if(parent.cancel)parent.cancel()}return targetsArray};const keepTime=createRefreshable;const randomPick=items=>items[random(0,items.length-1)];const roundPad=(v,decimalLength)=>(+v).toFixed(decimalLength);const padStart=(v,totalLength,padString)=>`${v}`.padStart(totalLength,padString);const padEnd=(v,totalLength,padString)=>`${v}`.padEnd(totalLength,padString);const wrap=(v,min,max)=>((v-min)%(max-min)+(max-min))%(max-min)+min;const mapRange=(value,inLow,inHigh,outLow,outHigh)=>outLow+(value-inLow)/(inHigh-inLow)*(outHigh-outLow);const degToRad=degrees=>degrees*PI/180;const radToDeg=radians=>radians*180/PI;const lerp=(start,end,amount,renderable)=>{let dt=K/globals.defaults.frameRate;if(renderable!==false){const ticker=renderable||engine._hasChildren&&engine;if(ticker&&ticker.deltaTime){dt=ticker.deltaTime}}const t=1-Math.exp(-amount*dt*.1);return!amount?start:amount===1?end:(1-t)*start+t*end};const curry=(fn,last=0)=>(...args)=>last?v=>fn(...args,v):v=>fn(v,...args);const chain=fn=>(...args)=>{const result=fn(...args);return new Proxy(noop,{apply:(_,__,[v])=>result(v),get:(_,prop)=>chain(((...nextArgs)=>{const nextResult=utils[prop](...nextArgs);return v=>nextResult(result(v))}))})};const makeChainable=(fn,right=0)=>(...args)=>(args.length<fn.length?chain(curry(fn,right)):fn)(...args);const utils={$:registerTargets,get:getTargetValue,set:setTargetValues,remove:remove,cleanInlineStyles:cleanInlineStyles,random:random,randomPick:randomPick,shuffle:shuffle,lerp:lerp,sync:sync,keepTime:keepTime,clamp:makeChainable(clamp),round:makeChainable(round),snap:makeChainable(snap),wrap:makeChainable(wrap),interpolate:makeChainable(interpolate,1),mapRange:makeChainable(mapRange),roundPad:makeChainable(roundPad),padStart:makeChainable(padStart),padEnd:makeChainable(padEnd),degToRad:makeChainable(degToRad),radToDeg:makeChainable(radToDeg)};const getPrevChildOffset=(timeline,timePosition)=>{if(stringStartsWith(timePosition,"<")){const goToPrevAnimationOffset=timePosition[1]==="<";const prevAnimation=timeline._tail;const prevOffset=prevAnimation?prevAnimation._offset+prevAnimation._delay:0;return goToPrevAnimationOffset?prevOffset:prevOffset+prevAnimation.duration}};const parseTimelinePosition=(timeline,timePosition)=>{let tlDuration=timeline.iterationDuration;if(tlDuration===minValue)tlDuration=0;if(isUnd(timePosition))return tlDuration;if(isNum(+timePosition))return+timePosition;const timePosStr=timePosition;const tlLabels=timeline?timeline.labels:null;const hasLabels=!isNil(tlLabels);const prevOffset=getPrevChildOffset(timeline,timePosStr);const hasSibling=!isUnd(prevOffset);const matchedRelativeOperator=relativeValuesExecRgx.exec(timePosStr);if(matchedRelativeOperator){const fullOperator=matchedRelativeOperator[0];const split=timePosStr.split(fullOperator);const labelOffset=hasLabels&&split[0]?tlLabels[split[0]]:tlDuration;const parsedOffset=hasSibling?prevOffset:hasLabels?labelOffset:tlDuration;const parsedNumericalOffset=+split[1];return getRelativeValue(parsedOffset,parsedNumericalOffset,fullOperator[0])}else{return hasSibling?prevOffset:hasLabels?!isUnd(tlLabels[timePosStr])?tlLabels[timePosStr]:tlDuration:tlDuration}};function getTimelineTotalDuration(tl){return clampInfinity((tl.iterationDuration+tl._loopDelay)*tl.iterationCount-tl._loopDelay)||minValue}function addTlChild(childParams,tl,timePosition,targets,index,length){const isSetter=isNum(childParams.duration)&&childParams.duration<=minValue;const adjustedPosition=isSetter?timePosition-minValue:timePosition;tick(tl,adjustedPosition,1,1,tickModes.AUTO);const tlChild=targets?new JSAnimation(targets,childParams,tl,adjustedPosition,false,index,length):new Timer(childParams,tl,adjustedPosition);tlChild.init(1);addChild(tl,tlChild);forEachChildren(tl,(child=>{const childTLOffset=child._offset+child._delay;const childDur=childTLOffset+child.duration;if(childDur>tl.iterationDuration)tl.iterationDuration=childDur}));tl.duration=getTimelineTotalDuration(tl);return tl}class Timeline extends Timer{constructor(parameters={}){super(parameters,null,0);this.duration=0;this.labels={};const defaultsParams=parameters.defaults;const globalDefaults=globals.defaults;this.defaults=defaultsParams?mergeObjects(defaultsParams,globalDefaults):globalDefaults;this.onRender=parameters.onRender||globalDefaults.onRender;const tlPlaybackEase=setValue(parameters.playbackEase,globalDefaults.playbackEase);this._ease=tlPlaybackEase?parseEasings(tlPlaybackEase):null;this.iterationDuration=0}add(a1,a2,a3){const isAnim=isObj(a2);const isTimer=isObj(a1);if(isAnim||isTimer){this._hasChildren=true;if(isAnim){const childParams=a2;if(isFnc(a3)){const staggeredPosition=a3;const parsedTargetsArray=parseTargets(a1);const tlDuration=this.duration;const tlIterationDuration=this.iterationDuration;const id=childParams.id;let i=0;const parsedLength=parsedTargetsArray.length;parsedTargetsArray.forEach((target=>{const staggeredChildParams={...childParams};this.duration=tlDuration;this.iterationDuration=tlIterationDuration;if(!isUnd(id))staggeredChildParams.id=id+"-"+i;addTlChild(staggeredChildParams,this,parseTimelinePosition(this,staggeredPosition(target,i,parsedLength,this)),target,i,parsedLength);i++}))}else{addTlChild(childParams,this,parseTimelinePosition(this,a3),a1)}}else{addTlChild(a1,this,parseTimelinePosition(this,a2))}return this.init(1)}}sync(synced,position){if(isUnd(synced)||synced&&isUnd(synced.pause))return this;synced.pause();const duration=+(synced.effect?synced.effect.getTiming().duration:synced.duration);return this.add(synced,{currentTime:[0,duration],duration:duration,ease:"linear"},position)}set(targets,parameters,position){if(isUnd(parameters))return this;parameters.duration=minValue;parameters.composition=compositionTypes.replace;return this.add(targets,parameters,position)}call(callback,position){if(isUnd(callback)||callback&&!isFnc(callback))return this;return this.add({duration:0,onComplete:()=>callback(this)},position)}label(labelName,position){if(isUnd(labelName)||labelName&&!isStr(labelName))return this;this.labels[labelName]=parseTimelinePosition(this,position);return this}remove(targets,propertyName){remove(targets,this,propertyName);return this}stretch(newDuration){const currentDuration=this.duration;if(currentDuration===normalizeTime(newDuration))return this;const timeScale=newDuration/currentDuration;const labels=this.labels;forEachChildren(this,(child=>child.stretch(child.duration*timeScale)));for(let labelName in labels)labels[labelName]*=timeScale;return super.stretch(newDuration)}refresh(){forEachChildren(this,(child=>{if(child.refresh)child.refresh()}));return this}revert(){super.revert();forEachChildren(this,(child=>child.revert),true);return cleanInlineStyles(this)}then(callback){return super.then(callback)}}const createTimeline=parameters=>new Timeline(parameters).init();class Animatable{constructor(targets,parameters){if(scope.current)scope.current.register(this);const beginHandler=()=>{if(this.callbacks.completed)this.callbacks.reset();this.callbacks.play()};const pauseHandler=()=>{if(this.callbacks.completed)return;let paused=true;for(let name in this.animations){const anim=this.animations[name];if(!anim.paused&&paused){paused=false;break}}if(paused){this.callbacks.complete()}};const globalParams={onBegin:beginHandler,onComplete:pauseHandler,onPause:pauseHandler};const callbacksAnimationParams={v:1,autoplay:false};const properties={};this.targets=[];this.animations={};this.callbacks=null;if(isUnd(targets)||isUnd(parameters))return;for(let propName in parameters){const paramValue=parameters[propName];if(isKey(propName)){properties[propName]=paramValue}else if(stringStartsWith(propName,"on")){callbacksAnimationParams[propName]=paramValue}else{globalParams[propName]=paramValue}}this.callbacks=new JSAnimation({v:0},callbacksAnimationParams);for(let propName in properties){const propValue=properties[propName];const isObjValue=isObj(propValue);let propParams={};let to="+=0";if(isObjValue){const unit=propValue.unit;if(isStr(unit))to+=unit}else{propParams.duration=propValue}propParams[propName]=isObjValue?mergeObjects({to:to},propValue):to;const animParams=mergeObjects(globalParams,propParams);animParams.composition=compositionTypes.replace;animParams.autoplay=false;const animation=this.animations[propName]=new JSAnimation(targets,animParams,null,0,false).init();if(!this.targets.length)this.targets.push(...animation.targets);this[propName]=(to,duration,ease)=>{const tween=animation._head;if(isUnd(to)&&tween){const numbers=tween._numbers;if(numbers&&numbers.length){return numbers}else{return tween._modifier(tween._number)}}else{forEachChildren(animation,(tween=>{if(isArr(to)){for(let i=0,l=to.length;i<l;i++){if(!isUnd(tween._numbers[i])){tween._fromNumbers[i]=tween._modifier(tween._numbers[i]);tween._toNumbers[i]=to[i]}}}else{tween._fromNumber=tween._modifier(tween._number);tween._toNumber=to}if(!isUnd(ease))tween._ease=parseEasings(ease);tween._currentTime=0}));if(!isUnd(duration))animation.stretch(duration);animation.reset(1).resume();return this}}}}revert(){for(let propName in this.animations){this[propName]=noop;this.animations[propName].revert()}this.animations={};this.targets.length=0;if(this.callbacks)this.callbacks.revert();return this}}const createAnimatable=(targets,parameters)=>new Animatable(targets,parameters);const maxSpringParamValue=K*10;class Spring{constructor(parameters={}){this.timeStep=.02;this.restThreshold=5e-4;this.restDuration=200;this.maxDuration=6e4;this.maxRestSteps=this.restDuration/this.timeStep/K;this.maxIterations=this.maxDuration/this.timeStep/K;this.m=clamp(setValue(parameters.mass,1),0,maxSpringParamValue);this.s=clamp(setValue(parameters.stiffness,100),1,maxSpringParamValue);this.d=clamp(setValue(parameters.damping,10),.1,maxSpringParamValue);this.v=clamp(setValue(parameters.velocity,0),-1e4,maxSpringParamValue);this.w0=0;this.zeta=0;this.wd=0;this.b=0;this.solverDuration=0;this.duration=0;this.compute();this.ease=t=>t===0||t===1?t:this.solve(t*this.solverDuration)}solve(time){const{zeta:zeta,w0:w0,wd:wd,b:b}=this;let t=time;if(zeta<1){t=exp(-t*zeta*w0)*(1*cos(wd*t)+b*sin(wd*t))}else{t=(1+b*t)*exp(-t*w0)}return 1-t}compute(){const{maxRestSteps:maxRestSteps,maxIterations:maxIterations,restThreshold:restThreshold,timeStep:timeStep,m:m,d:d,s:s,v:v}=this;const w0=this.w0=clamp(sqrt(s/m),minValue,K);const zeta=this.zeta=d/(2*sqrt(s*m));const wd=this.wd=zeta<1?w0*sqrt(1-zeta*zeta):0;this.b=zeta<1?(zeta*w0+-v)/wd:-v+w0;let solverTime=0;let restSteps=0;let iterations=0;while(restSteps<maxRestSteps&&iterations<maxIterations){if(abs(1-this.solve(solverTime))<restThreshold){restSteps++}else{restSteps=0}this.solverDuration=solverTime;solverTime+=timeStep;iterations++}this.duration=round(this.solverDuration*K,0)*globals.timeScale}get mass(){return this.m}set mass(v){this.m=clamp(setValue(v,1),0,maxSpringParamValue);this.compute()}get stiffness(){return this.s}set stiffness(v){this.s=clamp(setValue(v,100),1,maxSpringParamValue);this.compute()}get damping(){return this.d}set damping(v){this.d=clamp(setValue(v,10),.1,maxSpringParamValue);this.compute()}get velocity(){return this.v}set velocity(v){this.v=clamp(setValue(v,0),-1e4,maxSpringParamValue);this.compute()}}const createSpring=parameters=>new Spring(parameters);const preventDefault=e=>{if(e.cancelable)e.preventDefault()};class DOMProxy{constructor(el){this.el=el;this.zIndex=0;this.parentElement=null;this.classList={add:noop,remove:noop}}get x(){return this.el.x||0}set x(v){this.el.x=v}get y(){return this.el.y||0}set y(v){this.el.y=v}get width(){return this.el.width||0}set width(v){this.el.width=v}get height(){return this.el.height||0}set height(v){this.el.height=v}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class Transforms{constructor($el){this.$el=$el;this.inlineTransforms=[];this.point=new DOMPoint;this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(x,y){this.point.x=x;this.point.y=y;return this.point.matrixTransform(this.inversedMatrix)}traverseUp(cb){let $el=this.$el.parentElement,i=0;while($el&&$el!==doc){cb($el,i);$el=$el.parentElement;i++}}getMatrix(){const matrix=new DOMMatrix;this.traverseUp(($el=>{const transformValue=getComputedStyle($el).transform;if(transformValue){const elMatrix=new DOMMatrix(transformValue);matrix.preMultiplySelf(elMatrix)}}));return matrix}remove(){this.traverseUp((($el,i)=>{this.inlineTransforms[i]=$el.style.transform;$el.style.transform="none"}))}revert(){this.traverseUp((($el,i)=>{const ct=this.inlineTransforms[i];if(ct===""){$el.style.removeProperty("transform")}else{$el.style.transform=ct}}))}}const parseDraggableFunctionParameter=(value,draggable)=>value&&isFnc(value)?value(draggable):value;let zIndex=0;class Draggable{constructor(target,parameters={}){if(!target)return;if(scope.current)scope.current.register(this);const paramX=parameters.x;const paramY=parameters.y;const trigger=parameters.trigger;const modifier=parameters.modifier;const ease=parameters.releaseEase;const customEase=ease&&parseEasings(ease);const hasSpring=!isUnd(ease)&&!isUnd(ease.ease);const xProp=isObj(paramX)&&!isUnd(paramX.mapTo)?paramX.mapTo:"translateX";const yProp=isObj(paramY)&&!isUnd(paramY.mapTo)?paramY.mapTo:"translateY";const container=parseDraggableFunctionParameter(parameters.container,this);this.containerArray=isArr(container)?container:null;this.$container=container&&!this.containerArray?parseTargets(container)[0]:doc.body;this.useWin=this.$container===doc.body;this.$scrollContainer=this.useWin?win:this.$container;this.$target=isObj(target)?new DOMProxy(target):parseTargets(target)[0];this.$trigger=parseTargets(trigger?trigger:target)[0];this.fixed=getTargetValue(this.$target,"position")==="fixed";this.isFinePointer=true;this.containerPadding=[0,0,0,0];this.containerFriction=0;this.releaseContainerFriction=0;this.snapX=0;this.snapY=0;this.scrollSpeed=0;this.scrollThreshold=0;this.dragSpeed=0;this.maxVelocity=0;this.minVelocity=0;this.velocityMultiplier=0;this.cursor=false;this.releaseXSpring=hasSpring?ease:createSpring({mass:setValue(parameters.releaseMass,1),stiffness:setValue(parameters.releaseStiffness,80),damping:setValue(parameters.releaseDamping,20)});this.releaseYSpring=hasSpring?ease:createSpring({mass:setValue(parameters.releaseMass,1),stiffness:setValue(parameters.releaseStiffness,80),damping:setValue(parameters.releaseDamping,20)});this.releaseEase=customEase||eases.outQuint;this.hasReleaseSpring=hasSpring;this.onGrab=parameters.onGrab||noop;this.onDrag=parameters.onDrag||noop;this.onRelease=parameters.onRelease||noop;this.onUpdate=parameters.onUpdate||noop;this.onSettle=parameters.onSettle||noop;this.onSnap=parameters.onSnap||noop;this.onResize=parameters.onResize||noop;this.onAfterResize=parameters.onAfterResize||noop;this.disabled=[0,0];const animatableParams={};if(modifier)animatableParams.modifier=modifier;if(isUnd(paramX)||paramX===true){animatableParams[xProp]=0}else if(isObj(paramX)){const paramXObject=paramX;const animatableXParams={};if(paramXObject.modifier)animatableXParams.modifier=paramXObject.modifier;if(paramXObject.composition)animatableXParams.composition=paramXObject.composition;animatableParams[xProp]=animatableXParams}else if(paramX===false){animatableParams[xProp]=0;this.disabled[0]=1}if(isUnd(paramY)||paramY===true){animatableParams[yProp]=0}else if(isObj(paramY)){const paramYObject=paramY;const animatableYParams={};if(paramYObject.modifier)animatableYParams.modifier=paramYObject.modifier;if(paramYObject.composition)animatableYParams.composition=paramYObject.composition;animatableParams[yProp]=animatableYParams}else if(paramY===false){animatableParams[yProp]=0;this.disabled[1]=1}this.animate=new Animatable(this.$target,animatableParams);this.xProp=xProp;this.yProp=yProp;this.destX=0;this.destY=0;this.deltaX=0;this.deltaY=0;this.scroll={x:0,y:0};this.coords=[this.x,this.y,0,0];this.snapped=[0,0];this.pointer=[0,0,0,0,0,0,0,0];this.scrollView=[0,0];this.dragArea=[0,0,0,0];this.containerBounds=[-1e12,maxValue,maxValue,-1e12];this.scrollBounds=[0,0,0,0];this.targetBounds=[0,0,0,0];this.window=[0,0];this.velocityStack=[0,0,0];this.velocityStackIndex=0;this.velocityTime=now();this.velocity=0;this.angle=0;this.cursorStyles=null;this.triggerStyles=null;this.bodyStyles=null;this.targetStyles=null;this.touchActionStyles=null;this.transforms=new Transforms(this.$target);this.overshootCoords={x:0,y:0};this.overshootTicker=new Timer({autoplay:false,onUpdate:()=>{this.updated=true;this.manual=true;if(!this.disabled[0])this.animate[this.xProp](this.overshootCoords.x,1);if(!this.disabled[1])this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=false;if(!this.disabled[0])this.animate[this.xProp](this.overshootCoords.x,0);if(!this.disabled[1])this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init();this.updateTicker=new Timer({autoplay:false,onUpdate:()=>this.update()},null,0).init();this.contained=!isUnd(container);this.manual=false;this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.enabled=false;this.initialized=false;this.activeProp=this.disabled[1]?xProp:yProp;this.animate.callbacks.onRender=()=>{const hasUpdated=this.updated;const hasMoved=this.grabbed&&hasUpdated;const hasReleased=!hasMoved&&this.released;const x=this.x;const y=this.y;const dx=x-this.coords[2];const dy=y-this.coords[3];this.deltaX=dx;this.deltaY=dy;this.coords[2]=x;this.coords[3]=y;if(hasUpdated&&(dx||dy)){this.onUpdate(this)}if(!hasReleased){this.updated=false}else{this.computeVelocity(dx,dy);this.angle=atan2(dy,dx)}};this.animate.callbacks.onComplete=()=>{if(!this.grabbed&&this.released){this.released=false}if(!this.manual){this.deltaX=0;this.deltaY=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.onSettle(this)}};this.resizeTicker=new Timer({autoplay:false,duration:150*globals.timeScale,onComplete:()=>{this.onResize(this);this.refresh();this.onAfterResize(this)}}).init();this.parameters=parameters;this.resizeObserver=new ResizeObserver((()=>{if(this.initialized){this.resizeTicker.restart()}else{this.initialized=true}}));this.enable();this.refresh();this.resizeObserver.observe(this.$container);if(!isObj(target))this.resizeObserver.observe(this.$target)}computeVelocity(dx,dy){const prevTime=this.velocityTime;const curTime=now();const elapsed=curTime-prevTime;if(elapsed<17)return this.velocity;this.velocityTime=curTime;const velocityStack=this.velocityStack;const vMul=this.velocityMultiplier;const minV=this.minVelocity;const maxV=this.maxVelocity;const vi=this.velocityStackIndex;velocityStack[vi]=round(clamp(sqrt(dx*dx+dy*dy)/elapsed*vMul,minV,maxV),5);const velocity=max(velocityStack[0],velocityStack[1],velocityStack[2]);this.velocity=velocity;this.velocityStackIndex=(vi+1)%3;return velocity}setX(x,muteUpdateCallback=false){if(this.disabled[0])return;const v=round(x,5);this.overshootTicker.pause();this.manual=true;this.updated=!muteUpdateCallback;this.destX=v;this.snapped[0]=snap(v,this.snapX);this.animate[this.xProp](v,0);this.manual=false;return this}setY(y,muteUpdateCallback=false){if(this.disabled[1])return;const v=round(y,5);this.overshootTicker.pause();this.manual=true;this.updated=!muteUpdateCallback;this.destY=v;this.snapped[1]=snap(v,this.snapY);this.animate[this.yProp](v,0);this.manual=false;return this}get x(){return round(this.animate[this.xProp](),globals.precision)}set x(x){this.setX(x,false)}get y(){return round(this.animate[this.yProp](),globals.precision)}set y(y){this.setY(y,false)}get progressX(){return mapRange(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(x){this.setX(mapRange(x,0,1,this.containerBounds[3],this.containerBounds[1]),false)}get progressY(){return mapRange(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(y){this.setY(mapRange(y,0,1,this.containerBounds[0],this.containerBounds[2]),false)}updateScrollCoords(){const sx=round(this.useWin?win.scrollX:this.$container.scrollLeft,0);const sy=round(this.useWin?win.scrollY:this.$container.scrollTop,0);const[cpt,cpr,cpb,cpl]=this.containerPadding;const threshold=this.scrollThreshold;this.scroll.x=sx;this.scroll.y=sy;this.scrollBounds[0]=sy-this.targetBounds[0]+cpt-threshold;this.scrollBounds[1]=sx-this.targetBounds[1]-cpr+threshold;this.scrollBounds[2]=sy-this.targetBounds[2]-cpb+threshold;this.scrollBounds[3]=sx-this.targetBounds[3]+cpl-threshold}updateBoundingValues(){const $container=this.$container;if(!$container)return;const cx=this.x;const cy=this.y;const cx2=this.coords[2];const cy2=this.coords[3];this.coords[2]=0;this.coords[3]=0;this.setX(0,true);this.setY(0,true);this.transforms.remove();const iw=this.window[0]=win.innerWidth;const ih=this.window[1]=win.innerHeight;const uw=this.useWin;const sw=$container.scrollWidth;const sh=$container.scrollHeight;const fx=this.fixed;const transformContainerRect=$container.getBoundingClientRect();const[cpt,cpr,cpb,cpl]=this.containerPadding;this.dragArea[0]=uw?0:transformContainerRect.left;this.dragArea[1]=uw?0:transformContainerRect.top;this.scrollView[0]=uw?clamp(sw,iw,sw):sw;this.scrollView[1]=uw?clamp(sh,ih,sh):sh;this.updateScrollCoords();const{width:width,height:height,left:left,top:top,right:right,bottom:bottom}=$container.getBoundingClientRect();this.dragArea[2]=round(uw?clamp(width,iw,iw):width,0);this.dragArea[3]=round(uw?clamp(height,ih,ih):height,0);const containerOverflow=getTargetValue($container,"overflow");const visibleOverflow=containerOverflow==="visible";const hiddenOverflow=containerOverflow==="hidden";this.canScroll=fx?false:this.contained&&($container===doc.body&&visibleOverflow||!hiddenOverflow&&!visibleOverflow)&&(sw>this.dragArea[2]+cpl-cpr||sh>this.dragArea[3]+cpt-cpb)&&(!this.containerArray||this.containerArray&&!isArr(this.containerArray));if(this.contained){const sx=this.scroll.x;const sy=this.scroll.y;const canScroll=this.canScroll;const targetRect=this.$target.getBoundingClientRect();const hiddenLeft=canScroll?uw?0:$container.scrollLeft:0;const hiddenTop=canScroll?uw?0:$container.scrollTop:0;const hiddenRight=canScroll?this.scrollView[0]-hiddenLeft-width:0;const hiddenBottom=canScroll?this.scrollView[1]-hiddenTop-height:0;this.targetBounds[0]=round(targetRect.top+sy-(uw?0:top),0);this.targetBounds[1]=round(targetRect.right+sx-(uw?iw:right),0);this.targetBounds[2]=round(targetRect.bottom+sy-(uw?ih:bottom),0);this.targetBounds[3]=round(targetRect.left+sx-(uw?0:left),0);if(this.containerArray){this.containerBounds[0]=this.containerArray[0]+cpt;this.containerBounds[1]=this.containerArray[1]-cpr;this.containerBounds[2]=this.containerArray[2]-cpb;this.containerBounds[3]=this.containerArray[3]+cpl}else{this.containerBounds[0]=-round(targetRect.top-(fx?clamp(top,0,ih):top)+hiddenTop-cpt,0);this.containerBounds[1]=-round(targetRect.right-(fx?clamp(right,0,iw):right)-hiddenRight+cpr,0);this.containerBounds[2]=-round(targetRect.bottom-(fx?clamp(bottom,0,ih):bottom)-hiddenBottom+cpb,0);this.containerBounds[3]=-round(targetRect.left-(fx?clamp(left,0,iw):left)+hiddenLeft-cpl,0)}}this.transforms.revert();this.coords[2]=cx2;this.coords[3]=cy2;this.setX(cx,true);this.setY(cy,true)}isOutOfBounds(bounds,x,y){if(!this.contained)return 0;const[bt,br,bb,bl]=bounds;const[dx,dy]=this.disabled;const obx=!dx&&x<bl||!dx&&x>br;const oby=!dy&&y<bt||!dy&&y>bb;return obx&&!oby?1:!obx&&oby?2:obx&&oby?3:0}refresh(){const params=this.parameters;const paramX=params.x;const paramY=params.y;const container=parseDraggableFunctionParameter(params.container,this);const cp=parseDraggableFunctionParameter(params.containerPadding,this)||0;const containerPadding=isArr(cp)?cp:[cp,cp,cp,cp];const cx=this.x;const cy=this.y;const parsedCursorStyles=parseDraggableFunctionParameter(params.cursor,this);const cursorStyles={onHover:"grab",onGrab:"grabbing"};if(parsedCursorStyles){const{onHover:onHover,onGrab:onGrab}=parsedCursorStyles;if(onHover)cursorStyles.onHover=onHover;if(onGrab)cursorStyles.onGrab=onGrab}this.containerArray=isArr(container)?container:null;this.$container=container&&!this.containerArray?parseTargets(container)[0]:doc.body;this.useWin=this.$container===doc.body;this.$scrollContainer=this.useWin?win:this.$container;this.isFinePointer=matchMedia("(pointer:fine)").matches;this.containerPadding=setValue(containerPadding,[0,0,0,0]);this.containerFriction=clamp(setValue(parseDraggableFunctionParameter(params.containerFriction,this),.8),0,1);this.releaseContainerFriction=clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction,this),this.containerFriction),0,1);this.snapX=parseDraggableFunctionParameter(isObj(paramX)&&!isUnd(paramX.snap)?paramX.snap:params.snap,this);this.snapY=parseDraggableFunctionParameter(isObj(paramY)&&!isUnd(paramY.snap)?paramY.snap:params.snap,this);this.scrollSpeed=setValue(parseDraggableFunctionParameter(params.scrollSpeed,this),1.5);this.scrollThreshold=setValue(parseDraggableFunctionParameter(params.scrollThreshold,this),20);this.dragSpeed=setValue(parseDraggableFunctionParameter(params.dragSpeed,this),1);this.minVelocity=setValue(parseDraggableFunctionParameter(params.minVelocity,this),0);this.maxVelocity=setValue(parseDraggableFunctionParameter(params.maxVelocity,this),50);this.velocityMultiplier=setValue(parseDraggableFunctionParameter(params.velocityMultiplier,this),1);this.cursor=parsedCursorStyles===false?false:cursorStyles;this.updateBoundingValues();const[bt,br,bb,bl]=this.containerBounds;this.setX(clamp(cx,bl,br),true);this.setY(clamp(cy,bt,bb),true)}update(){this.updateScrollCoords();if(this.canScroll){const[cpt,cpr,cpb,cpl]=this.containerPadding;const[sw,sh]=this.scrollView;const daw=this.dragArea[2];const dah=this.dragArea[3];const csx=this.scroll.x;const csy=this.scroll.y;const nsw=this.$container.scrollWidth;const nsh=this.$container.scrollHeight;const csw=this.useWin?clamp(nsw,this.window[0],nsw):nsw;const csh=this.useWin?clamp(nsh,this.window[1],nsh):nsh;const swd=sw-csw;const shd=sh-csh;if(this.dragged&&swd>0){this.coords[0]-=swd;this.scrollView[0]=csw}if(this.dragged&&shd>0){this.coords[1]-=shd;this.scrollView[1]=csh}const s=this.scrollSpeed*10;const threshold=this.scrollThreshold;const[x,y]=this.coords;const[st,sr,sb,sl]=this.scrollBounds;const t=round(clamp((y-st+cpt)/threshold,-1,0)*s,0);const r=round(clamp((x-sr-cpr)/threshold,0,1)*s,0);const b=round(clamp((y-sb-cpb)/threshold,0,1)*s,0);const l=round(clamp((x-sl+cpl)/threshold,-1,0)*s,0);if(t||b||l||r){const[nx,ny]=this.disabled;let scrollX=csx;let scrollY=csy;if(!nx){scrollX=round(clamp(csx+(l||r),0,sw-daw),0);this.coords[0]-=csx-scrollX}if(!ny){scrollY=round(clamp(csy+(t||b),0,sh-dah),0);this.coords[1]-=csy-scrollY}if(this.useWin){this.$scrollContainer.scrollBy(-(csx-scrollX),-(csy-scrollY))}else{this.$scrollContainer.scrollTo(scrollX,scrollY)}}}const[ct,cr,cb,cl]=this.containerBounds;const[px1,py1,px2,py2,px3,py3]=this.pointer;this.coords[0]+=(px1-px3)*this.dragSpeed;this.coords[1]+=(py1-py3)*this.dragSpeed;this.pointer[4]=px1;this.pointer[5]=py1;const[cx,cy]=this.coords;const[sx,sy]=this.snapped;const cf=(1-this.containerFriction)*this.dragSpeed;this.setX(cx>cr?cr+(cx-cr)*cf:cx<cl?cl+(cx-cl)*cf:cx,false);this.setY(cy>cb?cb+(cy-cb)*cf:cy<ct?ct+(cy-ct)*cf:cy,false);this.computeVelocity(px1-px3,py1-py3);this.angle=atan2(py1-py2,px1-px2);const[nsx,nsy]=this.snapped;if(nsx!==sx&&this.snapX||nsy!==sy&&this.snapY){this.onSnap(this)}}stop(){this.updateTicker.pause();this.overshootTicker.pause();for(let prop in this.animate.animations)this.animate.animations[prop].pause();remove(this,null,"x");remove(this,null,"y");remove(this,null,"progressX");remove(this,null,"progressY");remove(this.scroll);remove(this.overshootCoords);return this}scrollInView(duration,gap=0,ease=eases.inOutQuad){this.updateScrollCoords();const x=this.destX;const y=this.destY;const scroll=this.scroll;const scrollBounds=this.scrollBounds;const canScroll=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(scrollBounds,x,y)){const[st,sr,sb,sl]=scrollBounds;const t=round(clamp(y-st,-1e12,0),0);const r=round(clamp(x-sr,0,maxValue),0);const b=round(clamp(y-sb,0,maxValue),0);const l=round(clamp(x-sl,-1e12,0),0);new JSAnimation(scroll,{x:round(scroll.x+(l?l-gap:r?r+gap:0),0),y:round(scroll.y+(t?t-gap:b?b+gap:0),0),duration:isUnd(duration)?350*globals.timeScale:duration,ease:ease,onUpdate:()=>{this.canScroll=false;this.$scrollContainer.scrollTo(scroll.x,scroll.y)}}).init().then((()=>{this.canScroll=canScroll}))}return this}handleHover(){if(this.isFinePointer&&this.cursor&&!this.cursorStyles){this.cursorStyles=setTargetValues(this.$trigger,{cursor:this.cursor.onHover})}}animateInView(duration,gap=0,ease=eases.inOutQuad){this.stop();this.updateBoundingValues();const x=this.x;const y=this.y;const[cpt,cpr,cpb,cpl]=this.containerPadding;const bt=this.scroll.y-this.targetBounds[0]+cpt+gap;const br=this.scroll.x-this.targetBounds[1]-cpr-gap;const bb=this.scroll.y-this.targetBounds[2]-cpb-gap;const bl=this.scroll.x-this.targetBounds[3]+cpl+gap;const ob=this.isOutOfBounds([bt,br,bb,bl],x,y);if(ob){const[disabledX,disabledY]=this.disabled;const destX=clamp(snap(x,this.snapX),bl,br);const destY=clamp(snap(y,this.snapY),bt,bb);const dur=isUnd(duration)?350*globals.timeScale:duration;if(!disabledX&&(ob===1||ob===3))this.animate[this.xProp](destX,dur,ease);if(!disabledY&&(ob===2||ob===3))this.animate[this.yProp](destY,dur,ease)}return this}handleDown(e){const $eTarget=e.target;if(this.grabbed||$eTarget.type==="range")return;e.stopPropagation();this.grabbed=true;this.released=false;this.stop();this.updateBoundingValues();const touches=e.changedTouches;const eventX=touches?touches[0].clientX:e.clientX;const eventY=touches?touches[0].clientY:e.clientY;const{x:x,y:y}=this.transforms.normalizePoint(eventX,eventY);const[ct,cr,cb,cl]=this.containerBounds;const cf=(1-this.containerFriction)*this.dragSpeed;const cx=this.x;const cy=this.y;this.coords[0]=this.coords[2]=!cf?cx:cx>cr?cr+(cx-cr)/cf:cx<cl?cl+(cx-cl)/cf:cx;this.coords[1]=this.coords[3]=!cf?cy:cy>cb?cb+(cy-cb)/cf:cy<ct?ct+(cy-ct)/cf:cy;this.pointer[0]=x;this.pointer[1]=y;this.pointer[2]=x;this.pointer[3]=y;this.pointer[4]=x;this.pointer[5]=y;this.pointer[6]=x;this.pointer[7]=y;this.deltaX=0;this.deltaY=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.angle=0;if(this.targetStyles){this.targetStyles.revert();this.targetStyles=null}const z=getTargetValue(this.$target,"zIndex",false);zIndex=(z>zIndex?z:zIndex)+1;this.targetStyles=setTargetValues(this.$target,{zIndex:zIndex});if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.cursorStyles){this.cursorStyles.revert();this.cursorStyles=null}if(this.isFinePointer&&this.cursor){this.bodyStyles=setTargetValues(doc.body,{cursor:this.cursor.onGrab})}this.scrollInView(100,0,eases.out(3));this.onGrab(this);doc.addEventListener("touchmove",this);doc.addEventListener("touchend",this);doc.addEventListener("touchcancel",this);doc.addEventListener("mousemove",this);doc.addEventListener("mouseup",this);doc.addEventListener("selectstart",this)}handleMove(e){if(!this.grabbed)return;const touches=e.changedTouches;const eventX=touches?touches[0].clientX:e.clientX;const eventY=touches?touches[0].clientY:e.clientY;const{x:x,y:y}=this.transforms.normalizePoint(eventX,eventY);const movedX=x-this.pointer[6];const movedY=y-this.pointer[7];let $parent=e.target;let isAtTop=false;let isAtBottom=false;let canTouchScroll=false;while(touches&&$parent&&$parent!==this.$trigger){const overflowY=getTargetValue($parent,"overflow-y");if(overflowY!=="hidden"&&overflowY!=="visible"){const{scrollTop:scrollTop,scrollHeight:scrollHeight,clientHeight:clientHeight}=$parent;if(scrollHeight>clientHeight){canTouchScroll=true;isAtTop=scrollTop<=3;isAtBottom=scrollTop>=scrollHeight-clientHeight-3;break}}$parent=$parent.parentNode}if(canTouchScroll&&(!isAtTop&&!isAtBottom||isAtTop&&movedY<0||isAtBottom&&movedY>0)){this.pointer[0]=x;this.pointer[1]=y;this.pointer[2]=x;this.pointer[3]=y;this.pointer[4]=x;this.pointer[5]=y;this.pointer[6]=x;this.pointer[7]=y}else{preventDefault(e);if(!this.triggerStyles)this.triggerStyles=setTargetValues(this.$trigger,{pointerEvents:"none"});this.$trigger.addEventListener("touchstart",preventDefault,{passive:false});this.$trigger.addEventListener("touchmove",preventDefault,{passive:false});this.$trigger.addEventListener("touchend",preventDefault);if(!this.disabled[0]&&abs(movedX)>3||!this.disabled[1]&&abs(movedY)>3){this.updateTicker.resume();this.pointer[2]=this.pointer[0];this.pointer[3]=this.pointer[1];this.pointer[0]=x;this.pointer[1]=y;this.dragged=true;this.released=false;this.onDrag(this)}}}handleUp(){if(!this.grabbed)return;this.updateTicker.pause();if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.bodyStyles){this.bodyStyles.revert();this.bodyStyles=null}const[disabledX,disabledY]=this.disabled;const[px1,py1,px2,py2,px3,py3]=this.pointer;const[ct,cr,cb,cl]=this.containerBounds;const[sx,sy]=this.snapped;const springX=this.releaseXSpring;const springY=this.releaseYSpring;const releaseEase=this.releaseEase;const hasReleaseSpring=this.hasReleaseSpring;const overshootCoords=this.overshootCoords;const cx=this.x;const cy=this.y;const pv=this.computeVelocity(px1-px3,py1-py3);const pa=this.angle=atan2(py1-py2,px1-px2);const ds=pv*150;const cf=(1-this.releaseContainerFriction)*this.dragSpeed;const nx=cx+cos(pa)*ds;const ny=cy+sin(pa)*ds;const bx=nx>cr?cr+(nx-cr)*cf:nx<cl?cl+(nx-cl)*cf:nx;const by=ny>cb?cb+(ny-cb)*cf:ny<ct?ct+(ny-ct)*cf:ny;const dx=this.destX=clamp(round(snap(bx,this.snapX),5),cl,cr);const dy=this.destY=clamp(round(snap(by,this.snapY),5),ct,cb);const ob=this.isOutOfBounds(this.containerBounds,nx,ny);let durationX=0;let durationY=0;let easeX=releaseEase;let easeY=releaseEase;let longestReleaseDuration=0;overshootCoords.x=cx;overshootCoords.y=cy;if(!disabledX){const directionX=dx===cr?cx>cr?-1:1:cx<cl?-1:1;const distanceX=round(cx-dx,0);springX.velocity=disabledY&&hasReleaseSpring?distanceX?ds*directionX/abs(distanceX):0:pv;const{ease:ease,duration:duration,restDuration:restDuration}=springX;durationX=cx===dx?0:hasReleaseSpring?duration:duration-restDuration*globals.timeScale;if(hasReleaseSpring)easeX=ease;if(durationX>longestReleaseDuration)longestReleaseDuration=durationX}if(!disabledY){const directionY=dy===cb?cy>cb?-1:1:cy<ct?-1:1;const distanceY=round(cy-dy,0);springY.velocity=disabledX&&hasReleaseSpring?distanceY?ds*directionY/abs(distanceY):0:pv;const{ease:ease,duration:duration,restDuration:restDuration}=springY;durationY=cy===dy?0:hasReleaseSpring?duration:duration-restDuration*globals.timeScale;if(hasReleaseSpring)easeY=ease;if(durationY>longestReleaseDuration)longestReleaseDuration=durationY}if(!hasReleaseSpring&&ob&&cf&&(durationX||durationY)){const composition=compositionTypes.blend;new JSAnimation(overshootCoords,{x:{to:bx,duration:durationX*.65},y:{to:by,duration:durationY*.65},ease:releaseEase,composition:composition}).init();new JSAnimation(overshootCoords,{x:{to:dx,duration:durationX},y:{to:dy,duration:durationY},ease:releaseEase,composition:composition}).init();this.overshootTicker.stretch(max(durationX,durationY)).restart()}else{if(!disabledX)this.animate[this.xProp](dx,durationX,easeX);if(!disabledY)this.animate[this.yProp](dy,durationY,easeY)}this.scrollInView(longestReleaseDuration,this.scrollThreshold,releaseEase);let hasSnapped=false;if(dx!==sx){this.snapped[0]=dx;if(this.snapX)hasSnapped=true}if(dy!==sy&&this.snapY){this.snapped[1]=dy;if(this.snapY)hasSnapped=true}if(hasSnapped)this.onSnap(this);this.grabbed=false;this.dragged=false;this.updated=true;this.released=true;this.onRelease(this);this.$trigger.removeEventListener("touchstart",preventDefault);this.$trigger.removeEventListener("touchmove",preventDefault);this.$trigger.removeEventListener("touchend",preventDefault);doc.removeEventListener("touchmove",this);doc.removeEventListener("touchend",this);doc.removeEventListener("touchcancel",this);doc.removeEventListener("mousemove",this);doc.removeEventListener("mouseup",this);doc.removeEventListener("selectstart",this)}reset(){this.stop();this.resizeTicker.pause();this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.setX(0,true);this.setY(0,true);this.coords[0]=0;this.coords[1]=0;this.pointer[0]=0;this.pointer[1]=0;this.pointer[2]=0;this.pointer[3]=0;this.pointer[4]=0;this.pointer[5]=0;this.pointer[6]=0;this.pointer[7]=0;this.velocity=0;this.velocityStack[0]=0;this.velocityStack[1]=0;this.velocityStack[2]=0;this.velocityStackIndex=0;this.angle=0;return this}enable(){if(!this.enabled){this.enabled=true;this.$target.classList.remove("is-disabled");this.touchActionStyles=setTargetValues(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"});this.$trigger.addEventListener("touchstart",this,{passive:true});this.$trigger.addEventListener("mousedown",this,{passive:true});this.$trigger.addEventListener("mouseenter",this)}return this}disable(){this.enabled=false;this.grabbed=false;this.dragged=false;this.updated=false;this.released=false;this.canScroll=false;this.touchActionStyles.revert();if(this.cursorStyles){this.cursorStyles.revert();this.cursorStyles=null}if(this.triggerStyles){this.triggerStyles.revert();this.triggerStyles=null}if(this.bodyStyles){this.bodyStyles.revert();this.bodyStyles=null}if(this.targetStyles){this.targetStyles.revert();this.targetStyles=null}this.$target.classList.add("is-disabled");this.$trigger.removeEventListener("touchstart",this);this.$trigger.removeEventListener("mousedown",this);this.$trigger.removeEventListener("mouseenter",this);doc.removeEventListener("touchmove",this);doc.removeEventListener("touchend",this);doc.removeEventListener("touchcancel",this);doc.removeEventListener("mousemove",this);doc.removeEventListener("mouseup",this);doc.removeEventListener("selectstart",this);return this}revert(){this.reset();this.disable();this.$target.classList.remove("is-disabled");this.updateTicker.revert();this.overshootTicker.revert();this.resizeTicker.revert();this.animate.revert();this.resizeObserver.disconnect();return this}handleEvent(e){switch(e.type){case"mousedown":this.handleDown(e);break;case"touchstart":this.handleDown(e);break;case"mousemove":this.handleMove(e);break;case"touchmove":this.handleMove(e);break;case"mouseup":this.handleUp();break;case"touchend":this.handleUp();break;case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":preventDefault(e);break}}}const createDraggable=(target,parameters)=>new Draggable(target,parameters);class Scope{constructor(parameters={}){if(scope.current)scope.current.register(this);const rootParam=parameters.root;let root=doc;if(rootParam){root=rootParam.current||rootParam.nativeElement||parseTargets(rootParam)[0]||doc}const scopeDefaults=parameters.defaults;const globalDefault=globals.defaults;const mediaQueries=parameters.mediaQueries;this.defaults=scopeDefaults?mergeObjects(scopeDefaults,globalDefault):globalDefault;this.root=root;this.constructors=[];this.revertConstructors=[];this.revertibles=[];this.constructorsOnce=[];this.revertConstructorsOnce=[];this.revertiblesOnce=[];this.once=false;this.onceIndex=0;this.methods={};this.matches={};this.mediaQueryLists={};this.data={};if(mediaQueries){for(let mq in mediaQueries){const _mq=win.matchMedia(mediaQueries[mq]);this.mediaQueryLists[mq]=_mq;_mq.addEventListener("change",this)}}}register(revertible){const store=this.once?this.revertiblesOnce:this.revertibles;store.push(revertible)}execute(cb){let activeScope=scope.current;let activeRoot=scope.root;let activeDefaults=globals.defaults;scope.current=this;scope.root=this.root;globals.defaults=this.defaults;const mqs=this.mediaQueryLists;for(let mq in mqs)this.matches[mq]=mqs[mq].matches;const returned=cb(this);scope.current=activeScope;scope.root=activeRoot;globals.defaults=activeDefaults;return returned}refresh(){this.onceIndex=0;this.execute((()=>{let i=this.revertibles.length;let y=this.revertConstructors.length;while(i--)this.revertibles[i].revert();while(y--)this.revertConstructors[y](this);this.revertibles.length=0;this.revertConstructors.length=0;this.constructors.forEach((constructor=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructors.push(revertConstructor)}}))}));return this}add(a1,a2){this.once=false;if(isFnc(a1)){const constructor=a1;this.constructors.push(constructor);this.execute((()=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructors.push(revertConstructor)}}))}else{this.methods[a1]=(...args)=>this.execute((()=>a2(...args)))}return this}addOnce(scopeConstructorCallback){this.once=true;if(isFnc(scopeConstructorCallback)){const currentIndex=this.onceIndex++;const tracked=this.constructorsOnce[currentIndex];if(tracked)return this;const constructor=scopeConstructorCallback;this.constructorsOnce[currentIndex]=constructor;this.execute((()=>{const revertConstructor=constructor(this);if(isFnc(revertConstructor)){this.revertConstructorsOnce.push(revertConstructor)}}))}return this}keepTime(cb){this.once=true;const currentIndex=this.onceIndex++;const tracked=this.constructorsOnce[currentIndex];if(isFnc(tracked))return tracked(this);const constructor=createRefreshable(cb);this.constructorsOnce[currentIndex]=constructor;let trackedTickable;this.execute((()=>{trackedTickable=constructor(this)}));return trackedTickable}handleEvent(e){switch(e.type){case"change":this.refresh();break}}revert(){const revertibles=this.revertibles;const revertConstructors=this.revertConstructors;const revertiblesOnce=this.revertiblesOnce;const revertConstructorsOnce=this.revertConstructorsOnce;const mqs=this.mediaQueryLists;let i=revertibles.length;let j=revertConstructors.length;let k=revertiblesOnce.length;let l=revertConstructorsOnce.length;while(i--)revertibles[i].revert();while(j--)revertConstructors[j](this);while(k--)revertiblesOnce[k].revert();while(l--)revertConstructorsOnce[l](this);for(let mq in mqs)mqs[mq].removeEventListener("change",this);revertibles.length=0;revertConstructors.length=0;this.constructors.length=0;revertiblesOnce.length=0;revertConstructorsOnce.length=0;this.constructorsOnce.length=0;this.onceIndex=0;this.matches={};this.methods={};this.mediaQueryLists={};this.data={}}}const createScope=params=>new Scope(params);const getMaxViewHeight=()=>{const $el=doc.createElement("div");doc.body.appendChild($el);$el.style.height="100lvh";const height=$el.offsetHeight;doc.body.removeChild($el);return height};const parseScrollObserverFunctionParameter=(value,scroller)=>value&&isFnc(value)?value(scroller):value;const scrollContainers=new Map;class ScrollContainer{constructor($el){this.element=$el;this.useWin=this.element===doc.body;this.winWidth=0;this.winHeight=0;this.width=0;this.height=0;this.left=0;this.top=0;this.zIndex=0;this.scrollX=0;this.scrollY=0;this.prevScrollX=0;this.prevScrollY=0;this.scrollWidth=0;this.scrollHeight=0;this.velocity=0;this.backwardX=false;this.backwardY=false;this.scrollTicker=new Timer({autoplay:false,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const backwards=this.backwardX||this.backwardY;forEachChildren(this,(child=>child.handleScroll()),backwards)},onComplete:()=>this.dataTimer.pause()}).init();this.dataTimer=new Timer({autoplay:false,frameRate:30,onUpdate:self=>{const dt=self.deltaTime;const px=this.prevScrollX;const py=this.prevScrollY;const nx=this.scrollX;const ny=this.scrollY;const dx=px-nx;const dy=py-ny;this.prevScrollX=nx;this.prevScrollY=ny;if(dx)this.backwardX=px>nx;if(dy)this.backwardY=py>ny;this.velocity=round(dt>0?Math.sqrt(dx*dx+dy*dy)/dt:0,5)}}).init();this.resizeTicker=new Timer({autoplay:false,duration:250*globals.timeScale,onComplete:()=>{this.updateWindowBounds();this.refreshScrollObservers();this.handleScroll()}}).init();this.wakeTicker=new Timer({autoplay:false,duration:500*globals.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init();this._head=null;this._tail=null;this.updateScrollCoords();this.updateWindowBounds();this.updateBounds();this.refreshScrollObservers();this.handleScroll();this.resizeObserver=new ResizeObserver((()=>this.resizeTicker.restart()));this.resizeObserver.observe(this.element);(this.useWin?win:this.element).addEventListener("scroll",this,false)}updateScrollCoords(){const useWin=this.useWin;const $el=this.element;this.scrollX=round(useWin?win.scrollX:$el.scrollLeft,0);this.scrollY=round(useWin?win.scrollY:$el.scrollTop,0)}updateWindowBounds(){this.winWidth=win.innerWidth;this.winHeight=getMaxViewHeight()}updateBounds(){const style=getComputedStyle(this.element);const $el=this.element;this.scrollWidth=$el.scrollWidth+parseFloat(style.marginLeft)+parseFloat(style.marginRight);this.scrollHeight=$el.scrollHeight+parseFloat(style.marginTop)+parseFloat(style.marginBottom);this.updateWindowBounds();let width,height;if(this.useWin){width=this.winWidth;height=this.winHeight}else{const elRect=$el.getBoundingClientRect();width=$el.clientWidth;height=$el.clientHeight;this.top=elRect.top;this.left=elRect.left}this.width=width;this.height=height}refreshScrollObservers(){forEachChildren(this,(child=>{if(child._debug){child.removeDebug()}}));this.updateBounds();forEachChildren(this,(child=>{child.refresh();if(child._debug){child.debug()}}))}refresh(){this.updateWindowBounds();this.updateBounds();this.refreshScrollObservers();this.handleScroll()}handleScroll(){this.updateScrollCoords();this.wakeTicker.restart()}handleEvent(e){switch(e.type){case"scroll":this.handleScroll();break}}revert(){this.scrollTicker.cancel();this.dataTimer.cancel();this.resizeTicker.cancel();this.wakeTicker.cancel();this.resizeObserver.disconnect();(this.useWin?win:this.element).removeEventListener("scroll",this);scrollContainers.delete(this.element)}}const registerAndGetScrollContainer=target=>{const $el=target?parseTargets(target)[0]||doc.body:doc.body;let scrollContainer=scrollContainers.get($el);if(!scrollContainer){scrollContainer=new ScrollContainer($el);scrollContainers.set($el,scrollContainer)}return scrollContainer};const convertValueToPx=($el,v,size,under,over)=>{const clampMin=v==="min";const clampMax=v==="max";const value=v==="top"||v==="left"||v==="start"||clampMin?0:v==="bottom"||v==="right"||v==="end"||clampMax?"100%":v==="center"?"50%":v;const{n:n,u:u}=decomposeRawValue(value,decomposedOriginalValue);let px=n;if(u==="%"){px=n/100*size}else if(u){px=convertValueUnit($el,decomposedOriginalValue,"px",true).n}if(clampMax&&under<0)px+=under;if(clampMin&&over>0)px+=over;return px};const parseBoundValue=($el,v,size,under,over)=>{let value;if(isStr(v)){const matchedOperator=relativeValuesExecRgx.exec(v);if(matchedOperator){const splitter=matchedOperator[0];const operator=splitter[0];const splitted=v.split(splitter);const clampMin=splitted[0]==="min";const clampMax=splitted[0]==="max";const valueAPx=convertValueToPx($el,splitted[0],size,under,over);const valueBPx=convertValueToPx($el,splitted[1],size,under,over);if(clampMin){const min=getRelativeValue(convertValueToPx($el,"min",size),valueBPx,operator);value=min<valueAPx?valueAPx:min}else if(clampMax){const max=getRelativeValue(convertValueToPx($el,"max",size),valueBPx,operator);value=max>valueAPx?valueAPx:max}else{value=getRelativeValue(valueAPx,valueBPx,operator)}}else{value=convertValueToPx($el,v,size,under,over)}}else{value=v}return round(value,0)};const getAnimationDomTarget=linked=>{let $linkedTarget;const linkedTargets=linked.targets;for(let i=0,l=linkedTargets.length;i<l;i++){const target=linkedTargets[i];if(target[isDomSymbol]){$linkedTarget=target;break}}return $linkedTarget};let scrollerIndex=0;const debugColors$1=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class ScrollObserver{constructor(parameters={}){if(scope.current)scope.current.register(this);const syncMode=setValue(parameters.sync,"play pause");const ease=syncMode?parseEasings(syncMode):null;const isLinear=syncMode&&(syncMode==="linear"||syncMode===none);const isEase=syncMode&&!(ease===none&&!isLinear);const isSmooth=syncMode&&(isNum(syncMode)||syncMode===true||isLinear);const isMethods=syncMode&&(isStr(syncMode)&&!isEase&&!isSmooth);const syncMethods=isMethods?syncMode.split(" ").map((m=>()=>{const linked=this.linked;return linked&&linked[m]?linked[m]():null})):null;const biDirSync=isMethods&&syncMethods.length>2;this.index=scrollerIndex++;this.id=!isUnd(parameters.id)?parameters.id:this.index;this.container=registerAndGetScrollContainer(parameters.container);this.target=null;this.linked=null;this.repeat=null;this.horizontal=null;this.enter=null;this.leave=null;this.sync=isEase||isSmooth||!!syncMethods;this.syncEase=isEase?ease:null;this.syncSmooth=isSmooth?syncMode===true||isLinear?1:syncMode:null;this.onSyncEnter=syncMethods&&!biDirSync&&syncMethods[0]?syncMethods[0]:noop;this.onSyncLeave=syncMethods&&!biDirSync&&syncMethods[1]?syncMethods[1]:noop;this.onSyncEnterForward=syncMethods&&biDirSync&&syncMethods[0]?syncMethods[0]:noop;this.onSyncLeaveForward=syncMethods&&biDirSync&&syncMethods[1]?syncMethods[1]:noop;this.onSyncEnterBackward=syncMethods&&biDirSync&&syncMethods[2]?syncMethods[2]:noop;this.onSyncLeaveBackward=syncMethods&&biDirSync&&syncMethods[3]?syncMethods[3]:noop;this.onEnter=parameters.onEnter||noop;this.onLeave=parameters.onLeave||noop;this.onEnterForward=parameters.onEnterForward||noop;this.onLeaveForward=parameters.onLeaveForward||noop;this.onEnterBackward=parameters.onEnterBackward||noop;this.onLeaveBackward=parameters.onLeaveBackward||noop;this.onUpdate=parameters.onUpdate||noop;this.onSyncComplete=parameters.onSyncComplete||noop;this.reverted=false;this.completed=false;this.began=false;this.isInView=false;this.forceEnter=false;this.hasEntered=false;this.offset=0;this.offsetStart=0;this.offsetEnd=0;this.distance=0;this.prevProgress=0;this.thresholds=["start","end","end","start"];this.coords=[0,0,0,0];this.debugStyles=null;this.$debug=null;this._params=parameters;this._debug=setValue(parameters.debug,false);this._next=null;this._prev=null;addChild(this.container,this);sync((()=>{if(this.reverted)return;if(!this.target){const target=parseTargets(parameters.target)[0];this.target=target||doc.body;this.refresh()}if(this._debug)this.debug()}))}link(linked){if(linked){linked.pause();this.linked=linked;if(!this._params.target){let $linkedTarget;if(!isUnd(linked.targets)){$linkedTarget=getAnimationDomTarget(linked)}else{forEachChildren(linked,(child=>{if(child.targets&&!$linkedTarget){$linkedTarget=getAnimationDomTarget(child)}}))}this.target=$linkedTarget||doc.body;this.refresh()}}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const p=(this.scroll-this.offsetStart)/this.distance;return p===Infinity||isNaN(p)?0:round(clamp(p,0,1),6)}refresh(){this.reverted=false;const params=this._params;this.repeat=setValue(parseScrollObserverFunctionParameter(params.repeat,this),true);this.horizontal=setValue(parseScrollObserverFunctionParameter(params.axis,this),"y")==="x";this.enter=setValue(parseScrollObserverFunctionParameter(params.enter,this),"end start");this.leave=setValue(parseScrollObserverFunctionParameter(params.leave,this),"start end");this.updateBounds();this.handleScroll();return this}removeDebug(){if(this.$debug){this.$debug.parentNode.removeChild(this.$debug);this.$debug=null}if(this.debugStyles){this.debugStyles.revert();this.$debug=null}return this}debug(){this.removeDebug();const container=this.container;const isHori=this.horizontal;const $existingDebug=container.element.querySelector(":scope > .animejs-onscroll-debug");const $debug=doc.createElement("div");const $thresholds=doc.createElement("div");const $triggers=doc.createElement("div");const color=debugColors$1[this.index%debugColors$1.length];const useWin=container.useWin;const containerWidth=useWin?container.winWidth:container.width;const containerHeight=useWin?container.winHeight:container.height;const scrollWidth=container.scrollWidth;const scrollHeight=container.scrollHeight;const size=this.container.width>360?320:260;const offLeft=isHori?0:10;const offTop=isHori?10:0;const half=isHori?24:size/2;const labelHeight=isHori?half:15;const labelWidth=isHori?60:half;const labelSize=isHori?labelWidth:labelHeight;const repeat=isHori?"repeat-x":"repeat-y";const gradientOffset=v=>isHori?"0px "+v+"px":v+"px"+" 2px";const lineCSS=c=>`linear-gradient(${isHori?90:0}deg, ${c} 2px, transparent 1px)`;const baseCSS=(p,l,t,w,h)=>`position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`;$debug.style.cssText=`${baseCSS("absolute",offLeft,offTop,isHori?scrollWidth:size,isHori?size:scrollHeight)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${isHori?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `;$thresholds.style.cssText=`${baseCSS("sticky",0,0,isHori?containerWidth:half,isHori?half:containerHeight)}`;if(!$existingDebug){$thresholds.style.cssText+=`background:\n ${lineCSS("#FFFF")}${gradientOffset(half-10)} / ${isHori?"100px 100px":"100px 100px"} ${repeat},\n ${lineCSS("#FFF8")}${gradientOffset(half-10)} / ${isHori?"10px 10px":"10px 10px"} ${repeat};\n `}$triggers.style.cssText=`${baseCSS("relative",0,0,isHori?scrollWidth:half,isHori?half:scrollHeight)}`;if(!$existingDebug){$triggers.style.cssText+=`background:\n ${lineCSS("#FFFF")}${gradientOffset(0)} / ${isHori?"100px 10px":"10px 100px"} ${repeat},\n ${lineCSS("#FFF8")}${gradientOffset(0)} / ${isHori?"10px 0px":"0px 10px"} ${repeat};\n `}const labels=[" enter: "," leave: "];this.coords.forEach(((v,i)=>{const isView=i>1;const value=(isView?0:this.offset)+v;const isTail=i%2;const isFirst=value<labelSize;const isOver=value>(isView?isHori?containerWidth:containerHeight:isHori?scrollWidth:scrollHeight)-labelSize;const isFlip=(isView?isTail&&!isFirst:!isTail&&!isFirst)||isOver;const $label=doc.createElement("div");const $text=doc.createElement("div");const dirProp=isHori?isFlip?"right":"left":isFlip?"bottom":"top";const flipOffset=isFlip?(isHori?labelWidth:labelHeight)+(!isView?isHori?-1:-2:isHori?-1:isOver?0:-2):!isView?isHori?1:0:isHori?1:0;$text.innerHTML=`${this.id}${labels[isTail]}${this.thresholds[i]}`;$label.style.cssText=`${baseCSS("absolute",0,0,labelWidth,labelHeight)}\n display: flex;\n flex-direction: ${isHori?"column":"row"};\n justify-content: flex-${isView?"start":"end"};\n align-items: flex-${isFlip?"end":"start"};\n border-${dirProp}: 2px ${isTail?"solid":"solid"} ${color};\n `;$text.style.cssText=`\n overflow: hidden;\n max-width: ${size/2-10}px;\n height: ${labelHeight};\n margin-${isHori?isFlip?"right":"left":isFlip?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${isHori&&isFlip||!isHori&&!isView?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${isTail?color:"rgba(0,0,0,.75)"};\n background-color: ${isTail?"rgba(0,0,0,.65)":color};\n border: 2px solid ${isTail?color:"transparent"};\n border-${isHori?isFlip?"top-left":"top-right":isFlip?"top-left":"bottom-left"}-radius: 5px;\n border-${isHori?isFlip?"bottom-left":"bottom-right":isFlip?"top-right":"bottom-right"}-radius: 5px;\n `;$label.appendChild($text);let position=value-flipOffset+(isHori?1:0);$label.style[isHori?"left":"top"]=`${position}px`;(isView?$thresholds:$triggers).appendChild($label)}));$debug.appendChild($thresholds);$debug.appendChild($triggers);container.element.appendChild($debug);if(!$existingDebug)$debug.classList.add("animejs-onscroll-debug");this.$debug=$debug;const containerPosition=getTargetValue(container.element,"position");if(containerPosition==="static"){this.debugStyles=setTargetValues(container.element,{position:"relative "})}}updateBounds(){if(this._debug){this.removeDebug()}let stickys;const $target=this.target;const container=this.container;const isHori=this.horizontal;const linked=this.linked;let linkedTime;let $el=$target;if(linked){linkedTime=linked.currentTime;linked.seek(0,true)}$el.parentElement;while($el&&$el!==container.element&&$el!==doc.body){const isSticky=getTargetValue($el,"position")==="sticky"?setTargetValues($el,{position:"static"}):false;$el=$el.parentElement;if(isSticky){if(!stickys)stickys=[];stickys.push(isSticky)}}const rect=$target.getBoundingClientRect();const offset=isHori?rect.left+container.scrollX-container.left:rect.top+container.scrollY-container.top;const targetSize=isHori?rect.width:rect.height;const containerSize=isHori?container.width:container.height;const scrollSize=isHori?container.scrollWidth:container.scrollHeight;const maxScroll=scrollSize-containerSize;const enter=this.enter;const leave=this.leave;let enterTarget="start";let leaveTarget="end";let enterContainer="end";let leaveContainer="start";if(isStr(enter)){const splitted=enter.split(" ");enterContainer=splitted[0];enterTarget=splitted.length>1?splitted[1]:enterTarget}else if(isObj(enter)){const e=enter;if(!isUnd(e.container))enterContainer=e.container;if(!isUnd(e.target))enterTarget=e.target}else if(isNum(enter)){enterContainer=enter}if(isStr(leave)){const splitted=leave.split(" ");leaveContainer=splitted[0];leaveTarget=splitted.length>1?splitted[1]:leaveTarget}else if(isObj(leave)){const t=leave;if(!isUnd(t.container))leaveContainer=t.container;if(!isUnd(t.target))leaveTarget=t.target}else if(isNum(leave)){leaveContainer=leave}const parsedEnterTarget=parseBoundValue($target,enterTarget,targetSize);const parsedLeaveTarget=parseBoundValue($target,leaveTarget,targetSize);const under=parsedEnterTarget+offset-containerSize;const over=parsedLeaveTarget+offset-maxScroll;const parsedEnterContainer=parseBoundValue($target,enterContainer,containerSize,under,over);const parsedLeaveContainer=parseBoundValue($target,leaveContainer,containerSize,under,over);const offsetStart=parsedEnterTarget+offset-parsedEnterContainer;const offsetEnd=parsedLeaveTarget+offset-parsedLeaveContainer;const scrollDelta=offsetEnd-offsetStart;this.offset=offset;this.offsetStart=offsetStart;this.offsetEnd=offsetEnd;this.distance=scrollDelta<=0?0:scrollDelta;this.thresholds=[enterTarget,leaveTarget,enterContainer,leaveContainer];this.coords=[parsedEnterTarget,parsedLeaveTarget,parsedEnterContainer,parsedLeaveContainer];if(stickys){stickys.forEach((sticky=>sticky.revert()))}if(linked){linked.seek(linkedTime,true)}if(this._debug){this.debug()}}handleScroll(){const linked=this.linked;const sync=this.sync;const syncEase=this.syncEase;const syncSmooth=this.syncSmooth;const shouldSeek=linked&&(syncEase||syncSmooth);const isHori=this.horizontal;const container=this.container;const scroll=this.scroll;const isBefore=scroll<=this.offsetStart;const isAfter=scroll>=this.offsetEnd;const isInView=!isBefore&&!isAfter;const isOnTheEdge=scroll===this.offsetStart||scroll===this.offsetEnd;const forceEnter=!this.hasEntered&&isOnTheEdge;const $debug=this._debug&&this.$debug;let hasUpdated=false;let syncCompleted=false;let p=this.progress;if(isBefore&&this.began){this.began=false}if(p>0&&!this.began){this.began=true}if(shouldSeek){const lp=linked.progress;if(syncSmooth&&isNum(syncSmooth)){if(syncSmooth<1){const step=1e-4;const snap=lp<p&&p===1?step:lp>p&&!p?-1e-4:0;p=round(lerp(lp,p,interpolate(.01,.2,syncSmooth),false)+snap,6)}}else if(syncEase){p=syncEase(p)}hasUpdated=p!==this.prevProgress;syncCompleted=lp===1;if(hasUpdated&&!syncCompleted&&(syncSmooth&&lp)){container.wakeTicker.restart()}}if($debug){const sticky=isHori?container.scrollY:container.scrollX;$debug.style[isHori?"top":"left"]=sticky+10+"px"}if(isInView&&!this.isInView||forceEnter&&!this.forceEnter&&!this.hasEntered){if(isInView)this.isInView=true;if(!this.forceEnter||!this.hasEntered){if($debug&&isInView)$debug.style.zIndex=`${this.container.zIndex++}`;this.onSyncEnter(this);this.onEnter(this);if(this.backward){this.onSyncEnterBackward(this);this.onEnterBackward(this)}else{this.onSyncEnterForward(this);this.onEnterForward(this)}this.hasEntered=true;if(forceEnter)this.forceEnter=true}else if(isInView){this.forceEnter=false}}if(isInView||!isInView&&this.isInView){hasUpdated=true}if(hasUpdated){if(shouldSeek)linked.seek(linked.duration*p);this.onUpdate(this)}if(!isInView&&this.isInView){this.isInView=false;this.onSyncLeave(this);this.onLeave(this);if(this.backward){this.onSyncLeaveBackward(this);this.onLeaveBackward(this)}else{this.onSyncLeaveForward(this);this.onLeaveForward(this)}if(sync&&!syncSmooth){syncCompleted=true}}if(p>=1&&this.began&&!this.completed&&(sync&&syncCompleted||!sync)){if(sync){this.onSyncComplete(this)}this.completed=true;if(!this.repeat&&!linked||!this.repeat&&linked&&linked.completed){this.revert()}}if(p<1&&this.completed){this.completed=false}this.prevProgress=p}revert(){if(this.reverted)return;const container=this.container;removeChild(container,this);if(!container._head){container.revert()}if(this._debug){this.removeDebug()}this.reverted=true;return this}}const onScroll=(parameters={})=>new ScrollObserver(parameters);const segmenter=typeof Intl!=="undefined"&&Intl.Segmenter;const valueRgx=/\{value\}/g;const indexRgx=/\{i\}/g;const whiteSpaceGroupRgx=/(\s+)/;const whiteSpaceRgx=/^\s+$/;const lineType="line";const wordType="word";const charType="char";const dataLine=`data-line`;let wordSegmenter=null;let graphemeSegmenter=null;let $splitTemplate=null;const isSegmentWordLike=seg=>seg.isWordLike||seg.segment===" "||isNum(+seg.segment);const setAriaHidden=$el=>$el.setAttribute("aria-hidden","true");const getAllTopLevelElements=($el,type)=>[...$el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`)];const debugColors={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"};const filterEmptyElements=$el=>{if(!$el.childElementCount&&!$el.textContent.trim()){const $parent=$el.parentElement;$el.remove();if($parent)filterEmptyElements($parent)}};const filterLineElements=($el,lineIndex,bin)=>{const dataLineAttr=$el.getAttribute(dataLine);if(dataLineAttr!==null&&+dataLineAttr!==lineIndex||$el.tagName==="BR")bin.add($el);let i=$el.childElementCount;while(i--)filterLineElements($el.children[i],lineIndex,bin);return bin};const generateTemplate=(type,params={})=>{let template=``;const classString=isStr(params.class)?` class="${params.class}"`:"";const cloneType=setValue(params.clone,false);const wrapType=setValue(params.wrap,false);const overflow=wrapType?wrapType===true?"clip":wrapType:cloneType?"clip":false;if(wrapType)template+=`<span${overflow?` style="overflow:${overflow};"`:""}>`;template+=`<span${classString}${cloneType?` style="position:relative;"`:""} data-${type}="{i}">`;if(cloneType){const left=cloneType==="left"?"-100%":cloneType==="right"?"100%":"0";const top=cloneType==="top"?"-100%":cloneType==="bottom"?"100%":"0";template+=`<span>{value}</span>`;template+=`<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`}else{template+=`{value}`}template+=`</span>`;if(wrapType)template+=`</span>`;return template};const processHTMLTemplate=(htmlTemplate,store,node,$parentFragment,type,debug,lineIndex,wordIndex,charIndex)=>{const isLine=type===lineType;const isChar=type===charType;const className=`_${type}_`;const template=isFnc(htmlTemplate)?htmlTemplate(node):htmlTemplate;const displayStyle=isLine?"block":"inline-block";$splitTemplate.innerHTML=template.replace(valueRgx,`<i class="${className}"></i>`).replace(indexRgx,`${isChar?charIndex:isLine?lineIndex:wordIndex}`);const $content=$splitTemplate.content;const $highestParent=$content.firstElementChild;const $split=$content.querySelector(`[data-${type}]`)||$highestParent;const $replacables=$content.querySelectorAll(`i.${className}`);const replacablesLength=$replacables.length;if(replacablesLength){$highestParent.style.display=displayStyle;$split.style.display=displayStyle;$split.setAttribute(dataLine,`${lineIndex}`);if(!isLine){$split.setAttribute("data-word",`${wordIndex}`);if(isChar)$split.setAttribute("data-char",`${charIndex}`)}let i=replacablesLength;while(i--){const $replace=$replacables[i];const $closestParent=$replace.parentElement;$closestParent.style.display=displayStyle;if(isLine){$closestParent.innerHTML=node.innerHTML}else{$closestParent.replaceChild(node.cloneNode(true),$replace)}}store.push($split);$parentFragment.appendChild($content)}else{console.warn(`The expression "{value}" is missing from the provided template.`)}if(debug)$highestParent.style.outline=`1px dotted ${debugColors[type]}`;return $highestParent};class TextSplitter{constructor(target,parameters={}){if(!wordSegmenter)wordSegmenter=segmenter?new segmenter([],{granularity:wordType}):{segment:text=>{const segments=[];const words=text.split(whiteSpaceGroupRgx);for(let i=0,l=words.length;i<l;i++){const segment=words[i];segments.push({segment:segment,isWordLike:!whiteSpaceRgx.test(segment)})}return segments}};if(!graphemeSegmenter)graphemeSegmenter=segmenter?new segmenter([],{granularity:"grapheme"}):{segment:text=>[...text].map((char=>({segment:char})))};if(!$splitTemplate&&isBrowser)$splitTemplate=doc.createElement("template");if(scope.current)scope.current.register(this);const{words:words,chars:chars,lines:lines,accessible:accessible,includeSpaces:includeSpaces,debug:debug}=parameters;const $target=(target=isArr(target)?target[0]:target)&&target.nodeType?target:(getNodeList(target)||[])[0];const lineParams=lines===true?{}:lines;const wordParams=words===true||isUnd(words)?{}:words;const charParams=chars===true?{}:chars;this.debug=setValue(debug,false);this.includeSpaces=setValue(includeSpaces,false);this.accessible=setValue(accessible,true);this.linesOnly=lineParams&&(!wordParams&&!charParams);this.lineTemplate=isObj(lineParams)?generateTemplate(lineType,lineParams):lineParams;this.wordTemplate=isObj(wordParams)||this.linesOnly?generateTemplate(wordType,wordParams):wordParams;this.charTemplate=isObj(charParams)?generateTemplate(charType,charParams):charParams;this.$target=$target;this.html=$target&&$target.innerHTML;this.lines=[];this.words=[];this.chars=[];this.effects=[];this.effectsCleanups=[];this.cache=null;this.ready=false;this.width=0;this.resizeTimeout=null;const handleSplit=()=>this.html&&(lineParams||wordParams||charParams)&&this.split();this.resizeObserver=new ResizeObserver((()=>{clearTimeout(this.resizeTimeout);this.resizeTimeout=setTimeout((()=>{const currentWidth=$target.offsetWidth;if(currentWidth===this.width)return;this.width=currentWidth;handleSplit()}),150)}));if(this.lineTemplate&&!this.ready){doc.fonts.ready.then(handleSplit)}else{handleSplit()}$target?this.resizeObserver.observe($target):console.warn("No Text Splitter target found.")}addEffect(effect){if(!isFnc(effect))return console.warn("Effect must return a function.");const refreshableEffect=createRefreshable(effect);this.effects.push(refreshableEffect);if(this.ready)this.effectsCleanups[this.effects.length-1]=refreshableEffect(this);return this}revert(){clearTimeout(this.resizeTimeout);this.lines.length=this.words.length=this.chars.length=0;this.resizeObserver.disconnect();this.effectsCleanups.forEach((cleanup=>isFnc(cleanup)?cleanup(this):cleanup.revert&&cleanup.revert()));this.$target.innerHTML=this.html;return this}splitNode(node){const wordTemplate=this.wordTemplate;const charTemplate=this.charTemplate;const includeSpaces=this.includeSpaces;const debug=this.debug;const nodeType=node.nodeType;if(nodeType===3){const nodeText=node.nodeValue;if(nodeText.trim()){const tempWords=[];const words=this.words;const chars=this.chars;const wordSegments=wordSegmenter.segment(nodeText);const $wordsFragment=doc.createDocumentFragment();let prevSeg=null;for(const wordSegment of wordSegments){const segment=wordSegment.segment;const isWordLike=isSegmentWordLike(wordSegment);if(!prevSeg||isWordLike&&(prevSeg&&isSegmentWordLike(prevSeg))){tempWords.push(segment)}else{const lastWordIndex=tempWords.length-1;const lastWord=tempWords[lastWordIndex];if(!lastWord.includes(" ")&&!segment.includes(" ")){tempWords[lastWordIndex]+=segment}else{tempWords.push(segment)}}prevSeg=wordSegment}for(let i=0,l=tempWords.length;i<l;i++){const word=tempWords[i];if(!word.trim()){if(i&&includeSpaces)continue;$wordsFragment.appendChild(doc.createTextNode(word))}else{const nextWord=tempWords[i+1];const hasWordFollowingSpace=includeSpaces&&nextWord&&!nextWord.trim();const wordToProcess=word;const charSegments=charTemplate?graphemeSegmenter.segment(wordToProcess):null;const $charsFragment=charTemplate?doc.createDocumentFragment():doc.createTextNode(hasWordFollowingSpace?word+" ":word);if(charTemplate){const charSegmentsArray=[...charSegments];for(let j=0,jl=charSegmentsArray.length;j<jl;j++){const charSegment=charSegmentsArray[j];const isLastChar=j===jl-1;const charText=isLastChar&&hasWordFollowingSpace?charSegment.segment+" ":charSegment.segment;const $charNode=doc.createTextNode(charText);processHTMLTemplate(charTemplate,chars,$charNode,$charsFragment,charType,debug,-1,words.length,chars.length)}}if(wordTemplate){processHTMLTemplate(wordTemplate,words,$charsFragment,$wordsFragment,wordType,debug,-1,words.length,chars.length)}else if(charTemplate){$wordsFragment.appendChild($charsFragment)}else{$wordsFragment.appendChild(doc.createTextNode(word))}if(hasWordFollowingSpace)i++}}node.parentNode.replaceChild($wordsFragment,node)}}else if(nodeType===1){const childNodes=[...node.childNodes];for(let i=0,l=childNodes.length;i<l;i++)this.splitNode(childNodes[i])}}split(clearCache=false){const $el=this.$target;const isCached=!!this.cache&&!clearCache;const lineTemplate=this.lineTemplate;const wordTemplate=this.wordTemplate;const charTemplate=this.charTemplate;const fontsReady=doc.fonts.status!=="loading";const canSplitLines=lineTemplate&&fontsReady;this.ready=!lineTemplate||fontsReady;if(canSplitLines||clearCache){this.effectsCleanups.forEach((cleanup=>isFnc(cleanup)&&cleanup(this)))}if(!isCached){if(clearCache){$el.innerHTML=this.html;this.words.length=this.chars.length=0}this.splitNode($el);this.cache=$el.innerHTML}if(canSplitLines){if(isCached)$el.innerHTML=this.cache;this.lines.length=0;if(wordTemplate)this.words=getAllTopLevelElements($el,wordType)}if(charTemplate&&(canSplitLines||wordTemplate)){this.chars=getAllTopLevelElements($el,charType)}const elementsArray=this.words.length?this.words:this.chars;let y,linesCount=0;for(let i=0,l=elementsArray.length;i<l;i++){const $el=elementsArray[i];const{top:top,height:height}=$el.getBoundingClientRect();if(y&&top-y>height*.5)linesCount++;$el.setAttribute(dataLine,`${linesCount}`);const nested=$el.querySelectorAll(`[${dataLine}]`);let c=nested.length;while(c--)nested[c].setAttribute(dataLine,`${linesCount}`);y=top}if(canSplitLines){const linesFragment=doc.createDocumentFragment();const parents=new Set;const clones=[];for(let lineIndex=0;lineIndex<linesCount+1;lineIndex++){const $clone=$el.cloneNode(true);filterLineElements($clone,lineIndex,new Set).forEach(($el=>{const $parent=$el.parentElement;if($parent)parents.add($parent);$el.remove()}));clones.push($clone)}parents.forEach(filterEmptyElements);for(let cloneIndex=0,clonesLength=clones.length;cloneIndex<clonesLength;cloneIndex++){processHTMLTemplate(lineTemplate,this.lines,clones[cloneIndex],linesFragment,lineType,this.debug,cloneIndex)}$el.innerHTML="";$el.appendChild(linesFragment);if(wordTemplate)this.words=getAllTopLevelElements($el,wordType);if(charTemplate)this.chars=getAllTopLevelElements($el,charType)}if(this.linesOnly){const words=this.words;let w=words.length;while(w--){const $word=words[w];$word.replaceWith($word.textContent)}words.length=0}if(this.accessible&&(canSplitLines||!isCached)){const $accessible=doc.createElement("span");$accessible.style.cssText=`position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;$accessible.innerHTML=this.html;$el.insertBefore($accessible,$el.firstChild);this.lines.forEach(setAriaHidden);this.words.forEach(setAriaHidden);this.chars.forEach(setAriaHidden)}this.width=$el.offsetWidth;if(canSplitLines||clearCache){this.effects.forEach(((effect,i)=>this.effectsCleanups[i]=effect(this)))}return this}refresh(){this.split(true)}}const split=(target,parameters)=>new TextSplitter(target,parameters);const text={split:split};const stagger=(val,params={})=>{let values=[];let maxValue=0;const from=params.from;const reversed=params.reversed;const ease=params.ease;const hasEasing=!isUnd(ease);const hasSpring=hasEasing&&!isUnd(ease.ease);const staggerEase=hasSpring?ease.ease:hasEasing?parseEasings(ease):null;const grid=params.grid;const axis=params.axis;const customTotal=params.total;const fromFirst=isUnd(from)||from===0||from==="first";const fromCenter=from==="center";const fromLast=from==="last";const fromRandom=from==="random";const isRange=isArr(val);const useProp=params.use;const val1=isRange?parseNumber(val[0]):parseNumber(val);const val2=isRange?parseNumber(val[1]):0;const unitMatch=unitsExecRgx.exec((isRange?val[1]:val)+emptyString);const start=params.start||0+(isRange?val1:0);let fromIndex=fromFirst?0:isNum(from)?from:0;return(target,i,t,tl)=>{const[registeredTarget]=registerTargets(target);const total=isUnd(customTotal)?t:customTotal;const customIndex=!isUnd(useProp)?isFnc(useProp)?useProp(registeredTarget,i,total):getOriginalAnimatableValue(registeredTarget,useProp):false;const staggerIndex=isNum(customIndex)||isStr(customIndex)&&isNum(+customIndex)?+customIndex:i;if(fromCenter)fromIndex=(total-1)/2;if(fromLast)fromIndex=total-1;if(!values.length){for(let index=0;index<total;index++){if(!grid){values.push(abs(fromIndex-index))}else{const fromX=!fromCenter?fromIndex%grid[0]:(grid[0]-1)/2;const fromY=!fromCenter?floor(fromIndex/grid[0]):(grid[1]-1)/2;const toX=index%grid[0];const toY=floor(index/grid[0]);const distanceX=fromX-toX;const distanceY=fromY-toY;let value=sqrt(distanceX*distanceX+distanceY*distanceY);if(axis==="x")value=-distanceX;if(axis==="y")value=-distanceY;values.push(value)}maxValue=max(...values)}if(staggerEase)values=values.map((val=>staggerEase(val/maxValue)*maxValue));if(reversed)values=values.map((val=>axis?val<0?val*-1:-val:abs(maxValue-val)));if(fromRandom)values=shuffle(values)}const spacing=isRange?(val2-val1)/maxValue:val1;const offset=tl?parseTimelinePosition(tl,isUnd(params.start)?tl.iterationDuration:start):start;let output=offset+(spacing*round(values[staggerIndex],2)||0);if(params.modifier)output=params.modifier(output);if(unitMatch)output=`${output}${unitMatch[2]}`;return output}};exports.Animatable=Animatable;exports.Draggable=Draggable;exports.JSAnimation=JSAnimation;exports.Scope=Scope;exports.ScrollObserver=ScrollObserver;exports.Spring=Spring;exports.TextSplitter=TextSplitter;exports.Timeline=Timeline;exports.Timer=Timer;exports.WAAPIAnimation=WAAPIAnimation;exports.animate=animate;exports.createAnimatable=createAnimatable;exports.createDraggable=createDraggable;exports.createScope=createScope;exports.createSpring=createSpring;exports.createTimeline=createTimeline;exports.createTimer=createTimer;exports.eases=eases;exports.engine=engine;exports.onScroll=onScroll;exports.scrollContainers=scrollContainers;exports.stagger=stagger;exports.svg=svg;exports.text=text;exports.utils=utils;exports.waapi=waapi}));
diff --git a/lib/anime.umd.min.js b/lib/anime.umd.min.js
deleted file mode 100644
index 14234774..00000000
--- a/lib/anime.umd.min.js
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * anime.js - UMD
- * @version v4.1.3
- * @author Julian Garnier
- * @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
- */
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).anime={})}(this,(function(t){"use strict";const e="undefined"!=typeof window,s=e?window:null,i=e?document:null,r={replace:0,none:1,blend:2},n=Symbol(),o=Symbol(),a=Symbol(),h=Symbol(),l=Symbol(),c=Symbol(),d=1e-11,u=1e12,p=1e3,m="",f=(()=>{const t=new Map;return t.set("x","translateX"),t.set("y","translateY"),t.set("z","translateZ"),t})(),g=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],y=g.reduce(((t,e)=>({...t,[e]:e+"("})),{}),_=()=>{},v=/(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i,b=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i,T=/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,w=/hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i,x=/hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i,S=/[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi,k=/^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i,$=/([a-z])([A-Z])/g,C=/(\w+)(\([^)]+\)+)/g,E=/(\*=|\+=|-=)/,B={id:null,keyframes:null,playbackEase:null,playbackRate:1,frameRate:120,loop:0,reversed:!1,alternate:!1,autoplay:!0,duration:p,delay:0,loopDelay:0,ease:"out(2)",composition:r.replace,modifier:t=>t,onBegin:_,onBeforeUpdate:_,onUpdate:_,onLoop:_,onPause:_,onComplete:_,onRender:_},L={current:null,root:i},D={defaults:B,precision:4,timeScale:1,tickThreshold:200},A={version:"4.1.3",engine:null};e&&(s.AnimeJS||(s.AnimeJS=[]),s.AnimeJS.push(A));const N=t=>t.replace($,"$1-$2").toLowerCase(),F=(t,e)=>0===t.indexOf(e),O=Date.now,P=Array.isArray,R=t=>t&&t.constructor===Object,M=t=>"number"==typeof t&&!isNaN(t),I=t=>"string"==typeof t,z=t=>"function"==typeof t,Y=t=>void 0===t,X=t=>Y(t)||null===t,W=t=>e&&t instanceof SVGElement,V=t=>v.test(t),H=t=>F(t,"rgb"),U=t=>F(t,"hsl"),q=t=>!D.defaults.hasOwnProperty(t),Q=t=>I(t)?parseFloat(t):t,j=Math.pow,G=Math.sqrt,Z=Math.sin,J=Math.cos,K=Math.abs,tt=Math.exp,et=Math.ceil,st=Math.floor,it=Math.asin,rt=Math.max,nt=Math.atan2,ot=Math.PI,at=Math.round,ht=(t,e,s)=>t<e?e:t>s?s:t,lt={},ct=(t,e)=>{if(e<0)return t;if(!e)return at(t);let s=lt[e];return s||(s=lt[e]=10**e),at(t*s)/s},dt=(t,e)=>P(e)?e.reduce(((e,s)=>K(s-t)<K(e-t)?s:e)):e?at(t/e)*e:t,ut=(t,e,s)=>t+(e-t)*s,pt=(t,e,s)=>{const i=10**(s||0);return st((Math.random()*(e-t+1/i)+t)*i)/i},mt=t=>{let e,s,i=t.length;for(;i;)s=pt(0,--i),e=t[i],t[i]=t[s],t[s]=e;return t},ft=t=>t===1/0?u:t===-1/0?-1e12:t,gt=t=>t<=d?d:ft(ct(t,11)),yt=t=>P(t)?[...t]:t,_t=(t,e)=>{const s={...t};for(let i in e){const r=t[i];s[i]=Y(r)?e[i]:r}return s},vt=(t,e,s,i="_prev",r="_next")=>{let n=t._head,o=r;for(s&&(n=t._tail,o=i);n;){const t=n[o];e(n),n=t}},bt=(t,e,s="_prev",i="_next")=>{const r=e[s],n=e[i];r?r[i]=n:t._head=n,n?n[s]=r:t._tail=r,e[s]=null,e[i]=null},Tt=(t,e,s,i="_prev",r="_next")=>{let n=t._tail;for(;n&&s&&s(n,e);)n=n[i];const o=n?n[r]:t._head;n?n[r]=e:t._head=e,o?o[i]=e:t._tail=e,e[i]=n,e[r]=o},wt=t=>{let e;return(...s)=>{let i,r,n,o;e&&(i=e.currentIteration,r=e.iterationProgress,n=e.reversed,o=e._alternate,e.revert());const a=t(...s);return a&&!z(a)&&a.revert&&(e=a),Y(r)||(e.currentIteration=i,e.iterationProgress=(o&&i%2?!n:n)?1-r:r),a||_}};class xt{constructor(t=0){this.deltaTime=0,this._currentTime=t,this._elapsedTime=t,this._startTime=t,this._lastTime=t,this._scheduledTime=0,this._frameDuration=ct(p/120,0),this._fps=120,this._speed=1,this._hasChildren=!1,this._head=null,this._tail=null}get fps(){return this._fps}set fps(t){const e=this._frameDuration,s=+t,i=s<d?d:s,r=ct(p/i,0);this._fps=i,this._frameDuration=r,this._scheduledTime+=r-e}get speed(){return this._speed}set speed(t){const e=+t;this._speed=e<d?d:e}requestTick(t){const e=this._scheduledTime,s=this._elapsedTime;if(this._elapsedTime+=t-s,s<e)return 0;const i=this._frameDuration,r=s-e;return this._scheduledTime+=r<i?i:r,1}computeDeltaTime(t){const e=t-this._lastTime;return this.deltaTime=e,this._lastTime=t,e}}const St=(t,e,s,i,n)=>{const o=t.parent,a=t.duration,l=t.completed,c=t.iterationDuration,u=t.iterationCount,p=t._currentIteration,f=t._loopDelay,g=t._reversed,_=t._alternate,v=t._hasChildren,b=t._delay,T=t._currentTime,w=b+c,x=e-b,S=ht(T,-b,a),k=ht(x,-b,a),$=x-T,C=k>0,E=k>=a,B=a<=d,L=2===n;let A=0,N=x,F=0;if(u>1){const e=~~(k/(c+(E?0:f)));t._currentIteration=ht(e,0,u),E&&t._currentIteration--,A=t._currentIteration%2,N=k%(c+f)||0}const O=g^(_&&A),P=t._ease;let R=E?O?0:a:O?c-N:N;P&&(R=c*P(R/c)||0);const M=(o?o.backwards:x<T)?!O:!!O;if(t._currentTime=x,t._iterationTime=R,t.backwards=M,C&&!t.began?(t.began=!0,s||o&&(M||!o.began)||t.onBegin(t)):x<=0&&(t.began=!1),s||v||!C||t._currentIteration===p||t.onLoop(t),L||1===n&&(e>=b&&e<=w||e<=b&&S>b||e>=w&&S!==a)||R>=w&&S!==a||R<=b&&S>0||e<=S&&S===a&&l||E&&!l&&B){if(C&&(t.computeDeltaTime(S),s||t.onBeforeUpdate(t)),!v){const e=L||(M?-1*$:$)>=D.tickThreshold,n=t._offset+(o?o._offset:0)+b+R;let a,l,c,d,u=t._head,p=0;for(;u;){const t=u._composition,s=u._currentTime,o=u._changeDuration,f=u._absoluteStartTime+u._changeDuration,g=u._nextRep,_=u._prevRep,v=t!==r.none;if((e||(s!==o||n<=f+(g?g._delay:0))&&(0!==s||n>=u._absoluteStartTime))&&(!v||!u._isOverridden&&(!u._isOverlapped||n<=f)&&(!g||g._isOverridden||n<=g._absoluteStartTime)&&(!_||_._isOverridden||n>=_._absoluteStartTime+_._changeDuration+u._delay))){const e=u._currentTime=ht(R-u._startTime,0,o),s=u._ease(e/u._updateDuration),n=u._modifier,m=u._valueType,f=u._tweenType,g=0===f,y=0===m,_=y&&g||0===s||1===s?-1:D.precision;let b,T;if(y)b=T=n(ct(ut(u._fromNumber,u._toNumber,s),_));else if(1===m)T=n(ct(ut(u._fromNumber,u._toNumber,s),_)),b=`${T}${u._unit}`;else if(2===m){const t=u._fromNumbers,e=u._toNumbers,i=ct(ht(n(ut(t[0],e[0],s)),0,255),0),r=ct(ht(n(ut(t[1],e[1],s)),0,255),0),o=ct(ht(n(ut(t[2],e[2],s)),0,255),0),a=ht(n(ct(ut(t[3],e[3],s),_)),0,1);if(b=`rgba(${i},${r},${o},${a})`,v){const t=u._numbers;t[0]=i,t[1]=r,t[2]=o,t[3]=a}}else if(3===m){b=u._strings[0];for(let t=0,e=u._toNumbers.length;t<e;t++){const e=n(ct(ut(u._fromNumbers[t],u._toNumbers[t],s),_)),i=u._strings[t+1];b+=`${i?e+i:e}`,v&&(u._numbers[t]=e)}}if(v&&(u._number=T),i||t===r.blend)u._value=b;else{const t=u.property;a=u.target,g?a[t]=b:1===f?a.setAttribute(t,b):(l=a.style,3===f?(a!==c&&(c=a,d=a[h]),d[t]=b,p=1):2===f?l[t]=b:4===f&&l.setProperty(t,b)),C&&(F=1)}}if(p&&u._renderTransforms){let t=m;for(let e in d)t+=`${y[e]}${d[e]}) `;l.transform=t,p=0}u=u._next}!s&&F&&t.onRender(t)}!s&&C&&t.onUpdate(t)}return o&&B?!s&&(o.began&&!M&&x>=a&&!l||M&&x<=d&&l)&&(t.onComplete(t),t.completed=!M):C&&E?u===1/0?t._startTime+=t.duration:t._currentIteration>=u-1&&(t.paused=!0,l||v||(t.completed=!0,s||o&&(M||!o.began)||(t.onComplete(t),t._resolve(t)))):t.completed=!1,F},kt=(t,e,s,i,r)=>{const n=t._currentIteration;if(St(t,e,s,i,r),t._hasChildren){const o=t,a=o.backwards,h=i?e:o._iterationTime,l=O();let c=0,u=!0;if(!i&&o._currentIteration!==n){const t=o.iterationDuration;vt(o,(e=>{if(a){const i=e.duration,r=e._offset+e._delay;s||!(i<=d)||r&&r+i!==t||e.onComplete(e)}else!e.completed&&!e.backwards&&e._currentTime<e.iterationDuration&&St(e,t,s,1,2),e.began=!1,e.completed=!1})),s||o.onLoop(o)}vt(o,(t=>{const e=ct((h-t._offset)*t._speed,12),n=t._fps<o._fps?t.requestTick(l):r;c+=St(t,e,s,i,n),!t.completed&&u&&(u=!1)}),a),!s&&c&&o.onRender(o),(u||a)&&o._currentTime>=o.duration&&(o.paused=!0,o.completed||(o.completed=!0,s||(o.onComplete(o),o._resolve(o))))}},$t={animation:null,update:_},Ct=(()=>e?requestAnimationFrame:setImmediate)(),Et=(()=>e?cancelAnimationFrame:clearImmediate)();class Bt extends xt{constructor(t){super(t),this.useDefaultMainLoop=!0,this.pauseOnDocumentHidden=!0,this.defaults=B,this.paused=!0,this.reqId=0}update(){const t=this._currentTime=O();if(this.requestTick(t)){this.computeDeltaTime(t);const e=this._speed,s=this._fps;let i=this._head;for(;i;){const r=i._next;i.paused?(bt(this,i),this._hasChildren=!!this._tail,i._running=!1,i.completed&&!i._cancelled&&i.cancel()):kt(i,(t-i._startTime)*i._speed*e,0,0,i._fps<s?i.requestTick(t):1),i=r}$t.update()}}wake(){return this.useDefaultMainLoop&&!this.reqId&&(this.requestTick(O()),this.reqId=Ct(Dt)),this}pause(){if(this.reqId)return this.paused=!0,At()}resume(){if(this.paused)return this.paused=!1,vt(this,(t=>t.resetTime())),this.wake()}get speed(){return this._speed*(1===D.timeScale?1:p)}set speed(t){this._speed=t*D.timeScale,vt(this,(t=>t.speed=t._speed))}get timeUnit(){return 1===D.timeScale?"ms":"s"}set timeUnit(t){const e="s"===t,s=e?.001:1;if(D.timeScale!==s){D.timeScale=s,D.tickThreshold=200*s;const t=e?.001:p;this.defaults.duration*=t,this._speed*=t}}get precision(){return D.precision}set precision(t){D.precision=t}}const Lt=(()=>{const t=new Bt(O());return e&&(A.engine=t,i.addEventListener("visibilitychange",(()=>{t.pauseOnDocumentHidden&&(i.hidden?t.pause():t.resume())}))),t})(),Dt=()=>{Lt._head?(Lt.reqId=Ct(Dt),Lt.update()):Lt.reqId=0},At=()=>(Et(Lt.reqId),Lt.reqId=0,Lt);function Nt(t){const e=I(t)?L.root.querySelectorAll(t):t;if(e instanceof NodeList||e instanceof HTMLCollection)return e}function Ft(t){if(X(t))return[];if(!e)return P(t)&&t.flat(1/0)||[t];if(P(t)){const e=t.flat(1/0),s=[];for(let t=0,i=e.length;t<i;t++){const i=e[t];if(!X(i)){const t=Nt(i);if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!X(i)){let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}else{let t=!1;for(let e=0,r=s.length;e<r;e++)if(s[e]===i){t=!0;break}t||s.push(i)}}}return s}const s=Nt(t);return s?Array.from(s):[t]}function Ot(t){const e=Ft(t),s=e.length;if(s)for(let t=0;t<s;t++){const s=e[t];if(!s[n]){s[n]=!0;const t=W(s);(s.nodeType||t)&&(s[o]=!0,s[a]=t,s[h]={})}}return e}const Pt=t=>{const e=Ft(t)[0];if(e&&W(e))return e},Rt=(t,e,s=0)=>t.getPointAtLength(e+s>=1?e+s:0),Mt=(t,e)=>s=>{const i=+t.getTotalLength(),r=s[a],n=t.getCTM();return{from:0,to:i,modifier:s=>{if("a"===e){const e=Rt(t,s,-1),i=Rt(t,s,1);return 180*nt(i.y-e.y,i.x-e.x)/ot}{const i=Rt(t,s,0);return"x"===e?r||!n?i.x:i.x*n.a+i.y*n.c+n.e:r||!n?i.y:i.x*n.b+i.y*n.d+n.f}}}},It=["opacity","rotate","overflow","color"],zt={morphTo:(t,e=.33)=>s=>{const i=Pt(t);if(!i)return;const r="path"===s.tagName,n=r?" ":",",o=s[l];o&&s.setAttribute(r?"d":"points",o);let a="",h="";if(e){const t=s.getTotalLength(),o=i.getTotalLength(),l=Math.max(Math.ceil(t*e),Math.ceil(o*e));for(let e=0;e<l;e++){const c=e/(l-1),d=s.getPointAtLength(t*c),u=i.getPointAtLength(o*c),p=r?0===e?"M":"L":"";a+=p+ct(d.x,3)+n+d.y+" ",h+=p+ct(u.x,3)+n+u.y+" "}}else a=s.getAttribute(r?"d":"points"),h=i.getAttribute(r?"d":"points");return s[l]=h,[a,h]},createMotionPath:t=>{const e=Pt(t);if(e)return{translateX:Mt(e,"x"),translateY:Mt(e,"y"),rotate:Mt(e,"a")}},createDrawable:(t,e=0,s=0)=>Ft(t).map((t=>((t,e,s)=>{const i=p,r=getComputedStyle(t),n=r.strokeLinecap,o="non-scaling-stroke"===r.vectorEffect?t:null;let a=n;const h=new Proxy(t,{get(t,e){const s=t[e];return e===c?t:"setAttribute"===e?(...e)=>{if("draw"===e[0]){const s=e[1].split(" "),r=+s[0],h=+s[1],l=(t=>{let e=1;if(t&&t.getCTM){const s=t.getCTM();s&&(e=(G(s.a*s.a+s.b*s.b)+G(s.c*s.c+s.d*s.d))/2)}return e})(o),c=-1e3*r*l,d=h*i*l+c,u=i*l+(0===r&&1===h||1===r&&0===h?0:10*l)-d;if("butt"!==n){const e=r===h?"butt":n;a!==e&&(t.style.strokeLinecap=`${e}`,a=e)}t.setAttribute("stroke-dashoffset",`${c}`),t.setAttribute("stroke-dasharray",`${d} ${u}`)}return Reflect.apply(s,t,e)}:z(s)?(...e)=>Reflect.apply(s,t,e):s}});return"1000"!==t.getAttribute("pathLength")&&(t.setAttribute("pathLength","1000"),h.setAttribute("draw",`${e} ${s}`)),h})(t,e,s)))},Yt=(t,e,s)=>(s<0&&(s+=1),s>1&&(s-=1),s<1/6?t+6*(e-t)*s:s<.5?e:s<2/3?t+(e-t)*(2/3-s)*6:t),Xt=(t,e)=>Y(t)?e:t,Wt=(t,e,s,i,r)=>{if(z(t)){const n=()=>{const r=t(e,s,i);return isNaN(+r)?r||0:+r};return r&&(r.func=n),n()}return t},Vt=(t,e)=>t[o]?t[a]&&((t,e)=>{if(It.includes(e))return!1;if(t.getAttribute(e)||e in t){if("scale"===e){const e=t.parentNode;return e&&"filter"===e.tagName}return!0}})(t,e)?1:g.includes(e)||f.get(e)?3:F(e,"--")?4:e in t.style?2:e in t?0:1:0,Ht=(t,e,s)=>{const i=t.style[e];i&&s&&(s[e]=i);const r=i||getComputedStyle(t[c]||t).getPropertyValue(e);return"auto"===r?"0":r},Ut=(t,e,s,i)=>{const r=Y(s)?Vt(t,e):s;return 0===r?t[e]||0:1===r?t.getAttribute(e):3===r?((t,e,s)=>{const i=t.style.transform;let r;if(i){const n=t[h];let o;for(;o=C.exec(i);){const t=o[1],i=o[2].slice(1,-1);n[t]=i,t===e&&(r=i,s&&(s[e]=i))}}return i&&!Y(r)?r:F(e,"scale")?"1":F(e,"rotate")||F(e,"skew")?"0deg":"0px"})(t,e,i):4===r?Ht(t,e,i).trimStart():Ht(t,e,i)},qt=(t,e,s)=>"-"===s?t-e:"+"===s?t+e:t*e,Qt=(t,e)=>{if(e.t=0,e.n=0,e.u=null,e.o=null,e.d=null,e.s=null,!t)return e;const s=+t;if(isNaN(s)){let s=t;"="===s[1]&&(e.o=s[0],s=s.slice(2));const n=!s.includes(" ")&&k.exec(s);if(n)return e.t=1,e.n=+n[1],e.u=n[2],e;if(e.o)return e.n=+s,e;if(V(r=s)||H(r)||U(r))return e.t=2,e.d=H(i=s)?(t=>{const e=b.exec(t)||T.exec(t),s=Y(e[4])?1:+e[4];return[+e[1],+e[2],+e[3],s]})(i):V(i)?(t=>{const e=t.length,s=4===e||5===e;return[+("0x"+t[1]+t[s?1:2]),+("0x"+t[s?2:3]+t[s?2:4]),+("0x"+t[s?3:5]+t[s?3:6]),5===e||9===e?+(+("0x"+t[s?4:7]+t[s?4:8])/255).toFixed(3):1]})(i):U(i)?(t=>{const e=w.exec(t)||x.exec(t),s=+e[1]/360,i=+e[2]/100,r=+e[3]/100,n=Y(e[4])?1:+e[4];let o,a,h;if(0===i)o=a=h=r;else{const t=r<.5?r*(1+i):r+i-r*i,e=2*r-t;o=ct(255*Yt(e,t,s+1/3),0),a=ct(255*Yt(e,t,s),0),h=ct(255*Yt(e,t,s-1/3),0)}return[o,a,h,n]})(i):[0,0,0,1],e;{const t=s.match(S);return e.t=3,e.d=t?t.map(Number):[],e.s=s.split(S)||[],e}}var i,r;return e.n=s,e},jt=(t,e)=>(e.t=t._valueType,e.n=t._toNumber,e.u=t._unit,e.o=null,e.d=yt(t._toNumbers),e.s=yt(t._strings),e),Gt={t:0,n:0,u:null,o:null,d:null,s:null},Zt={_rep:new WeakMap,_add:new Map},Jt=(t,e,s="_rep")=>{const i=Zt[s];let r=i.get(t);return r||(r={},i.set(t,r)),r[e]?r[e]:r[e]={_head:null,_tail:null}},Kt=(t,e)=>t._isOverridden||t._absoluteStartTime>e._absoluteStartTime,te=t=>{t._isOverlapped=1,t._isOverridden=1,t._changeDuration=d,t._currentTime=d},ee=(t,e)=>{const s=t._composition;if(s===r.replace){const s=t._absoluteStartTime;Tt(e,t,Kt,"_prevRep","_nextRep");const i=t._prevRep;if(i){const e=i.parent,r=i._absoluteStartTime+i._changeDuration;if(t.parent.id!==e.id&&e.iterationCount>1&&r+(e.duration-e.iterationDuration)>s){te(i);let t=i._prevRep;for(;t&&t.parent.id===e.id;)te(t),t=t._prevRep}const n=s-t._delay;if(r>n){const t=i._startTime,e=r-(t+i._updateDuration),s=ct(n-e-t,12);i._changeDuration=s,i._currentTime=s,i._isOverlapped=1,s<d&&te(i)}let o=!0;if(vt(e,(t=>{t._isOverlapped||(o=!1)})),o){const t=e.parent;if(t){let s=!0;vt(t,(t=>{t!==e&&vt(t,(t=>{t._isOverlapped||(s=!1)}))})),s&&t.cancel()}else e.cancel()}}}else if(s===r.blend){const e=Jt(t.target,t.property,"_add"),s=(t=>{let e=$t.animation;return e||(e={duration:d,computeDeltaTime:_,_offset:0,_delay:0,_head:null,_tail:null},$t.animation=e,$t.update=()=>{t.forEach((t=>{for(let e in t){const s=t[e],i=s._head;if(i){const t=i._valueType,e=3===t||2===t?yt(i._fromNumbers):null;let r=i._fromNumber,n=s._tail;for(;n&&n!==i;){if(e)for(let t=0,s=n._numbers.length;t<s;t++)e[t]+=n._numbers[t];else r+=n._number;n=n._prevAdd}i._toNumber=r,i._toNumbers=e}}})),St(e,1,1,0,2)}),e})(Zt._add);let i=e._head;i||(i={...t},i._composition=r.replace,i._updateDuration=d,i._startTime=0,i._numbers=yt(t._fromNumbers),i._number=0,i._next=null,i._prev=null,Tt(e,i),Tt(s,i));const n=t._toNumber;if(t._fromNumber=i._fromNumber-n,t._toNumber=0,t._numbers=yt(t._fromNumbers),t._number=0,i._fromNumber=n,t._toNumbers){const e=yt(t._toNumbers);e&&e.forEach(((e,s)=>{t._fromNumbers[s]=i._fromNumbers[s]-e,t._toNumbers[s]=0})),i._fromNumbers=e}Tt(e,t,null,"_prevAdd","_nextAdd")}return t},se=t=>{const e=t._composition;if(e!==r.none){const s=t.target,i=t.property,n=Zt._rep.get(s)[i];if(bt(n,t,"_prevRep","_nextRep"),e===r.blend){const e=Zt._add,r=e.get(s);if(!r)return;const n=r[i],o=$t.animation;bt(n,t,"_prevAdd","_nextAdd");const a=n._head;if(a&&a===n._tail){bt(n,a,"_prevAdd","_nextAdd"),bt(o,a);let t=!0;for(let e in r)if(r[e]._head){t=!1;break}t&&e.delete(s)}}}return t},ie=t=>(t.paused=!0,t.began=!1,t.completed=!1,t),re=t=>t._cancelled?(t._hasChildren?vt(t,re):vt(t,(t=>{t._composition!==r.none&&ee(t,Jt(t.target,t.property))})),t._cancelled=0,t):t;let ne=0;class oe extends xt{constructor(t={},e=null,s=0){super(0);const{id:i,delay:r,duration:n,reversed:o,alternate:a,loop:h,loopDelay:l,autoplay:c,frameRate:u,playbackRate:p,onComplete:m,onLoop:f,onPause:g,onBegin:y,onBeforeUpdate:v,onUpdate:b}=t;L.current&&L.current.register(this);const T=e?0:Lt._elapsedTime,w=e?e.defaults:D.defaults,x=z(r)||Y(r)?w.delay:+r,S=z(n)||Y(n)?1/0:+n,k=Xt(h,w.loop),$=Xt(l,w.loopDelay),C=!0===k||k===1/0||k<0?1/0:k+1;let E=0;e?E=s:(Lt.reqId||Lt.requestTick(O()),E=(Lt._elapsedTime-Lt._startTime)*D.timeScale),this.id=Y(i)?++ne:i,this.parent=e,this.duration=ft((S+$)*C-$)||d,this.backwards=!1,this.paused=!0,this.began=!1,this.completed=!1,this.onBegin=y||w.onBegin,this.onBeforeUpdate=v||w.onBeforeUpdate,this.onUpdate=b||w.onUpdate,this.onLoop=f||w.onLoop,this.onPause=g||w.onPause,this.onComplete=m||w.onComplete,this.iterationDuration=S,this.iterationCount=C,this._autoplay=!e&&Xt(c,w.autoplay),this._offset=E,this._delay=x,this._loopDelay=$,this._iterationTime=0,this._currentIteration=0,this._resolve=_,this._running=!1,this._reversed=+Xt(o,w.reversed),this._reverse=this._reversed,this._cancelled=0,this._alternate=Xt(a,w.alternate),this._prev=null,this._next=null,this._elapsedTime=T,this._startTime=T,this._lastTime=T,this._fps=Xt(u,w.frameRate),this._speed=Xt(p,w.playbackRate)}get cancelled(){return!!this._cancelled}set cancelled(t){t?this.cancel():this.reset(1).play()}get currentTime(){return ht(ct(this._currentTime,D.precision),-this._delay,this.duration)}set currentTime(t){const e=this.paused;this.pause().seek(+t),e||this.resume()}get iterationCurrentTime(){return ct(this._iterationTime,D.precision)}set iterationCurrentTime(t){this.currentTime=this.iterationDuration*this._currentIteration+t}get progress(){return ht(ct(this._currentTime/this.duration,10),0,1)}set progress(t){this.currentTime=this.duration*t}get iterationProgress(){return ht(ct(this._iterationTime/this.iterationDuration,10),0,1)}set iterationProgress(t){const e=this.iterationDuration;this.currentTime=e*this._currentIteration+e*t}get currentIteration(){return this._currentIteration}set currentIteration(t){this.currentTime=this.iterationDuration*ht(+t,0,this.iterationCount-1)}get reversed(){return!!this._reversed}set reversed(t){t?this.reverse():this.play()}get speed(){return super.speed}set speed(t){super.speed=t,this.resetTime()}reset(t=0){return re(this),this._reversed&&!this._reverse&&(this.reversed=!1),this._iterationTime=this.iterationDuration,kt(this,0,1,t,2),ie(this),this._hasChildren&&vt(this,ie),this}init(t=0){this.fps=this._fps,this.speed=this._speed,!t&&this._hasChildren&&kt(this,this.duration,1,t,2),this.reset(t);const e=this._autoplay;return!0===e?this.resume():e&&!Y(e.linked)&&e.link(this),this}resetTime(){const t=1/(this._speed*Lt._speed);return this._startTime=O()-(this._currentTime+this._delay)*t,this}pause(){return this.paused||(this.paused=!0,this.onPause(this)),this}resume(){return this.paused?(this.paused=!1,this.duration<=d&&!this._hasChildren?kt(this,d,0,0,2):(this._running||(Tt(Lt,this),Lt._hasChildren=!0,this._running=!0),this.resetTime(),this._startTime-=12,Lt.wake()),this):this}restart(){return this.reset(0).resume()}seek(t,e=0,s=0){re(this),this.completed=!1;const i=this.paused;return this.paused=!0,kt(this,t+this._delay,~~e,~~s,1),i?this:this.resume()}alternate(){const t=this._reversed,e=this.iterationCount,s=this.iterationDuration,i=e===1/0?st(u/s):e;return this._reversed=+(!this._alternate||i%2?!t:t),e===1/0?this.iterationProgress=this._reversed?1-this.iterationProgress:this.iterationProgress:this.seek(s*i-this._currentTime),this.resetTime(),this}play(){return this._reversed&&this.alternate(),this.resume()}reverse(){return this._reversed||this.alternate(),this.resume()}cancel(){return this._hasChildren?vt(this,(t=>t.cancel()),!0):vt(this,se),this._cancelled=1,this.pause()}stretch(t){const e=this.duration,s=gt(t);if(e===s)return this;const i=t/e,r=t<=d;return this.duration=r?d:s,this.iterationDuration=r?d:gt(this.iterationDuration*i),this._offset*=i,this._delay*=i,this._loopDelay*=i,this}revert(){kt(this,0,1,0,1);const t=this._autoplay;return t&&t.linked&&t.linked===this&&t.revert(),this.cancel()}complete(){return this.seek(this.duration).cancel()}then(t=_){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=_};return new Promise((t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this)))}}const ae=t=>t,he=(t,e,s)=>(((1-3*s+3*e)*t+(3*s-6*e))*t+3*e)*t,le=(t=.5,e=0,s=.5,i=1)=>t===e&&s===i?ae:r=>0===r||1===r?r:he(((t,e,s)=>{let i,r,n=0,o=1,a=0;do{r=n+(o-n)/2,i=he(r,e,s)-t,i>0?o=r:n=r}while(K(i)>1e-7&&++a<100);return r})(r,t,s),e,i),ce=(t=10,e)=>{const s=e?et:st;return e=>s(ht(e,0,1)*t)*(1/t)},de=(...t)=>{const e=t.length;if(!e)return ae;const s=e-1,i=t[0],r=t[s],n=[0],o=[Q(i)];for(let e=1;e<s;e++){const i=t[e],r=I(i)?i.trim().split(" "):[i],a=r[0],h=r[1];n.push(Y(h)?e/s:Q(h)/100),o.push(Q(a))}return o.push(Q(r)),n.push(1),function(t){for(let e=1,s=n.length;e<s;e++){const s=n[e];if(t<=s){const i=n[e-1],r=o[e-1];return r+(o[e]-r)*(t-i)/(s-i)}}return o[o.length-1]}},ue=(t=10,e=1)=>{const s=[0],i=t-1;for(let t=1;t<i;t++){const r=s[t-1],n=t/i,o=n*(1-e)+(n+((t+1)/i-n)*Math.random())*e;s.push(ht(o,r,1))}return s.push(1),de(...s)},pe=ot/2,me=2*ot,fe=(t=1.68)=>e=>j(e,+t),ge={[m]:fe,Quad:fe(2),Cubic:fe(3),Quart:fe(4),Quint:fe(5),Sine:t=>1-J(t*pe),Circ:t=>1-G(1-t*t),Expo:t=>t?j(2,10*t-10):0,Bounce:t=>{let e,s=4;for(;t<((e=j(2,--s))-1)/11;);return 1/j(4,3-s)-7.5625*j((3*e-2)/22-t,2)},Back:(t=1.70158)=>e=>(+t+1)*e*e*e-+t*e*e,Elastic:(t=1,e=.3)=>{const s=ht(+t,1,10),i=ht(+e,d,2),r=i/me*it(1/s),n=me/i;return t=>0===t||1===t?t:-s*j(2,-10*(1-t))*Z((1-t-r)*n)}},ye={in:t=>e=>t(e),out:t=>e=>1-t(1-e),inOut:t=>e=>e<.5?t(2*e)/2:1-t(-2*e+2)/2,outIn:t=>e=>e<.5?(1-t(1-2*e))/2:(t(2*e-1)+1)/2},_e=(t,e,s)=>{if(s[t])return s[t];if(t.indexOf("(")<=-1){const i=ye[t]||t.includes("Back")||t.includes("Elastic")?e[t]():e[t];return i?s[t]=i:ae}{const i=t.slice(0,-1).split("("),r=e[i[0]];return r?s[t]=r(...i[1].split(",")):ae}},ve=(()=>{const t={linear:de,irregular:ue,steps:ce,cubicBezier:le};for(let e in ye)for(let s in ge){const i=ge[s],r=ye[e];t[e+s]=s===m||"Back"===s||"Elastic"===s?(t,e)=>r(i(t,e)):r(i)}return t})(),be={linear:ae},Te=t=>z(t)?t:I(t)?_e(t,ve,be):ae,we={},xe=(t,e,s)=>{if(3===s)return f.get(t)||t;if(2===s||1===s&&W(e)&&t in e.style){const e=we[t];if(e)return e;{const e=t?N(t):t;return we[t]=e,e}}return t},Se={deg:1,rad:180/ot,turn:360},ke={},$e=(t,e,s,r=!1)=>{const n=e.u,o=e.n;if(1===e.t&&n===s)return e;const a=o+n+s,h=ke[a];if(Y(h)||r){let r;if(n in Se)r=o*Se[n]/Se[s];else{const e=100,a=t.cloneNode(),h=t.parentNode,l=h&&h!==i?h:i.body;l.appendChild(a);const c=a.style;c.width=e+n;const d=a.offsetWidth||e;c.width=e+s;const u=d/(a.offsetWidth||e);l.removeChild(a),r=u*o}e.n=r,ke[a]=r}else e.n=h;return e.t,e.u=s,e},Ce=t=>{if(t._hasChildren)vt(t,Ce,!0);else{const e=t;e.pause(),vt(e,(t=>{const s=t.property,i=t.target;if(i[o]){const r=i.style,n=e._inlineStyles[s];if(3===t._tweenType){const e=i[h];if(Y(n)||n===m?delete e[s]:e[s]=n,t._renderTransforms)if(Object.keys(e).length){let t=m;for(let s in e)t+=y[s]+e[s]+") ";r.transform=t}else r.removeProperty("transform")}else Y(n)||n===m?r.removeProperty(s):r[s]=n;e._tail===t&&e.targets.forEach((t=>{t.getAttribute&&t.getAttribute("style")===m&&t.removeAttribute("style")}))}}))}return t},Ee={t:0,n:0,u:null,o:null,d:null,s:null},Be={t:0,n:0,u:null,o:null,d:null,s:null},Le={func:null},De=[null],Ae=[null,null],Ne={to:null};let Fe,Oe,Pe=0;class Re extends oe{constructor(t,e,s,i,n=!1,o=0,a=0){super(e,s,i);const h=Ot(t),l=h.length,c=e.keyframes,u=c?_t(((t,e)=>{const s={};if(P(t)){const e=[].concat(...t.map((t=>Object.keys(t)))).filter(q);for(let i=0,r=e.length;i<r;i++){const r=e[i],n=t.map((t=>{const e={};for(let s in t){const i=t[s];q(s)?s===r&&(e.to=i):e[s]=i}return e}));s[r]=n}}else{const i=Xt(e.duration,D.defaults.duration),r=Object.keys(t).map((e=>({o:parseFloat(e)/100,p:t[e]}))).sort(((t,e)=>t.o-e.o));r.forEach((t=>{const e=t.o,r=t.p;for(let t in r)if(q(t)){let n=s[t];n||(n=s[t]=[]);const o=e*i;let a=n.length,h=n[a-1];const l={to:r[t]};let c=0;for(let t=0;t<a;t++)c+=n[t].duration;1===a&&(l.from=h.to),r.ease&&(l.ease=r.ease),l.duration=o-(a?c:0),n.push(l)}return t}));for(let t in s){const e=s[t];let i;for(let t=0,s=e.length;t<s;t++){const s=e[t],r=s.ease;s.ease=i||void 0,i=r}e[0].duration||e.shift()}}return s})(c,e),e):e,{delay:m,duration:f,ease:g,playbackEase:y,modifier:_,composition:v,onRender:b}=u,T=s?s.defaults:D.defaults,w=Xt(y,T.playbackEase),x=w?Te(w):null,S=!Y(g)&&!Y(g.ease),k=S?g.ease:Xt(g,x?"linear":T.ease),$=S?g.duration:Xt(f,T.duration),C=Xt(m,T.delay),E=_||T.modifier,B=Y(v)&&l>=p?r.none:Y(v)?T.composition:v,L={},A=this._offset+(s?s._offset:0);let N=NaN,F=NaN,O=0,I=0;for(let t=0;t<l;t++){const e=h[t],i=o||t,c=a||l;let p=NaN,m=NaN;for(let t in u)if(q(t)){const o=Vt(e,t),a=xe(t,e,o);let h=u[t];const l=P(h);if(n&&!l&&(Ae[0]=h,Ae[1]=h,h=Ae),l){const t=h.length,e=!R(h[0]);2===t&&e?(Ne.to=h,De[0]=Ne,Fe=De):t>2&&e?(Fe=[],h.forEach(((t,e)=>{e?1===e?(Ae[1]=t,Fe.push(Ae)):Fe.push(t):Ae[0]=t}))):Fe=h}else De[0]=h,Fe=De;let f=null,g=null,y=NaN,_=0,v=0;for(let t=Fe.length;v<t;v++){const n=Fe[v];R(n)?Oe=n:(Ne.to=n,Oe=Ne),Le.func=null;const h=Wt(Oe.to,e,i,c,Le);let l;R(h)&&!Y(h.to)?(Oe=h,l=h.to):l=h;const u=Wt(Oe.from,e,i,c),p=Oe.ease,m=!Y(p)&&!Y(p.ease),b=m?p.ease:p||k,T=m?p.duration:Wt(Xt(Oe.duration,t>1?Wt($,e,i,c)/t:$),e,i,c),w=Wt(Xt(Oe.delay,v?0:C),e,i,c),x=Wt(Xt(Oe.composition,B),e,i,c),S=M(x)?x:r[x],D=Oe.modifier||E,N=!Y(u),F=!Y(l),z=P(l),X=z||N&&F,W=g?_+w:w,V=ct(A+W,12);I||!N&&!z||(I=1);let H=g;if(S!==r.none){f||(f=Jt(e,a));let t=f._head;for(;t&&!t._isOverridden&&t._absoluteStartTime<=V;)if(H=t,t=t._nextRep,t&&t._absoluteStartTime>=V)for(;t;)te(t),t=t._nextRep}if(X?(Qt(z?Wt(l[0],e,i,c):u,Ee),Qt(z?Wt(l[1],e,i,c,Le):l,Be),0===Ee.t&&(H?1===H._valueType&&(Ee.t=1,Ee.u=H._unit):(Qt(Ut(e,a,o,L),Gt),1===Gt.t&&(Ee.t=1,Ee.u=Gt.u)))):(F?Qt(l,Be):g?jt(g,Be):Qt(s&&H&&H.parent.parent===s?H._value:Ut(e,a,o,L),Be),N?Qt(u,Ee):g?jt(g,Ee):Qt(s&&H&&H.parent.parent===s?H._value:Ut(e,a,o,L),Ee)),Ee.o&&(Ee.n=qt(H?H._toNumber:Qt(Ut(e,a,o,L),Gt).n,Ee.n,Ee.o)),Be.o&&(Be.n=qt(Ee.n,Be.n,Be.o)),Ee.t!==Be.t)if(3===Ee.t||3===Be.t){const t=3===Ee.t?Ee:Be,e=3===Ee.t?Be:Ee;e.t=3,e.s=yt(t.s),e.d=t.d.map((()=>e.n))}else if(1===Ee.t||1===Be.t){const t=1===Ee.t?Ee:Be,e=1===Ee.t?Be:Ee;e.t=1,e.u=t.u}else if(2===Ee.t||2===Be.t){const t=2===Ee.t?Ee:Be,e=2===Ee.t?Be:Ee;e.t=2,e.s=t.s,e.d=[0,0,0,1]}if(Ee.u!==Be.u){let t=Be.u?Ee:Be;t=$e(e,t,Be.u?Be.u:Ee.u,!1)}if(Be.d&&Ee.d&&Be.d.length!==Ee.d.length){const t=Ee.d.length>Be.d.length?Ee:Be,e=t===Ee?Be:Ee;e.d=t.d.map(((t,s)=>Y(e.d[s])?0:e.d[s])),e.s=yt(t.s)}const U=ct(+T||d,12),q={parent:this,id:Pe++,property:a,target:e,_value:null,_func:Le.func,_ease:Te(b),_fromNumbers:yt(Ee.d),_toNumbers:yt(Be.d),_strings:yt(Be.s),_fromNumber:Ee.n,_toNumber:Be.n,_numbers:yt(Ee.d),_number:Ee.n,_unit:Be.u,_modifier:D,_currentTime:0,_startTime:W,_delay:+w,_updateDuration:U,_changeDuration:U,_absoluteStartTime:V,_tweenType:o,_valueType:Be.t,_composition:S,_isOverlapped:0,_isOverridden:0,_renderTransforms:0,_prevRep:null,_nextRep:null,_prevAdd:null,_nextAdd:null,_prev:null,_next:null};S!==r.none&&ee(q,f),isNaN(y)&&(y=q._startTime),_=ct(W+U,12),g=q,O++,Tt(this,q)}(isNaN(F)||y<F)&&(F=y),(isNaN(N)||_>N)&&(N=_),3===o&&(p=O-v,m=O)}if(!isNaN(p)){let t=0;vt(this,(e=>{t>=p&&t<m&&(e._renderTransforms=1,e._composition===r.blend&&vt($t.animation,(t=>{t.id===e.id&&(t._renderTransforms=1)}))),t++}))}}l||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation."),F?(vt(this,(t=>{t._startTime-t._delay||(t._delay-=F),t._startTime-=F})),N-=F):F=0,N||(N=d,this.iterationCount=0),this.targets=h,this.duration=N===d?d:ft((N+this._loopDelay)*this.iterationCount-this._loopDelay)||d,this.onRender=b||T.onRender,this._ease=x,this._delay=F,this.iterationDuration=N,this._inlineStyles=L,!this._autoplay&&I&&this.onRender(this)}stretch(t){const e=this.duration;if(e===gt(t))return this;const s=t/e;return vt(this,(t=>{t._updateDuration=gt(t._updateDuration*s),t._changeDuration=gt(t._changeDuration*s),t._currentTime*=s,t._startTime*=s,t._absoluteStartTime*=s})),super.stretch(t)}refresh(){return vt(this,(t=>{const e=t._func;if(e){const s=Ut(t.target,t.property,t._tweenType);Qt(s,Gt),Qt(e(),Be),t._fromNumbers=yt(Gt.d),t._fromNumber=Gt.n,t._toNumbers=yt(Be.d),t._strings=yt(Be.s),t._toNumber=Be.o?qt(Gt.n,Be.n,Be.o):Be.n}})),this}revert(){return super.revert(),Ce(this)}then(t){return super.then(t)}}const Me=(t,e=100)=>{const s=[];for(let i=0;i<=e;i++)s.push(t(i/e));return`linear(${s.join(", ")})`},Ie={in:"ease-in",out:"ease-out",inOut:"ease-in-out"},ze=(()=>{const t={};for(let e in ye)t[e]=t=>ye[e](fe(t));return t})(),Ye=t=>{let e=Ie[t];if(e)return e;if(e="linear",I(t)){if(F(t,"linear")||F(t,"cubic-")||F(t,"steps")||F(t,"ease"))e=t;else if(F(t,"cubicB"))e=N(t);else{const s=_e(t,ze,Ie);z(s)&&(e=s===ae?"linear":Me(s))}Ie[t]=e}else if(z(t)){const s=Me(t);s&&(e=s)}else t.ease&&(e=Me(t.ease));return e},Xe=["x","y","z"],We=["perspective","width","height","margin","padding","top","right","bottom","left","borderWidth","fontSize","borderRadius",...Xe],Ve=(()=>[...Xe,...g.filter((t=>["X","Y","Z"].some((e=>t.endsWith(e)))))])();let He=null;const Ue={_head:null,_tail:null},qe=(t,e,s)=>{let i=Ue._head;for(;i;){const r=i._next,n=i.$el===t,o=!e||i.property===e,a=!s||i.parent===s;if(n&&o&&a){const t=i.animation;try{t.commitStyles()}catch{}t.cancel(),bt(Ue,i);const e=i.parent;e&&(e._completed++,e.animations.length===e._completed&&(e.completed=!0,e.muteCallbacks||(e.paused=!0,e.onComplete(e),e._resolve(e))))}i=r}},Qe=(t,e,s,i,r)=>{const n=e.animate(i,r),o=r.delay+ +r.duration*r.iterations;n.playbackRate=t._speed,t.paused&&n.pause(),t.duration<o&&(t.duration=o,t.controlAnimation=n),t.animations.push(n),qe(e,s),Tt(Ue,{parent:t,animation:n,$el:e,property:s,_next:null,_prev:null});const a=()=>{qe(e,s,t)};return n.onremove=a,n.onfinish=a,n},je=(t,e,s,i,r)=>{let n=Wt(e,s,i,r);return M(n)?We.includes(t)||F(t,"translate")?`${n}px`:F(t,"rotate")||F(t,"skew")?`${n}deg`:`${n}`:n},Ge=(t,e,s,i,r,n)=>{let o="0";const a=Y(i)?getComputedStyle(t)[e]:je(e,i,t,r,n);return o=Y(s)?P(i)?i.map((s=>je(e,s,t,r,n))):a:[je(e,s,t,r,n),a],o};class Ze{constructor(t,s){L.current&&L.current.register(this),X(He)&&(!e||!Y(CSS)&&Object.hasOwnProperty.call(CSS,"registerProperty")?(g.forEach((t=>{const e=F(t,"skew"),s=F(t,"scale"),i=F(t,"rotate"),r=F(t,"translate"),n=i||e,o=n?"<angle>":s?"<number>":r?"<length-percentage>":"*";try{CSS.registerProperty({name:"--"+t,syntax:o,inherits:!1,initialValue:r?"0px":n?"0deg":s?"1":"0"})}catch{}})),He=!0):He=!1);const i=Ot(t),r=i.length;r||console.warn("No target found. Make sure the element you're trying to animate is accessible before creating your animation.");const n=Xt(s.ease,Ye(D.defaults.ease)),o=n.ease&&n,a=Xt(s.autoplay,D.defaults.autoplay),l=!(!a||!a.link)&&a,c=s.alternate&&!0===s.alternate,d=s.reversed&&!0===s.reversed,u=Xt(s.loop,D.defaults.loop),v=!0===u||u===1/0?1/0:M(u)?u+1:1,b=c?d?"alternate-reverse":"alternate":d?"reverse":"normal",T=Ye(n),w=1===D.timeScale?1:p;this.targets=i,this.animations=[],this.controlAnimation=null,this.onComplete=s.onComplete||_,this.duration=0,this.muteCallbacks=!1,this.completed=!1,this.paused=!a||!1!==l,this.reversed=d,this.autoplay=a,this._speed=Xt(s.playbackRate,D.defaults.playbackRate),this._resolve=_,this._completed=0,this._inlineStyles=i.map((t=>t.getAttribute("style"))),i.forEach(((t,e)=>{const i=t[h],a=Ve.some((t=>s.hasOwnProperty(t))),l=(o?o.duration:Wt(Xt(s.duration,D.defaults.duration),t,e,r))*w,c=Wt(Xt(s.delay,D.defaults.delay),t,e,r)*w,d=Xt(s.composition,"replace");for(let o in s){if(!q(o))continue;const h={},u={iterations:v,direction:b,fill:"forwards",easing:T,duration:l,delay:c,composite:d},p=s[o],m=!!a&&(g.includes(o)?o:f.get(o));let y;if(R(p)){const s=p,a=Xt(s.ease,n),f=a.ease&&a,g=s.to,_=s.from;if(u.duration=(f?f.duration:Wt(Xt(s.duration,l),t,e,r))*w,u.delay=Wt(Xt(s.delay,c),t,e,r)*w,u.composite=Xt(s.composition,d),u.easing=Ye(a),y=Ge(t,o,_,g,e,r),m?(h[`--${m}`]=y,i[m]=y):h[o]=Ge(t,o,_,g,e,r),Qe(this,t,o,h,u),!Y(_))if(m){const e=`--${m}`;t.style.setProperty(e,h[e][0])}else t.style[o]=h[o][0]}else y=P(p)?p.map((s=>je(o,s,t,e,r))):je(o,p,t,e,r),m?(h[`--${m}`]=y,i[m]=y):h[o]=y,Qe(this,t,o,h,u)}if(a){let e=m;for(let t in i)e+=`${y[t]}var(--${t})) `;t.style.transform=e}})),l&&this.autoplay.link(this)}forEach(t){const e=I(t)?e=>e[t]():t;return this.animations.forEach(e),this}get speed(){return this._speed}set speed(t){this._speed=+t,this.forEach((e=>e.playbackRate=t))}get currentTime(){const t=this.controlAnimation,e=D.timeScale;return this.completed?this.duration:t?+t.currentTime*(1===e?1:e):0}set currentTime(t){const e=t*(1===D.timeScale?1:p);this.forEach((t=>{e>=this.duration&&t.play(),t.currentTime=e}))}get progress(){return this.currentTime/this.duration}set progress(t){this.forEach((e=>e.currentTime=t*this.duration||0))}resume(){return this.paused?(this.paused=!1,this.forEach("play")):this}pause(){return this.paused?this:(this.paused=!0,this.forEach("pause"))}alternate(){return this.reversed=!this.reversed,this.forEach("reverse"),this.paused&&this.forEach("pause"),this}play(){return this.reversed&&this.alternate(),this.resume()}reverse(){return this.reversed||this.alternate(),this.resume()}seek(t,e=!1){return e&&(this.muteCallbacks=!0),t<this.duration&&(this.completed=!1),this.currentTime=t,this.muteCallbacks=!1,this.paused&&this.pause(),this}restart(){return this.completed=!1,this.seek(0,!0).resume()}commitStyles(){return this.forEach("commitStyles")}complete(){return this.seek(this.duration)}cancel(){return this.forEach("cancel"),this.pause()}revert(){return this.cancel(),this.targets.forEach(((t,e)=>t.setAttribute("style",this._inlineStyles[e]))),this}then(t=_){const e=this.then,s=()=>{this.then=null,t(this),this.then=e,this._resolve=_};return new Promise((t=>(this._resolve=()=>t(s()),this.completed&&this._resolve(),this)))}}const Je={animate:(t,e)=>new Ze(t,e),convertEase:Me},Ke=(t=_)=>new oe({duration:1*D.timeScale,onComplete:t},null,0).resume();function ts(t,e,s){const i=Ot(t);if(!i.length)return;const[r]=i,n=Vt(r,e),o=xe(e,r,n);let a=Ut(r,o);if(Y(s))return a;if(Qt(a,Gt),0===Gt.t||1===Gt.t){if(!1===s)return Gt.n;{const t=$e(r,Gt,s,!1);return`${ct(t.n,D.precision)}${t.u}`}}}const es=(t,e)=>{if(!Y(e))return e.duration=d,e.composition=Xt(e.composition,r.none),new Re(t,e,null,0,!0).resume()},ss=(t,e,s)=>{let i=!1;return vt(e,(r=>{const n=r.target;if(t.includes(n)){const t=r.property,o=r._tweenType,a=xe(s,n,o);(!a||a&&a===t)&&(r.parent._tail===r&&3===r._tweenType&&r._prev&&3===r._prev._tweenType&&(r._prev._renderTransforms=1),bt(e,r),se(r),i=!0)}}),!0),i},is=(t,e,s)=>{const i=Ft(t),r=e||Lt,n=e&&e.controlAnimation&&e;for(let t=0,e=i.length;t<e;t++){const e=i[t];qe(e,s,n)}let o;if(r._hasChildren){let e=0;vt(r,(n=>{if(!n._hasChildren)if(o=ss(i,n,s),o&&!n._head)n.cancel(),bt(r,n);else{const t=n._offset+n._delay+n.duration;t>e&&(e=t)}n._head?is(t,n,s):n._hasChildren=!1}),!0),Y(r.iterationDuration)||(r.iterationDuration=e)}else o=ss(i,r,s);return o&&!r._head&&(r._hasChildren=!1,r.cancel&&r.cancel()),i},rs=(t,e,s,i,r)=>i+(t-e)/(s-e)*(r-i),ns=(t,e,s,i)=>{let r=p/D.defaults.frameRate;if(!1!==i){const t=i||Lt._hasChildren&&Lt;t&&t.deltaTime&&(r=t.deltaTime)}const n=1-Math.exp(-s*r*.1);return s?1===s?e:(1-n)*t+n*e:t},os=t=>(...e)=>{const s=t(...e);return new Proxy(_,{apply:(t,e,[i])=>s(i),get:(t,e)=>os(((...t)=>{const i=hs[e](...t);return t=>i(s(t))}))})},as=(t,e=0)=>(...s)=>(s.length<t.length?os(((t,e=0)=>(...s)=>e?e=>t(...s,e):e=>t(e,...s))(t,e)):t)(...s),hs={$:Ot,get:ts,set:es,remove:is,cleanInlineStyles:Ce,random:pt,randomPick:t=>t[pt(0,t.length-1)],shuffle:mt,lerp:ns,sync:Ke,keepTime:wt,clamp:as(ht),round:as(ct),snap:as(dt),wrap:as(((t,e,s)=>((t-e)%(s-e)+(s-e))%(s-e)+e)),interpolate:as(ut,1),mapRange:as(rs),roundPad:as(((t,e)=>(+t).toFixed(e))),padStart:as(((t,e,s)=>`${t}`.padStart(e,s))),padEnd:as(((t,e,s)=>`${t}`.padEnd(e,s))),degToRad:as((t=>t*ot/180)),radToDeg:as((t=>180*t/ot))},ls=(t,e)=>{let s=t.iterationDuration;if(s===d&&(s=0),Y(e))return s;if(M(+e))return+e;const i=e,r=t?t.labels:null,n=!X(r),o=((t,e)=>{if(F(e,"<")){const s="<"===e[1],i=t._tail,r=i?i._offset+i._delay:0;return s?r:r+i.duration}})(t,i),a=!Y(o),h=E.exec(i);if(h){const t=h[0],e=i.split(t),l=n&&e[0]?r[e[0]]:s,c=a?o:n?l:s,d=+e[1];return qt(c,d,t[0])}return a?o:n?Y(r[i])?s:r[i]:s};function cs(t,e,s,i,r,n){const o=M(t.duration)&&t.duration<=d?s-d:s;kt(e,o,1,1,1);const a=i?new Re(i,t,e,o,!1,r,n):new oe(t,e,o);return a.init(1),Tt(e,a),vt(e,(t=>{const s=t._offset+t._delay+t.duration;s>e.iterationDuration&&(e.iterationDuration=s)})),e.duration=function(t){return ft((t.iterationDuration+t._loopDelay)*t.iterationCount-t._loopDelay)||d}(e),e}class ds extends oe{constructor(t={}){super(t,null,0),this.duration=0,this.labels={};const e=t.defaults,s=D.defaults;this.defaults=e?_t(e,s):s,this.onRender=t.onRender||s.onRender;const i=Xt(t.playbackEase,s.playbackEase);this._ease=i?Te(i):null,this.iterationDuration=0}add(t,e,s){const i=R(e),r=R(t);if(i||r){if(this._hasChildren=!0,i){const i=e;if(z(s)){const e=s,r=Ft(t),n=this.duration,o=this.iterationDuration,a=i.id;let h=0;const l=r.length;r.forEach((t=>{const s={...i};this.duration=n,this.iterationDuration=o,Y(a)||(s.id=a+"-"+h),cs(s,this,ls(this,e(t,h,l,this)),t,h,l),h++}))}else cs(i,this,ls(this,s),t)}else cs(t,this,ls(this,e));return this.init(1)}}sync(t,e){if(Y(t)||t&&Y(t.pause))return this;t.pause();const s=+(t.effect?t.effect.getTiming().duration:t.duration);return this.add(t,{currentTime:[0,s],duration:s,ease:"linear"},e)}set(t,e,s){return Y(e)?this:(e.duration=d,e.composition=r.replace,this.add(t,e,s))}call(t,e){return Y(t)||t&&!z(t)?this:this.add({duration:0,onComplete:()=>t(this)},e)}label(t,e){return Y(t)||t&&!I(t)||(this.labels[t]=ls(this,e)),this}remove(t,e){return is(t,this,e),this}stretch(t){const e=this.duration;if(e===gt(t))return this;const s=t/e,i=this.labels;vt(this,(t=>t.stretch(t.duration*s)));for(let t in i)i[t]*=s;return super.stretch(t)}refresh(){return vt(this,(t=>{t.refresh&&t.refresh()})),this}revert(){return super.revert(),vt(this,(t=>t.revert),!0),Ce(this)}then(t){return super.then(t)}}class us{constructor(t,e){L.current&&L.current.register(this);const s=()=>{if(this.callbacks.completed)return;let t=!0;for(let e in this.animations)if(!this.animations[e].paused&&t){t=!1;break}t&&this.callbacks.complete()},i={onBegin:()=>{this.callbacks.completed&&this.callbacks.reset(),this.callbacks.play()},onComplete:s,onPause:s},n={v:1,autoplay:!1},o={};if(this.targets=[],this.animations={},this.callbacks=null,!Y(t)&&!Y(e)){for(let t in e){const s=e[t];q(t)?o[t]=s:F(t,"on")?n[t]=s:i[t]=s}this.callbacks=new Re({v:0},n);for(let e in o){const s=o[e],n=R(s);let a={},h="+=0";if(n){const t=s.unit;I(t)&&(h+=t)}else a.duration=s;a[e]=n?_t({to:h},s):h;const l=_t(i,a);l.composition=r.replace,l.autoplay=!1;const c=this.animations[e]=new Re(t,l,null,0,!1).init();this.targets.length||this.targets.push(...c.targets),this[e]=(t,e,s)=>{const i=c._head;if(Y(t)&&i){const t=i._numbers;return t&&t.length?t:i._modifier(i._number)}return vt(c,(e=>{if(P(t))for(let s=0,i=t.length;s<i;s++)Y(e._numbers[s])||(e._fromNumbers[s]=e._modifier(e._numbers[s]),e._toNumbers[s]=t[s]);else e._fromNumber=e._modifier(e._number),e._toNumber=t;Y(s)||(e._ease=Te(s)),e._currentTime=0})),Y(e)||c.stretch(e),c.reset(1).resume(),this}}}}revert(){for(let t in this.animations)this[t]=_,this.animations[t].revert();return this.animations={},this.targets.length=0,this.callbacks&&this.callbacks.revert(),this}}const ps=10*p;class ms{constructor(t={}){this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/p,this.maxIterations=this.maxDuration/this.timeStep/p,this.m=ht(Xt(t.mass,1),0,ps),this.s=ht(Xt(t.stiffness,100),1,ps),this.d=ht(Xt(t.damping,10),.1,ps),this.v=ht(Xt(t.velocity,0),-1e4,ps),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.solverDuration=0,this.duration=0,this.compute(),this.ease=t=>0===t||1===t?t:this.solve(t*this.solverDuration)}solve(t){const{zeta:e,w0:s,wd:i,b:r}=this;let n=t;return n=e<1?tt(-n*e*s)*(1*J(i*n)+r*Z(i*n)):(1+r*n)*tt(-n*s),1-n}compute(){const{maxRestSteps:t,maxIterations:e,restThreshold:s,timeStep:i,m:r,d:n,s:o,v:a}=this,h=this.w0=ht(G(o/r),d,p),l=this.zeta=n/(2*G(o*r)),c=this.wd=l<1?h*G(1-l*l):0;this.b=l<1?(l*h-a)/c:-a+h;let u=0,m=0,f=0;for(;m<t&&f<e;)K(1-this.solve(u))<s?m++:m=0,this.solverDuration=u,u+=i,f++;this.duration=ct(this.solverDuration*p,0)*D.timeScale}get mass(){return this.m}set mass(t){this.m=ht(Xt(t,1),0,ps),this.compute()}get stiffness(){return this.s}set stiffness(t){this.s=ht(Xt(t,100),1,ps),this.compute()}get damping(){return this.d}set damping(t){this.d=ht(Xt(t,10),.1,ps),this.compute()}get velocity(){return this.v}set velocity(t){this.v=ht(Xt(t,0),-1e4,ps),this.compute()}}const fs=t=>new ms(t),gs=t=>{t.cancelable&&t.preventDefault()};class ys{constructor(t){this.el=t,this.zIndex=0,this.parentElement=null,this.classList={add:_,remove:_}}get x(){return this.el.x||0}set x(t){this.el.x=t}get y(){return this.el.y||0}set y(t){this.el.y=t}get width(){return this.el.width||0}set width(t){this.el.width=t}get height(){return this.el.height||0}set height(t){this.el.height=t}getBoundingClientRect(){return{top:this.y,right:this.x,bottom:this.y+this.height,left:this.x+this.width}}}class _s{constructor(t){this.$el=t,this.inlineTransforms=[],this.point=new DOMPoint,this.inversedMatrix=this.getMatrix().inverse()}normalizePoint(t,e){return this.point.x=t,this.point.y=e,this.point.matrixTransform(this.inversedMatrix)}traverseUp(t){let e=this.$el.parentElement,s=0;for(;e&&e!==i;)t(e,s),e=e.parentElement,s++}getMatrix(){const t=new DOMMatrix;return this.traverseUp((e=>{const s=getComputedStyle(e).transform;if(s){const e=new DOMMatrix(s);t.preMultiplySelf(e)}})),t}remove(){this.traverseUp(((t,e)=>{this.inlineTransforms[e]=t.style.transform,t.style.transform="none"}))}revert(){this.traverseUp(((t,e)=>{const s=this.inlineTransforms[e];""===s?t.style.removeProperty("transform"):t.style.transform=s}))}}const vs=(t,e)=>t&&z(t)?t(e):t;let bs=0;class Ts{constructor(t,e={}){if(!t)return;L.current&&L.current.register(this);const r=e.x,n=e.y,o=e.trigger,a=e.modifier,h=e.releaseEase,l=h&&Te(h),c=!Y(h)&&!Y(h.ease),d=R(r)&&!Y(r.mapTo)?r.mapTo:"translateX",p=R(n)&&!Y(n.mapTo)?n.mapTo:"translateY",m=vs(e.container,this);this.containerArray=P(m)?m:null,this.$container=m&&!this.containerArray?Ft(m)[0]:i.body,this.useWin=this.$container===i.body,this.$scrollContainer=this.useWin?s:this.$container,this.$target=R(t)?new ys(t):Ft(t)[0],this.$trigger=Ft(o||t)[0],this.fixed="fixed"===ts(this.$target,"position"),this.isFinePointer=!0,this.containerPadding=[0,0,0,0],this.containerFriction=0,this.releaseContainerFriction=0,this.snapX=0,this.snapY=0,this.scrollSpeed=0,this.scrollThreshold=0,this.dragSpeed=0,this.maxVelocity=0,this.minVelocity=0,this.velocityMultiplier=0,this.cursor=!1,this.releaseXSpring=c?h:fs({mass:Xt(e.releaseMass,1),stiffness:Xt(e.releaseStiffness,80),damping:Xt(e.releaseDamping,20)}),this.releaseYSpring=c?h:fs({mass:Xt(e.releaseMass,1),stiffness:Xt(e.releaseStiffness,80),damping:Xt(e.releaseDamping,20)}),this.releaseEase=l||ve.outQuint,this.hasReleaseSpring=c,this.onGrab=e.onGrab||_,this.onDrag=e.onDrag||_,this.onRelease=e.onRelease||_,this.onUpdate=e.onUpdate||_,this.onSettle=e.onSettle||_,this.onSnap=e.onSnap||_,this.onResize=e.onResize||_,this.onAfterResize=e.onAfterResize||_,this.disabled=[0,0];const f={};if(a&&(f.modifier=a),Y(r)||!0===r)f[d]=0;else if(R(r)){const t=r,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[d]=e}else!1===r&&(f[d]=0,this.disabled[0]=1);if(Y(n)||!0===n)f[p]=0;else if(R(n)){const t=n,e={};t.modifier&&(e.modifier=t.modifier),t.composition&&(e.composition=t.composition),f[p]=e}else!1===n&&(f[p]=0,this.disabled[1]=1);this.animate=new us(this.$target,f),this.xProp=d,this.yProp=p,this.destX=0,this.destY=0,this.deltaX=0,this.deltaY=0,this.scroll={x:0,y:0},this.coords=[this.x,this.y,0,0],this.snapped=[0,0],this.pointer=[0,0,0,0,0,0,0,0],this.scrollView=[0,0],this.dragArea=[0,0,0,0],this.containerBounds=[-1e12,u,u,-1e12],this.scrollBounds=[0,0,0,0],this.targetBounds=[0,0,0,0],this.window=[0,0],this.velocityStack=[0,0,0],this.velocityStackIndex=0,this.velocityTime=O(),this.velocity=0,this.angle=0,this.cursorStyles=null,this.triggerStyles=null,this.bodyStyles=null,this.targetStyles=null,this.touchActionStyles=null,this.transforms=new _s(this.$target),this.overshootCoords={x:0,y:0},this.overshootTicker=new oe({autoplay:!1,onUpdate:()=>{this.updated=!0,this.manual=!0,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,1),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,1)},onComplete:()=>{this.manual=!1,this.disabled[0]||this.animate[this.xProp](this.overshootCoords.x,0),this.disabled[1]||this.animate[this.yProp](this.overshootCoords.y,0)}},null,0).init(),this.updateTicker=new oe({autoplay:!1,onUpdate:()=>this.update()},null,0).init(),this.contained=!Y(m),this.manual=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.enabled=!1,this.initialized=!1,this.activeProp=this.disabled[1]?d:p,this.animate.callbacks.onRender=()=>{const t=this.updated,e=!(this.grabbed&&t)&&this.released,s=this.x,i=this.y,r=s-this.coords[2],n=i-this.coords[3];this.deltaX=r,this.deltaY=n,this.coords[2]=s,this.coords[3]=i,t&&(r||n)&&this.onUpdate(this),e?(this.computeVelocity(r,n),this.angle=nt(n,r)):this.updated=!1},this.animate.callbacks.onComplete=()=>{!this.grabbed&&this.released&&(this.released=!1),this.manual||(this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.onSettle(this))},this.resizeTicker=new oe({autoplay:!1,duration:150*D.timeScale,onComplete:()=>{this.onResize(this),this.refresh(),this.onAfterResize(this)}}).init(),this.parameters=e,this.resizeObserver=new ResizeObserver((()=>{this.initialized?this.resizeTicker.restart():this.initialized=!0})),this.enable(),this.refresh(),this.resizeObserver.observe(this.$container),R(t)||this.resizeObserver.observe(this.$target)}computeVelocity(t,e){const s=this.velocityTime,i=O(),r=i-s;if(r<17)return this.velocity;this.velocityTime=i;const n=this.velocityStack,o=this.velocityMultiplier,a=this.minVelocity,h=this.maxVelocity,l=this.velocityStackIndex;n[l]=ct(ht(G(t*t+e*e)/r*o,a,h),5);const c=rt(n[0],n[1],n[2]);return this.velocity=c,this.velocityStackIndex=(l+1)%3,c}setX(t,e=!1){if(this.disabled[0])return;const s=ct(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destX=s,this.snapped[0]=dt(s,this.snapX),this.animate[this.xProp](s,0),this.manual=!1,this}setY(t,e=!1){if(this.disabled[1])return;const s=ct(t,5);return this.overshootTicker.pause(),this.manual=!0,this.updated=!e,this.destY=s,this.snapped[1]=dt(s,this.snapY),this.animate[this.yProp](s,0),this.manual=!1,this}get x(){return ct(this.animate[this.xProp](),D.precision)}set x(t){this.setX(t,!1)}get y(){return ct(this.animate[this.yProp](),D.precision)}set y(t){this.setY(t,!1)}get progressX(){return rs(this.x,this.containerBounds[3],this.containerBounds[1],0,1)}set progressX(t){this.setX(rs(t,0,1,this.containerBounds[3],this.containerBounds[1]),!1)}get progressY(){return rs(this.y,this.containerBounds[0],this.containerBounds[2],0,1)}set progressY(t){this.setY(rs(t,0,1,this.containerBounds[0],this.containerBounds[2]),!1)}updateScrollCoords(){const t=ct(this.useWin?s.scrollX:this.$container.scrollLeft,0),e=ct(this.useWin?s.scrollY:this.$container.scrollTop,0),[i,r,n,o]=this.containerPadding,a=this.scrollThreshold;this.scroll.x=t,this.scroll.y=e,this.scrollBounds[0]=e-this.targetBounds[0]+i-a,this.scrollBounds[1]=t-this.targetBounds[1]-r+a,this.scrollBounds[2]=e-this.targetBounds[2]-n+a,this.scrollBounds[3]=t-this.targetBounds[3]+o-a}updateBoundingValues(){const t=this.$container;if(!t)return;const e=this.x,r=this.y,n=this.coords[2],o=this.coords[3];this.coords[2]=0,this.coords[3]=0,this.setX(0,!0),this.setY(0,!0),this.transforms.remove();const a=this.window[0]=s.innerWidth,h=this.window[1]=s.innerHeight,l=this.useWin,c=t.scrollWidth,d=t.scrollHeight,u=this.fixed,p=t.getBoundingClientRect(),[m,f,g,y]=this.containerPadding;this.dragArea[0]=l?0:p.left,this.dragArea[1]=l?0:p.top,this.scrollView[0]=l?ht(c,a,c):c,this.scrollView[1]=l?ht(d,h,d):d,this.updateScrollCoords();const{width:_,height:v,left:b,top:T,right:w,bottom:x}=t.getBoundingClientRect();this.dragArea[2]=ct(l?ht(_,a,a):_,0),this.dragArea[3]=ct(l?ht(v,h,h):v,0);const S=ts(t,"overflow"),k="visible"===S,$="hidden"===S;if(this.canScroll=!u&&this.contained&&(t===i.body&&k||!$&&!k)&&(c>this.dragArea[2]+y-f||d>this.dragArea[3]+m-g)&&(!this.containerArray||this.containerArray&&!P(this.containerArray)),this.contained){const e=this.scroll.x,s=this.scroll.y,i=this.canScroll,r=this.$target.getBoundingClientRect(),n=i?l?0:t.scrollLeft:0,o=i?l?0:t.scrollTop:0,c=i?this.scrollView[0]-n-_:0,d=i?this.scrollView[1]-o-v:0;this.targetBounds[0]=ct(r.top+s-(l?0:T),0),this.targetBounds[1]=ct(r.right+e-(l?a:w),0),this.targetBounds[2]=ct(r.bottom+s-(l?h:x),0),this.targetBounds[3]=ct(r.left+e-(l?0:b),0),this.containerArray?(this.containerBounds[0]=this.containerArray[0]+m,this.containerBounds[1]=this.containerArray[1]-f,this.containerBounds[2]=this.containerArray[2]-g,this.containerBounds[3]=this.containerArray[3]+y):(this.containerBounds[0]=-ct(r.top-(u?ht(T,0,h):T)+o-m,0),this.containerBounds[1]=-ct(r.right-(u?ht(w,0,a):w)-c+f,0),this.containerBounds[2]=-ct(r.bottom-(u?ht(x,0,h):x)-d+g,0),this.containerBounds[3]=-ct(r.left-(u?ht(b,0,a):b)+n-y,0))}this.transforms.revert(),this.coords[2]=n,this.coords[3]=o,this.setX(e,!0),this.setY(r,!0)}isOutOfBounds(t,e,s){if(!this.contained)return 0;const[i,r,n,o]=t,[a,h]=this.disabled,l=!a&&e<o||!a&&e>r,c=!h&&s<i||!h&&s>n;return l&&!c?1:!l&&c?2:l&&c?3:0}refresh(){const t=this.parameters,e=t.x,r=t.y,n=vs(t.container,this),o=vs(t.containerPadding,this)||0,a=P(o)?o:[o,o,o,o],h=this.x,l=this.y,c=vs(t.cursor,this),d={onHover:"grab",onGrab:"grabbing"};if(c){const{onHover:t,onGrab:e}=c;t&&(d.onHover=t),e&&(d.onGrab=e)}this.containerArray=P(n)?n:null,this.$container=n&&!this.containerArray?Ft(n)[0]:i.body,this.useWin=this.$container===i.body,this.$scrollContainer=this.useWin?s:this.$container,this.isFinePointer=matchMedia("(pointer:fine)").matches,this.containerPadding=Xt(a,[0,0,0,0]),this.containerFriction=ht(Xt(vs(t.containerFriction,this),.8),0,1),this.releaseContainerFriction=ht(Xt(vs(t.releaseContainerFriction,this),this.containerFriction),0,1),this.snapX=vs(R(e)&&!Y(e.snap)?e.snap:t.snap,this),this.snapY=vs(R(r)&&!Y(r.snap)?r.snap:t.snap,this),this.scrollSpeed=Xt(vs(t.scrollSpeed,this),1.5),this.scrollThreshold=Xt(vs(t.scrollThreshold,this),20),this.dragSpeed=Xt(vs(t.dragSpeed,this),1),this.minVelocity=Xt(vs(t.minVelocity,this),0),this.maxVelocity=Xt(vs(t.maxVelocity,this),50),this.velocityMultiplier=Xt(vs(t.velocityMultiplier,this),1),this.cursor=!1!==c&&d,this.updateBoundingValues();const[u,p,m,f]=this.containerBounds;this.setX(ht(h,f,p),!0),this.setY(ht(l,u,m),!0)}update(){if(this.updateScrollCoords(),this.canScroll){const[t,e,s,i]=this.containerPadding,[r,n]=this.scrollView,o=this.dragArea[2],a=this.dragArea[3],h=this.scroll.x,l=this.scroll.y,c=this.$container.scrollWidth,d=this.$container.scrollHeight,u=this.useWin?ht(c,this.window[0],c):c,p=this.useWin?ht(d,this.window[1],d):d,m=r-u,f=n-p;this.dragged&&m>0&&(this.coords[0]-=m,this.scrollView[0]=u),this.dragged&&f>0&&(this.coords[1]-=f,this.scrollView[1]=p);const g=10*this.scrollSpeed,y=this.scrollThreshold,[_,v]=this.coords,[b,T,w,x]=this.scrollBounds,S=ct(ht((v-b+t)/y,-1,0)*g,0),k=ct(ht((_-T-e)/y,0,1)*g,0),$=ct(ht((v-w-s)/y,0,1)*g,0),C=ct(ht((_-x+i)/y,-1,0)*g,0);if(S||$||C||k){const[t,e]=this.disabled;let s=h,i=l;t||(s=ct(ht(h+(C||k),0,r-o),0),this.coords[0]-=h-s),e||(i=ct(ht(l+(S||$),0,n-a),0),this.coords[1]-=l-i),this.useWin?this.$scrollContainer.scrollBy(-(h-s),-(l-i)):this.$scrollContainer.scrollTo(s,i)}}const[t,e,s,i]=this.containerBounds,[r,n,o,a,h,l]=this.pointer;this.coords[0]+=(r-h)*this.dragSpeed,this.coords[1]+=(n-l)*this.dragSpeed,this.pointer[4]=r,this.pointer[5]=n;const[c,d]=this.coords,[u,p]=this.snapped,m=(1-this.containerFriction)*this.dragSpeed;this.setX(c>e?e+(c-e)*m:c<i?i+(c-i)*m:c,!1),this.setY(d>s?s+(d-s)*m:d<t?t+(d-t)*m:d,!1),this.computeVelocity(r-h,n-l),this.angle=nt(n-a,r-o);const[f,g]=this.snapped;(f!==u&&this.snapX||g!==p&&this.snapY)&&this.onSnap(this)}stop(){this.updateTicker.pause(),this.overshootTicker.pause();for(let t in this.animate.animations)this.animate.animations[t].pause();return is(this,null,"x"),is(this,null,"y"),is(this,null,"progressX"),is(this,null,"progressY"),is(this.scroll),is(this.overshootCoords),this}scrollInView(t,e=0,s=ve.inOutQuad){this.updateScrollCoords();const i=this.destX,r=this.destY,n=this.scroll,o=this.scrollBounds,a=this.canScroll;if(!this.containerArray&&this.isOutOfBounds(o,i,r)){const[h,l,c,d]=o,p=ct(ht(r-h,-1e12,0),0),m=ct(ht(i-l,0,u),0),f=ct(ht(r-c,0,u),0),g=ct(ht(i-d,-1e12,0),0);new Re(n,{x:ct(n.x+(g?g-e:m?m+e:0),0),y:ct(n.y+(p?p-e:f?f+e:0),0),duration:Y(t)?350*D.timeScale:t,ease:s,onUpdate:()=>{this.canScroll=!1,this.$scrollContainer.scrollTo(n.x,n.y)}}).init().then((()=>{this.canScroll=a}))}return this}handleHover(){this.isFinePointer&&this.cursor&&!this.cursorStyles&&(this.cursorStyles=es(this.$trigger,{cursor:this.cursor.onHover}))}animateInView(t,e=0,s=ve.inOutQuad){this.stop(),this.updateBoundingValues();const i=this.x,r=this.y,[n,o,a,h]=this.containerPadding,l=this.scroll.y-this.targetBounds[0]+n+e,c=this.scroll.x-this.targetBounds[1]-o-e,d=this.scroll.y-this.targetBounds[2]-a-e,u=this.scroll.x-this.targetBounds[3]+h+e,p=this.isOutOfBounds([l,c,d,u],i,r);if(p){const[e,n]=this.disabled,o=ht(dt(i,this.snapX),u,c),a=ht(dt(r,this.snapY),l,d),h=Y(t)?350*D.timeScale:t;e||1!==p&&3!==p||this.animate[this.xProp](o,h,s),n||2!==p&&3!==p||this.animate[this.yProp](a,h,s)}return this}handleDown(t){const e=t.target;if(this.grabbed||"range"===e.type)return;t.stopPropagation(),this.grabbed=!0,this.released=!1,this.stop(),this.updateBoundingValues();const s=t.changedTouches,r=s?s[0].clientX:t.clientX,n=s?s[0].clientY:t.clientY,{x:o,y:a}=this.transforms.normalizePoint(r,n),[h,l,c,d]=this.containerBounds,u=(1-this.containerFriction)*this.dragSpeed,p=this.x,m=this.y;this.coords[0]=this.coords[2]=u?p>l?l+(p-l)/u:p<d?d+(p-d)/u:p:p,this.coords[1]=this.coords[3]=u?m>c?c+(m-c)/u:m<h?h+(m-h)/u:m:m,this.pointer[0]=o,this.pointer[1]=a,this.pointer[2]=o,this.pointer[3]=a,this.pointer[4]=o,this.pointer[5]=a,this.pointer[6]=o,this.pointer[7]=a,this.deltaX=0,this.deltaY=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null);const f=ts(this.$target,"zIndex",!1);bs=(f>bs?f:bs)+1,this.targetStyles=es(this.$target,{zIndex:bs}),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.isFinePointer&&this.cursor&&(this.bodyStyles=es(i.body,{cursor:this.cursor.onGrab})),this.scrollInView(100,0,ve.out(3)),this.onGrab(this),i.addEventListener("touchmove",this),i.addEventListener("touchend",this),i.addEventListener("touchcancel",this),i.addEventListener("mousemove",this),i.addEventListener("mouseup",this),i.addEventListener("selectstart",this)}handleMove(t){if(!this.grabbed)return;const e=t.changedTouches,s=e?e[0].clientX:t.clientX,i=e?e[0].clientY:t.clientY,{x:r,y:n}=this.transforms.normalizePoint(s,i),o=r-this.pointer[6],a=n-this.pointer[7];let h=t.target,l=!1,c=!1,d=!1;for(;e&&h&&h!==this.$trigger;){const t=ts(h,"overflow-y");if("hidden"!==t&&"visible"!==t){const{scrollTop:t,scrollHeight:e,clientHeight:s}=h;if(e>s){d=!0,l=t<=3,c=t>=e-s-3;break}}h=h.parentNode}d&&(!l&&!c||l&&a<0||c&&a>0)?(this.pointer[0]=r,this.pointer[1]=n,this.pointer[2]=r,this.pointer[3]=n,this.pointer[4]=r,this.pointer[5]=n,this.pointer[6]=r,this.pointer[7]=n):(gs(t),this.triggerStyles||(this.triggerStyles=es(this.$trigger,{pointerEvents:"none"})),this.$trigger.addEventListener("touchstart",gs,{passive:!1}),this.$trigger.addEventListener("touchmove",gs,{passive:!1}),this.$trigger.addEventListener("touchend",gs),(!this.disabled[0]&&K(o)>3||!this.disabled[1]&&K(a)>3)&&(this.updateTicker.resume(),this.pointer[2]=this.pointer[0],this.pointer[3]=this.pointer[1],this.pointer[0]=r,this.pointer[1]=n,this.dragged=!0,this.released=!1,this.onDrag(this)))}handleUp(){if(!this.grabbed)return;this.updateTicker.pause(),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null);const[t,e]=this.disabled,[s,n,o,a,h,l]=this.pointer,[c,d,u,p]=this.containerBounds,[m,f]=this.snapped,g=this.releaseXSpring,y=this.releaseYSpring,_=this.releaseEase,v=this.hasReleaseSpring,b=this.overshootCoords,T=this.x,w=this.y,x=this.computeVelocity(s-h,n-l),S=this.angle=nt(n-a,s-o),k=150*x,$=(1-this.releaseContainerFriction)*this.dragSpeed,C=T+J(S)*k,E=w+Z(S)*k,B=C>d?d+(C-d)*$:C<p?p+(C-p)*$:C,L=E>u?u+(E-u)*$:E<c?c+(E-c)*$:E,A=this.destX=ht(ct(dt(B,this.snapX),5),p,d),N=this.destY=ht(ct(dt(L,this.snapY),5),c,u),F=this.isOutOfBounds(this.containerBounds,C,E);let O=0,P=0,R=_,M=_,I=0;if(b.x=T,b.y=w,!t){const t=A===d?T>d?-1:1:T<p?-1:1,s=ct(T-A,0);g.velocity=e&&v?s?k*t/K(s):0:x;const{ease:i,duration:r,restDuration:n}=g;O=T===A?0:v?r:r-n*D.timeScale,v&&(R=i),O>I&&(I=O)}if(!e){const e=N===u?w>u?-1:1:w<c?-1:1,s=ct(w-N,0);y.velocity=t&&v?s?k*e/K(s):0:x;const{ease:i,duration:r,restDuration:n}=y;P=w===N?0:v?r:r-n*D.timeScale,v&&(M=i),P>I&&(I=P)}if(!v&&F&&$&&(O||P)){const t=r.blend;new Re(b,{x:{to:B,duration:.65*O},y:{to:L,duration:.65*P},ease:_,composition:t}).init(),new Re(b,{x:{to:A,duration:O},y:{to:N,duration:P},ease:_,composition:t}).init(),this.overshootTicker.stretch(rt(O,P)).restart()}else t||this.animate[this.xProp](A,O,R),e||this.animate[this.yProp](N,P,M);this.scrollInView(I,this.scrollThreshold,_);let z=!1;A!==m&&(this.snapped[0]=A,this.snapX&&(z=!0)),N!==f&&this.snapY&&(this.snapped[1]=N,this.snapY&&(z=!0)),z&&this.onSnap(this),this.grabbed=!1,this.dragged=!1,this.updated=!0,this.released=!0,this.onRelease(this),this.$trigger.removeEventListener("touchstart",gs),this.$trigger.removeEventListener("touchmove",gs),this.$trigger.removeEventListener("touchend",gs),i.removeEventListener("touchmove",this),i.removeEventListener("touchend",this),i.removeEventListener("touchcancel",this),i.removeEventListener("mousemove",this),i.removeEventListener("mouseup",this),i.removeEventListener("selectstart",this)}reset(){return this.stop(),this.resizeTicker.pause(),this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.setX(0,!0),this.setY(0,!0),this.coords[0]=0,this.coords[1]=0,this.pointer[0]=0,this.pointer[1]=0,this.pointer[2]=0,this.pointer[3]=0,this.pointer[4]=0,this.pointer[5]=0,this.pointer[6]=0,this.pointer[7]=0,this.velocity=0,this.velocityStack[0]=0,this.velocityStack[1]=0,this.velocityStack[2]=0,this.velocityStackIndex=0,this.angle=0,this}enable(){return this.enabled||(this.enabled=!0,this.$target.classList.remove("is-disabled"),this.touchActionStyles=es(this.$trigger,{touchAction:this.disabled[0]?"pan-x":this.disabled[1]?"pan-y":"none"}),this.$trigger.addEventListener("touchstart",this,{passive:!0}),this.$trigger.addEventListener("mousedown",this,{passive:!0}),this.$trigger.addEventListener("mouseenter",this)),this}disable(){return this.enabled=!1,this.grabbed=!1,this.dragged=!1,this.updated=!1,this.released=!1,this.canScroll=!1,this.touchActionStyles.revert(),this.cursorStyles&&(this.cursorStyles.revert(),this.cursorStyles=null),this.triggerStyles&&(this.triggerStyles.revert(),this.triggerStyles=null),this.bodyStyles&&(this.bodyStyles.revert(),this.bodyStyles=null),this.targetStyles&&(this.targetStyles.revert(),this.targetStyles=null),this.$target.classList.add("is-disabled"),this.$trigger.removeEventListener("touchstart",this),this.$trigger.removeEventListener("mousedown",this),this.$trigger.removeEventListener("mouseenter",this),i.removeEventListener("touchmove",this),i.removeEventListener("touchend",this),i.removeEventListener("touchcancel",this),i.removeEventListener("mousemove",this),i.removeEventListener("mouseup",this),i.removeEventListener("selectstart",this),this}revert(){return this.reset(),this.disable(),this.$target.classList.remove("is-disabled"),this.updateTicker.revert(),this.overshootTicker.revert(),this.resizeTicker.revert(),this.animate.revert(),this.resizeObserver.disconnect(),this}handleEvent(t){switch(t.type){case"mousedown":case"touchstart":this.handleDown(t);break;case"mousemove":case"touchmove":this.handleMove(t);break;case"mouseup":case"touchend":case"touchcancel":this.handleUp();break;case"mouseenter":this.handleHover();break;case"selectstart":gs(t)}}}class ws{constructor(t={}){L.current&&L.current.register(this);const e=t.root;let r=i;e&&(r=e.current||e.nativeElement||Ft(e)[0]||i);const n=t.defaults,o=D.defaults,a=t.mediaQueries;if(this.defaults=n?_t(n,o):o,this.root=r,this.constructors=[],this.revertConstructors=[],this.revertibles=[],this.constructorsOnce=[],this.revertConstructorsOnce=[],this.revertiblesOnce=[],this.once=!1,this.onceIndex=0,this.methods={},this.matches={},this.mediaQueryLists={},this.data={},a)for(let t in a){const e=s.matchMedia(a[t]);this.mediaQueryLists[t]=e,e.addEventListener("change",this)}}register(t){(this.once?this.revertiblesOnce:this.revertibles).push(t)}execute(t){let e=L.current,s=L.root,i=D.defaults;L.current=this,L.root=this.root,D.defaults=this.defaults;const r=this.mediaQueryLists;for(let t in r)this.matches[t]=r[t].matches;const n=t(this);return L.current=e,L.root=s,D.defaults=i,n}refresh(){return this.onceIndex=0,this.execute((()=>{let t=this.revertibles.length,e=this.revertConstructors.length;for(;t--;)this.revertibles[t].revert();for(;e--;)this.revertConstructors[e](this);this.revertibles.length=0,this.revertConstructors.length=0,this.constructors.forEach((t=>{const e=t(this);z(e)&&this.revertConstructors.push(e)}))})),this}add(t,e){if(this.once=!1,z(t)){const e=t;this.constructors.push(e),this.execute((()=>{const t=e(this);z(t)&&this.revertConstructors.push(t)}))}else this.methods[t]=(...t)=>this.execute((()=>e(...t)));return this}addOnce(t){if(this.once=!0,z(t)){const e=this.onceIndex++;if(this.constructorsOnce[e])return this;const s=t;this.constructorsOnce[e]=s,this.execute((()=>{const t=s(this);z(t)&&this.revertConstructorsOnce.push(t)}))}return this}keepTime(t){this.once=!0;const e=this.onceIndex++,s=this.constructorsOnce[e];if(z(s))return s(this);const i=wt(t);let r;return this.constructorsOnce[e]=i,this.execute((()=>{r=i(this)})),r}handleEvent(t){"change"===t.type&&this.refresh()}revert(){const t=this.revertibles,e=this.revertConstructors,s=this.revertiblesOnce,i=this.revertConstructorsOnce,r=this.mediaQueryLists;let n=t.length,o=e.length,a=s.length,h=i.length;for(;n--;)t[n].revert();for(;o--;)e[o](this);for(;a--;)s[a].revert();for(;h--;)i[h](this);for(let t in r)r[t].removeEventListener("change",this);t.length=0,e.length=0,this.constructors.length=0,s.length=0,i.length=0,this.constructorsOnce.length=0,this.onceIndex=0,this.matches={},this.methods={},this.mediaQueryLists={},this.data={}}}const xs=(t,e)=>t&&z(t)?t(e):t,Ss=new Map;class ks{constructor(t){this.element=t,this.useWin=this.element===i.body,this.winWidth=0,this.winHeight=0,this.width=0,this.height=0,this.left=0,this.top=0,this.zIndex=0,this.scrollX=0,this.scrollY=0,this.prevScrollX=0,this.prevScrollY=0,this.scrollWidth=0,this.scrollHeight=0,this.velocity=0,this.backwardX=!1,this.backwardY=!1,this.scrollTicker=new oe({autoplay:!1,onBegin:()=>this.dataTimer.resume(),onUpdate:()=>{const t=this.backwardX||this.backwardY;vt(this,(t=>t.handleScroll()),t)},onComplete:()=>this.dataTimer.pause()}).init(),this.dataTimer=new oe({autoplay:!1,frameRate:30,onUpdate:t=>{const e=t.deltaTime,s=this.prevScrollX,i=this.prevScrollY,r=this.scrollX,n=this.scrollY,o=s-r,a=i-n;this.prevScrollX=r,this.prevScrollY=n,o&&(this.backwardX=s>r),a&&(this.backwardY=i>n),this.velocity=ct(e>0?Math.sqrt(o*o+a*a)/e:0,5)}}).init(),this.resizeTicker=new oe({autoplay:!1,duration:250*D.timeScale,onComplete:()=>{this.updateWindowBounds(),this.refreshScrollObservers(),this.handleScroll()}}).init(),this.wakeTicker=new oe({autoplay:!1,duration:500*D.timeScale,onBegin:()=>{this.scrollTicker.resume()},onComplete:()=>{this.scrollTicker.pause()}}).init(),this._head=null,this._tail=null,this.updateScrollCoords(),this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll(),this.resizeObserver=new ResizeObserver((()=>this.resizeTicker.restart())),this.resizeObserver.observe(this.element),(this.useWin?s:this.element).addEventListener("scroll",this,!1)}updateScrollCoords(){const t=this.useWin,e=this.element;this.scrollX=ct(t?s.scrollX:e.scrollLeft,0),this.scrollY=ct(t?s.scrollY:e.scrollTop,0)}updateWindowBounds(){this.winWidth=s.innerWidth,this.winHeight=(()=>{const t=i.createElement("div");i.body.appendChild(t),t.style.height="100lvh";const e=t.offsetHeight;return i.body.removeChild(t),e})()}updateBounds(){const t=getComputedStyle(this.element),e=this.element;let s,i;if(this.scrollWidth=e.scrollWidth+parseFloat(t.marginLeft)+parseFloat(t.marginRight),this.scrollHeight=e.scrollHeight+parseFloat(t.marginTop)+parseFloat(t.marginBottom),this.updateWindowBounds(),this.useWin)s=this.winWidth,i=this.winHeight;else{const t=e.getBoundingClientRect();s=e.clientWidth,i=e.clientHeight,this.top=t.top,this.left=t.left}this.width=s,this.height=i}refreshScrollObservers(){vt(this,(t=>{t._debug&&t.removeDebug()})),this.updateBounds(),vt(this,(t=>{t.refresh(),t._debug&&t.debug()}))}refresh(){this.updateWindowBounds(),this.updateBounds(),this.refreshScrollObservers(),this.handleScroll()}handleScroll(){this.updateScrollCoords(),this.wakeTicker.restart()}handleEvent(t){"scroll"===t.type&&this.handleScroll()}revert(){this.scrollTicker.cancel(),this.dataTimer.cancel(),this.resizeTicker.cancel(),this.wakeTicker.cancel(),this.resizeObserver.disconnect(),(this.useWin?s:this.element).removeEventListener("scroll",this),Ss.delete(this.element)}}const $s=(t,e,s,i,r)=>{const n="min"===e,o="max"===e,a="top"===e||"left"===e||"start"===e||n?0:"bottom"===e||"right"===e||"end"===e||o?"100%":"center"===e?"50%":e,{n:h,u:l}=Qt(a,Gt);let c=h;return"%"===l?c=h/100*s:l&&(c=$e(t,Gt,"px",!0).n),o&&i<0&&(c+=i),n&&r>0&&(c+=r),c},Cs=(t,e,s,i,r)=>{let n;if(I(e)){const o=E.exec(e);if(o){const a=o[0],h=a[0],l=e.split(a),c="min"===l[0],d="max"===l[0],u=$s(t,l[0],s,i,r),p=$s(t,l[1],s,i,r);if(c){const e=qt($s(t,"min",s),p,h);n=e<u?u:e}else if(d){const e=qt($s(t,"max",s),p,h);n=e>u?u:e}else n=qt(u,p,h)}else n=$s(t,e,s,i,r)}else n=e;return ct(n,0)},Es=t=>{let e;const s=t.targets;for(let t=0,i=s.length;t<i;t++){const i=s[t];if(i[o]){e=i;break}}return e};let Bs=0;const Ls=["#FF4B4B","#FF971B","#FFC730","#F9F640","#7AFF5A","#18FF74","#17E09B","#3CFFEC","#05DBE9","#33B3F1","#638CF9","#C563FE","#FF4FCF","#F93F8A"];class Ds{constructor(t={}){L.current&&L.current.register(this);const e=Xt(t.sync,"play pause"),s=e?Te(e):null,r=e&&("linear"===e||e===ae),n=e&&!(s===ae&&!r),o=e&&(M(e)||!0===e||r),a=e&&I(e)&&!n&&!o,h=a?e.split(" ").map((t=>()=>{const e=this.linked;return e&&e[t]?e[t]():null})):null,l=a&&h.length>2;this.index=Bs++,this.id=Y(t.id)?this.index:t.id,this.container=(t=>{const e=t&&Ft(t)[0]||i.body;let s=Ss.get(e);return s||(s=new ks(e),Ss.set(e,s)),s})(t.container),this.target=null,this.linked=null,this.repeat=null,this.horizontal=null,this.enter=null,this.leave=null,this.sync=n||o||!!h,this.syncEase=n?s:null,this.syncSmooth=o?!0===e||r?1:e:null,this.onSyncEnter=h&&!l&&h[0]?h[0]:_,this.onSyncLeave=h&&!l&&h[1]?h[1]:_,this.onSyncEnterForward=h&&l&&h[0]?h[0]:_,this.onSyncLeaveForward=h&&l&&h[1]?h[1]:_,this.onSyncEnterBackward=h&&l&&h[2]?h[2]:_,this.onSyncLeaveBackward=h&&l&&h[3]?h[3]:_,this.onEnter=t.onEnter||_,this.onLeave=t.onLeave||_,this.onEnterForward=t.onEnterForward||_,this.onLeaveForward=t.onLeaveForward||_,this.onEnterBackward=t.onEnterBackward||_,this.onLeaveBackward=t.onLeaveBackward||_,this.onUpdate=t.onUpdate||_,this.onSyncComplete=t.onSyncComplete||_,this.reverted=!1,this.completed=!1,this.began=!1,this.isInView=!1,this.forceEnter=!1,this.hasEntered=!1,this.offset=0,this.offsetStart=0,this.offsetEnd=0,this.distance=0,this.prevProgress=0,this.thresholds=["start","end","end","start"],this.coords=[0,0,0,0],this.debugStyles=null,this.$debug=null,this._params=t,this._debug=Xt(t.debug,!1),this._next=null,this._prev=null,Tt(this.container,this),Ke((()=>{if(!this.reverted){if(!this.target){const e=Ft(t.target)[0];this.target=e||i.body,this.refresh()}this._debug&&this.debug()}}))}link(t){if(t&&(t.pause(),this.linked=t,!this._params.target)){let e;Y(t.targets)?vt(t,(t=>{t.targets&&!e&&(e=Es(t))})):e=Es(t),this.target=e||i.body,this.refresh()}return this}get velocity(){return this.container.velocity}get backward(){return this.horizontal?this.container.backwardX:this.container.backwardY}get scroll(){return this.horizontal?this.container.scrollX:this.container.scrollY}get progress(){const t=(this.scroll-this.offsetStart)/this.distance;return t===1/0||isNaN(t)?0:ct(ht(t,0,1),6)}refresh(){this.reverted=!1;const t=this._params;return this.repeat=Xt(xs(t.repeat,this),!0),this.horizontal="x"===Xt(xs(t.axis,this),"y"),this.enter=Xt(xs(t.enter,this),"end start"),this.leave=Xt(xs(t.leave,this),"start end"),this.updateBounds(),this.handleScroll(),this}removeDebug(){return this.$debug&&(this.$debug.parentNode.removeChild(this.$debug),this.$debug=null),this.debugStyles&&(this.debugStyles.revert(),this.$debug=null),this}debug(){this.removeDebug();const t=this.container,e=this.horizontal,s=t.element.querySelector(":scope > .animejs-onscroll-debug"),r=i.createElement("div"),n=i.createElement("div"),o=i.createElement("div"),a=Ls[this.index%Ls.length],h=t.useWin,l=h?t.winWidth:t.width,c=h?t.winHeight:t.height,d=t.scrollWidth,u=t.scrollHeight,p=this.container.width>360?320:260,m=e?0:10,f=e?10:0,g=e?24:p/2,y=e?g:15,_=e?60:g,v=e?_:y,b=e?"repeat-x":"repeat-y",T=t=>e?"0px "+t+"px":t+"px 2px",w=t=>`linear-gradient(${e?90:0}deg, ${t} 2px, transparent 1px)`,x=(t,e,s,i,r)=>`position:${t};left:${e}px;top:${s}px;width:${i}px;height:${r}px;`;r.style.cssText=`${x("absolute",m,f,e?d:p,e?p:u)}\n pointer-events: none;\n z-index: ${this.container.zIndex++};\n display: flex;\n flex-direction: ${e?"column":"row"};\n filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75));\n `,n.style.cssText=`${x("sticky",0,0,e?l:g,e?g:c)}`,s||(n.style.cssText+=`background:\n ${w("#FFFF")}${T(g-10)} / 100px 100px ${b},\n ${w("#FFF8")}${T(g-10)} / 10px 10px ${b};\n `),o.style.cssText=`${x("relative",0,0,e?d:g,e?g:u)}`,s||(o.style.cssText+=`background:\n ${w("#FFFF")}${T(0)} / ${e?"100px 10px":"10px 100px"} ${b},\n ${w("#FFF8")}${T(0)} / ${e?"10px 0px":"0px 10px"} ${b};\n `);const S=[" enter: "," leave: "];this.coords.forEach(((t,s)=>{const r=s>1,h=(r?0:this.offset)+t,m=s%2,f=h<v,g=h>(r?e?l:c:e?d:u)-v,b=(r?m&&!f:!m&&!f)||g,T=i.createElement("div"),w=i.createElement("div"),k=e?b?"right":"left":b?"bottom":"top",$=b?(e?_:y)+(r?e?-1:g?0:-2:e?-1:-2):e?1:0;w.innerHTML=`${this.id}${S[m]}${this.thresholds[s]}`,T.style.cssText=`${x("absolute",0,0,_,y)}\n display: flex;\n flex-direction: ${e?"column":"row"};\n justify-content: flex-${r?"start":"end"};\n align-items: flex-${b?"end":"start"};\n border-${k}: 2px solid ${a};\n `,w.style.cssText=`\n overflow: hidden;\n max-width: ${p/2-10}px;\n height: ${y};\n margin-${e?b?"right":"left":b?"bottom":"top"}: -2px;\n padding: 1px;\n font-family: ui-monospace, monospace;\n font-size: 10px;\n letter-spacing: -.025em;\n line-height: 9px;\n font-weight: 600;\n text-align: ${e&&b||!e&&!r?"right":"left"};\n white-space: pre;\n text-overflow: ellipsis;\n color: ${m?a:"rgba(0,0,0,.75)"};\n background-color: ${m?"rgba(0,0,0,.65)":a};\n border: 2px solid ${m?a:"transparent"};\n border-${e?b?"top-left":"top-right":b?"top-left":"bottom-left"}-radius: 5px;\n border-${e?b?"bottom-left":"bottom-right":b?"top-right":"bottom-right"}-radius: 5px;\n `,T.appendChild(w);let C=h-$+(e?1:0);T.style[e?"left":"top"]=`${C}px`,(r?n:o).appendChild(T)})),r.appendChild(n),r.appendChild(o),t.element.appendChild(r),s||r.classList.add("animejs-onscroll-debug"),this.$debug=r,"static"===ts(t.element,"position")&&(this.debugStyles=es(t.element,{position:"relative "}))}updateBounds(){let t;this._debug&&this.removeDebug();const e=this.target,s=this.container,r=this.horizontal,n=this.linked;let o,a=e;for(n&&(o=n.currentTime,n.seek(0,!0)),a.parentElement;a&&a!==s.element&&a!==i.body;){const e="sticky"===ts(a,"position")&&es(a,{position:"static"});a=a.parentElement,e&&(t||(t=[]),t.push(e))}const h=e.getBoundingClientRect(),l=r?h.left+s.scrollX-s.left:h.top+s.scrollY-s.top,c=r?h.width:h.height,d=r?s.width:s.height,u=(r?s.scrollWidth:s.scrollHeight)-d,p=this.enter,m=this.leave;let f="start",g="end",y="end",_="start";if(I(p)){const t=p.split(" ");y=t[0],f=t.length>1?t[1]:f}else if(R(p)){const t=p;Y(t.container)||(y=t.container),Y(t.target)||(f=t.target)}else M(p)&&(y=p);if(I(m)){const t=m.split(" ");_=t[0],g=t.length>1?t[1]:g}else if(R(m)){const t=m;Y(t.container)||(_=t.container),Y(t.target)||(g=t.target)}else M(m)&&(_=m);const v=Cs(e,f,c),b=Cs(e,g,c),T=v+l-d,w=b+l-u,x=Cs(e,y,d,T,w),S=Cs(e,_,d,T,w),k=v+l-x,$=b+l-S,C=$-k;this.offset=l,this.offsetStart=k,this.offsetEnd=$,this.distance=C<=0?0:C,this.thresholds=[f,g,y,_],this.coords=[v,b,x,S],t&&t.forEach((t=>t.revert())),n&&n.seek(o,!0),this._debug&&this.debug()}handleScroll(){const t=this.linked,e=this.sync,s=this.syncEase,i=this.syncSmooth,r=t&&(s||i),n=this.horizontal,o=this.container,a=this.scroll,h=a<=this.offsetStart,l=a>=this.offsetEnd,c=!h&&!l,d=a===this.offsetStart||a===this.offsetEnd,u=!this.hasEntered&&d,p=this._debug&&this.$debug;let m=!1,f=!1,g=this.progress;if(h&&this.began&&(this.began=!1),g>0&&!this.began&&(this.began=!0),r){const e=t.progress;if(i&&M(i)){if(i<1){const t=e<g&&1===g?1e-4:e>g&&!g?-1e-4:0;g=ct(ns(e,g,ut(.01,.2,i),!1)+t,6)}}else s&&(g=s(g));m=g!==this.prevProgress,f=1===e,m&&!f&&i&&e&&o.wakeTicker.restart()}if(p){const t=n?o.scrollY:o.scrollX;p.style[n?"top":"left"]=t+10+"px"}(c&&!this.isInView||u&&!this.forceEnter&&!this.hasEntered)&&(c&&(this.isInView=!0),this.forceEnter&&this.hasEntered?c&&(this.forceEnter=!1):(p&&c&&(p.style.zIndex=""+this.container.zIndex++),this.onSyncEnter(this),this.onEnter(this),this.backward?(this.onSyncEnterBackward(this),this.onEnterBackward(this)):(this.onSyncEnterForward(this),this.onEnterForward(this)),this.hasEntered=!0,u&&(this.forceEnter=!0))),(c||!c&&this.isInView)&&(m=!0),m&&(r&&t.seek(t.duration*g),this.onUpdate(this)),!c&&this.isInView&&(this.isInView=!1,this.onSyncLeave(this),this.onLeave(this),this.backward?(this.onSyncLeaveBackward(this),this.onLeaveBackward(this)):(this.onSyncLeaveForward(this),this.onLeaveForward(this)),e&&!i&&(f=!0)),g>=1&&this.began&&!this.completed&&(e&&f||!e)&&(e&&this.onSyncComplete(this),this.completed=!0,(!this.repeat&&!t||!this.repeat&&t&&t.completed)&&this.revert()),g<1&&this.completed&&(this.completed=!1),this.prevProgress=g}revert(){if(this.reverted)return;const t=this.container;return bt(t,this),t._head||t.revert(),this._debug&&this.removeDebug(),this.reverted=!0,this}}const As="undefined"!=typeof Intl&&Intl.Segmenter,Ns=/\{value\}/g,Fs=/\{i\}/g,Os=/(\s+)/,Ps=/^\s+$/,Rs="line",Ms="word",Is="char",zs="data-line";let Ys=null,Xs=null,Ws=null;const Vs=t=>t.isWordLike||" "===t.segment||M(+t.segment),Hs=t=>t.setAttribute("aria-hidden","true"),Us=(t,e)=>[...t.querySelectorAll(`[data-${e}]:not([data-${e}] [data-${e}])`)],qs={line:"#00D672",word:"#FF4B4B",char:"#5A87FF"},Qs=t=>{if(!t.childElementCount&&!t.textContent.trim()){const e=t.parentElement;t.remove(),e&&Qs(e)}},js=(t,e,s)=>{const i=t.getAttribute(zs);(null!==i&&+i!==e||"BR"===t.tagName)&&s.add(t);let r=t.childElementCount;for(;r--;)js(t.children[r],e,s);return s},Gs=(t,e={})=>{let s="";const i=I(e.class)?` class="${e.class}"`:"",r=Xt(e.clone,!1),n=Xt(e.wrap,!1),o=n?!0===n?"clip":n:!!r&&"clip";return n&&(s+=`<span${o?` style="overflow:${o};"`:""}>`),s+=`<span${i}${r?' style="position:relative;"':""} data-${t}="{i}">`,r?(s+="<span>{value}</span>",s+=`<span inert style="position:absolute;top:${"top"===r?"-100%":"bottom"===r?"100%":"0"};left:${"left"===r?"-100%":"right"===r?"100%":"0"};white-space:nowrap;">{value}</span>`):s+="{value}",s+="</span>",n&&(s+="</span>"),s},Zs=(t,e,s,i,r,n,o,a,h)=>{const l=r===Rs,c=r===Is,d=`_${r}_`,u=z(t)?t(s):t,p=l?"block":"inline-block";Ws.innerHTML=u.replace(Ns,`<i class="${d}"></i>`).replace(Fs,`${c?h:l?o:a}`);const m=Ws.content,f=m.firstElementChild,g=m.querySelector(`[data-${r}]`)||f,y=m.querySelectorAll(`i.${d}`),_=y.length;if(_){f.style.display=p,g.style.display=p,g.setAttribute(zs,`${o}`),l||(g.setAttribute("data-word",`${a}`),c&&g.setAttribute("data-char",`${h}`));let t=_;for(;t--;){const e=y[t],i=e.parentElement;i.style.display=p,l?i.innerHTML=s.innerHTML:i.replaceChild(s.cloneNode(!0),e)}e.push(g),i.appendChild(m)}else console.warn('The expression "{value}" is missing from the provided template.');return n&&(f.style.outline=`1px dotted ${qs[r]}`),f};class Js{constructor(t,s={}){Ys||(Ys=As?new As([],{granularity:Ms}):{segment:t=>{const e=[],s=t.split(Os);for(let t=0,i=s.length;t<i;t++){const i=s[t];e.push({segment:i,isWordLike:!Ps.test(i)})}return e}}),Xs||(Xs=As?new As([],{granularity:"grapheme"}):{segment:t=>[...t].map((t=>({segment:t})))}),!Ws&&e&&(Ws=i.createElement("template")),L.current&&L.current.register(this);const{words:r,chars:n,lines:o,accessible:a,includeSpaces:h,debug:l}=s,c=(t=P(t)?t[0]:t)&&t.nodeType?t:(Nt(t)||[])[0],d=!0===o?{}:o,u=!0===r||Y(r)?{}:r,p=!0===n?{}:n;this.debug=Xt(l,!1),this.includeSpaces=Xt(h,!1),this.accessible=Xt(a,!0),this.linesOnly=d&&!u&&!p,this.lineTemplate=R(d)?Gs(Rs,d):d,this.wordTemplate=R(u)||this.linesOnly?Gs(Ms,u):u,this.charTemplate=R(p)?Gs(Is,p):p,this.$target=c,this.html=c&&c.innerHTML,this.lines=[],this.words=[],this.chars=[],this.effects=[],this.effectsCleanups=[],this.cache=null,this.ready=!1,this.width=0,this.resizeTimeout=null;const m=()=>this.html&&(d||u||p)&&this.split();this.resizeObserver=new ResizeObserver((()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout((()=>{const t=c.offsetWidth;t!==this.width&&(this.width=t,m())}),150)})),this.lineTemplate&&!this.ready?i.fonts.ready.then(m):m(),c?this.resizeObserver.observe(c):console.warn("No Text Splitter target found.")}addEffect(t){if(!z(t))return console.warn("Effect must return a function.");const e=wt(t);return this.effects.push(e),this.ready&&(this.effectsCleanups[this.effects.length-1]=e(this)),this}revert(){return clearTimeout(this.resizeTimeout),this.lines.length=this.words.length=this.chars.length=0,this.resizeObserver.disconnect(),this.effectsCleanups.forEach((t=>z(t)?t(this):t.revert&&t.revert())),this.$target.innerHTML=this.html,this}splitNode(t){const e=this.wordTemplate,s=this.charTemplate,r=this.includeSpaces,n=this.debug,o=t.nodeType;if(3===o){const o=t.nodeValue;if(o.trim()){const a=[],h=this.words,l=this.chars,c=Ys.segment(o),d=i.createDocumentFragment();let u=null;for(const t of c){const e=t.segment,s=Vs(t);if(!u||s&&u&&Vs(u))a.push(e);else{const t=a.length-1;a[t].includes(" ")||e.includes(" ")?a.push(e):a[t]+=e}u=t}for(let t=0,o=a.length;t<o;t++){const o=a[t];if(o.trim()){const c=a[t+1],u=r&&c&&!c.trim(),p=o,m=s?Xs.segment(p):null,f=s?i.createDocumentFragment():i.createTextNode(u?o+" ":o);if(s){const t=[...m];for(let e=0,r=t.length;e<r;e++){const o=t[e],a=e===r-1&&u?o.segment+" ":o.segment,c=i.createTextNode(a);Zs(s,l,c,f,Is,n,-1,h.length,l.length)}}e?Zs(e,h,f,d,Ms,n,-1,h.length,l.length):s?d.appendChild(f):d.appendChild(i.createTextNode(o)),u&&t++}else{if(t&&r)continue;d.appendChild(i.createTextNode(o))}}t.parentNode.replaceChild(d,t)}}else if(1===o){const e=[...t.childNodes];for(let t=0,s=e.length;t<s;t++)this.splitNode(e[t])}}split(t=!1){const e=this.$target,s=!!this.cache&&!t,r=this.lineTemplate,n=this.wordTemplate,o=this.charTemplate,a="loading"!==i.fonts.status,h=r&&a;this.ready=!r||a,(h||t)&&this.effectsCleanups.forEach((t=>z(t)&&t(this))),s||(t&&(e.innerHTML=this.html,this.words.length=this.chars.length=0),this.splitNode(e),this.cache=e.innerHTML),h&&(s&&(e.innerHTML=this.cache),this.lines.length=0,n&&(this.words=Us(e,Ms))),o&&(h||n)&&(this.chars=Us(e,Is));const l=this.words.length?this.words:this.chars;let c,d=0;for(let t=0,e=l.length;t<e;t++){const e=l[t],{top:s,height:i}=e.getBoundingClientRect();c&&s-c>.5*i&&d++,e.setAttribute(zs,`${d}`);const r=e.querySelectorAll(`[${zs}]`);let n=r.length;for(;n--;)r[n].setAttribute(zs,`${d}`);c=s}if(h){const t=i.createDocumentFragment(),s=new Set,a=[];for(let t=0;t<d+1;t++){const i=e.cloneNode(!0);js(i,t,new Set).forEach((t=>{const e=t.parentElement;e&&s.add(e),t.remove()})),a.push(i)}s.forEach(Qs);for(let e=0,s=a.length;e<s;e++)Zs(r,this.lines,a[e],t,Rs,this.debug,e);e.innerHTML="",e.appendChild(t),n&&(this.words=Us(e,Ms)),o&&(this.chars=Us(e,Is))}if(this.linesOnly){const t=this.words;let e=t.length;for(;e--;){const s=t[e];s.replaceWith(s.textContent)}t.length=0}if(this.accessible&&(h||!s)){const t=i.createElement("span");t.style.cssText="position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;",t.innerHTML=this.html,e.insertBefore(t,e.firstChild),this.lines.forEach(Hs),this.words.forEach(Hs),this.chars.forEach(Hs)}return this.width=e.offsetWidth,(h||t)&&this.effects.forEach(((t,e)=>this.effectsCleanups[e]=t(this))),this}refresh(){this.split(!0)}}const Ks={split:(t,e)=>new Js(t,e)};t.Animatable=us,t.Draggable=Ts,t.JSAnimation=Re,t.Scope=ws,t.ScrollObserver=Ds,t.Spring=ms,t.TextSplitter=Js,t.Timeline=ds,t.Timer=oe,t.WAAPIAnimation=Ze,t.animate=(t,e)=>new Re(t,e,null,0,!1).init(),t.createAnimatable=(t,e)=>new us(t,e),t.createDraggable=(t,e)=>new Ts(t,e),t.createScope=t=>new ws(t),t.createSpring=fs,t.createTimeline=t=>new ds(t).init(),t.createTimer=t=>new oe(t,null,0).init(),t.eases=ve,t.engine=Lt,t.onScroll=(t={})=>new Ds(t),t.scrollContainers=Ss,t.stagger=(t,e={})=>{let s=[],i=0;const r=e.from,n=e.reversed,o=e.ease,a=!Y(o),h=a&&!Y(o.ease)?o.ease:a?Te(o):null,l=e.grid,c=e.axis,d=e.total,u=Y(r)||0===r||"first"===r,p="center"===r,f="last"===r,g="random"===r,y=P(t),_=e.use,v=Q(y?t[0]:t),b=y?Q(t[1]):0,T=k.exec((y?t[1]:t)+m),w=e.start||0+(y?v:0);let x=u?0:M(r)?r:0;return(t,r,o,a)=>{const[u]=Ot(t),m=Y(d)?o:d,S=!Y(_)&&(z(_)?_(u,r,m):Ut(u,_)),k=M(S)||I(S)&&M(+S)?+S:r;if(p&&(x=(m-1)/2),f&&(x=m-1),!s.length){for(let t=0;t<m;t++){if(l){const e=p?(l[0]-1)/2:x%l[0],i=p?(l[1]-1)/2:st(x/l[0]),r=e-t%l[0],n=i-st(t/l[0]);let o=G(r*r+n*n);"x"===c&&(o=-r),"y"===c&&(o=-n),s.push(o)}else s.push(K(x-t));i=rt(...s)}h&&(s=s.map((t=>h(t/i)*i))),n&&(s=s.map((t=>c?t<0?-1*t:-t:K(i-t)))),g&&(s=mt(s))}const $=y?(b-v)/i:v;let C=(a?ls(a,Y(e.start)?a.iterationDuration:w):w)+($*ct(s[k],2)||0);return e.modifier&&(C=e.modifier(C)),T&&(C=`${C}${T[2]}`),C}},t.svg=zt,t.text=Ks,t.utils=hs,t.waapi=Je}));
diff --git a/lib/gui/index.js b/lib/gui/index.js
deleted file mode 100644
index 68454eba..00000000
--- a/lib/gui/index.js
+++ /dev/null
@@ -1,6341 +0,0 @@
-/**
- * anime.js GUI - ESM
- * @version v4.1.0
- * @author Julian Garnier
- * @license MIT
- * @copyright (c) 2025 Julian Garnier
- * @see https://animejs.com
- */
-
-// Global types ///////////////////////////////////////////////////////////////
-
-/**
- * @typedef {Object} DefaultsParams
- * @property {Number|String} [id]
- * @property {PercentageKeyframes|DurationKeyframes} [keyframes]
- * @property {EasingParam} [playbackEase]
- * @property {Number} [playbackRate]
- * @property {Number} [frameRate]
- * @property {Number|Boolean} [loop]
- * @property {Boolean} [reversed]
- * @property {Boolean} [alternate]
- * @property {Boolean|ScrollObserver} [autoplay]
- * @property {Number|FunctionValue} [duration]
- * @property {Number|FunctionValue} [delay]
- * @property {Number} [loopDelay]
- * @property {EasingParam} [ease]
- * @property {'none'|'replace'|'blend'|compositionTypes} [composition]
- * @property {(v: any) => any} [modifier]
- * @property {(tickable: Tickable) => void} [onBegin]
- * @property {(tickable: Tickable) => void} [onBeforeUpdate]
- * @property {(tickable: Tickable) => void} [onUpdate]
- * @property {(tickable: Tickable) => void} [onLoop]
- * @property {(tickable: Tickable) => void} [onPause]
- * @property {(tickable: Tickable) => void} [onComplete]
- * @property {(renderable: Renderable) => void} [onRender]
- */
-
-/** @typedef {JSAnimation|Timeline} Renderable */
-/** @typedef {Timer|Renderable} Tickable */
-/** @typedef {Timer&JSAnimation&Timeline} CallbackArgument */
-/** @typedef {Animatable|Tickable|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */
-
-// Stagger types //////////////////////////////////////////////////////////////
-
-/**
- * @callback StaggerFunction
- * @param {Target} [target]
- * @param {Number} [index]
- * @param {Number} [length]
- * @param {Timeline} [tl]
- * @return {Number|String}
- */
-
-/**
- * @typedef {Object} StaggerParams
- * @property {Number|String} [start]
- * @property {Number|'first'|'center'|'last'|'random'} [from]
- * @property {Boolean} [reversed]
- * @property {Array.<Number>} [grid]
- * @property {('x'|'y')} [axis]
- * @property {String|StaggerFunction} [use]
- * @property {Number} [total]
- * @property {EasingParam} [ease]
- * @property {TweenModifier} [modifier]
- */
-
-// Eases types ////////////////////////////////////////////////////////////////
-
-/**
- * @callback EasingFunction
- * @param {Number} time
- * @return {Number}
- */
-
-/**
- * @typedef {('linear'|'linear(x1, x2 25%, x3)'|'in'|'out'|'inOut'|'inQuad'|'outQuad'|'inOutQuad'|'inCubic'|'outCubic'|'inOutCubic'|'inQuart'|'outQuart'|'inOutQuart'|'inQuint'|'outQuint'|'inOutQuint'|'inSine'|'outSine'|'inOutSine'|'inCirc'|'outCirc'|'inOutCirc'|'inExpo'|'outExpo'|'inOutExpo'|'inBounce'|'outBounce'|'inOutBounce'|'inBack'|'outBack'|'inOutBack'|'inElastic'|'outElastic'|'inOutElastic'|'irregular'|'cubicBezier'|'steps'|'in(p = 1.675)'|'out(p = 1.675)'|'inOut(p = 1.675)'|'inBack(overshoot = 1.70158)'|'outBack(overshoot = 1.70158)'|'inOutBack(overshoot = 1.70158)'|'inElastic(amplitude = 1, period = .3)'|'outElastic(amplitude = 1, period = .3)'|'inOutElastic(amplitude = 1, period = .3)'|'irregular(length = 10, randomness = 1)'|'cubicBezier(x1, y1, x2, y2)'|'steps(steps = 10)')} EaseStringParamNames
- */
-
-// A hack to get both ease names suggestions AND allow any strings
-// https://github.com/microsoft/TypeScript/issues/29729#issuecomment-460346421
-/** @typedef {(String & {})|EaseStringParamNames|EasingFunction|Spring} EasingParam */
-
-/** @typedef {HTMLElement|SVGElement} DOMTarget */
-/** @typedef {Record<String, any>} JSTarget */
-/** @typedef {DOMTarget|JSTarget} Target */
-/** @typedef {Target|NodeList|String} TargetSelector */
-/** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */
-/** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */
-/** @typedef {Array.<DOMTarget>} DOMTargetsArray */
-/** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */
-/** @typedef {Array.<JSTarget>} JSTargetsArray */
-/** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */
-/** @typedef {Array.<Target>} TargetsArray */
-
- // Callback types ////////////////////////////////////////////////////////////
-
-/**
- * @template T
- * @callback Callback
- * @param {T} self - Returns itself
- * @param {PointerEvent} [e]
- * @return {*}
- */
-
-/**
- * @template {object} T
- * @typedef {Object} TickableCallbacks
- * @property {Callback<T>} [onBegin]
- * @property {Callback<T>} [onBeforeUpdate]
- * @property {Callback<T>} [onUpdate]
- * @property {Callback<T>} [onLoop]
- * @property {Callback<T>} [onPause]
- * @property {Callback<T>} [onComplete]
- */
-
-/**
- * @template {object} T
- * @typedef {Object} RenderableCallbacks
- * @property {Callback<T>} [onRender]
- */
-
-// Timer types ////////////////////////////////////////////////////////////////
-
-/**
- * @typedef {Object} TimerOptions
- * @property {Number|String} [id]
- * @property {TweenParamValue} [duration]
- * @property {TweenParamValue} [delay]
- * @property {Number} [loopDelay]
- * @property {Boolean} [reversed]
- * @property {Boolean} [alternate]
- * @property {Boolean|Number} [loop]
- * @property {Boolean|ScrollObserver} [autoplay]
- * @property {Number} [frameRate]
- * @property {Number} [playbackRate]
- */
-
-/**
-
-/**
- * @typedef {TimerOptions & TickableCallbacks<Timer>} TimerParams
- */
-
-// Tween types ////////////////////////////////////////////////////////////////
-
-/**
- * @callback FunctionValue
- * @param {Target} target - The animated target
- * @param {Number} index - The target index
- * @param {Number} length - The total number of animated targets
- * @return {Number|String|TweenObjectValue|Array.<Number|String|TweenObjectValue>}
- */
-
-/**
- * @callback TweenModifier
- * @param {Number} value - The animated value
- * @return {Number|String}
- */
-
-/** @typedef {[Number, Number, Number, Number]} ColorArray */
-
-/**
- * @typedef {Object} Tween
- * @property {Number} id
- * @property {JSAnimation} parent
- * @property {String} property
- * @property {Target} target
- * @property {String|Number} _value
- * @property {Function|null} _func
- * @property {EasingFunction} _ease
- * @property {Array.<Number>} _fromNumbers
- * @property {Array.<Number>} _toNumbers
- * @property {Array.<String>} _strings
- * @property {Number} _fromNumber
- * @property {Number} _toNumber
- * @property {Array.<Number>} _numbers
- * @property {Number} _number
- * @property {String} _unit
- * @property {TweenModifier} _modifier
- * @property {Number} _currentTime
- * @property {Number} _delay
- * @property {Number} _updateDuration
- * @property {Number} _startTime
- * @property {Number} _changeDuration
- * @property {Number} _absoluteStartTime
- * @property {tweenTypes} _tweenType
- * @property {valueTypes} _valueType
- * @property {Number} _composition
- * @property {Number} _isOverlapped
- * @property {Number} _isOverridden
- * @property {Number} _renderTransforms
- * @property {Tween} _prevRep
- * @property {Tween} _nextRep
- * @property {Tween} _prevAdd
- * @property {Tween} _nextAdd
- * @property {Tween} _prev
- * @property {Tween} _next
- */
-
-/**
- * @typedef TweenDecomposedValue
- * @property {Number} t - Type
- * @property {Number} n - Single number value
- * @property {String} u - Value unit
- * @property {String} o - Value operator
- * @property {Array.<Number>} d - Array of Numbers (in case of complex value type)
- * @property {Array.<String>} s - Strings (in case of complex value type)
- */
-
-/** @typedef {{_head: null|Tween, _tail: null|Tween}} TweenPropertySiblings */
-/** @typedef {Record<String, TweenPropertySiblings>} TweenLookups */
-/** @typedef {WeakMap.<Target, TweenLookups>} TweenReplaceLookups */
-/** @typedef {Map.<Target, TweenLookups>} TweenAdditiveLookups */
-
-// Animation types ////////////////////////////////////////////////////////////
-
-/**
- * @typedef {Number|String|FunctionValue} TweenParamValue
- */
-
-/**
- * @typedef {TweenParamValue|[TweenParamValue, TweenParamValue]} TweenPropValue
- */
-
-/**
- * @typedef {(String & {})|'none'|'replace'|'blend'|compositionTypes} TweenComposition
- */
-
-/**
- * @typedef {Object} TweenParamsOptions
- * @property {TweenParamValue} [duration]
- * @property {TweenParamValue} [delay]
- * @property {EasingParam} [ease]
- * @property {TweenModifier} [modifier]
- * @property {TweenComposition} [composition]
- */
-
-/**
- * @typedef {Object} TweenValues
- * @property {TweenParamValue} [from]
- * @property {TweenPropValue} [to]
- * @property {TweenPropValue} [fromTo]
- */
-
-/**
- * @typedef {TweenParamsOptions & TweenValues} TweenKeyValue
- */
-
-/**
- * @typedef {Array.<TweenKeyValue|TweenPropValue>} ArraySyntaxValue
- */
-
-/**
- * @typedef {TweenParamValue|ArraySyntaxValue|TweenKeyValue} TweenOptions
- */
-
-/**
- * @typedef {Partial<{to: TweenParamValue|Array.<TweenParamValue>; from: TweenParamValue|Array.<TweenParamValue>; fromTo: TweenParamValue|Array.<TweenParamValue>;}>} TweenObjectValue
- */
-
-/**
- * @typedef {Object} PercentageKeyframeOptions
- * @property {EasingParam} [ease]
- */
-
-/**
- * @typedef {Record<String, TweenParamValue>} PercentageKeyframeParams
- */
-
-/**
- * @typedef {Record<String, PercentageKeyframeParams & PercentageKeyframeOptions>} PercentageKeyframes
- */
-
-/**
- * @typedef {Array<Record<String, TweenOptions | TweenModifier | boolean> & TweenParamsOptions>} DurationKeyframes
- */
-
-/**
- * @typedef {Object} AnimationOptions
- * @property {PercentageKeyframes|DurationKeyframes} [keyframes]
- * @property {EasingParam} [playbackEase]
- */
-
-// TODO: Currently setting TweenModifier to the intersected Record<> makes the FunctionValue type target param any if only one parameter is set
-/**
- * @typedef {Record<String, TweenOptions | Callback<JSAnimation> | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & TickableCallbacks<JSAnimation> & RenderableCallbacks<JSAnimation>} AnimationParams
- */
-
-// Timeline types /////////////////////////////////////////////////////////////
-
-/**
- * @typedef {Object} TimelineOptions
- * @property {DefaultsParams} [defaults]
- * @property {EasingParam} [playbackEase]
- */
-
-/**
- * @typedef {TimerOptions & TimelineOptions & TickableCallbacks<Timeline> & RenderableCallbacks<Timeline>} TimelineParams
- */
-
-// Animatable types ///////////////////////////////////////////////////////////
-
-/**
- * @callback AnimatablePropertySetter
- * @param {Number|Array.<Number>} to
- * @param {Number} [duration]
- * @param {EasingParam} [ease]
- * @return {AnimatableObject}
- */
-
-/**
- * @callback AnimatablePropertyGetter
- * @return {Number|Array.<Number>}
- */
-
-/**
- * @typedef {AnimatablePropertySetter & AnimatablePropertyGetter} AnimatableProperty
- */
-
-/**
- * @typedef {Animatable & Record<String, AnimatableProperty>} AnimatableObject
- */
-
-/**
- * @typedef {Object} AnimatablePropertyParamsOptions
- * @property {String} [unit]
- * @property {TweenParamValue} [duration]
- * @property {EasingParam} [ease]
- * @property {TweenModifier} [modifier]
- * @property {TweenComposition} [composition]
- */
-
-/**
- * @typedef {Record<String, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions} AnimatableParams
- */
-
-// Scope types ////////////////////////////////////////////////////////////////
-
-/**
- * @typedef {Object} ReactRef
- * @property {HTMLElement|SVGElement|null} [current]
- */
-
-/**
- * @typedef {Object} AngularRef
- * @property {HTMLElement|SVGElement} [nativeElement]
- */
-
-/**
- * @typedef {Object} ScopeParams
- * @property {DOMTargetSelector|ReactRef|AngularRef} [root]
- * @property {DefaultsParams} [defaults]
- * @property {Record<String, String>} [mediaQueries]
- */
-
-/**
- * @template T
- * @callback ScopedCallback
- * @param {Scope} scope
- * @return {T}
- */
-
-/**
- * @callback ScopeCleanupCallback
- * @param {Scope} [scope]
- */
-
-/**
- * @callback ScopeConstructorCallback
- * @param {Scope} [scope]
- * @return {ScopeCleanupCallback|void}
- */
-
-/**
- * @callback ScopeMethod
- * @param {...*} args
- * @return {ScopeCleanupCallback|void}
- */
-
-// Draggable types ////////////////////////////////////////////////////////////
-
-/**
- * @typedef {Object} DraggableAxisParam
- * @property {String} [mapTo]
- * @property {TweenModifier} [modifier]
- * @property {TweenComposition} [composition]
- * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap]
- */
-
-/**
- * @typedef {Object} DraggableCursorParams
- * @property {String} [onHover]
- * @property {String} [onGrab]
- */
-
-/**
- * @typedef {Object} DraggableParams
- * @property {DOMTargetSelector} [trigger]
- * @property {DOMTargetSelector|Array<Number>|((draggable: Draggable) => DOMTargetSelector|Array<Number>)} [container]
- * @property {Boolean|DraggableAxisParam} [x]
- * @property {Boolean|DraggableAxisParam} [y]
- * @property {TweenModifier} [modifier]
- * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap]
- * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [containerPadding]
- * @property {Number|((draggable: Draggable) => Number)} [containerFriction]
- * @property {Number|((draggable: Draggable) => Number)} [releaseContainerFriction]
- * @property {Number|((draggable: Draggable) => Number)} [dragSpeed]
- * @property {Number|((draggable: Draggable) => Number)} [scrollSpeed]
- * @property {Number|((draggable: Draggable) => Number)} [scrollThreshold]
- * @property {Number|((draggable: Draggable) => Number)} [minVelocity]
- * @property {Number|((draggable: Draggable) => Number)} [maxVelocity]
- * @property {Number|((draggable: Draggable) => Number)} [velocityMultiplier]
- * @property {Number} [releaseMass]
- * @property {Number} [releaseStiffness]
- * @property {Number} [releaseDamping]
- * @property {Boolean} [releaseDamping]
- * @property {EasingParam} [releaseEase]
- * @property {Boolean|DraggableCursorParams|((draggable: Draggable) => Boolean|DraggableCursorParams)} [cursor]
- * @property {Callback<Draggable>} [onGrab]
- * @property {Callback<Draggable>} [onDrag]
- * @property {Callback<Draggable>} [onRelease]
- * @property {Callback<Draggable>} [onUpdate]
- * @property {Callback<Draggable>} [onSettle]
- * @property {Callback<Draggable>} [onSnap]
- * @property {Callback<Draggable>} [onResize]
- * @property {Callback<Draggable>} [onAfterResize]
- */
-
-// Text types /////////////////////////////////////////////////////////////////
-
-/**
- * @typedef {Object} splitTemplateParams
- * @property {false|String} [class]
- * @property {Boolean|'visible'|'clip'} [wrap]
- * @property {Boolean|'top'|'right'|'bottom'|'left'} [clone]
- */
-
-/**
- * @typedef {Boolean|String} SplitValue
- */
-
-/**
- * @callback SplitFunctionValue
- * @param {Node|HTMLElement} [value]
- * @return String
- */
-
-/**
- * @typedef {Object} TextSplitterParams
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [lines]
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [words]
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [chars]
- * @property {Boolean} [accessible]
- * @property {Boolean} [includeSpaces]
- * @property {Boolean} [debug]
- * @property {Callback<TextSplitter>} [onLineCalc]
- */
-
-// SVG types //////////////////////////////////////////////////////////////////
-
-/**
- * @typedef {SVGGeometryElement & {
- * setAttribute(name: 'draw', value: `${number} ${number}`): void;
- * draw: `${number} ${number}`;
- * }} DrawableSVGGeometry
- */
-
-
-// Environments
-
-// TODO: Do we need to check if we're running inside a worker ?
-const isBrowser = typeof window !== 'undefined';
-
-/** @type {Object|Null} */
-const win = isBrowser ? window : null;
-
-/** @type {Document} */
-const doc = isBrowser ? document : null;
-
-// Enums
-
-/** @enum {Number} */
-const tweenTypes = {
- OBJECT: 0,
- ATTRIBUTE: 1,
- CSS: 2,
- TRANSFORM: 3,
- CSS_VAR: 4,
-};
-
-/** @enum {Number} */
-const valueTypes = {
- NUMBER: 0,
- UNIT: 1,
- COLOR: 2,
- COMPLEX: 3,
-};
-
-/** @enum {Number} */
-const tickModes = {
- NONE: 0,
- AUTO: 1,
- FORCE: 2,
-};
-
-/** @enum {Number} */
-const compositionTypes = {
- replace: 0,
- none: 1,
- blend: 2,
-};
-
-// Cache symbols
-
-const isRegisteredTargetSymbol = Symbol();
-const isDomSymbol = Symbol();
-const isSvgSymbol = Symbol();
-const transformsSymbol = Symbol();
-const morphPointsSymbol = Symbol();
-const proxyTargetSymbol = Symbol();
-
-// Numbers
-
-const minValue = 1e-11;
-const maxValue = 1e12;
-const K = 1e3;
-const maxFps = 120;
-
-// Strings
-
-const emptyString = '';
-const shortTransforms = new Map();
-
-shortTransforms.set('x', 'translateX');
-shortTransforms.set('y', 'translateY');
-shortTransforms.set('z', 'translateZ');
-
-const validTransforms = [
- 'translateX',
- 'translateY',
- 'translateZ',
- 'rotate',
- 'rotateX',
- 'rotateY',
- 'rotateZ',
- 'scale',
- 'scaleX',
- 'scaleY',
- 'scaleZ',
- 'skew',
- 'skewX',
- 'skewY',
- 'perspective',
- 'matrix',
- 'matrix3d',
-];
-
-const transformsFragmentStrings = validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {});
-
-// Functions
-
-/** @return {void} */
-const noop = () => {};
-
-// Regex
-
-const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;
-const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;
-const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
-const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;
-const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
-// export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g;
-const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;
-// export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i;
-const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;
-const lowerCaseRgx = /([a-z])([A-Z])/g;
-const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in ()
-const relativeValuesExecRgx = /(\*=|\+=|-=)/;
-
-
-
-
-/** @type {DefaultsParams} */
-const defaults = {
- id: null,
- keyframes: null,
- playbackEase: null,
- playbackRate: 1,
- frameRate: maxFps,
- loop: 0,
- reversed: false,
- alternate: false,
- autoplay: true,
- duration: K,
- delay: 0,
- loopDelay: 0,
- ease: 'out(2)',
- composition: compositionTypes.replace,
- modifier: v => v,
- onBegin: noop,
- onBeforeUpdate: noop,
- onUpdate: noop,
- onLoop: noop,
- onPause: noop,
- onComplete: noop,
- onRender: noop,
-};
-
-const globals = {
- /** @type {DefaultsParams} */
- defaults,
- /** @type {Document|DOMTarget} */
- root: doc,
- /** @type {Scope} */
- scope: null,
- /** @type {Number} */
- precision: 4,
- /** @type {Number} */
- timeScale: 1,
- /** @type {Number} */
- tickThreshold: 200,
-};
-
-const globalVersions = { version: '4.1.0', engine: null };
-
-if (isBrowser) {
- if (!win.AnimeJS) win.AnimeJS = [];
- win.AnimeJS.push(globalVersions);
-}
-
-// Strings
-
-/**
- * @param {String} str
- * @return {String}
- */
-const toLowerCase = str => str.replace(lowerCaseRgx, '$1-$2').toLowerCase();
-
-/**
- * Prioritize this method instead of regex when possible
- * @param {String} str
- * @param {String} sub
- * @return {Boolean}
- */
-const stringStartsWith = (str, sub) => str.indexOf(sub) === 0;
-
-// Time
-// Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement.
-const now = Date.now;
-
-// Types checkers
-
-const isArr = Array.isArray;
-/**@param {any} a @return {a is Record<String, any>} */
-const isObj = a => a && a.constructor === Object;
-/**@param {any} a @return {a is Number} */
-const isNum = a => typeof a === 'number' && !isNaN(a);
-/**@param {any} a @return {a is String} */
-const isStr = a => typeof a === 'string';
-/**@param {any} a @return {a is Function} */
-const isFnc = a => typeof a === 'function';
-/**@param {any} a @return {a is undefined} */
-const isUnd = a => typeof a === 'undefined';
-/**@param {any} a @return {a is null | undefined} */
-const isNil = a => isUnd(a) || a === null;
-/**@param {any} a @return {a is SVGElement} */
-const isSvg = a => isBrowser && a instanceof SVGElement;
-/**@param {any} a @return {Boolean} */
-const isHex = a => hexTestRgx.test(a);
-/**@param {any} a @return {Boolean} */
-const isRgb = a => stringStartsWith(a, 'rgb');
-/**@param {any} a @return {Boolean} */
-const isHsl = a => stringStartsWith(a, 'hsl');
-/**@param {any} a @return {Boolean} */
-const isCol = a => isHex(a) || isRgb(a) || isHsl(a);
-/**@param {any} a @return {Boolean} */
-const isKey = a => !globals.defaults.hasOwnProperty(a);
-
-// Number
-
-/**
- * @param {Number|String} str
- * @return {Number}
- */
-const parseNumber = str => isStr(str) ?
- parseFloat(/** @type {String} */(str)) :
- /** @type {Number} */(str);
-
-// Math
-
-const pow = Math.pow;
-const sqrt = Math.sqrt;
-const sin = Math.sin;
-const cos = Math.cos;
-const abs = Math.abs;
-const ceil = Math.ceil;
-const floor = Math.floor;
-const asin = Math.asin;
-const atan2 = Math.atan2;
-const PI = Math.PI;
-const _round = Math.round;
-
-/**
- * @param {Number} v
- * @param {Number} min
- * @param {Number} max
- * @return {Number}
- */
-const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
-
-const powCache = {};
-
-/**
- * @param {Number} v
- * @param {Number} decimalLength
- * @return {Number}
- */
-const round = (v, decimalLength) => {
- if (decimalLength < 0) return v;
- if (!decimalLength) return _round(v);
- let p = powCache[decimalLength];
- if (!p) p = powCache[decimalLength] = 10 ** decimalLength;
- return _round(v * p) / p;
-};
-
-/**
- * @param {Number} v
- * @param {Number|Array<Number>} increment
- * @return {Number}
- */
-const snap = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
-
-/**
- * @param {Number} start
- * @param {Number} end
- * @param {Number} progress
- * @return {Number}
- */
-const interpolate = (start, end, progress) => start + (end - start) * progress;
-
-/**
- * @param {Number} min
- * @param {Number} max
- * @param {Number} [decimalLength]
- * @return {Number}
- */
-const random = (min, max, decimalLength) => { const m = 10 ** (decimalLength || 0); return floor((Math.random() * (max - min + (1 / m)) + min) * m) / m };
-
-/**
- * Adapted from https://bost.ocks.org/mike/shuffle/
- * @param {Array} items
- * @return {Array}
- */
-const shuffle = items => {
- let m = items.length, t, i;
- while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; }
- return items;
-};
-
-/**
- * @param {Number} v
- * @return {Number}
- */
-const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -1e12 : v;
-
-/**
- * @param {Number} v
- * @return {Number}
- */
-const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round(v, 11));
-
-// Arrays
-
-/**
- * @template T
- * @param {T[]} a
- * @return {T[]}
- */
-const cloneArray = a => isArr(a) ? [ ...a ] : a;
-
-// Objects
-
-/**
- * @template T
- * @template U
- * @param {T} o1
- * @param {U} o2
- * @return {T & U}
- */
-const mergeObjects = (o1, o2) => {
- const merged = /** @type {T & U} */({ ...o1 });
- for (let p in o2) {
- const o1p = /** @type {T & U} */(o1)[p];
- merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p;
- } return merged;
-};
-
-// Linked lists
-
-/**
- * @param {Object} parent
- * @param {Function} callback
- * @param {Boolean} [reverse]
- * @param {String} [prevProp]
- * @param {String} [nextProp]
- * @return {void}
- */
-const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => {
- let next = parent._head;
- let adjustedNextProp = nextProp;
- if (reverse) {
- next = parent._tail;
- adjustedNextProp = prevProp;
- }
- while (next) {
- const currentNext = next[adjustedNextProp];
- callback(next);
- next = currentNext;
- }
-};
-
-/**
- * @param {Object} parent
- * @param {Object} child
- * @param {String} [prevProp]
- * @param {String} [nextProp]
- * @return {void}
- */
-const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => {
- const prev = child[prevProp];
- const next = child[nextProp];
- prev ? prev[nextProp] = next : parent._head = next;
- next ? next[prevProp] = prev : parent._tail = prev;
- child[prevProp] = null;
- child[nextProp] = null;
-};
-
-/**
- * @param {Object} parent
- * @param {Object} child
- * @param {Function} [sortMethod]
- * @param {String} prevProp
- * @param {String} nextProp
- * @return {void}
- */
-const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => {
- let prev = parent._tail;
- while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp];
- const next = prev ? prev[nextProp] : parent._head;
- prev ? prev[nextProp] = child : parent._head = child;
- next ? next[prevProp] = child : parent._tail = child;
- child[prevProp] = prev;
- child[nextProp] = next;
-};
-
-/*
- * Base class to control framerate and playback rate.
- * Inherited by Engine, Timer, Animation and Timeline.
- */
-class Clock {
-
- /** @param {Number} [initTime] */
- constructor(initTime = 0) {
- /** @type {Number} */
- this.deltaTime = 0;
- /** @type {Number} */
- this._currentTime = initTime;
- /** @type {Number} */
- this._elapsedTime = initTime;
- /** @type {Number} */
- this._startTime = initTime;
- /** @type {Number} */
- this._lastTime = initTime;
- /** @type {Number} */
- this._scheduledTime = 0;
- /** @type {Number} */
- this._frameDuration = round(K / maxFps, 0);
- /** @type {Number} */
- this._fps = maxFps;
- /** @type {Number} */
- this._speed = 1;
- /** @type {Boolean} */
- this._hasChildren = false;
- /** @type {Tickable|Tween} */
- this._head = null;
- /** @type {Tickable|Tween} */
- this._tail = null;
- }
-
- get fps() {
- return this._fps;
- }
-
- set fps(frameRate) {
- const previousFrameDuration = this._frameDuration;
- const fr = +frameRate;
- const fps = fr < minValue ? minValue : fr;
- const frameDuration = round(K / fps, 0);
- this._fps = fps;
- this._frameDuration = frameDuration;
- this._scheduledTime += frameDuration - previousFrameDuration;
- }
-
- get speed() {
- return this._speed;
- }
-
- set speed(playbackRate) {
- const pbr = +playbackRate;
- this._speed = pbr < minValue ? minValue : pbr;
- }
-
- /**
- * @param {Number} time
- * @return {tickModes}
- */
- requestTick(time) {
- const scheduledTime = this._scheduledTime;
- const elapsedTime = this._elapsedTime;
- this._elapsedTime += (time - elapsedTime);
- // If the elapsed time is lower than the scheduled time
- // this means not enough time has passed to hit one frameDuration
- // so skip that frame
- if (elapsedTime < scheduledTime) return tickModes.NONE;
- const frameDuration = this._frameDuration;
- const frameDelta = elapsedTime - scheduledTime;
- // Ensures that _scheduledTime progresses in steps of at least 1 frameDuration.
- // Skips ahead if the actual elapsed time is higher.
- this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta;
- return tickModes.AUTO;
- }
-
- /**
- * @param {Number} time
- * @return {Number}
- */
- computeDeltaTime(time) {
- const delta = time - this._lastTime;
- this.deltaTime = delta;
- this._lastTime = time;
- return delta;
- }
-
-}
-
-
-
-
-/**
- * @param {Tickable} tickable
- * @param {Number} time
- * @param {Number} muteCallbacks
- * @param {Number} internalRender
- * @param {tickModes} tickMode
- * @return {Number}
- */
-const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
-
- const parent = tickable.parent;
- const duration = tickable.duration;
- const completed = tickable.completed;
- const iterationDuration = tickable.iterationDuration;
- const iterationCount = tickable.iterationCount;
- const _currentIteration = tickable._currentIteration;
- const _loopDelay = tickable._loopDelay;
- const _reversed = tickable._reversed;
- const _alternate = tickable._alternate;
- const _hasChildren = tickable._hasChildren;
- const tickableDelay = tickable._delay;
- const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime
-
- const tickableEndTime = tickableDelay + iterationDuration;
- const tickableAbsoluteTime = time - tickableDelay;
- const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration);
- const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration);
- const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime;
- const isCurrentTimeAboveZero = tickableCurrentTime > 0;
- const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration;
- const isSetter = duration <= minValue;
- const forcedTick = tickMode === tickModes.FORCE;
-
- let isOdd = 0;
- let iterationElapsedTime = tickableAbsoluteTime;
- // Render checks
- // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer
- let hasRendered = 0;
-
- // Execute the "expensive" iterations calculations only when necessary
- if (iterationCount > 1) {
- // bitwise NOT operator seems to be generally faster than Math.floor() across browsers
- const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay)));
- tickable._currentIteration = clamp(currentIteration, 0, iterationCount);
- // Prevent the iteration count to go above the max iterations when reaching the end of the animation
- if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--;
- isOdd = tickable._currentIteration % 2;
- iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0;
- }
-
- // Checks if exactly one of _reversed and (_alternate && isOdd) is true
- const isReversed = _reversed ^ (_alternate && isOdd);
- const _ease = /** @type {Renderable} */(tickable)._ease;
- let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime;
- if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0;
- const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed;
-
- tickable._currentTime = tickableAbsoluteTime;
- tickable._iterationTime = iterationTime;
- tickable.backwards = isRunningBackwards;
-
- if (isCurrentTimeAboveZero && !tickable.began) {
- tickable.began = true;
- if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) {
- tickable.onBegin(/** @type {CallbackArgument} */(tickable));
- }
- } else if (tickableAbsoluteTime <= 0) {
- tickable.began = false;
- }
-
- // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function
- // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values
- if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) {
- tickable.onLoop(/** @type {CallbackArgument} */(tickable));
- }
-
- if (
- forcedTick ||
- tickMode === tickModes.AUTO && (
- time >= tickableDelay && time <= tickableEndTime || // Normal render
- time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state
- time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state
- ) ||
- iterationTime >= tickableEndTime && tickablePrevTime !== duration ||
- iterationTime <= tickableDelay && tickablePrevTime > 0 ||
- time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation
- isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped
- ) {
-
- if (isCurrentTimeAboveZero) {
- // Trigger onUpdate callback before rendering
- tickable.computeDeltaTime(tickablePrevTime);
- if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable));
- }
-
- // Start tweens rendering
- if (!_hasChildren) {
-
- // Time has jumped more than globals.tickThreshold so consider this tick manual
- const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold;
- const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime;
-
- // Only Animation can have tweens, Timer returns undefined
- let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head);
- let tweenTarget;
- let tweenStyle;
- let tweenTargetTransforms;
- let tweenTargetTransformsProperties;
- let tweenTransformsNeedUpdate = 0;
-
- while (tween) {
-
- const tweenComposition = tween._composition;
- const tweenCurrentTime = tween._currentTime;
- const tweenChangeDuration = tween._changeDuration;
- const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration;
- const tweenNextRep = tween._nextRep;
- const tweenPrevRep = tween._prevRep;
- const tweenHasComposition = tweenComposition !== compositionTypes.none;
-
- if ((forcedRender || (
- (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) &&
- (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime)
- )) && (!tweenHasComposition || (
- !tween._isOverridden &&
- (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) &&
- (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) &&
- (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay)))
- ))
- ) {
-
- const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration);
- const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration);
- const tweenModifier = tween._modifier;
- const tweenValueType = tween._valueType;
- const tweenType = tween._tweenType;
- const tweenIsObject = tweenType === tweenTypes.OBJECT;
- const tweenIsNumber = tweenValueType === valueTypes.NUMBER;
- // Only round the in-between frames values if the final value is a string
- const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision;
-
- // Recompose tween value
- /** @type {String|Number} */
- let value;
- /** @type {Number} */
- let number;
-
- if (tweenIsNumber) {
- value = number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
- } else if (tweenValueType === valueTypes.UNIT) {
- // Rounding the values speed up string composition
- number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
- value = `${number}${tween._unit}`;
- } else if (tweenValueType === valueTypes.COLOR) {
- const fn = tween._fromNumbers;
- const tn = tween._toNumbers;
- const r = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[0], tn[0], tweenProgress))), 0, 255), 0);
- const g = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[1], tn[1], tweenProgress))), 0, 255), 0);
- const b = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[2], tn[2], tweenProgress))), 0, 255), 0);
- const a = clamp(/** @type {Number} */(tweenModifier(round(interpolate(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
- value = `rgba(${r},${g},${b},${a})`;
- if (tweenHasComposition) {
- const ns = tween._numbers;
- ns[0] = r;
- ns[1] = g;
- ns[2] = b;
- ns[3] = a;
- }
- } else if (tweenValueType === valueTypes.COMPLEX) {
- value = tween._strings[0];
- for (let j = 0, l = tween._toNumbers.length; j < l; j++) {
- const n = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
- const s = tween._strings[j + 1];
- value += `${s ? n + s : n}`;
- if (tweenHasComposition) {
- tween._numbers[j] = n;
- }
- }
- }
-
- // For additive tweens and Animatables
- if (tweenHasComposition) {
- tween._number = number;
- }
-
- if (!internalRender && tweenComposition !== compositionTypes.blend) {
-
- const tweenProperty = tween.property;
- tweenTarget = tween.target;
-
- if (tweenIsObject) {
- tweenTarget[tweenProperty] = value;
- } else if (tweenType === tweenTypes.ATTRIBUTE) {
- /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value));
- } else {
- tweenStyle = /** @type {DOMTarget} */(tweenTarget).style;
- if (tweenType === tweenTypes.TRANSFORM) {
- if (tweenTarget !== tweenTargetTransforms) {
- tweenTargetTransforms = tweenTarget;
- // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage.
- tweenTargetTransformsProperties = tweenTarget[transformsSymbol];
- }
- tweenTargetTransformsProperties[tweenProperty] = value;
- tweenTransformsNeedUpdate = 1;
- } else if (tweenType === tweenTypes.CSS) {
- tweenStyle[tweenProperty] = value;
- } else if (tweenType === tweenTypes.CSS_VAR) {
- tweenStyle.setProperty(tweenProperty,/** @type {String} */(value));
- }
- }
-
- if (isCurrentTimeAboveZero) hasRendered = 1;
-
- } else {
- // Used for composing timeline tweens without having to do a real render
- tween._value = value;
- }
-
- }
-
- // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax
- // to reduce memory usage on string composition
- if (tweenTransformsNeedUpdate && tween._renderTransforms) {
- let str = emptyString;
- for (let key in tweenTargetTransformsProperties) {
- str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `;
- }
- tweenStyle.transform = str;
- tweenTransformsNeedUpdate = 0;
- }
-
- tween = tween._next;
- }
-
- if (!muteCallbacks && hasRendered) {
- /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable));
- }
- }
-
- if (!muteCallbacks && isCurrentTimeAboveZero) {
- tickable.onUpdate(/** @type {CallbackArgument} */(tickable));
- }
-
- }
-
- // End tweens rendering
-
- // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards
- if (parent && isSetter) {
- if (!muteCallbacks && (
- (parent.began && !isRunningBackwards && tickableAbsoluteTime >= duration && !completed) ||
- (isRunningBackwards && tickableAbsoluteTime <= minValue && completed)
- )) {
- tickable.onComplete(/** @type {CallbackArgument} */(tickable));
- tickable.completed = !isRunningBackwards;
- }
- // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops
- } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) {
- if (iterationCount === Infinity) {
- // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer
- tickable._startTime += tickable.duration;
- } else if (tickable._currentIteration >= iterationCount - 1) {
- // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick
- tickable.paused = true;
- if (!completed && !_hasChildren) {
- // If the tickable has children, triggers onComplete() only when all children have completed in the tick function
- tickable.completed = true;
- if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) {
- tickable.onComplete(/** @type {CallbackArgument} */(tickable));
- tickable._resolve(/** @type {CallbackArgument} */(tickable));
- }
- }
- }
- // Otherwise set the completed flag to false
- } else {
- tickable.completed = false;
- }
-
- // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ?
- return hasRendered;
-};
-
-/**
- * @param {Tickable} tickable
- * @param {Number} time
- * @param {Number} muteCallbacks
- * @param {Number} internalRender
- * @param {Number} tickMode
- * @return {void}
- */
-const tick = (tickable, time, muteCallbacks, internalRender, tickMode) => {
- const _currentIteration = tickable._currentIteration;
- render(tickable, time, muteCallbacks, internalRender, tickMode);
- if (tickable._hasChildren) {
- const tl = /** @type {Timeline} */(tickable);
- const tlIsRunningBackwards = tl.backwards;
- const tlChildrenTime = internalRender ? time : tl._iterationTime;
- const tlCildrenTickTime = now();
-
- let tlChildrenHasRendered = 0;
- let tlChildrenHaveCompleted = true;
-
- // If the timeline has looped forward, we need to manually triggers children skipped callbacks
- if (!internalRender && tl._currentIteration !== _currentIteration) {
- const tlIterationDuration = tl.iterationDuration;
- forEachChildren(tl, (/** @type {JSAnimation} */child) => {
- if (!tlIsRunningBackwards) {
- // Force an internal render to trigger the callbacks if the child has not completed on loop
- if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) {
- render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE);
- }
- // Reset their began and completed flags to allow retrigering callbacks on the next iteration
- child.began = false;
- child.completed = false;
- } else {
- const childDuration = child.duration;
- const childStartTime = child._offset + child._delay;
- const childEndTime = childStartTime + childDuration;
- // Triggers the onComplete callback on reverse for children on the edges of the timeline
- if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) {
- child.onComplete(child);
- }
- }
- });
- if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl));
- }
-
- forEachChildren(tl, (/** @type {JSAnimation} */child) => {
- const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds
- const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode;
- tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode);
- if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false;
- }, tlIsRunningBackwards);
-
- // Renders on timeline are triggered by its children so it needs to be set after rendering the children
- if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl));
-
- // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end
- if (tlChildrenHaveCompleted && tl._currentTime >= tl.duration) {
- // Make sure the paused flag is false in case it has been skipped in the render function
- tl.paused = true;
- if (!tl.completed) {
- tl.completed = true;
- if (!muteCallbacks) {
- tl.onComplete(/** @type {CallbackArgument} */(tl));
- tl._resolve(/** @type {CallbackArgument} */(tl));
- }
- }
- }
- }
-};
-
-
-
-
-const additive = {
- animation: null,
- update: noop,
-};
-
-/**
- * @typedef AdditiveAnimation
- * @property {Number} duration
- * @property {Number} _offset
- * @property {Number} _delay
- * @property {Tween} _head
- * @property {Tween} _tail
- */
-
-/**
- * @param {TweenAdditiveLookups} lookups
- * @return {AdditiveAnimation}
- */
-const addAdditiveAnimation = lookups => {
- let animation = additive.animation;
- if (!animation) {
- animation = {
- duration: minValue,
- computeDeltaTime: noop,
- _offset: 0,
- _delay: 0,
- _head: null,
- _tail: null,
- };
- additive.animation = animation;
- additive.update = () => {
- lookups.forEach(propertyAnimation => {
- for (let propertyName in propertyAnimation) {
- const tweens = propertyAnimation[propertyName];
- const lookupTween = tweens._head;
- if (lookupTween) {
- const valueType = lookupTween._valueType;
- const additiveValues = valueType === valueTypes.COMPLEX || valueType === valueTypes.COLOR ? cloneArray(lookupTween._fromNumbers) : null;
- let additiveValue = lookupTween._fromNumber;
- let tween = tweens._tail;
- while (tween && tween !== lookupTween) {
- if (additiveValues) {
- for (let i = 0, l = tween._numbers.length; i < l; i++) additiveValues[i] += tween._numbers[i];
- } else {
- additiveValue += tween._number;
- }
- tween = tween._prevAdd;
- }
- lookupTween._toNumber = additiveValue;
- lookupTween._toNumbers = additiveValues;
- }
- }
- });
- // TODO: Avoid polymorphism here, idealy the additive animation should be a regular animation with a higher priority in the render loop
- render(animation, 1, 1, 0, tickModes.FORCE);
- };
- }
- return animation;
-};
-
-const engineTickMethod = isBrowser ? requestAnimationFrame : setImmediate;
-const engineCancelMethod = isBrowser ? cancelAnimationFrame : clearImmediate;
-
-class Engine extends Clock {
-
- /** @param {Number} [initTime] */
- constructor(initTime) {
- super(initTime);
- this.useDefaultMainLoop = true;
- this.pauseOnDocumentHidden = true;
- /** @type {DefaultsParams} */
- this.defaults = defaults;
- this.paused = isBrowser && doc.hidden ? true : false;
- /** @type {Number|NodeJS.Immediate} */
- this.reqId = null;
- }
-
- update() {
- const time = this._currentTime = now();
- if (this.requestTick(time)) {
- this.computeDeltaTime(time);
- const engineSpeed = this._speed;
- const engineFps = this._fps;
- let activeTickable = /** @type {Tickable} */(this._head);
- while (activeTickable) {
- const nextTickable = activeTickable._next;
- if (!activeTickable.paused) {
- tick(
- activeTickable,
- (time - activeTickable._startTime) * activeTickable._speed * engineSpeed,
- 0, // !muteCallbacks
- 0, // !internalRender
- activeTickable._fps < engineFps ? activeTickable.requestTick(time) : tickModes.AUTO
- );
- } else {
- removeChild(this, activeTickable);
- this._hasChildren = !!this._tail;
- activeTickable._running = false;
- if (activeTickable.completed && !activeTickable._cancelled) {
- activeTickable.cancel();
- }
- }
- activeTickable = nextTickable;
- }
- additive.update();
- }
- }
-
- wake() {
- if (this.useDefaultMainLoop && !this.reqId && !this.paused) {
- this.reqId = engineTickMethod(tickEngine);
- }
- return this;
- }
-
- pause() {
- this.paused = true;
- return killEngine();
- }
-
- resume() {
- if (!this.paused) return;
- this.paused = false;
- forEachChildren(this, (/** @type {Tickable} */child) => child.resetTime());
- return this.wake();
- }
-
- // Getter and setter for speed
- get speed() {
- return this._speed * (globals.timeScale === 1 ? 1 : K);
- }
-
- set speed(playbackRate) {
- this._speed = playbackRate * globals.timeScale;
- forEachChildren(this, (/** @type {Tickable} */child) => child.speed = child._speed);
- }
-
- // Getter and setter for timeUnit
- get timeUnit() {
- return globals.timeScale === 1 ? 'ms' : 's';
- };
-
- set timeUnit(unit) {
- const secondsScale = 0.001;
- const isSecond = unit === 's';
- const newScale = isSecond ? secondsScale : 1;
- if (globals.timeScale !== newScale) {
- globals.timeScale = newScale;
- globals.tickThreshold = 200 * newScale;
- const scaleFactor = isSecond ? secondsScale : K;
- /** @type {Number} */
- (this.defaults.duration) *= scaleFactor;
- this._speed *= scaleFactor;
- }
- }
-
- // Getter and setter for precision
- get precision() {
- return globals.precision;
- }
-
- set precision(precision) {
- globals.precision = precision;
- }
-
-}
-const engine = /*#__PURE__*/(() => {
- const engine = new Engine(now());
- if (isBrowser) {
- globalVersions.engine = engine;
- doc.addEventListener('visibilitychange', () => {
- if (!engine.pauseOnDocumentHidden) return;
- doc.hidden ? engine.pause() : engine.resume();
- });
- }
- return engine;
-})();
-
-
-const tickEngine = () => {
- if (engine._head) {
- engine.reqId = engineTickMethod(tickEngine);
- engine.update();
- } else {
- engine.reqId = 0;
- }
-};
-
-const killEngine = () => {
- engineCancelMethod(/** @type {NodeJS.Immediate & Number} */(engine.reqId));
- engine.reqId = 0;
- return engine;
-};
-
-
-
-
-/**
- * @param {DOMTarget} target
- * @param {String} propName
- * @param {Object} animationInlineStyles
- * @return {String}
- */
-const parseInlineTransforms = (target, propName, animationInlineStyles) => {
- const inlineTransforms = target.style.transform;
- let inlinedStylesPropertyValue;
- if (inlineTransforms) {
- const cachedTransforms = target[transformsSymbol];
- let t; while (t = transformsExecRgx.exec(inlineTransforms)) {
- const inlinePropertyName = t[1];
- // const inlinePropertyValue = t[2];
- const inlinePropertyValue = t[2].slice(1, -1);
- cachedTransforms[inlinePropertyName] = inlinePropertyValue;
- if (inlinePropertyName === propName) {
- inlinedStylesPropertyValue = inlinePropertyValue;
- // Store the new parsed inline styles if animationInlineStyles is provided
- if (animationInlineStyles) {
- animationInlineStyles[propName] = inlinePropertyValue;
- }
- }
- }
- }
- return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue :
- stringStartsWith(propName, 'scale') ? '1' :
- stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px';
-};
-
-
-
-
-/**
- * @param {DOMTargetsParam|TargetsParam} v
- * @return {NodeList|HTMLCollection}
- */
-function getNodeList(v) {
- const n = isStr(v) ? globals.root.querySelectorAll(v) : v;
- if (n instanceof NodeList || n instanceof HTMLCollection) return n;
-}
-
-/**
- * @overload
- * @param {DOMTargetsParam} targets
- * @return {DOMTargetsArray}
- *
- * @overload
- * @param {JSTargetsParam} targets
- * @return {JSTargetsArray}
- *
- * @overload
- * @param {TargetsParam} targets
- * @return {TargetsArray}
- *
- * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
- */
-function parseTargets(targets) {
- if (isNil(targets)) return /** @type {TargetsArray} */([]);
- if (isArr(targets)) {
- const flattened = targets.flat(Infinity);
- /** @type {TargetsArray} */
- const parsed = [];
- for (let i = 0, l = flattened.length; i < l; i++) {
- const item = flattened[i];
- if (!isNil(item)) {
- const nodeList = getNodeList(item);
- if (nodeList) {
- for (let j = 0, jl = nodeList.length; j < jl; j++) {
- const subItem = nodeList[j];
- if (!isNil(subItem)) {
- let isDuplicate = false;
- for (let k = 0, kl = parsed.length; k < kl; k++) {
- if (parsed[k] === subItem) {
- isDuplicate = true;
- break;
- }
- }
- if (!isDuplicate) {
- parsed.push(subItem);
- }
- }
- }
- } else {
- let isDuplicate = false;
- for (let j = 0, jl = parsed.length; j < jl; j++) {
- if (parsed[j] === item) {
- isDuplicate = true;
- break;
- }
- }
- if (!isDuplicate) {
- parsed.push(item);
- }
- }
- }
- }
- return parsed;
- }
- if (!isBrowser) return /** @type {JSTargetsArray} */([targets]);
- const nodeList = getNodeList(targets);
- if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList));
- return /** @type {TargetsArray} */([targets]);
-}
-
-/**
- * @overload
- * @param {DOMTargetsParam} targets
- * @return {DOMTargetsArray}
- *
- * @overload
- * @param {JSTargetsParam} targets
- * @return {JSTargetsArray}
- *
- * @overload
- * @param {TargetsParam} targets
- * @return {TargetsArray}
- *
- * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
- */
-function registerTargets(targets) {
- const parsedTargetsArray = parseTargets(targets);
- const parsedTargetsLength = parsedTargetsArray.length;
- if (parsedTargetsLength) {
- for (let i = 0; i < parsedTargetsLength; i++) {
- const target = parsedTargetsArray[i];
- if (!target[isRegisteredTargetSymbol]) {
- target[isRegisteredTargetSymbol] = true;
- const isSvgType = isSvg(target);
- const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType;
- if (isDom) {
- target[isDomSymbol] = true;
- target[isSvgSymbol] = isSvgType;
- target[transformsSymbol] = {};
- }
- }
- }
- }
- return parsedTargetsArray;
-}
-
-
-
-
-/**
- * @param {TargetsParam} path
- * @return {SVGGeometryElement|undefined}
- */
-const getPath = path => {
- const parsedTargets = parseTargets(path);
- const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
- if (!$parsedSvg || !isSvg($parsedSvg)) return;
- return $parsedSvg;
-};
-
-/**
- * @param {TargetsParam} path2
- * @param {Number} [precision]
- * @return {FunctionValue}
- */
-const morphTo = (path2, precision = .33) => ($path1) => {
- const $path2 = /** @type {SVGGeometryElement} */(getPath(path2));
- if (!$path2) return;
- const isPath = $path1.tagName === 'path';
- const separator = isPath ? ' ' : ',';
- const previousPoints = $path1[morphPointsSymbol];
- if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
-
- let v1 = '', v2 = '';
-
- if (!precision) {
- v1 = $path1.getAttribute(isPath ? 'd' : 'points');
- v2 = $path2.getAttribute(isPath ? 'd' : 'points');
- } else {
- const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
- const length2 = $path2.getTotalLength();
- const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
- for (let i = 0; i < maxPoints; i++) {
- const t = i / (maxPoints - 1);
- const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
- const pointOnPath2 = $path2.getPointAtLength(length2 * t);
- const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
- v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
- v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
- }
- }
-
- $path1[morphPointsSymbol] = v2;
-
- return [v1, v2];
-};
-
-/**
- * @param {SVGGeometryElement} [$el]
- * @return {Number}
- */
-const getScaleFactor = $el => {
- let scaleFactor = 1;
- if ($el && $el.getCTM) {
- const ctm = $el.getCTM();
- if (ctm) {
- const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
- const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
- scaleFactor = (scaleX + scaleY) / 2;
- }
- }
- return scaleFactor;
-};
-
-/**
- * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
- * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
- * @param {number} start - Starting position (0-1)
- * @param {number} end - Ending position (0-1)
- * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
- */
-const createDrawableProxy = ($el, start, end) => {
- const pathLength = K;
- const computedStyles = getComputedStyle($el);
- const strokeLineCap = computedStyles.strokeLinecap;
- // @ts-ignore
- const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
- let currentCap = strokeLineCap;
-
- const proxy = new Proxy($el, {
- get(target, property) {
- const value = target[property];
- if (property === proxyTargetSymbol) return target;
- if (property === 'setAttribute') {
- return (...args) => {
- if (args[0] === 'draw') {
- const value = args[1];
- const values = value.split(' ');
- const v1 = +values[0];
- const v2 = +values[1];
- // TOTO: Benchmark if performing two slices is more performant than one split
- // const spaceIndex = value.indexOf(' ');
- // const v1 = round(+value.slice(0, spaceIndex), precision);
- // const v2 = round(+value.slice(spaceIndex + 1), precision);
- const scaleFactor = getScaleFactor($scalled);
- const os = v1 * -1e3 * scaleFactor;
- const d1 = (v2 * pathLength * scaleFactor) + os;
- const d2 = (pathLength * scaleFactor +
- ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
- if (strokeLineCap !== 'butt') {
- const newCap = v1 === v2 ? 'butt' : strokeLineCap;
- if (currentCap !== newCap) {
- target.style.strokeLinecap = `${newCap}`;
- currentCap = newCap;
- }
- }
- target.setAttribute('stroke-dashoffset', `${os}`);
- target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
- }
- return Reflect.apply(value, target, args);
- };
- }
-
- if (isFnc(value)) {
- return (...args) => Reflect.apply(value, target, args);
- } else {
- return value;
- }
- }
- });
-
- if ($el.getAttribute('pathLength') !== `${pathLength}`) {
- $el.setAttribute('pathLength', `${pathLength}`);
- proxy.setAttribute('draw', `${start} ${end}`);
- }
-
- return /** @type {DrawableSVGGeometry} */(proxy);
-};
-
-/**
- * Creates drawable proxies for multiple SVG elements.
- * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
- * @param {number} [start=0] - Starting position (0-1)
- * @param {number} [end=0] - Ending position (0-1)
- * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
- */
-const createDrawable = (selector, start = 0, end = 0) => {
- const els = parseTargets(selector);
- return els.map($el => createDrawableProxy(
- /** @type {SVGGeometryElement} */($el),
- start,
- end
- ));
-};
-
-// Motion path animation
-
-/**
- * @param {SVGGeometryElement} $path
- * @param {Number} progress
- * @param {Number}lookup
- * @return {DOMPoint}
- */
-const getPathPoint = ($path, progress, lookup = 0) => {
- return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0);
-};
-
-/**
- * @param {SVGGeometryElement} $path
- * @param {String} pathProperty
- * @return {FunctionValue}
- */
-const getPathProgess = ($path, pathProperty) => {
- return $el => {
- const totalLength = +($path.getTotalLength());
- const inSvg = $el[isSvgSymbol];
- const ctm = $path.getCTM();
- /** @type {TweenObjectValue} */
- return {
- from: 0,
- to: totalLength,
- /** @type {TweenModifier} */
- modifier: progress => {
- if (pathProperty === 'a') {
- const p0 = getPathPoint($path, progress, -1);
- const p1 = getPathPoint($path, progress, 1);
- return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI;
- } else {
- const p = getPathPoint($path, progress, 0);
- return pathProperty === 'x' ?
- inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
- inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
- }
- }
- }
- }
-};
-
-/**
- * @param {TargetsParam} path
- */
-const createMotionPath = path => {
- const $path = getPath(path);
- if (!$path) return;
- return {
- translateX: getPathProgess($path, 'x'),
- translateY: getPathProgess($path, 'y'),
- rotate: getPathProgess($path, 'a'),
- }
-};
-
-// Check for valid SVG attribute
-
-const cssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
-
-/**
- * @param {Target} el
- * @param {String} propertyName
- * @return {Boolean}
- */
-const isValidSVGAttribute = (el, propertyName) => {
- // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform
- if (cssReservedProperties.includes(propertyName)) return false;
- if (el.getAttribute(propertyName) || propertyName in el) {
- if (propertyName === 'scale') { // Scale
- const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
- // Only consider scale as a valid SVG attribute on filter element
- return elParentNode && elParentNode.tagName === 'filter';
- }
- return true;
- }
-};
-
-const svg = {
- morphTo,
- createMotionPath,
- createDrawable,
-};
-
-
-
-
-/**
- * RGB / RGBA Color value string -> RGBA values array
- * @param {String} rgbValue
- * @return {ColorArray}
- */
-const rgbToRgba = rgbValue => {
- const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue);
- const a = !isUnd(rgba[4]) ? +rgba[4] : 1;
- return [
- +rgba[1],
- +rgba[2],
- +rgba[3],
- a
- ]
-};
-
-/**
- * HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array
- * @param {String} hexValue
- * @return {ColorArray}
- */
-const hexToRgba = hexValue => {
- const hexLength = hexValue.length;
- const isShort = hexLength === 4 || hexLength === 5;
- return [
- +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]),
- +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]),
- +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]),
- ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1)
- ]
-};
-
-/**
- * @param {Number} p
- * @param {Number} q
- * @param {Number} t
- * @return {Number}
- */
-const hue2rgb = (p, q, t) => {
- if (t < 0) t += 1;
- if (t > 1) t -= 1;
- return t < 1 / 6 ? p + (q - p) * 6 * t :
- t < 1 / 2 ? q :
- t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 :
- p;
-};
-
-/**
- * HSL / HSLA Color value string -> RGBA values array
- * @param {String} hslValue
- * @return {ColorArray}
- */
-const hslToRgba = hslValue => {
- const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue);
- const h = +hsla[1] / 360;
- const s = +hsla[2] / 100;
- const l = +hsla[3] / 100;
- const a = !isUnd(hsla[4]) ? +hsla[4] : 1;
- let r, g, b;
- if (s === 0) {
- r = g = b = l;
- } else {
- const q = l < .5 ? l * (1 + s) : l + s - l * s;
- const p = 2 * l - q;
- r = round(hue2rgb(p, q, h + 1 / 3) * 255, 0);
- g = round(hue2rgb(p, q, h) * 255, 0);
- b = round(hue2rgb(p, q, h - 1 / 3) * 255, 0);
- }
- return [r, g, b, a];
-};
-
-/**
- * All in one color converter that converts a color string value into an array of RGBA values
- * @param {String} colorString
- * @return {ColorArray}
- */
-const convertColorStringValuesToRgbaArray = colorString => {
- return isRgb(colorString) ? rgbToRgba(colorString) :
- isHex(colorString) ? hexToRgba(colorString) :
- isHsl(colorString) ? hslToRgba(colorString) :
- [0, 0, 0, 1];
-};
-
-
-
-
-/**
- * @template T, D
- * @param {T|undefined} targetValue
- * @param {D} defaultValue
- * @return {T|D}
- */
-const setValue = (targetValue, defaultValue) => {
- return isUnd(targetValue) ? defaultValue : targetValue;
-};
-
-/**
- * @param {TweenPropValue} value
- * @param {Target} target
- * @param {Number} index
- * @param {Number} total
- * @param {Object} [store]
- * @return {any}
- */
-const getFunctionValue = (value, target, index, total, store) => {
- if (isFnc(value)) {
- const func = () => {
- const computed = /** @type {Function} */(value)(target, index, total);
- // Fallback to 0 if the function returns undefined / NaN / null / false / 0
- return !isNaN(+computed) ? +computed : computed || 0;
- };
- if (store) {
- store.func = func;
- }
- return func();
- } else {
- return value;
- }
-};
-
-/**
- * @param {Target} target
- * @param {String} prop
- * @return {tweenTypes}
- */
-const getTweenType = (target, prop) => {
- return !target[isDomSymbol] ? tweenTypes.OBJECT :
- // Handle SVG attributes
- target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE :
- // Handle CSS Transform properties differently than CSS to allow individual animations
- validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM :
- // CSS variables
- stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR :
- // All other CSS properties
- prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS :
- // Handle other DOM Attributes
- prop in target ? tweenTypes.OBJECT :
- tweenTypes.ATTRIBUTE;
-};
-
-/**
- * @param {DOMTarget} target
- * @param {String} propName
- * @param {Object} animationInlineStyles
- * @return {String}
- */
-const getCSSValue = (target, propName, animationInlineStyles) => {
- const inlineStyles = target.style[propName];
- if (inlineStyles && animationInlineStyles) {
- animationInlineStyles[propName] = inlineStyles;
- }
- const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName);
- return value === 'auto' ? '0' : value;
-};
-
-/**
- * @param {Target} target
- * @param {String} propName
- * @param {tweenTypes} [tweenType]
- * @param {Object|void} [animationInlineStyles]
- * @return {String|Number}
- */
-const getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => {
- const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName);
- return type === tweenTypes.OBJECT ? target[propName] || 0 :
- type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) :
- type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) :
- type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() :
- getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles);
-};
-
-/**
- * @param {Number} x
- * @param {Number} y
- * @param {String} operator
- * @return {Number}
- */
-const getRelativeValue = (x, y, operator) => {
- return operator === '-' ? x - y :
- operator === '+' ? x + y :
- x * y;
-};
-
-/** @return {TweenDecomposedValue} */
-const createDecomposedValueTargetObject = () => {
- return {
- /** @type {valueTypes} */
- t: valueTypes.NUMBER,
- n: 0,
- u: null,
- o: null,
- d: null,
- s: null,
- }
-};
-
-/**
- * @param {String|Number} rawValue
- * @param {TweenDecomposedValue} targetObject
- * @return {TweenDecomposedValue}
- */
-const decomposeRawValue = (rawValue, targetObject) => {
- /** @type {valueTypes} */
- targetObject.t = valueTypes.NUMBER;
- targetObject.n = 0;
- targetObject.u = null;
- targetObject.o = null;
- targetObject.d = null;
- targetObject.s = null;
- if (!rawValue) return targetObject;
- const num = +rawValue;
- if (!isNaN(num)) {
- // It's a number
- targetObject.n = num;
- return targetObject;
- } else {
- // let str = /** @type {String} */(rawValue).trim();
- let str = /** @type {String} */(rawValue);
- // Parsing operators (+=, -=, *=) manually is much faster than using regex here
- if (str[1] === '=') {
- targetObject.o = str[0];
- str = str.slice(2);
- }
- // Skip exec regex if the value type is complex or color to avoid long regex backtracking
- const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str);
- if (unitMatch) {
- // Has a number and a unit
- targetObject.t = valueTypes.UNIT;
- targetObject.n = +unitMatch[1];
- targetObject.u = unitMatch[2];
- return targetObject;
- } else if (targetObject.o) {
- // Has an operator (+=, -=, *=)
- targetObject.n = +str;
- return targetObject;
- } else if (isCol(str)) {
- // Is a color
- targetObject.t = valueTypes.COLOR;
- targetObject.d = convertColorStringValuesToRgbaArray(str);
- return targetObject;
- } else {
- // Is a more complex string (generally svg coords, calc() or filters CSS values)
- const matchedNumbers = str.match(digitWithExponentRgx);
- targetObject.t = valueTypes.COMPLEX;
- targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : [];
- targetObject.s = str.split(digitWithExponentRgx) || [];
- return targetObject;
- }
- }
-};
-
-/**
- * @param {Tween} tween
- * @param {TweenDecomposedValue} targetObject
- * @return {TweenDecomposedValue}
- */
-const decomposeTweenValue = (tween, targetObject) => {
- targetObject.t = tween._valueType;
- targetObject.n = tween._toNumber;
- targetObject.u = tween._unit;
- targetObject.o = null;
- targetObject.d = cloneArray(tween._toNumbers);
- targetObject.s = cloneArray(tween._strings);
- return targetObject;
-};
-
-const decomposedOriginalValue = createDecomposedValueTargetObject();
-
-
-
-
-const lookups = {
- /** @type {TweenReplaceLookups} */
- _rep: new WeakMap(),
- /** @type {TweenAdditiveLookups} */
- _add: new Map(),
-};
-
-/**
- * @param {Target} target
- * @param {String} property
- * @param {String} lookup
- * @return {TweenPropertySiblings}
- */
-const getTweenSiblings = (target, property, lookup = '_rep') => {
- const lookupMap = lookups[lookup];
- let targetLookup = lookupMap.get(target);
- if (!targetLookup) {
- targetLookup = {};
- lookupMap.set(target, targetLookup);
- }
- return targetLookup[property] ? targetLookup[property] : targetLookup[property] = {
- _head: null,
- _tail: null,
- }
-};
-
-/**
- * @param {Tween} p
- * @param {Tween} c
- * @return {Number|Boolean}
- */
-const addTweenSortMethod = (p, c) => {
- return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime;
-};
-
-/**
- * @param {Tween} tween
- */
-const overrideTween = tween => {
- tween._isOverlapped = 1;
- tween._isOverridden = 1;
- tween._changeDuration = minValue;
- tween._currentTime = minValue;
-};
-
-/**
- * @param {Tween} tween
- * @param {TweenPropertySiblings} siblings
- * @return {Tween}
- */
-const composeTween = (tween, siblings) => {
-
- const tweenCompositionType = tween._composition;
-
- // Handle replaced tweens
-
- if (tweenCompositionType === compositionTypes.replace) {
-
- const tweenAbsStartTime = tween._absoluteStartTime;
-
- addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep');
-
- const prevSibling = tween._prevRep;
-
- // Update the previous siblings for composition replace tweens
-
- if (prevSibling) {
-
- const prevParent = prevSibling.parent;
- const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration;
-
- // Handle looped animations tween
-
- if (
- // Check if the previous tween is from a different animation
- tween.parent.id !== prevParent.id &&
- // Check if the animation has loops
- prevParent.iterationCount> 1 &&
- // Check if _absoluteChangeEndTime of last loop overlaps the current tween
- prevAbsEndTime + (prevParent.duration - prevParent.iterationDuration) > tweenAbsStartTime
- ) {
-
- // TODO: Find a way to only override the iterations overlapping with the tween
- overrideTween(prevSibling);
-
- let prevPrevSibling = prevSibling._prevRep;
-
- // If the tween was part of a set of keyframes, override its siblings
- while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) {
- overrideTween(prevPrevSibling);
- prevPrevSibling = prevPrevSibling._prevRep;
- }
-
- }
-
- const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay;
-
- if (prevAbsEndTime > absoluteUpdateStartTime) {
-
- const prevChangeStartTime = prevSibling._startTime;
- const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration);
-
- prevSibling._changeDuration = absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime;
- prevSibling._currentTime = prevSibling._changeDuration;
- prevSibling._isOverlapped = 1;
-
- if (prevSibling._changeDuration < minValue) {
- overrideTween(prevSibling);
- }
- }
-
- // Pause (and cancel) the parent if it only contains overlapped tweens
-
- let pausePrevParentAnimation = true;
-
- forEachChildren(prevParent, (/** @type Tween */t) => {
- if (!t._isOverlapped) pausePrevParentAnimation = false;
- });
-
- if (pausePrevParentAnimation) {
- const prevParentTL = prevParent.parent;
- if (prevParentTL) {
- let pausePrevParentTL = true;
- forEachChildren(prevParentTL, (/** @type JSAnimation */a) => {
- if (a !== prevParent) {
- forEachChildren(a, (/** @type Tween */t) => {
- if (!t._isOverlapped) pausePrevParentTL = false;
- });
- }
- });
- if (pausePrevParentTL) {
- prevParentTL.cancel();
- }
- } else {
- prevParent.cancel();
- // Previously, calling .cancel() on a timeline child would affect the render order of other children
- // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop
- // This is no longer needed since timeline tween composition is now handled separatly
- // Keeping this here for reference
- // prevParent.completed = true;
- // prevParent.pause();
- }
- }
-
- }
-
- // let nextSibling = tween._nextRep;
-
- // // All the next siblings are automatically overridden
-
- // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) {
- // while (nextSibling) {
- // overrideTween(nextSibling);
- // nextSibling = nextSibling._nextRep;
- // }
- // }
-
- // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) {
- // while (nextSibling) {
- // overrideTween(nextSibling);
- // console.log(tween.id, nextSibling.id);
- // nextSibling = nextSibling._nextRep;
- // }
- // }
-
- // Handle additive tweens composition
-
- } else if (tweenCompositionType === compositionTypes.blend) {
-
- const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add');
- const additiveAnimation = addAdditiveAnimation(lookups._add);
-
- let lookupTween = additiveTweenSiblings._head;
-
- if (!lookupTween) {
- lookupTween = { ...tween };
- lookupTween._composition = compositionTypes.replace;
- lookupTween._updateDuration = minValue;
- lookupTween._startTime = 0;
- lookupTween._numbers = cloneArray(tween._fromNumbers);
- lookupTween._number = 0;
- lookupTween._next = null;
- lookupTween._prev = null;
- addChild(additiveTweenSiblings, lookupTween);
- addChild(additiveAnimation, lookupTween);
- }
-
- // Convert the values of TO to FROM and set TO to 0
-
- const toNumber = tween._toNumber;
- tween._fromNumber = lookupTween._fromNumber - toNumber;
- tween._toNumber = 0;
- tween._numbers = cloneArray(tween._fromNumbers);
- tween._number = 0;
- lookupTween._fromNumber = toNumber;
-
- if (tween._toNumbers) {
- const toNumbers = cloneArray(tween._toNumbers);
- if (toNumbers) {
- toNumbers.forEach((value, i) => {
- tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value;
- tween._toNumbers[i] = 0;
- });
- }
- lookupTween._fromNumbers = toNumbers;
- }
-
- addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd');
-
- }
-
- return tween;
-
-};
-
-/**
- * @param {Tween} tween
- * @return {Tween}
- */
-const removeTweenSliblings = tween => {
- const tweenComposition = tween._composition;
- if (tweenComposition !== compositionTypes.none) {
- const tweenTarget = tween.target;
- const tweenProperty = tween.property;
- const replaceTweensLookup = lookups._rep;
- const replaceTargetProps = replaceTweensLookup.get(tweenTarget);
- const tweenReplaceSiblings = replaceTargetProps[tweenProperty];
- removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep');
- if (tweenComposition === compositionTypes.blend) {
- const addTweensLookup = lookups._add;
- const addTargetProps = addTweensLookup.get(tweenTarget);
- if (!addTargetProps) return;
- const additiveTweenSiblings = addTargetProps[tweenProperty];
- const additiveAnimation = additive.animation;
- removeChild(additiveTweenSiblings, tween, '_prevAdd', '_nextAdd');
- // If only one tween is left in the additive lookup, it's the tween lookup
- const lookupTween = additiveTweenSiblings._head;
- if (lookupTween && lookupTween === additiveTweenSiblings._tail) {
- removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd');
- removeChild(additiveAnimation, lookupTween);
- let shouldClean = true;
- for (let prop in addTargetProps) {
- if (addTargetProps[prop]._head) {
- shouldClean = false;
- break;
- }
- }
- if (shouldClean) {
- addTweensLookup.delete(tweenTarget);
- }
- }
- }
- }
- return tween;
-};
-
-
-
-
-/**
- * @param {Timer} timer
- * @return {Timer}
- */
-const resetTimerProperties = timer => {
- timer.paused = true;
- timer.began = false;
- timer.completed = false;
- return timer;
-};
-
-/**
- * @param {Timer} timer
- * @return {Timer}
- */
-const reviveTimer = timer => {
- if (!timer._cancelled) return timer;
- if (timer._hasChildren) {
- forEachChildren(timer, reviveTimer);
- } else {
- forEachChildren(timer, (/** @type {Tween} tween*/tween) => {
- if (tween._composition !== compositionTypes.none) {
- composeTween(tween, getTweenSiblings(tween.target, tween.property));
- }
- });
- }
- timer._cancelled = 0;
- return timer;
-};
-
-let timerId = 0;
-
-/**
- * Base class used to create Timers, Animations and Timelines
- */
-class Timer extends Clock {
- /**
- * @param {TimerParams} [parameters]
- * @param {Timeline} [parent]
- * @param {Number} [parentPosition]
- */
- constructor(parameters = {}, parent = null, parentPosition = 0) {
-
- super(0);
-
- const {
- id,
- delay,
- duration,
- reversed,
- alternate,
- loop,
- loopDelay,
- autoplay,
- frameRate,
- playbackRate,
- onComplete,
- onLoop,
- onPause,
- onBegin,
- onBeforeUpdate,
- onUpdate,
- } = parameters;
-
- const timerInitTime = parent ? 0 : engine._elapsedTime;
- const timerDefaults = parent ? parent.defaults : globals.defaults;
- const timerDelay = /** @type {Number} */(isFnc(delay) || isUnd(delay) ? timerDefaults.delay : +delay);
- const timerDuration = isFnc(duration) || isUnd(duration) ? Infinity : +duration;
- const timerLoop = setValue(loop, timerDefaults.loop);
- const timerLoopDelay = setValue(loopDelay, timerDefaults.loopDelay);
- const timerIterationCount = timerLoop === true ||
- timerLoop === Infinity ||
- /** @type {Number} */(timerLoop) < 0 ? Infinity :
- /** @type {Number} */(timerLoop) + 1;
-
- let offsetPosition = 0;
-
- if (parent) {
- offsetPosition = parentPosition;
- } else {
- let startTime = now();
- // Make sure to tick the engine once if suspended to avoid big gaps with the following offsetPosition calculation
- if (engine.paused) {
- engine.requestTick(startTime);
- startTime = engine._elapsedTime;
- }
- offsetPosition = startTime - engine._startTime;
- }
-
- // Timer's parameters
- this.id = !isUnd(id) ? id : ++timerId;
- /** @type {Timeline} */
- this.parent = parent;
- // Total duration of the timer
- this.duration = clampInfinity(((timerDuration + timerLoopDelay) * timerIterationCount) - timerLoopDelay) || minValue;
- /** @type {Boolean} */
- this.backwards = false;
- /** @type {Boolean} */
- this.paused = true;
- /** @type {Boolean} */
- this.began = false;
- /** @type {Boolean} */
- this.completed = false;
- /** @type {Callback<this>} */
- this.onBegin = onBegin || timerDefaults.onBegin;
- /** @type {Callback<this>} */
- this.onBeforeUpdate = onBeforeUpdate || timerDefaults.onBeforeUpdate;
- /** @type {Callback<this>} */
- this.onUpdate = onUpdate || timerDefaults.onUpdate;
- /** @type {Callback<this>} */
- this.onLoop = onLoop || timerDefaults.onLoop;
- /** @type {Callback<this>} */
- this.onPause = onPause || timerDefaults.onPause;
- /** @type {Callback<this>} */
- this.onComplete = onComplete || timerDefaults.onComplete;
- /** @type {Number} */
- this.iterationDuration = timerDuration; // Duration of one loop
- /** @type {Number} */
- this.iterationCount = timerIterationCount; // Number of loops
- /** @type {Boolean|ScrollObserver} */
- this._autoplay = parent ? false : setValue(autoplay, timerDefaults.autoplay);
- /** @type {Number} */
- this._offset = offsetPosition;
- /** @type {Number} */
- this._delay = timerDelay;
- /** @type {Number} */
- this._loopDelay = timerLoopDelay;
- /** @type {Number} */
- this._iterationTime = 0;
- /** @type {Number} */
- this._currentIteration = 0; // Current loop index
- /** @type {Function} */
- this._resolve = noop; // Used by .then()
- /** @type {Boolean} */
- this._running = false;
- /** @type {Number} */
- this._reversed = +setValue(reversed, timerDefaults.reversed);
- /** @type {Number} */
- this._reverse = this._reversed;
- /** @type {Number} */
- this._cancelled = 0;
- /** @type {Boolean} */
- this._alternate = setValue(alternate, timerDefaults.alternate);
- /** @type {Renderable} */
- this._prev = null;
- /** @type {Renderable} */
- this._next = null;
-
- // Clock's parameters
- /** @type {Number} */
- this._elapsedTime = timerInitTime;
- /** @type {Number} */
- this._startTime = timerInitTime;
- /** @type {Number} */
- this._lastTime = timerInitTime;
- /** @type {Number} */
- this._fps = setValue(frameRate, timerDefaults.frameRate);
- /** @type {Number} */
- this._speed = setValue(playbackRate, timerDefaults.playbackRate);
- }
-
- get cancelled() {
- return !!this._cancelled;
- }
-
- /** @param {Boolean} cancelled */
- set cancelled(cancelled) {
- cancelled ? this.cancel() : this.reset(1).play();
- }
-
- get currentTime() {
- return clamp(round(this._currentTime, globals.precision), -this._delay, this.duration);
- }
-
- /** @param {Number} time */
- set currentTime(time) {
- const paused = this.paused;
- // Pausing the timer is necessary to avoid time jumps on a running instance
- this.pause().seek(+time);
- if (!paused) this.resume();
- }
-
- get iterationCurrentTime() {
- return round(this._iterationTime, globals.precision);
- }
-
- /** @param {Number} time */
- set iterationCurrentTime(time) {
- this.currentTime = (this.iterationDuration * this._currentIteration) + time;
- }
-
- get progress() {
- return clamp(round(this._currentTime / this.duration, 10), 0, 1);
- }
-
- /** @param {Number} progress */
- set progress(progress) {
- this.currentTime = this.duration * progress;
- }
-
- get iterationProgress() {
- return clamp(round(this._iterationTime / this.iterationDuration, 10), 0, 1);
- }
-
- /** @param {Number} progress */
- set iterationProgress(progress) {
- const iterationDuration = this.iterationDuration;
- this.currentTime = (iterationDuration * this._currentIteration) + (iterationDuration * progress);
- }
-
- get currentIteration() {
- return this._currentIteration;
- }
-
- /** @param {Number} iterationCount */
- set currentIteration(iterationCount) {
- this.currentTime = (this.iterationDuration * clamp(+iterationCount, 0, this.iterationCount - 1));
- }
-
- get reversed() {
- return !!this._reversed;
- }
-
- /** @param {Boolean} reverse */
- set reversed(reverse) {
- reverse ? this.reverse() : this.play();
- }
-
- get speed() {
- return super.speed;
- }
-
- /** @param {Number} playbackRate */
- set speed(playbackRate) {
- super.speed = playbackRate;
- this.resetTime();
- }
-
- /**
- * @param {Number} internalRender
- * @return {this}
- */
- reset(internalRender = 0) {
- // If cancelled, revive the timer before rendering in order to have propertly composed tweens siblings
- reviveTimer(this);
- if (this._reversed && !this._reverse) this.reversed = false;
- // Rendering before updating the completed flag to prevent skips and to make sure the properties are not overridden
- // Setting the iterationTime at the end to force the rendering to happend backwards, otherwise calling .reset() on Timelines might not render children in the right order
- // NOTE: This is only required for Timelines and might be better to move to the Timeline class?
- this._iterationTime = this.iterationDuration;
- // Set tickMode to tickModes.FORCE to force rendering
- tick(this, 0, 1, internalRender, tickModes.FORCE);
- // Reset timer properties after revive / render to make sure the props are not updated again
- resetTimerProperties(this);
- // Also reset children properties
- if (this._hasChildren) {
- forEachChildren(this, resetTimerProperties);
- }
- return this;
- }
-
- /**
- * @param {Number} internalRender
- * @return {this}
- */
- init(internalRender = 0) {
- this.fps = this._fps;
- this.speed = this._speed;
- // Manually calling .init() on timelines should render all children intial state
- // Forces all children to render once then render to 0 when reseted
- if (!internalRender && this._hasChildren) {
- tick(this, this.duration, 1, internalRender, tickModes.FORCE);
- }
- this.reset(internalRender);
- // Make sure to set autoplay to false to child timers so it doesn't attempt to autoplay / link
- const autoplay = this._autoplay;
- if (autoplay === true) {
- this.resume();
- } else if (autoplay && !isUnd(/** @type {ScrollObserver} */(autoplay).linked)) {
- /** @type {ScrollObserver} */(autoplay).link(this);
- }
- return this;
- }
-
- /** @return {this} */
- resetTime() {
- const timeScale = 1 / (this._speed * engine._speed);
- this._startTime = now() - (this._currentTime + this._delay) * timeScale;
- return this;
- }
-
- /** @return {this} */
- pause() {
- if (this.paused) return this;
- this.paused = true;
- this.onPause(this);
- return this;
- }
-
- /** @return {this} */
- resume() {
- if (!this.paused) return this;
- this.paused = false;
- // We can safely imediatly render a timer that has no duration and no children
- if (this.duration <= minValue && !this._hasChildren) {
- tick(this, minValue, 0, 0, tickModes.FORCE);
- } else {
- if (!this._running) {
- addChild(engine, this);
- engine._hasChildren = true;
- this._running = true;
- }
- this.resetTime();
- // Forces the timer to advance by at least one frame when the next tick occurs
- this._startTime -= 12;
- engine.wake();
- }
- return this;
- }
-
- /** @return {this} */
- restart() {
- return this.reset(0).resume();
- }
-
- /**
- * @param {Number} time
- * @param {Boolean|Number} [muteCallbacks]
- * @param {Boolean|Number} [internalRender]
- * @return {this}
- */
- seek(time, muteCallbacks = 0, internalRender = 0) {
- // Recompose the tween siblings in case the timer has been cancelled
- reviveTimer(this);
- // If you seek a completed animation, otherwise the next play will starts at 0
- this.completed = false;
- const isPaused = this.paused;
- this.paused = true;
- // timer, time, muteCallbacks, internalRender, tickMode
- tick(this, time + this._delay, ~~muteCallbacks, ~~internalRender, tickModes.AUTO);
- return isPaused ? this : this.resume();
- }
-
- /** @return {this} */
- alternate() {
- const reversed = this._reversed;
- const count = this.iterationCount;
- const duration = this.iterationDuration;
- // Calculate the maximum iterations possible given the iteration duration
- const iterations = count === Infinity ? floor(maxValue / duration) : count;
- this._reversed = +(this._alternate && !(iterations % 2) ? reversed : !reversed);
- if (count === Infinity) {
- // Handle infinite loops to loop on themself
- this.iterationProgress = this._reversed ? 1 - this.iterationProgress : this.iterationProgress;
- } else {
- this.seek((duration * iterations) - this._currentTime);
- }
- this.resetTime();
- return this;
- }
-
- /** @return {this} */
- play() {
- if (this._reversed) this.alternate();
- return this.resume();
- }
-
- /** @return {this} */
- reverse() {
- if (!this._reversed) this.alternate();
- return this.resume();
- }
-
- // TODO: Move all the animation / tweens / children related code to Animation / Timeline
-
- /** @return {this} */
- cancel() {
- if (this._hasChildren) {
- forEachChildren(this, (/** @type {Renderable} */child) => child.cancel(), true);
- } else {
- forEachChildren(this, removeTweenSliblings);
- }
- this._cancelled = 1;
- // Pausing the timer removes it from the engine
- return this.pause();
- }
-
- /**
- * @param {Number} newDuration
- * @return {this}
- */
- stretch(newDuration) {
- const currentDuration = this.duration;
- const normlizedDuration = normalizeTime(newDuration);
- if (currentDuration === normlizedDuration) return this;
- const timeScale = newDuration / currentDuration;
- const isSetter = newDuration <= minValue;
- this.duration = isSetter ? minValue : normlizedDuration;
- this.iterationDuration = isSetter ? minValue : normalizeTime(this.iterationDuration * timeScale);
- this._offset *= timeScale;
- this._delay *= timeScale;
- this._loopDelay *= timeScale;
- return this;
- }
-
- /**
- * Cancels the timer by seeking it back to 0 and reverting the attached scroller if necessary
- * @return {this}
- */
- revert() {
- tick(this, 0, 1, 0, tickModes.AUTO);
- const ap = /** @type {ScrollObserver} */(this._autoplay);
- if (ap && ap.linked && ap.linked === this) ap.revert();
- return this.cancel();
- }
-
- /**
- * Imediatly completes the timer, cancels it and triggers the onComplete callback
- * @return {this}
- */
- complete() {
- return this.seek(this.duration).cancel();
- }
-
- /**
- * @param {Callback<this>} [callback]
- * @return {Promise}
- */
- then(callback = noop) {
- const then = this.then;
- const onResolve = () => {
- // this.then = null prevents infinite recursion if returned by an async function
- // https://github.com/juliangarnierorg/anime-beta/issues/26
- this.then = null;
- callback(this);
- this.then = then;
- this._resolve = noop;
- };
- return new Promise(r => {
- this._resolve = () => r(onResolve());
- // Make sure to resolve imediatly if the timer has already completed
- if (this.completed) this._resolve();
- return this;
- });
- }
-
-}
-
-
-
-
-/** @type {EasingFunction} */
-const none = t => t;
-
-// Cubic Bezier solver adapted from https://github.com/gre/bezier-ease © Gaëtan Renaudeau
-
-/**
- * @param {Number} aT
- * @param {Number} aA1
- * @param {Number} aA2
- * @return {Number}
- */
-const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT;
-
-/**
- * @param {Number} aX
- * @param {Number} mX1
- * @param {Number} mX2
- * @return {Number}
- */
-const binarySubdivide = (aX, mX1, mX2) => {
- let aA = 0, aB = 1, currentX, currentT, i = 0;
- do {
- currentT = aA + (aB - aA) / 2;
- currentX = calcBezier(currentT, mX1, mX2) - aX;
- if (currentX > 0) {
- aB = currentT;
- } else {
- aA = currentT;
- }
- } while (abs(currentX) > .0000001 && ++i < 100);
- return currentT;
-};
-
-/**
- * @param {Number} [mX1]
- * @param {Number} [mY1]
- * @param {Number} [mX2]
- * @param {Number} [mY2]
- * @return {EasingFunction}
- */
-
-const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none :
- t => t === 0 || t === 1 ? t :
- calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
-
-/**
- * Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
- * Only covers 'end' and 'start' jumpterms
- * @param {Number} steps
- * @param {Boolean} [fromStart]
- * @return {EasingFunction}
- */
-const steps = (steps = 10, fromStart) => {
- const roundMethod = fromStart ? ceil : floor;
- return t => roundMethod(clamp(t, 0, 1) * steps) * (1 / steps);
-};
-
-/**
- * Without parameters, the linear function creates a non-eased transition.
- * Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points.
- * @param {...String|Number} [args] - Points
- * @return {EasingFunction}
- */
-const linear = (...args) => {
- const argsLength = args.length;
- if (!argsLength) return none;
- const totalPoints = argsLength - 1;
- const firstArg = args[0];
- const lastArg = args[totalPoints];
- const xPoints = [0];
- const yPoints = [parseNumber(firstArg)];
- for (let i = 1; i < totalPoints; i++) {
- const arg = args[i];
- const splitValue = isStr(arg) ?
- /** @type {String} */(arg).trim().split(' ') :
- [arg];
- const value = splitValue[0];
- const percent = splitValue[1];
- xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints);
- yPoints.push(parseNumber(value));
- }
- yPoints.push(parseNumber(lastArg));
- xPoints.push(1);
- return function easeLinear(t) {
- for (let i = 1, l = xPoints.length; i < l; i++) {
- const currentX = xPoints[i];
- if (t <= currentX) {
- const prevX = xPoints[i - 1];
- const prevY = yPoints[i - 1];
- return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX);
- }
- }
- return yPoints[yPoints.length - 1];
- }
-};
-
-/**
- * Generate random steps
- * @param {Number} [length] - The number of steps
- * @param {Number} [randomness] - How strong the randomness is
- * @return {EasingFunction}
- */
-const irregular = (length = 10, randomness = 1) => {
- const values = [0];
- const total = length - 1;
- for (let i = 1; i < total; i++) {
- const previousValue = values[i - 1];
- const spacing = i / total;
- const segmentEnd = (i + 1) / total;
- const randomVariation = spacing + (segmentEnd - spacing) * Math.random();
- // Mix the even spacing and random variation based on the randomness parameter
- const randomValue = spacing * (1 - randomness) + randomVariation * randomness;
- values.push(clamp(randomValue, previousValue, 1));
- }
- values.push(1);
- return linear(...values);
-};
-
-// Easing functions adapted from http://www.robertpenner.com/ease © Robert Penner
-
-/**
- * @callback PowerEasing
- * @param {Number|String} [power=1.675]
- * @return {EasingFunction}
- */
-
-/**
- * @callback BackEasing
- * @param {Number|String} [overshoot=1.70158]
- * @return {EasingFunction}
- */
-
-/**
- * @callback ElasticEasing
- * @param {Number|String} [amplitude=1]
- * @param {Number|String} [period=.3]
- * @return {EasingFunction}
- */
-
-/**
- * @callback EaseFactory
- * @param {Number|String} [paramA]
- * @param {Number|String} [paramB]
- * @return {EasingFunction|Number}
- */
-
-/** @typedef {PowerEasing|BackEasing|ElasticEasing} EasesFactory */
-
-const halfPI = PI / 2;
-const doublePI = PI * 2;
-/** @type {PowerEasing} */
-const easeInPower = (p = 1.68) => t => pow(t, +p);
-
-/** @type {Record<String, EasesFactory|EasingFunction>} */
-const easeInFunctions = {
- [emptyString]: easeInPower,
- Quad: easeInPower(2),
- Cubic: easeInPower(3),
- Quart: easeInPower(4),
- Quint: easeInPower(5),
- /** @type {EasingFunction} */
- Sine: t => 1 - cos(t * halfPI),
- /** @type {EasingFunction} */
- Circ: t => 1 - sqrt(1 - t * t),
- /** @type {EasingFunction} */
- Expo: t => t ? pow(2, 10 * t - 10) : 0,
- /** @type {EasingFunction} */
- Bounce: t => {
- let pow2, b = 4;
- while (t < ((pow2 = pow(2, --b)) - 1) / 11);
- return 1 / pow(4, 3 - b) - 7.5625 * pow((pow2 * 3 - 2) / 22 - t, 2);
- },
- /** @type {BackEasing} */
- Back: (overshoot = 1.70158) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t,
- /** @type {ElasticEasing} */
- Elastic: (amplitude = 1, period = .3) => {
- const a = clamp(+amplitude, 1, 10);
- const p = clamp(+period, minValue, 2);
- const s = (p / doublePI) * asin(1 / a);
- const e = doublePI / p;
- return t => t === 0 || t === 1 ? t : -a * pow(2, -10 * (1 - t)) * sin(((1 - t) - s) * e);
- }
-};
-
-/**
- * @callback EaseType
- * @param {EasingFunction} Ease
- * @return {EasingFunction}
- */
-
-/** @type {Record<String, EaseType>} */
-const easeTypes = {
- in: easeIn => t => easeIn(t),
- out: easeIn => t => 1 - easeIn(1 - t),
- inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2,
- outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2,
-};
-
-/**
- * @param {String} string
- * @param {Record<String, EasesFactory|EasingFunction>} easesFunctions
- * @param {Object} easesLookups
- * @return {EasingFunction}
- */
-const parseEaseString = (string, easesFunctions, easesLookups) => {
- if (easesLookups[string]) return easesLookups[string];
- if (string.indexOf('(') <= -1) {
- const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic');
- const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasesFactory} */(easesFunctions[string])() : easesFunctions[string]);
- return parsedFn ? easesLookups[string] = parsedFn : none;
- } else {
- const split = string.slice(0, -1).split('(');
- const parsedFn = /** @type {EasesFactory} */(easesFunctions[split[0]]);
- return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none;
- }
-};
-
-/**
- * @typedef {Object} EasesFunctions
- * @property {typeof linear} linear
- * @property {typeof irregular} irregular
- * @property {typeof steps} steps
- * @property {typeof cubicBezier} cubicBezier
- * @property {PowerEasing} in
- * @property {PowerEasing} out
- * @property {PowerEasing} inOut
- * @property {PowerEasing} outIn
- * @property {EasingFunction} inQuad
- * @property {EasingFunction} outQuad
- * @property {EasingFunction} inOutQuad
- * @property {EasingFunction} outInQuad
- * @property {EasingFunction} inCubic
- * @property {EasingFunction} outCubic
- * @property {EasingFunction} inOutCubic
- * @property {EasingFunction} outInCubic
- * @property {EasingFunction} inQuart
- * @property {EasingFunction} outQuart
- * @property {EasingFunction} inOutQuart
- * @property {EasingFunction} outInQuart
- * @property {EasingFunction} inQuint
- * @property {EasingFunction} outQuint
- * @property {EasingFunction} inOutQuint
- * @property {EasingFunction} outInQuint
- * @property {EasingFunction} inSine
- * @property {EasingFunction} outSine
- * @property {EasingFunction} inOutSine
- * @property {EasingFunction} outInSine
- * @property {EasingFunction} inCirc
- * @property {EasingFunction} outCirc
- * @property {EasingFunction} inOutCirc
- * @property {EasingFunction} outInCirc
- * @property {EasingFunction} inExpo
- * @property {EasingFunction} outExpo
- * @property {EasingFunction} inOutExpo
- * @property {EasingFunction} outInExpo
- * @property {EasingFunction} inBounce
- * @property {EasingFunction} outBounce
- * @property {EasingFunction} inOutBounce
- * @property {EasingFunction} outInBounce
- * @property {BackEasing} inBack
- * @property {BackEasing} outBack
- * @property {BackEasing} inOutBack
- * @property {BackEasing} outInBack
- * @property {ElasticEasing} inElastic
- * @property {ElasticEasing} outElastic
- * @property {ElasticEasing} inOutElastic
- * @property {ElasticEasing} outInElastic
- */
-
-const eases = (/*#__PURE__*/ (() => {
- const list = { linear, irregular, steps, cubicBezier };
- for (let type in easeTypes) {
- for (let name in easeInFunctions) {
- const easeIn = easeInFunctions[name];
- const easeType = easeTypes[type];
- list[type + name] = /** @type {EasesFactory|EasingFunction} */(
- name === emptyString || name === 'Back' || name === 'Elastic' ?
- (a, b) => easeType(/** @type {EasesFactory} */(easeIn)(a, b)) :
- easeType(/** @type {EasingFunction} */(easeIn))
- );
- }
- }
- return /** @type {EasesFunctions} */(list);
-})());
-
-/** @type {Record<String, EasingFunction>} */
-const JSEasesLookups = { linear: none };
-
-/**
- * @param {EasingParam} ease
- * @return {EasingFunction}
- */
-const parseEasings = ease => isFnc(ease) ? ease :
- isStr(ease) ? parseEaseString(/** @type {String} */(ease), eases, JSEasesLookups) :
- none;
-
-
-
-
-const propertyNamesCache = {};
-
-/**
- * @param {String} propertyName
- * @param {Target} target
- * @param {tweenTypes} tweenType
- * @return {String}
- */
-const sanitizePropertyName = (propertyName, target, tweenType) => {
- if (tweenType === tweenTypes.TRANSFORM) {
- const t = shortTransforms.get(propertyName);
- return t ? t : propertyName;
- } else if (
- tweenType === tweenTypes.CSS ||
- // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
- // but properties like "baseFrequency" should stay in lowerCamelCase
- (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
- ) {
- const cachedPropertyName = propertyNamesCache[propertyName];
- if (cachedPropertyName) {
- return cachedPropertyName;
- } else {
- const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
- propertyNamesCache[propertyName] = lowerCaseName;
- return lowerCaseName;
- }
- } else {
- return propertyName;
- }
-};
-
-
-
-
-const angleUnitsMap = { 'deg': 1, 'rad': 180 / PI, 'turn': 360 };
-const convertedValuesCache = {};
-
-/**
- * @param {DOMTarget} el
- * @param {TweenDecomposedValue} decomposedValue
- * @param {String} unit
- * @param {Boolean} [force]
- * @return {TweenDecomposedValue}
- */
-const convertValueUnit = (el, decomposedValue, unit, force = false) => {
- const currentUnit = decomposedValue.u;
- const currentNumber = decomposedValue.n;
- if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary
- return decomposedValue;
- }
- const cachedKey = currentNumber + currentUnit + unit;
- const cached = convertedValuesCache[cachedKey];
- if (!isUnd(cached) && !force) {
- decomposedValue.n = cached;
- } else {
- let convertedValue;
- if (currentUnit in angleUnitsMap) {
- convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit];
- } else {
- const baseline = 100;
- const tempEl = /** @type {DOMTarget} */(el.cloneNode());
- const parentNode = el.parentNode;
- const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body;
- parentEl.appendChild(tempEl);
- const elStyle = tempEl.style;
- elStyle.width = baseline + currentUnit;
- const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
- elStyle.width = baseline + unit;
- const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline;
- const factor = currentUnitWidth / newUnitWidth;
- parentEl.removeChild(tempEl);
- convertedValue = factor * currentNumber;
- }
- decomposedValue.n = convertedValue;
- convertedValuesCache[cachedKey] = convertedValue;
- }
- decomposedValue.t === valueTypes.UNIT;
- decomposedValue.u = unit;
- return decomposedValue;
-};
-
-
-
-
-/**
- * @template {Renderable} T
- * @param {T} renderable
- * @return {T}
- */
-const cleanInlineStyles = renderable => {
- // Allow cleanInlineStyles() to be called on timelines
- if (renderable._hasChildren) {
- forEachChildren(renderable, cleanInlineStyles, true);
- } else {
- const animation = /** @type {JSAnimation} */(renderable);
- animation.pause();
- forEachChildren(animation, (/** @type {Tween} */tween) => {
- const tweenProperty = tween.property;
- const tweenTarget = tween.target;
- if (tweenTarget[isDomSymbol]) {
- const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
- const originalInlinedValue = animation._inlineStyles[tweenProperty];
- if (tween._tweenType === tweenTypes.TRANSFORM) {
- const cachedTransforms = tweenTarget[transformsSymbol];
- if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
- delete cachedTransforms[tweenProperty];
- } else {
- cachedTransforms[tweenProperty] = originalInlinedValue;
- }
- if (tween._renderTransforms) {
- if (!Object.keys(cachedTransforms).length) {
- targetStyle.removeProperty('transform');
- } else {
- let str = emptyString;
- for (let key in cachedTransforms) {
- str += transformsFragmentStrings[key] + cachedTransforms[key] + ') ';
- }
- targetStyle.transform = str;
- }
- }
- } else {
- if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
- targetStyle.removeProperty(tweenProperty);
- } else {
- targetStyle[tweenProperty] = originalInlinedValue;
- }
- }
- if (animation._tail === tween) {
- animation.targets.forEach(t => {
- if (t.getAttribute && t.getAttribute('style') === emptyString) {
- t.removeAttribute('style');
- } });
- }
- }
- });
- }
- return renderable;
-};
-
-// Defines decomposed values target objects only once and mutate their properties later to avoid GC
-// TODO: Maybe move the objects creation to values.js and use the decompose function to create the base object
-const fromTargetObject = createDecomposedValueTargetObject();
-const toTargetObject = createDecomposedValueTargetObject();
-const toFunctionStore = { func: null };
-const keyframesTargetArray = [null];
-const fastSetValuesArray = [null, null];
-/** @type {TweenKeyValue} */
-const keyObjectTarget = { to: null };
-
-let tweenId = 0;
-let keyframes;
-/** @type {TweenParamsOptions & TweenValues} */
-let key;
-
-/**
- * @param {DurationKeyframes | PercentageKeyframes} keyframes
- * @param {AnimationParams} parameters
- * @return {AnimationParams}
- */
-const generateKeyframes = (keyframes, parameters) => {
- /** @type {AnimationParams} */
- const properties = {};
- if (isArr(keyframes)) {
- const propertyNames = [].concat(.../** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(isKey);
- for (let i = 0, l = propertyNames.length; i < l; i++) {
- const propName = propertyNames[i];
- const propArray = /** @type {DurationKeyframes} */(keyframes).map(key => {
- /** @type {TweenKeyValue} */
- const newKey = {};
- for (let p in key) {
- const keyValue = /** @type {TweenPropValue} */(key[p]);
- if (isKey(p)) {
- if (p === propName) {
- newKey.to = keyValue;
- }
- } else {
- newKey[p] = keyValue;
- }
- }
- return newKey;
- });
- properties[propName] = /** @type {ArraySyntaxValue} */(propArray);
- }
-
- } else {
- const totalDuration = /** @type {Number} */(setValue(parameters.duration, globals.defaults.duration));
- const keys = Object.keys(keyframes)
- .map(key => { return {o: parseFloat(key) / 100, p: keyframes[key]} })
- .sort((a, b) => a.o - b.o);
- keys.forEach(key => {
- const offset = key.o;
- const prop = key.p;
- for (let name in prop) {
- if (isKey(name)) {
- let propArray = /** @type {Array} */(properties[name]);
- if (!propArray) propArray = properties[name] = [];
- const duration = offset * totalDuration;
- let length = propArray.length;
- let prevKey = propArray[length - 1];
- const keyObj = { to: prop[name] };
- let durProgress = 0;
- for (let i = 0; i < length; i++) {
- durProgress += propArray[i].duration;
- }
- if (length === 1) {
- keyObj.from = prevKey.to;
- }
- if (prop.ease) {
- keyObj.ease = prop.ease;
- }
- keyObj.duration = duration - (length ? durProgress : 0);
- propArray.push(keyObj);
- }
- }
- return key;
- });
-
- for (let name in properties) {
- const propArray = /** @type {Array} */(properties[name]);
- let prevEase;
- // let durProgress = 0
- for (let i = 0, l = propArray.length; i < l; i++) {
- const prop = propArray[i];
- // Emulate WAPPI easing parameter position
- const currentEase = prop.ease;
- prop.ease = prevEase ? prevEase : undefined;
- prevEase = currentEase;
- // durProgress += prop.duration;
- // if (i === l - 1 && durProgress !== totalDuration) {
- // propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress })
- // }
- }
- if (!propArray[0].duration) {
- propArray.shift();
- }
- }
-
- }
-
- return properties;
-};
-
-class JSAnimation extends Timer {
- /**
- * @param {TargetsParam} targets
- * @param {AnimationParams} parameters
- * @param {Timeline} [parent]
- * @param {Number} [parentPosition]
- * @param {Boolean} [fastSet=false]
- * @param {Number} [index=0]
- * @param {Number} [length=0]
- */
- constructor(
- targets,
- parameters,
- parent,
- parentPosition,
- fastSet = false,
- index = 0,
- length = 0
- ) {
-
- super(/** @type {TimerParams&AnimationParams} */(parameters), parent, parentPosition);
-
- const parsedTargets = registerTargets(targets);
- const targetsLength = parsedTargets.length;
-
- // If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties
-
- const kfParams = /** @type {AnimationParams} */(parameters).keyframes;
- const params = /** @type {AnimationParams} */(kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters);
-
- const {
- delay,
- duration,
- ease,
- playbackEase,
- modifier,
- composition,
- onRender,
- } = params;
-
- const animDefaults = parent ? parent.defaults : globals.defaults;
- const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
- const animEase = animaPlaybackEase ? parseEasings(animaPlaybackEase) : null;
- const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
- const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease);
- const tDuration = hasSpring ? /** @type {Spring} */(ease).duration : setValue(duration, animDefaults.duration);
- const tDelay = setValue(delay, animDefaults.delay);
- const tModifier = modifier || animDefaults.modifier;
- // If no composition is defined and the targets length is high (>= 1000) set the composition to 'none' (0) for faster tween creation
- const tComposition = isUnd(composition) && targetsLength >= K ? compositionTypes.none : !isUnd(composition) ? composition : animDefaults.composition;
- // TODO: Do not create an empty object until we know the animation will generate inline styles
- const animInlineStyles = {};
- // const absoluteOffsetTime = this._offset;
- const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0);
-
- let iterationDuration = NaN;
- let iterationDelay = NaN;
- let animationAnimationLength = 0;
- let shouldTriggerRender = 0;
-
- for (let targetIndex = 0; targetIndex < targetsLength; targetIndex++) {
-
- const target = parsedTargets[targetIndex];
- const ti = index || targetIndex;
- const tl = length || targetsLength;
-
- let lastTransformGroupIndex = NaN;
- let lastTransformGroupLength = NaN;
-
- for (let p in params) {
-
- if (isKey(p)) {
-
- const tweenType = getTweenType(target, p);
-
- const propName = sanitizePropertyName(p, target, tweenType);
-
- let propValue = params[p];
-
- const isPropValueArray = isArr(propValue);
-
- if (fastSet && !isPropValueArray) {
- fastSetValuesArray[0] = propValue;
- fastSetValuesArray[1] = propValue;
- propValue = fastSetValuesArray;
- }
-
- // TODO: Allow nested keyframes inside ObjectValue value (prop: { to: [.5, 1, .75, 2, 3] })
- // Normalize property values to valid keyframe syntax:
- // [x, y] to [{to: [x, y]}] or {to: x} to [{to: x}] or keep keys syntax [{}, {}, {}...]
- // const keyframes = isArr(propValue) ? propValue.length === 2 && !isObj(propValue[0]) ? [{ to: propValue }] : propValue : [propValue];
- if (isPropValueArray) {
- const arrayLength = /** @type {Array} */(propValue).length;
- const isNotObjectValue = !isObj(propValue[0]);
- // Convert [x, y] to [{to: [x, y]}]
- if (arrayLength === 2 && isNotObjectValue) {
- keyObjectTarget.to = /** @type {TweenParamValue} */(/** @type {unknown} */(propValue));
- keyframesTargetArray[0] = keyObjectTarget;
- keyframes = keyframesTargetArray;
- // Convert [x, y, z] to [[x, y], z]
- } else if (arrayLength > 2 && isNotObjectValue) {
- keyframes = [];
- /** @type {Array.<Number>} */(propValue).forEach((v, i) => {
- if (!i) {
- fastSetValuesArray[0] = v;
- } else if (i === 1) {
- fastSetValuesArray[1] = v;
- keyframes.push(fastSetValuesArray);
- } else {
- keyframes.push(v);
- }
- });
- } else {
- keyframes = /** @type {Array.<TweenKeyValue>} */(propValue);
- }
- } else {
- keyframesTargetArray[0] = propValue;
- keyframes = keyframesTargetArray;
- }
-
- let siblings = null;
- let prevTween = null;
- let firstTweenChangeStartTime = NaN;
- let lastTweenChangeEndTime = 0;
- let tweenIndex = 0;
-
- for (let l = keyframes.length; tweenIndex < l; tweenIndex++) {
-
- const keyframe = keyframes[tweenIndex];
-
- if (isObj(keyframe)) {
- key = keyframe;
- } else {
- keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe);
- key = keyObjectTarget;
- }
-
- toFunctionStore.func = null;
-
- const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore);
-
- let tweenToValue;
- // Allows function based values to return an object syntax value ({to: v})
- if (isObj(computedToValue) && !isUnd(computedToValue.to)) {
- key = computedToValue;
- tweenToValue = computedToValue.to;
- } else {
- tweenToValue = computedToValue;
- }
- const tweenFromValue = getFunctionValue(key.from, target, ti, tl);
- const keyEasing = key.ease;
- const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */(keyEasing).ease);
- // Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time
- const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing || tEasing;
- // Calculate default individual keyframe duration by dividing the tl of keyframes
- const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).duration : getFunctionValue(setValue(key.duration, (l > 1 ? getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl);
- // Default delay value should only be applied to the first tween
- const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl);
- const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl);
- const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition];
- // Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper
- const tweenModifier = key.modifier || tModifier;
- const hasFromvalue = !isUnd(tweenFromValue);
- const hasToValue = !isUnd(tweenToValue);
- const isFromToArray = isArr(tweenToValue);
- const isFromToValue = isFromToArray || (hasFromvalue && hasToValue);
- const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay;
- const absoluteStartTime = absoluteOffsetTime + tweenStartTime;
-
- // Force a onRender callback if the animation contains at least one from value and autoplay is set to false
- if (!shouldTriggerRender && (hasFromvalue || isFromToArray)) shouldTriggerRender = 1;
-
- let prevSibling = prevTween;
-
- if (tweenComposition !== compositionTypes.none) {
- if (!siblings) siblings = getTweenSiblings(target, propName);
- let nextSibling = siblings._head;
- // Iterate trough all the next siblings until we find a sibling with an equal or inferior start time
- while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) {
- prevSibling = nextSibling;
- nextSibling = nextSibling._nextRep;
- // Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time
- if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) {
- while (nextSibling) {
- overrideTween(nextSibling);
- // This will ends both the current while loop and the upper one once all the next sibllings have been overriden
- nextSibling = nextSibling._nextRep;
- }
- }
- }
- }
-
- // Decompose values
- if (isFromToValue) {
- decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject);
- decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject);
- if (fromTargetObject.t === valueTypes.NUMBER) {
- if (prevSibling) {
- if (prevSibling._valueType === valueTypes.UNIT) {
- fromTargetObject.t = valueTypes.UNIT;
- fromTargetObject.u = prevSibling._unit;
- }
- } else {
- decomposeRawValue(
- getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles),
- decomposedOriginalValue
- );
- if (decomposedOriginalValue.t === valueTypes.UNIT) {
- fromTargetObject.t = valueTypes.UNIT;
- fromTargetObject.u = decomposedOriginalValue.u;
- }
- }
- }
- } else {
- if (hasToValue) {
- decomposeRawValue(tweenToValue, toTargetObject);
- } else {
- if (prevTween) {
- decomposeTweenValue(prevTween, toTargetObject);
- } else {
- // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
- decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
- getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), toTargetObject);
- }
- }
- if (hasFromvalue) {
- decomposeRawValue(tweenFromValue, fromTargetObject);
- } else {
- if (prevTween) {
- decomposeTweenValue(prevTween, fromTargetObject);
- } else {
- decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
- // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
- getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), fromTargetObject);
- }
- }
- }
-
- // Apply operators
- if (fromTargetObject.o) {
- fromTargetObject.n = getRelativeValue(
- !prevSibling ? decomposeRawValue(
- getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles),
- decomposedOriginalValue
- ).n : prevSibling._toNumber,
- fromTargetObject.n,
- fromTargetObject.o
- );
- }
-
- if (toTargetObject.o) {
- toTargetObject.n = getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o);
- }
-
- // Values omogenisation in cases of type difference between "from" and "to"
- if (fromTargetObject.t !== toTargetObject.t) {
- if (fromTargetObject.t === valueTypes.COMPLEX || toTargetObject.t === valueTypes.COMPLEX) {
- const complexValue = fromTargetObject.t === valueTypes.COMPLEX ? fromTargetObject : toTargetObject;
- const notComplexValue = fromTargetObject.t === valueTypes.COMPLEX ? toTargetObject : fromTargetObject;
- notComplexValue.t = valueTypes.COMPLEX;
- notComplexValue.s = cloneArray(complexValue.s);
- notComplexValue.d = complexValue.d.map(() => notComplexValue.n);
- } else if (fromTargetObject.t === valueTypes.UNIT || toTargetObject.t === valueTypes.UNIT) {
- const unitValue = fromTargetObject.t === valueTypes.UNIT ? fromTargetObject : toTargetObject;
- const notUnitValue = fromTargetObject.t === valueTypes.UNIT ? toTargetObject : fromTargetObject;
- notUnitValue.t = valueTypes.UNIT;
- notUnitValue.u = unitValue.u;
- } else if (fromTargetObject.t === valueTypes.COLOR || toTargetObject.t === valueTypes.COLOR) {
- const colorValue = fromTargetObject.t === valueTypes.COLOR ? fromTargetObject : toTargetObject;
- const notColorValue = fromTargetObject.t === valueTypes.COLOR ? toTargetObject : fromTargetObject;
- notColorValue.t = valueTypes.COLOR;
- notColorValue.s = colorValue.s;
- notColorValue.d = [0, 0, 0, 1];
- }
- }
-
- // Unit conversion
- if (fromTargetObject.u !== toTargetObject.u) {
- let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject;
- valueToConvert = convertValueUnit(/** @type {DOMTarget} */(target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false);
- // TODO:
- // convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u);
- }
-
- // Fill in non existing complex values
- if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) {
- const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject;
- const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject;
- // TODO: Check if n should be used instead of 0 for default complex values
- shortestValue.d = longestValue.d.map((_, i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
- shortestValue.s = cloneArray(longestValue.s);
- }
-
- // Tween factory
-
- // Rounding is necessary here to minimize floating point errors
- const tweenUpdateDuration = round(+tweenDuration || minValue, 12);
-
- /** @type {Tween} */
- const tween = {
- parent: this,
- id: tweenId++,
- property: propName,
- target: target,
- _value: null,
- _func: toFunctionStore.func,
- _ease: parseEasings(tweenEasing),
- _fromNumbers: cloneArray(fromTargetObject.d),
- _toNumbers: cloneArray(toTargetObject.d),
- _strings: cloneArray(toTargetObject.s),
- _fromNumber: fromTargetObject.n,
- _toNumber: toTargetObject.n,
- _numbers: cloneArray(fromTargetObject.d), // For additive tween and animatables
- _number: fromTargetObject.n, // For additive tween and animatables
- _unit: toTargetObject.u,
- _modifier: tweenModifier,
- _currentTime: 0,
- _startTime: tweenStartTime,
- _delay: +tweenDelay,
- _updateDuration: tweenUpdateDuration,
- _changeDuration: tweenUpdateDuration,
- _absoluteStartTime: absoluteStartTime,
- // NOTE: Investigate bit packing to stores ENUM / BOOL
- _tweenType: tweenType,
- _valueType: toTargetObject.t,
- _composition: tweenComposition,
- _isOverlapped: 0,
- _isOverridden: 0,
- _renderTransforms: 0,
- _prevRep: null, // For replaced tween
- _nextRep: null, // For replaced tween
- _prevAdd: null, // For additive tween
- _nextAdd: null, // For additive tween
- _prev: null,
- _next: null,
- };
-
- if (tweenComposition !== compositionTypes.none) {
- composeTween(tween, siblings);
- }
-
- if (isNaN(firstTweenChangeStartTime)) {
- firstTweenChangeStartTime = tween._startTime;
- }
- // Rounding is necessary here to minimize floating point errors
- lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12);
- prevTween = tween;
- animationAnimationLength++;
-
- addChild(this, tween);
-
- }
-
- // Update animation timings with the added tweens properties
-
- if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) {
- iterationDelay = firstTweenChangeStartTime;
- }
-
- if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) {
- iterationDuration = lastTweenChangeEndTime;
- }
-
- // TODO: Find a way to inline tween._renderTransforms = 1 here
- if (tweenType === tweenTypes.TRANSFORM) {
- lastTransformGroupIndex = animationAnimationLength - tweenIndex;
- lastTransformGroupLength = animationAnimationLength;
- }
-
- }
-
- }
-
- // Set _renderTransforms to last transform property to correctly render the transforms list
- if (!isNaN(lastTransformGroupIndex)) {
- let i = 0;
- forEachChildren(this, (/** @type {Tween} */tween) => {
- if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) {
- tween._renderTransforms = 1;
- if (tween._composition === compositionTypes.blend) {
- forEachChildren(additive.animation, (/** @type {Tween} */additiveTween) => {
- if (additiveTween.id === tween.id) {
- additiveTween._renderTransforms = 1;
- }
- });
- }
- }
- i++;
- });
- }
-
- }
-
- if (!targetsLength) {
- console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
- }
-
- if (iterationDelay) {
- forEachChildren(this, (/** @type {Tween} */tween) => {
- // If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too
- if (!(tween._startTime - tween._delay)) {
- tween._delay -= iterationDelay;
- }
- tween._startTime -= iterationDelay;
- });
- iterationDuration -= iterationDelay;
- } else {
- iterationDelay = 0;
- }
-
- // Prevents iterationDuration to be NaN if no valid animatable props have been provided
- // Prevents _iterationCount to be NaN if no valid animatable props have been provided
- if (!iterationDuration) {
- iterationDuration = minValue;
- this.iterationCount = 0;
- }
- /** @type {TargetsArray} */
- this.targets = parsedTargets;
- /** @type {Number} */
- this.duration = iterationDuration === minValue ? minValue : clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || minValue;
- /** @type {Callback<this>} */
- this.onRender = onRender || animDefaults.onRender;
- /** @type {EasingFunction} */
- this._ease = animEase;
- /** @type {Number} */
- this._delay = iterationDelay;
- // NOTE: I'm keeping delay values separated from offsets in timelines because delays can override previous tweens and it could be confusing to debug a timeline with overridden tweens and no associated visible delays.
- // this._delay = parent ? 0 : iterationDelay;
- // this._offset += parent ? iterationDelay : 0;
- /** @type {Number} */
- this.iterationDuration = iterationDuration;
- /** @type {{}} */
- this._inlineStyles = animInlineStyles;
-
- if (!this._autoplay && shouldTriggerRender) this.onRender(this);
- }
-
- /**
- * @param {Number} newDuration
- * @return {this}
- */
- stretch(newDuration) {
- const currentDuration = this.duration;
- if (currentDuration === normalizeTime(newDuration)) return this;
- const timeScale = newDuration / currentDuration;
- // NOTE: Find a better way to handle the stretch of an animation after stretch = 0
- forEachChildren(this, (/** @type {Tween} */tween) => {
- // Rounding is necessary here to minimize floating point errors
- tween._updateDuration = normalizeTime(tween._updateDuration * timeScale);
- tween._changeDuration = normalizeTime(tween._changeDuration * timeScale);
- tween._currentTime *= timeScale;
- tween._startTime *= timeScale;
- tween._absoluteStartTime *= timeScale;
- });
- return super.stretch(newDuration);
- }
-
- /**
- * @return {this}
- */
- refresh() {
- forEachChildren(this, (/** @type {Tween} */tween) => {
- const ogValue = getOriginalAnimatableValue(tween.target, tween.property, tween._tweenType);
- decomposeRawValue(ogValue, decomposedOriginalValue);
- tween._fromNumbers = cloneArray(decomposedOriginalValue.d);
- tween._fromNumber = decomposedOriginalValue.n;
- if (tween._func) {
- decomposeRawValue(tween._func(), toTargetObject);
- tween._toNumbers = cloneArray(toTargetObject.d);
- tween._strings = cloneArray(toTargetObject.s);
- tween._toNumber = toTargetObject.n;
- }
- });
- return this;
- }
-
- /**
- * Cancel the animation and revert all the values affected by this animation to their original state
- * @return {this}
- */
- revert() {
- super.revert();
- return cleanInlineStyles(this);
- }
-
- /**
- * @param {Callback<this>} [callback]
- * @return {Promise}
- */
- then(callback) {
- return super.then(callback);
- }
-
-}
-
-/**
- * @param {TargetsParam} targets
- * @param {AnimationParams} parameters
- * @return {JSAnimation}
- */
-const animate = (targets, parameters) => new JSAnimation(targets, parameters, null, 0, false).init();
-
-
-
-
-/**
- * @typedef {String|Number|Array<String>|Array<Number>} WAAPITweenValue
- */
-
-/**
- * @callback WAAPIFunctionvalue
- * @param {DOMTarget} target - The animated target
- * @param {Number} index - The target index
- * @param {Number} length - The total number of animated targets
- * @return {WAAPITweenValue}
- */
-
-/**
- * @typedef {WAAPITweenValue|WAAPIFunctionvalue|Array<String|Number|WAAPIFunctionvalue>} WAAPIKeyframeValue
- */
-
-/**
- * @typedef {(animation: WAAPIAnimation) => void} WAAPICallback
- */
-
-/**
- * @typedef {Object} WAAPITweenOptions
- * @property {WAAPIKeyframeValue} [to]
- * @property {WAAPIKeyframeValue} [from]
- * @property {Number|WAAPIFunctionvalue} [duration]
- * @property {Number|WAAPIFunctionvalue} [delay]
- * @property {EasingParam} [ease]
- * @property {CompositeOperation} [composition]
- */
-
-/**
- * @typedef {Object} WAAPIAnimationOptions
- * @property {Number|Boolean} [loop]
- * @property {Boolean} [Reversed]
- * @property {Boolean} [Alternate]
- * @property {Boolean|ScrollObserver} [autoplay]
- * @property {Number} [playbackRate]
- * @property {Number|WAAPIFunctionvalue} [duration]
- * @property {Number|WAAPIFunctionvalue} [delay]
- * @property {EasingParam} [ease]
- * @property {CompositeOperation} [composition]
- * @property {WAAPICallback} [onComplete]
- */
-
-/**
- * @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | WAAPICallback | EasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams
- */
-
-const transformsShorthands = ['x', 'y', 'z'];
-
-[...transformsShorthands, ...validTransforms.filter(t => ['X', 'Y', 'Z'].some(axis => t.endsWith(axis)))];
-
-// Setting it to true in case CSS.registerProperty is not supported will automatically skip the registration and fallback to no animation
-isBrowser && (isUnd(CSS) || !Object.hasOwnProperty.call(CSS, 'registerProperty'));
-
-const WAAPIAnimationsLookups = {
- _head: null,
- _tail: null,
-};
-
-/**
- * @param {DOMTarget} $el
- * @param {String} [property]
- * @param {WAAPIAnimation} [parent]
- */
-const removeWAAPIAnimation = ($el, property, parent) => {
- let nextLookup = WAAPIAnimationsLookups._head;
- while (nextLookup) {
- const next = nextLookup._next;
- const matchTarget = nextLookup.$el === $el;
- const matchProperty = !property || nextLookup.property === property;
- const matchParent = !parent || nextLookup.parent === parent;
- if (matchTarget && matchProperty && matchParent) {
- const anim = nextLookup.animation;
- try { anim.commitStyles(); } catch {} anim.cancel();
- removeChild(WAAPIAnimationsLookups, nextLookup);
- const lookupParent = nextLookup.parent;
- if (lookupParent) {
- lookupParent._completed++;
- if (lookupParent.animations.length === lookupParent._completed) {
- lookupParent.completed = true;
- if (!lookupParent.muteCallbacks) {
- lookupParent.paused = true;
- lookupParent.onComplete(lookupParent);
- lookupParent._resolve(lookupParent);
- }
- }
- }
- }
- nextLookup = next;
- }
-};
-
-
-
-
-/**
- * @param {Callback<Timer>} [callback]
- * @return {Timer}
- */
-const sync = (callback = noop) => {
- return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
-};
-
-/**
- * @overload
- * @param {DOMTargetSelector} targetSelector
- * @param {String} propName
- * @return {String}
- *
- * @overload
- * @param {JSTargetsParam} targetSelector
- * @param {String} propName
- * @return {Number|String}
- *
- * @overload
- * @param {DOMTargetsParam} targetSelector
- * @param {String} propName
- * @param {String} unit
- * @return {String}
- *
- * @overload
- * @param {TargetsParam} targetSelector
- * @param {String} propName
- * @param {Boolean} unit
- * @return {Number}
- *
- * @param {TargetsParam} targetSelector
- * @param {String} propName
- * @param {String|Boolean} [unit]
- */
-function getTargetValue(targetSelector, propName, unit) {
- const targets = registerTargets(targetSelector);
- if (!targets.length) return;
- const [ target ] = targets;
- const tweenType = getTweenType(target, propName);
- const normalizePropName = sanitizePropertyName(propName, target, tweenType);
- let originalValue = getOriginalAnimatableValue(target, normalizePropName);
- if (isUnd(unit)) {
- return originalValue;
- } else {
- decomposeRawValue(originalValue, decomposedOriginalValue);
- if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) {
- if (unit === false) {
- return decomposedOriginalValue.n;
- } else {
- const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false);
- return `${round(convertedValue.n, globals.precision)}${convertedValue.u}`;
- }
- }
- }
-}
-
-/**
- * @param {TargetsParam} targets
- * @param {AnimationParams} parameters
- * @return {JSAnimation}
- */
-const setTargetValues = (targets, parameters) => {
- if (isUnd(parameters)) return;
- parameters.duration = minValue;
- // Do not overrides currently active tweens by default
- parameters.composition = setValue(parameters.composition, compositionTypes.none);
- // Skip init() and force rendering by playing the animation
- return new JSAnimation(targets, parameters, null, 0, true).resume();
-};
-
-/**
- * @param {TargetsArray} targetsArray
- * @param {JSAnimation} animation
- * @param {String} [propertyName]
- * @return {Boolean}
- */
-const removeTargetsFromAnimation = (targetsArray, animation, propertyName) => {
- let tweensMatchesTargets = false;
- forEachChildren(animation, (/**@type {Tween} */tween) => {
- const tweenTarget = tween.target;
- if (targetsArray.includes(tweenTarget)) {
- const tweenName = tween.property;
- const tweenType = tween._tweenType;
- const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
- if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
- // Make sure to flag the previous CSS transform tween to renderTransform
- if (tween.parent._tail === tween &&
- tween._tweenType === tweenTypes.TRANSFORM &&
- tween._prev &&
- tween._prev._tweenType === tweenTypes.TRANSFORM
- ) {
- tween._prev._renderTransforms = 1;
- }
- // Removes the tween from the selected animation
- removeChild(animation, tween);
- // Detach the tween from its siblings to make sure blended tweens are correctlly removed
- removeTweenSliblings(tween);
- tweensMatchesTargets = true;
- }
- }
- }, true);
- return tweensMatchesTargets;
-};
-
-/**
- * @param {TargetsParam} targets
- * @param {Renderable|WAAPIAnimation} [renderable]
- * @param {String} [propertyName]
- * @return {TargetsArray}
- */
-const remove = (targets, renderable, propertyName) => {
- const targetsArray = parseTargets(targets);
- const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine);
- const waapiAnimation = renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable);
- for (let i = 0, l = targetsArray.length; i < l; i++) {
- const $el = /** @type {DOMTarget} */(targetsArray[i]);
- removeWAAPIAnimation($el, propertyName, waapiAnimation);
- }
- let removeMatches;
- if (parent._hasChildren) {
- let iterationDuration = 0;
- forEachChildren(parent, (/** @type {Renderable} */child) => {
- if (!child._hasChildren) {
- removeMatches = removeTargetsFromAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName);
- // Remove the child from its parent if no tweens and no children left after the removal
- if (removeMatches && !child._head) {
- child.cancel();
- removeChild(parent, child);
- } else {
- // Calculate the new iterationDuration value to handle onComplete with last child in render()
- const childTLOffset = child._offset + child._delay;
- const childDur = childTLOffset + child.duration;
- if (childDur > iterationDuration) {
- iterationDuration = childDur;
- }
- }
- }
- // Make sure to also remove engine's children targets
- // NOTE: Avoid recursion?
- if (child._head) {
- remove(targets, child, propertyName);
- } else {
- child._hasChildren = false;
- }
- }, true);
- // Update iterationDuration value to handle onComplete with last child in render()
- if (!isUnd(/** @type {Renderable} */(parent).iterationDuration)) {
- /** @type {Renderable} */(parent).iterationDuration = iterationDuration;
- }
- } else {
- removeMatches = removeTargetsFromAnimation(
- targetsArray,
- /** @type {JSAnimation} */(parent),
- propertyName
- );
- }
-
- if (removeMatches && !parent._head) {
- parent._hasChildren = false;
- // Cancel the parent if there are no tweens and no children left after the removal
- // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
- if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel();
- }
-
- return targetsArray;
-};
-
-/**
- * @param {(...args: any[]) => Tickable} constructor
- * @return {(...args: any[]) => Tickable}
- */
-const keepTime = constructor => {
- /** @type {Tickable} */
- let tracked;
- return (...args) => {
- const currentIteration = tracked ? tracked.currentIteration : 0;
- const currentIterationProgress = tracked ? tracked.iterationProgress : 0;
- const reversed = tracked ? tracked.reversed : false;
- const alternate = tracked ? tracked._alternate : false;
- if (tracked) tracked.revert();
- tracked = constructor(...args);
- if (!tracked || tracked && isUnd(tracked.iterationProgress)) {
- console.warn('keepTime() first argument must be a function that returns a Timer, Animation or Timeline');
- } else {
- tracked.currentIteration = currentIteration;
- tracked.iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress;
- }
- return tracked;
- }
-};
-
-/**
- * @param {String|Array} items
- * @return {any}
- */
-const randomPick = items => items[random(0, items.length - 1)];
-
-/**
- * @param {Number|String} v
- * @param {Number} decimalLength
- * @return {String}
- */
-const roundPad = (v, decimalLength) => (+v).toFixed(decimalLength);
-
-/**
- * @param {Number} v
- * @param {Number} totalLength
- * @param {String} padString
- * @return {String}
- */
-const padStart = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString);
-
-/**
- * @param {Number} v
- * @param {Number} totalLength
- * @param {String} padString
- * @return {String}
- */
-const padEnd = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString);
-
-/**
- * @param {Number} v
- * @param {Number} min
- * @param {Number} max
- * @return {Number}
- */
-const wrap = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min;
-
-/**
- * @param {Number} value
- * @param {Number} inLow
- * @param {Number} inHigh
- * @param {Number} outLow
- * @param {Number} outHigh
- * @return {Number}
- */
-const mapRange = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow);
-
-/**
- * @param {Number} degrees
- * @return {Number}
- */
-const degToRad = degrees => degrees * PI / 180;
-
-/**
- * @param {Number} radians
- * @return {Number}
- */
-const radToDeg = radians => radians * 180 / PI;
-
-/**
- * https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
- * @param {Number} start
- * @param {Number} end
- * @param {Number} amount
- * @param {Renderable|Boolean} [renderable]
- * @return {Number}
- */
-const lerp = (start, end, amount, renderable) => {
- let dt = K / globals.defaults.frameRate;
- if (renderable !== false) {
- const ticker = /** @type Renderable */
- (renderable) ||
- (engine._hasChildren && engine);
- if (ticker && ticker.deltaTime) {
- dt = ticker.deltaTime;
- }
- }
- const t = 1 - Math.exp(-amount * dt * .1);
- return !amount ? start : amount === 1 ? end : (1 - t) * start + t * end;
-};
-
-// Chain-able utilities
-
-/**
- * @callback UtilityFunction
- * @param {...*} args
- * @return {Number|String}
- *
- * @param {UtilityFunction} fn
- * @param {Number} [last=0]
- * @return {function(...(Number|String)): function(Number|String): (Number|String)}
- */
-const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args);
-
-/**
- * @param {Function} fn
- * @return {function(...(Number|String))}
- */
-const chain = fn => {
- return (...args) => {
- const result = fn(...args);
- return new Proxy(noop, {
- apply: (_, __, [v]) => result(v),
- get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => {
- const nextResult = utils[prop](...nextArgs);
- return (/**@type {Number|String} */v) => nextResult(result(v));
- })
- });
- }
-};
-
-/**
- * @param {UtilityFunction} fn
- * @param {Number} [right]
- * @return {function(...(Number|String)): UtilityFunction}
- */
-const makeChainable = (fn, right = 0) => (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args);
-
-/**
- * @callback ChainedUtilsResult
- * @param {Number} value
- * @return {Number}
- *
- * @typedef {Object} ChainableUtils
- * @property {ChainedClamp} clamp
- * @property {ChainedRound} round
- * @property {ChainedSnap} snap
- * @property {ChainedWrap} wrap
- * @property {ChainedInterpolate} interpolate
- * @property {ChainedMapRange} mapRange
- * @property {ChainedRoundPad} roundPad
- * @property {ChainedPadStart} padStart
- * @property {ChainedPadEnd} padEnd
- * @property {ChainedDegToRad} degToRad
- * @property {ChainedRadToDeg} radToDeg
- *
- * @typedef {ChainableUtils & ChainedUtilsResult} ChainableUtil
- *
- * @callback ChainedClamp
- * @param {Number} min
- * @param {Number} max
- * @return {ChainableUtil}
- *
- * @callback ChainedRound
- * @param {Number} decimalLength
- * @return {ChainableUtil}
- *
- * @callback ChainedSnap
- * @param {Number} increment
- * @return {ChainableUtil}
- *
- * @callback ChainedWrap
- * @param {Number} min
- * @param {Number} max
- * @return {ChainableUtil}
- *
- * @callback ChainedInterpolate
- * @param {Number} start
- * @param {Number} end
- * @return {ChainableUtil}
- *
- * @callback ChainedMapRange
- * @param {Number} inLow
- * @param {Number} inHigh
- * @param {Number} outLow
- * @param {Number} outHigh
- * @return {ChainableUtil}
- *
- * @callback ChainedRoundPad
- * @param {Number} decimalLength
- * @return {ChainableUtil}
- *
- * @callback ChainedPadStart
- * @param {Number} totalLength
- * @param {String} padString
- * @return {ChainableUtil}
- *
- * @callback ChainedPadEnd
- * @param {Number} totalLength
- * @param {String} padString
- * @return {ChainableUtil}
- *
- * @callback ChainedDegToRad
- * @return {ChainableUtil}
- *
- * @callback ChainedRadToDeg
- * @return {ChainableUtil}
- */
-
-const utils = {
- $: registerTargets,
- get: getTargetValue,
- set: setTargetValues,
- remove,
- cleanInlineStyles,
- random,
- randomPick,
- shuffle,
- lerp,
- sync,
- keepTime,
- clamp: /** @type {typeof clamp & ChainedClamp} */(makeChainable(clamp)),
- round: /** @type {typeof round & ChainedRound} */(makeChainable(round)),
- snap: /** @type {typeof snap & ChainedSnap} */(makeChainable(snap)),
- wrap: /** @type {typeof wrap & ChainedWrap} */(makeChainable(wrap)),
- interpolate: /** @type {typeof interpolate & ChainedInterpolate} */(makeChainable(interpolate, 1)),
- mapRange: /** @type {typeof mapRange & ChainedMapRange} */(makeChainable(mapRange)),
- roundPad: /** @type {typeof roundPad & ChainedRoundPad} */(makeChainable(roundPad)),
- padStart: /** @type {typeof padStart & ChainedPadStart} */(makeChainable(padStart)),
- padEnd: /** @type {typeof padEnd & ChainedPadEnd} */(makeChainable(padEnd)),
- degToRad: /** @type {typeof degToRad & ChainedDegToRad} */(makeChainable(degToRad)),
- radToDeg: /** @type {typeof radToDeg & ChainedRadToDeg} */(makeChainable(radToDeg)),
-};
-
-
-
-
-/**
- * @typedef {Number|String|Function} TimePosition
- */
-
-/**
- * Timeline's children offsets positions parser
- * @param {Timeline} timeline
- * @param {String} timePosition
- * @return {Number}
- */
-const getPrevChildOffset = (timeline, timePosition) => {
- if (stringStartsWith(timePosition, '<')) {
- const goToPrevAnimationOffset = timePosition[1] === '<';
- const prevAnimation = /** @type {Tickable} */(timeline._tail);
- const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
- return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
- }
-};
-
-/**
- * @param {Timeline} timeline
- * @param {TimePosition} [timePosition]
- * @return {Number}
- */
-const parseTimelinePosition = (timeline, timePosition) => {
- let tlDuration = timeline.iterationDuration;
- if (tlDuration === minValue) tlDuration = 0;
- if (isUnd(timePosition)) return tlDuration;
- if (isNum(+timePosition)) return +timePosition;
- const timePosStr = /** @type {String} */(timePosition);
- const tlLabels = timeline ? timeline.labels : null;
- const hasLabels = !isNil(tlLabels);
- const prevOffset = getPrevChildOffset(timeline, timePosStr);
- const hasSibling = !isUnd(prevOffset);
- const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
- if (matchedRelativeOperator) {
- const fullOperator = matchedRelativeOperator[0];
- const split = timePosStr.split(fullOperator);
- const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
- const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
- const parsedNumericalOffset = +split[1];
- return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
- } else {
- return hasSibling ? prevOffset :
- hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
- tlDuration : tlDuration;
- }
-};
-
-/**
- * @param {Timeline} tl
- * @return {Number}
- */
-function getTimelineTotalDuration(tl) {
- return clampInfinity(((tl.iterationDuration + tl._loopDelay) * tl.iterationCount) - tl._loopDelay) || minValue;
-}
-
-/**
- * @overload
- * @param {TimerParams} childParams
- * @param {Timeline} tl
- * @param {Number} timePosition
- * @return {Timeline}
- *
- * @overload
- * @param {AnimationParams} childParams
- * @param {Timeline} tl
- * @param {Number} timePosition
- * @param {TargetsParam} targets
- * @param {Number} [index]
- * @param {Number} [length]
- * @return {Timeline}
- *
- * @param {TimerParams|AnimationParams} childParams
- * @param {Timeline} tl
- * @param {Number} timePosition
- * @param {TargetsParam} [targets]
- * @param {Number} [index]
- * @param {Number} [length]
- */
-function addTlChild(childParams, tl, timePosition, targets, index, length) {
- const isSetter = isNum(childParams.duration) && /** @type {Number} */(childParams.duration) <= minValue;
- // Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position
- const adjustedPosition = isSetter ? timePosition - minValue : timePosition;
- tick(tl, adjustedPosition, 1, 1, tickModes.AUTO);
- const tlChild = targets ?
- new JSAnimation(targets,/** @type {AnimationParams} */(childParams), tl, adjustedPosition, false, index, length) :
- new Timer(/** @type {TimerParams} */(childParams), tl, adjustedPosition);
- tlChild.init(1);
- // TODO: Might be better to insert at a position relative to startTime?
- addChild(tl, tlChild);
- forEachChildren(tl, (/** @type {Renderable} */child) => {
- const childTLOffset = child._offset + child._delay;
- const childDur = childTLOffset + child.duration;
- if (childDur > tl.iterationDuration) tl.iterationDuration = childDur;
- });
- tl.duration = getTimelineTotalDuration(tl);
- return tl;
-}
-
-class Timeline extends Timer {
-
- /**
- * @param {TimelineParams} [parameters]
- */
- constructor(parameters = {}) {
- super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0);
- /** @type {Number} */
- this.duration = 0; // TL duration starts at 0 and grows when adding children
- /** @type {Record<String, Number>} */
- this.labels = {};
- const defaultsParams = parameters.defaults;
- const globalDefaults = globals.defaults;
- /** @type {DefaultsParams} */
- this.defaults = defaultsParams ? mergeObjects(defaultsParams, globalDefaults) : globalDefaults;
- /** @type {Callback<this>} */
- this.onRender = parameters.onRender || globalDefaults.onRender;
- const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase);
- this._ease = tlPlaybackEase ? parseEasings(tlPlaybackEase) : null;
- /** @type {Number} */
- this.iterationDuration = 0;
- }
-
- /**
- * @overload
- * @param {TargetsParam} a1
- * @param {AnimationParams} a2
- * @param {TimePosition} [a3]
- * @return {this}
- *
- * @overload
- * @param {TimerParams} a1
- * @param {TimePosition} [a2]
- * @return {this}
- *
- * @param {TargetsParam|TimerParams} a1
- * @param {AnimationParams|TimePosition} a2
- * @param {TimePosition} [a3]
- */
- add(a1, a2, a3) {
- const isAnim = isObj(a2);
- const isTimer = isObj(a1);
- if (isAnim || isTimer) {
- this._hasChildren = true;
- if (isAnim) {
- const childParams = /** @type {AnimationParams} */(a2);
- // Check for function for children stagger positions
- if (isFnc(a3)) {
- const staggeredPosition = /** @type {Function} */(a3);
- const parsedTargetsArray = parseTargets(/** @type {TargetsParam} */(a1));
- // Store initial duration before adding new children that will change the duration
- const tlDuration = this.duration;
- // Store initial _iterationDuration before adding new children that will change the duration
- const tlIterationDuration = this.iterationDuration;
- // Store the original id in order to add specific indexes to the new animations ids
- const id = childParams.id;
- let i = 0;
- const parsedLength = parsedTargetsArray.length;
- parsedTargetsArray.forEach((/** @type {Target} */target) => {
- // Create a new parameter object for each staggered children
- const staggeredChildParams = { ...childParams };
- // Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation
- this.duration = tlDuration;
- this.iterationDuration = tlIterationDuration;
- if (!isUnd(id)) staggeredChildParams.id = id + '-' + i;
- addTlChild(
- staggeredChildParams,
- this,
- staggeredPosition(target, i, parsedLength, this),
- target,
- i,
- parsedLength
- );
- i++;
- });
- } else {
- addTlChild(
- childParams,
- this,
- parseTimelinePosition(this, a3),
- /** @type {TargetsParam} */(a1),
- );
- }
- } else {
- // It's a Timer
- addTlChild(
- /** @type TimerParams */(a1),
- this,
- parseTimelinePosition(this,/** @type TimePosition */(a2)),
- );
- }
- return this.init(1); // 1 = internalRender
- }
- }
-
- /**
- * @overload
- * @param {Tickable} [synced]
- * @param {TimePosition} [position]
- * @return {this}
- *
- * @overload
- * @param {globalThis.Animation} [synced]
- * @param {TimePosition} [position]
- * @return {this}
- *
- * @overload
- * @param {WAAPIAnimation} [synced]
- * @param {TimePosition} [position]
- * @return {this}
- *
- * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
- * @param {TimePosition} [position]
- */
- sync(synced, position) {
- if (isUnd(synced) || synced && isUnd(synced.pause)) return this;
- synced.pause();
- const duration = +(/** @type {globalThis.Animation} */(synced).effect ? /** @type {globalThis.Animation} */(synced).effect.getTiming().duration : /** @type {Tickable} */(synced).duration);
- return this.add(synced, { currentTime: [0, duration], duration, ease: 'linear' }, position);
- }
-
- /**
- * @param {TargetsParam} targets
- * @param {AnimationParams} parameters
- * @param {TimePosition} [position]
- * @return {this}
- */
- set(targets, parameters, position) {
- if (isUnd(parameters)) return this;
- parameters.duration = minValue;
- parameters.composition = compositionTypes.replace;
- return this.add(targets, parameters, position);
- }
-
- /**
- * @param {Callback<Timer>} callback
- * @param {TimePosition} [position]
- * @return {this}
- */
- call(callback, position) {
- if (isUnd(callback) || callback && !isFnc(callback)) return this;
- return this.add({ duration: 0, onComplete: () => callback(this) }, position);
- }
-
- /**
- * @param {String} labelName
- * @param {TimePosition} [position]
- * @return {this}
- *
- */
- label(labelName, position) {
- if (isUnd(labelName) || labelName && !isStr(labelName)) return this;
- this.labels[labelName] = parseTimelinePosition(this,/** @type TimePosition */(position));
- return this;
- }
-
- /**
- * @param {TargetsParam} targets
- * @param {String} [propertyName]
- * @return {this}
- */
- remove(targets, propertyName) {
- remove(targets, this, propertyName);
- return this;
- }
-
- /**
- * @param {Number} newDuration
- * @return {this}
- */
- stretch(newDuration) {
- const currentDuration = this.duration;
- if (currentDuration === normalizeTime(newDuration)) return this;
- const timeScale = newDuration / currentDuration;
- const labels = this.labels;
- forEachChildren(this, (/** @type {JSAnimation} */child) => child.stretch(child.duration * timeScale));
- for (let labelName in labels) labels[labelName] *= timeScale;
- return super.stretch(newDuration);
- }
-
- /**
- * @return {this}
- */
- refresh() {
- forEachChildren(this, (/** @type {JSAnimation} */child) => {
- if (child.refresh) child.refresh();
- });
- return this;
- }
-
- /**
- * @return {this}
- */
- revert() {
- super.revert();
- forEachChildren(this, (/** @type {JSAnimation} */child) => child.revert, true);
- return cleanInlineStyles(this);
- }
-
- /**
- * @param {Callback<this>} [callback]
- * @return {Promise}
- */
- then(callback) {
- return super.then(callback);
- }
-}
-
-/**
- * @param {TimelineParams} [parameters]
- * @return {Timeline}
- */
-const createTimeline = parameters => new Timeline(parameters).init();
-
-
-
-
-const segmenter = !isUnd(Intl) && Intl.Segmenter;
-isBrowser ? doc.createElement('template') : null;
-const whiteSpaceGroupRgx = /(\s+)/;
-const whiteSpaceRgx = /^\s+$/;
-
-/**
- * @typedef {Object} Segment
- * @property {String} segment
- * @property {Boolean} [isWordLike]
- */
-
-/**
- * @typedef {Object} Segmenter
- * @property {function(String): Iterable<Segment>} segment
- */
-
-/**
- * @type {Segmenter}
- */
-(() => {
- return segmenter ? new segmenter([], { granularity: 'word' }) : {
- segment: (text) => {
- const segments = [];
- const words = text.split(whiteSpaceGroupRgx);
- for (let i = 0, l = words.length; i < l; i++) {
- const segment = words[i];
- segments.push({
- segment,
- isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like
- });
- }
- return segments;
- }
- };
-})();
-
-/**
- * @type {Segmenter}
- */
-(() => {
- return segmenter ? new segmenter([], { granularity: 'grapheme' }) : {
- segment: text => Array.from(text).map(char => ({ segment: char }))
- };
-})();
-
-const icons = {
- toggle: `
- <polygon fill="currentColor" points="29 18 23 12 17 18"/>
- <polygon fill="currentColor" points="29 23 17 23 17 20 29 20"/>
- `,
- play: `
- <polygon fill="currentColor" fill-rule="nonzero" points="17 10 17 26 32 18"/>
- `,
- pause: `
- <rect width="5" height="14" x="17" y="11" fill="currentColor" fill-rule="nonzero"/>
- <rect width="5" height="14" x="24" y="11" fill="currentColor" fill-rule="nonzero"/>
- `,
- back: `
- <polygon fill="currentColor" points="28 12 22 18 28 24"/>
- <polygon fill="currentColor" points="21 12 21 24 18 24 18 12"/>
- `,
- settings: `<path fill="currentColor" fill-rule="nonzero" d="M24.455 10v2.178a5.964 5.964 0 0 1 1.633.676l1.54-1.54 2.057 2.058-1.54 1.54c.302.502.532 1.05.677 1.633H31v2.91h-2.178a5.964 5.964 0 0 1-.676 1.633l1.54 1.54-2.058 2.057-1.54-1.54a5.964 5.964 0 0 1-1.633.677V26h-2.91v-2.178a5.964 5.964 0 0 1-1.633-.676l-1.54 1.54-2.057-2.058 1.54-1.54a5.964 5.964 0 0 1-.677-1.633H15v-2.91h2.178a5.964 5.964 0 0 1 .676-1.633l-1.54-1.54 2.058-2.057 1.54 1.54a5.964 5.964 0 0 1 1.633-.677V10h2.91zM23 15a3 3 0 1 0 0 6 3 3 0 0 0 0-6z"/>
- `,
- clamp: `<path fill="currentColor" d="M15 25a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2h15a2 2 0 0 1 1.995 1.85L32 14v9a2 2 0 0 1-1.85 1.995L30 25H15zm13-12H17v11h11V13z"/>
- `,
-};
-
-const sideBarWidth = 212;
-const toolbarHeight = 56;
-const toolbarItemHeight = 36;
-const thumbWidth = 8;
-const tlScrubberHeight = 16;
-const tlLineHeight = 14;
-
-const instances = [];
-
-const parameters = {
- active: null,
- $container: document.body,
- highlightSiblings: true,
- showTweenId: true,
- startTime: 0,
- endTime: null,
- time: 0,
- speed: 1,
- loop: false,
- scrollX: 0,
- scrollY: 0,
- height: toolbarHeight,
- minified: window.innerHeight * .4,
- clamped: false,
-};
-
-function getActiveInstance() {
- return instances[parameters.active];
-}
-
-const url = new URL(window.location.href);
-
-const urlParams = url.searchParams;
-
-function getParsedParameter(paramName, userParams) {
- const fromUrl = urlParams.get(paramName);
- const fromUser = userParams[paramName];
- let param;
- if (!isUnd(fromUrl)) {
- param = fromUrl;
- } else if (!isUnd(fromUser)) {
- urlParams.set(paramName, fromUser);
- param = fromUser;
- }
- if (param === 'true') {
- param = true;
- } else if (param === 'false') {
- param = false;
- } else {
- const numParam = parseFloat(param);
- if (isNum(numParam)) {
- param = numParam;
- }
- }
- return param;
-}
-
-function parseParameters(userParams) {
- for (let paramName in parameters) {
- const parsedParam = getParsedParameter(paramName, userParams);
- if (!isNil(parsedParam)) {
- parameters[paramName] = parsedParam;
- }
- }
-}
-
-let setUrlParamTimeout;
-
-function setParameter(param, value) {
- parameters[param] = value;
- url.searchParams.set(param, value);
- clearTimeout(setUrlParamTimeout);
- setUrlParamTimeout = setTimeout(() => {
- window.history.replaceState(null, '', url);
- }, 66);
-}
-
-function msToEm(ms) {
- return ms / 125 + 'em';
-}
-
-const prefix = 'anime-gui-';
-
-const dot = '.';
-const classPrefix = dot + prefix;
-const prefixRgx = /\.-?[_a-zA-Z\-]+[\w\-:\[\]]*/gm;
-const commentsRgx = /\/\*.*?\*\//g;
-const spacesRgx = /\s{3,}/g;
-
-function prefixCSS(styles) {
- let prefixed = styles;
- styles.match(prefixRgx).forEach(match => prefixed = prefixed.replace(match, match.replace(dot, classPrefix)));
- return prefixed;
-}
-
-function minifyCSS(styles) {
- return styles.replace(commentsRgx, '').replace(spacesRgx, ''); // Remove comments then remove 3 or more consecutive spaces
-}
-
-function appendStyles(styles) {
- const styleEl = document.createElement('style');
- styleEl.setAttribute('id', prefix + 'styles');
- styleEl.innerHTML = minifyCSS(prefixCSS(styles));
- document.head.appendChild(styleEl);
-}
-
-function createBlock(className, css) {
- var $el = document.createElement('div');
- $el.classList.add(prefix + 'block');
- if (Array.isArray(className)) {
- for (let i = 0, l = className.length; i < l; i++) {
- $el.classList.add(prefix + className[i]);
- }
- } else {
- $el.classList.add(prefix + className);
- }
- if (css) $el.style.cssText = css;
- return $el;
-}
-
-function getIconCode(name) {
- return `<svg viewBox="0 0 45 36"><g fill-rule="evenodd">${icons[name]}</g></svg>`;
-}
-
-function createProgressBar() {
- const $el = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- $el.classList.add(`${prefix}progress-circle`);
- utils.set($el, { viewBox: '0 0 14 14'} );
- $el.innerHTML = `<g fill="none" fill-rule="evenodd"><circle cx="7" cy="7" r="6" stroke="#FFFFFF" stroke-width="2" opacity=".2"/><path stroke="#FFFFFF" stroke-width="2" d="M7 1a6 6 0 1 1-.023 0"/></g>`;
- return $el;
-}
-
-function createButton(className, innerHTML = '') {
- const $el = document.createElement('button');
- $el.classList.add(`${prefix}${className}`);
- $el.classList.add(`${prefix}sidebar-item`);
- $el.classList.add(`${prefix}sidebar-button`);
- $el.innerHTML = innerHTML;
- return $el;
-}
-
-function createSpeedButton() {
- const $el = document.createElement('select');
- const options = [2, 1.8, 1.5, 1.2, 1, .8, .5, .2, .1];
- $el.classList.add(`${prefix}speed-button`);
- $el.classList.add(`${prefix}sidebar-item`);
- $el.classList.add(`${prefix}sidebar-button`);
- for (let i = 0; i < options.length; i++) {
- const $option = document.createElement('option');
- $option.value = options[i];
- $option.text = options[i] + '×';
- $el.appendChild($option);
- }
- $el.value = 1;
- return $el;
-}
-
-function createScrubberInput(className) {
- const $input = document.createElement('input');
- $input.classList.add(`${prefix}scrubber`);
- $input.classList.add(`${prefix}${className}`);
- utils.set($input, { type: 'range', min: '0', max: '1', value: '0' });
- return $input;
-}
-
-function createScrubberBlock(className) {
- const $scrubber = createBlock(className);
- const tlScrubber = createScrubberInput('time-scrubber');
- const tlMinScrubber = createScrubberInput('min-scrubber');
- const tlMaxScrubber = createScrubberInput('max-scrubber');
- $scrubber.appendChild(tlScrubber);
- $scrubber.appendChild(tlMinScrubber);
- $scrubber.appendChild(tlMaxScrubber);
- return $scrubber;
-}
-
-function initDOM() {
- const $wrapper = createBlock('wrapper');
- const $tlWrapper = createBlock('tl-wrapper');
- const $toolbar = createBlock('toolbar');
- const $resizer = createBlock('resizer');
- const $sidebarLeft = createBlock('sidebar');
- const $sidebarRight = createBlock('sidebar');
- const $toggleButton = createButton('toggle-button', getIconCode('toggle'));
- const $playbackButton = createButton('playback-button', getIconCode('play'));
- const $backButton = createButton('back-button', getIconCode('back'));
- const $speedButton = createSpeedButton();
- const $clampButton = createButton('clamp-button', getIconCode('clamp'));
- const $mm = createBlock('mm');
- const $clock = createBlock(['clock', 'sidebar-item']);
- const $currentTime = createBlock('current-time');
- const $currentTimeShadow = createBlock(['current-time', 'current-time-shadow']);
- const $totalDuration = createBlock('total-duration');
- const $totalTime = createBlock('total-time');
- const $progressBar = createProgressBar();
- const $tl = createBlock(['tl', 'ruller-bg']);
- const $tlScrubber = createScrubberBlock('tl-scrubber');
- const $mmScrubber = createScrubberBlock('mm-scrubber');
- const $mmBox = createBlock('mm-box');
-
- $totalTime.appendChild($totalDuration);
- $clock.appendChild($currentTimeShadow);
- $clock.appendChild($currentTime);
- $clock.appendChild($totalTime);
- $clock.appendChild($progressBar);
- $mmScrubber.appendChild($mmBox);
- $mm.appendChild($mmScrubber);
- $tl.appendChild($tlScrubber);
- $sidebarLeft.appendChild($playbackButton);
- $sidebarLeft.appendChild($backButton);
- $sidebarLeft.appendChild($speedButton);
- $sidebarLeft.appendChild($clampButton);
- $sidebarRight.appendChild($clock);
- $sidebarRight.appendChild($toggleButton);
- $toolbar.appendChild($sidebarLeft);
- $toolbar.appendChild($mm);
- $toolbar.appendChild($resizer);
- $toolbar.appendChild($sidebarRight);
- $wrapper.appendChild($toolbar);
- $wrapper.appendChild($tlWrapper);
- $tlWrapper.appendChild($tl);
-
- return {
- $wrapper,
- $tlWrapper,
- $tl,
- $tlScrubber,
- $resizer,
- $mmScrubber,
- $mmBox,
- $speedButton,
- $clampButton,
- $currentTimeShadow,
- $currentTime,
- $totalDuration,
- }
-}
-
-const blackColor = '#1B1B1B';
-const whiteColor = '#F6F4F2';
-const whiteAlpha1Color = 'rgba(246, 244, 242, .05)';
-const whiteAlpha2Color = 'rgba(246, 244, 242, .5)';
-const whiteAlpha3Color = 'rgba(246, 244, 242, .75)';
-const blackAlpha1Color = 'rgba(46, 44, 44, .75)';
-const blackAlpha2Color = 'rgba(46, 44, 44, .9)';
-
-const colors = ['#FF4B4B','#FF8F42','#FFC730','#F6FF56','#A4FF4F','#18FF74','#00D672','#3CFFEC','#61C3FF','#5A87FF','#8453E3','#C26EFF','#FB89FB'];
-// const colors = [...Array(32)].map((c, i) => 'hsl(' + Math.round(360 / 32 * i) + ', 88%, 62%)');
-const colorLength = colors.length;
-const colorIds = {};
-let colorIndex = 0;
-
-function getNextColor() {
- const color = colors[colorIndex++];
- if (colorIndex > colorLength - 1) colorIndex = 0;
- return color;
-}
-
-function getColor(id) {
- if (id) {
- const idColor = colorIds[id];
- if (idColor) {
- return idColor;
- } else {
- return colorIds[id] = getNextColor();
- }
- } else {
- return getNextColor();
- }
-}
-
-const styles = `
- .wrapper,
- .wrapper *,
- .wrapper *:before,
- .wrapper *:after {
- box-sizing: border-box;
- display: flex;
- flex-shrink: 0;
- position: relative;
- user-select: none;
- font-variant-numeric: tabular-nums;
- }
- .wrapper {
- position: fixed;
- z-index: 999999;
- right: 0;
- bottom: 0;
- width: 100%;
- height: var(--anime-gui-height);
- font-family: sans-serif;
- background-color: ${blackColor};
- }
- .tl-wrapper {
- position: absolute;
- left: 0;
- top: ${toolbarHeight}px;
- overflow: auto;
- flex-direction: column;
- width: 100%;
- height: var(--anime-gui-tl-height);
- background-color: ${blackColor};
- }
- .toolbar {
- position: sticky;
- z-index: 99;
- left: 0;
- top: 0;
- width: 100%;
- height: ${toolbarHeight}px;
- padding: 10px;
- background-color: ${blackColor};
- box-shadow: inset 0 1px 0 0 rgba(255, 255, 255, .04),
- inset 0 -1px 0 0 rgba(0, 0, 0, .4);
- }
- .resizer {
- position: absolute;
- z-index: 9999;
- left: 0;
- top: -5px;
- width: 100%;
- height: 15px;
- cursor: row-resize;
- }
- .sidebar {
- overflow: hidden;
- flex-wrap: nowrap;
- width: ${sideBarWidth - 30}px;
- border-radius: 4px;
- background-color: ${whiteAlpha1Color};
- color: rgba(255,255,255,.65);
- }
- .sidebar:first-child {
- margin-right: 20px;
- }
- .sidebar:last-child {
- margin-left: 20px;
- }
- .sidebar-item {
- width: 100%;
- flex-shrink: 1;
- height: ${toolbarItemHeight}px;
- background-color: transparent;
- color: currentColor;
- box-shadow: inset 0 1px 0 0 rgba(255, 255, 255, .025),
- inset 0 -1px 0 0 rgba(0, 0, 0, .4);
- }
- .sidebar-item.is-active {
- background-color: rgba(0, 0, 0, .5);
- color: #FFF;
- box-shadow: inset 0 1px 0 0 rgba(0, 0, 0, .4),
- inset 0 -1px 0 0 rgba(255, 255, 255, .085);
- }
- .sidebar-button {
- overflow: hidden;
- cursor: pointer;
- }
- .sidebar > *:first-child {
- border-radius: 4px 0 0 4px;
- }
- .sidebar > *:last-child {
- border-radius: 0 4px 4px 0;
- }
- .sidebar > *:first-child:last-child {
- border-radius: 4px;
- }
- .sidebar-button:not(:first-child) {
- border-left: 1px solid ${blackColor};
- }
- .sidebar-button:not(.is-active):hover {
- color: rgba(255,255,255,.85);
- background-color: rgba(255,255,255,.1);
- }
- @keyframes focus {
- from {
- box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .25),
- inset 0 0 0 0 rgba(255, 255, 255, .25);
- }
- }
- .sidebar-button:focus {
- outline: none;
- animation: focus 1s linear forwards;
- }
- .sidebar-button svg {
- width: 100%;
- height: 100%;
- }
- .speed-button {
- -webkit-appearance: none;
- -moz-appearance: none;
- text-align: center;
- }
- .mm {
- width: calc(100% - ${sideBarWidth * 2}px + 20px);
- height: ${toolbarItemHeight}px;
- background-color: rgba(0, 0, 0, .25);
- border-radius: 4px;
- box-shadow: inset 0 1px 0 0 rgba(0, 0, 0, .4),
- inset 0 -1px 0 0 rgba(255, 255, 255, .085);
- }
- .ruller-bg {
- background-repeat: repeat-x;
- background-position: left bottom 0px;
- background-image: linear-gradient(
- to right, ${whiteAlpha1Color} 1px, transparent 1px
- );
- background-size: ${msToEm(500)} 100%;
- }
- .scrubber {
- -webkit-appearance: none;
- position: absolute;
-
- width: calc(100% + ${thumbWidth}px);
- margin-left: -${thumbWidth / 2}px;
-
- background: transparent;
- cursor: col-resize;
- }
- .time-scrubber {
- z-index: 1;
- top: 0;
- }
- .min-scrubber,
- .max-scrubber {
- z-index: 2;
- top: 0;
- }
- .scrubber:focus {
- outline: none;
- }
- .scrubber::-webkit-slider-runnable-track {
- -webkit-appearance: none;
- }
- .scrubber.time-scrubber::-webkit-slider-runnable-track {
- z-index: 99;
- height: ${tlScrubberHeight}px;
- border-radius: 10px;
- }
- .scrubber.min-scrubber::-webkit-slider-runnable-track,
- .scrubber.max-scrubber::-webkit-slider-runnable-track {
- z-index: 1;
- height: 0px;
- background-color: red;
- }
- .scrubber::-webkit-slider-thumb {
- -webkit-appearance: none;
- cursor: col-resize;
- width: ${thumbWidth}px;
- }
- .scrubber.time-scrubber::-webkit-slider-thumb {
- z-index: 1;
- height: var(--anime-gui-tl-height);
- background-color: transparent;
- background-image: linear-gradient(
- 90deg,
- rgba(27,26,26,0.00) 25%, #1B1A1A 25.5%,
- #1B1A1A 37.5%, #FFFFFF 38%,
- #FFFFFF 62%, #1B1A1A 62.5%,
- #1B1A1A 74.5%, rgba(27,26,26,0.00) 75%
- );
- }
- .is-playing .scrubber.time-scrubber::-webkit-slider-thumb {
- pointer-events: none;
- }
- .scrubber.min-scrubber::-webkit-slider-thumb,
- .scrubber.max-scrubber::-webkit-slider-thumb,
- .mm-box:before,
- .mm-box:after {
- z-index: 2;
- position: relative;
- height: ${tlScrubberHeight}px;
- height: var(--anime-gui-tl-height);
- background-color: ${whiteAlpha2Color};
- filter: saturate(2);
- backdrop-filter: blur(8px);
- cursor: ew-resize;
- }
- .scrubber.min-scrubber::-webkit-slider-thumb:hover,
- .scrubber.max-scrubber::-webkit-slider-thumb:hover {
- background-color: ${whiteAlpha3Color};
- }
- .scrubber.min-scrubber::-webkit-slider-thumb {
- transform: translateX(calc(-${thumbWidth / 2}px - 2px));
- border-radius: 4px 0 0 4px;
- }
- .scrubber.max-scrubber::-webkit-slider-thumb {
- transform: translateX(calc(${thumbWidth / 2}px + 2px));
- border-radius: 0 4px 4px 0;
- }
- .mm-tl {
- overflow: hidden;
- width: 100%;
- height: calc(100% - 6px);
- margin-top: 3px;
- }
- .mm-tl-scroll {
- flex-direction: column;
- justify-content: center;
- width: 100%;
- height: 100%;
- }
- .mm-tl-line {
- height: 100%;
- max-height: 4px;
- flex-shrink: 1;
- background-color: currentColor;
- box-shadow: 0 0 0 .25px currentColor;
- border-radius: 4px;
- }
- .mm-box {
- pointer-events: none;
- position: absolute;
- left: 0;
- top: 0;
- right: 0;
- bottom: 0;
- }
- .mm-box:before,
- .mm-box:after {
- content: "";
- display: block;
- position: absolute;
- z-index: 1;
- left: 0;
- right: 0;
- height: 2px;
- }
- .mm-box:before { top: 0; }
- .mm-box:after { bottom: 0; }
- .mm-scrubber .scrubber.time-scrubber {
- height: ${toolbarItemHeight - 6}px;
- margin-top: 3px;
- }
- .mm-scrubber {
- width: 100%;
- }
- .mm-scrubber .scrubber.time-scrubber::-webkit-slider-thumb {
- height: ${toolbarItemHeight - 6}px;
- margin-top: -7px;
- }
- .mm-scrubber .scrubber.min-scrubber::-webkit-slider-thumb,
- .mm-scrubber .scrubber.max-scrubber::-webkit-slider-thumb {
- height: ${toolbarItemHeight}px;
- }
- .wrapper:not(.is-clamped) .min-scrubber,
- .wrapper:not(.is-clamped) .max-scrubber,
- .wrapper:not(.is-clamped) .mm-box {
- display: none;
- }
- .tl {
- flex-direction: column;
- left: ${sideBarWidth}px;
- padding-right: ${sideBarWidth}px;
- color: ${whiteColor};
- backface-visibility: hidden;
- font-size: 40px;
- }
- .tl-scrubber {
- position: sticky;
- z-index: 3;
- top: 0;
- align-items: flex-start;
- height: ${tlScrubberHeight}px;
- }
- .clock {
- width: 140px;
- flex-shrink: 0;
- justify-content: flex-end;
- align-items: center;
- padding: 10px;
- align-items: center;
- }
- .current-time {
- justify-content: flex-end;
- position: absolute;
- left: 14px;
- top: 9px;
- width: 6ch;
- font-size: 16px;
- font-weight: bold;
- letter-spacing: 1px;
- text-align: right;
- }
- .current-time-shadow {
- opacity: .2;
- }
- .total-time {
- position: absolute;
- left: 67px;
- top: 9px;
- font-size: 16px;
- font-weight: 300;
- letter-spacing: 0.5px;
- text-align: left;
- }
- .total-duration {
- opacity: .75;
- margin-top: 4px;
- margin-left: 3px;
- font-weight: bold;
- font-size: 8px;
- letter-spacing: 0.5px;
- line-height: 6px;
- border-left: 1px solid currentColor;
- padding-left: 4px;
- }
- .progress-circle {
- opacity: .7;
- width: 14px;
- height: 14px;
- margin-left: 10px;
- }
- .time-ruller {
- overflow: hidden;
- pointer-events: none;
- align-items: center;
- justify-content: flex-start;
- position: absolute;
- top: 0;
- left: 0;
- height: ${tlScrubberHeight}px;
- color: ${whiteAlpha3Color};
- background-color: ${blackColor}AA;
- backdrop-filter: blur(8px);
- }
- .time-ruller-digit {
- justify-content: flex-start;
- width: ${msToEm(500)};
- height: ${tlScrubberHeight}px;
- padding-left: 4px;
- text-align: center;
- }
- .time-ruller-digit span {
- font-weight: bold;
- font-size: 10px;
- margin-top: 2px;
- }
- .timeline-block {
- flex-direction: column;
- }
- .animation-block {
- flex-direction: column;
- }
- .iterations-block {
- flex-direction: row;
- align-items: flex-start;
- }
- .iteration-block {
- flex-direction: column;
- }
- .iteration-block.is-reversed {
- transform: scaleX(-1);
- }
- .iteration-block.is-reversed .label-block {
- transform: scaleX(-1);
- }
- .iteration-block.is-reversed .iteration-label {
- right: 0;
- transform: translateX(100%);
- }
- .line-block {
- height: ${tlLineHeight}px;
- margin-top: 1px;
- margin-bottom: 1px;
- opacity: .87;
- cursor: pointer;
- }
- .line-block:hover {
- opacity: 1;
- filter: saturate(1.2);
- }
- .line-block:before {
- content: "";
- display: block;
- position: absolute;
- left: 0;
- top: -1px;
- right: 0;
- bottom: -1px;
- background-color: transparent;
- }
- .iteration-line-block {
- border-radius: 4px;
- background-color: currentColor;
- }
- .iteration-background-block {
- position: absolute;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- background-color: ${blackAlpha1Color};
- border-radius: 3px;
- }
- .iteration-delay-block {
- border-radius: 3px 0 0 3px;
- }
- .iteration-duration-block {
- justify-content: space-between;
- background-color: currentColor;
- border-radius: 3px;
- }
- .iteration-endDelay-block {
- border-radius: 0 3px 3px 0;
- }
- .tween-line-block {
- border-radius: ${tlLineHeight / 2}px;
- }
- .tween-block {
- background-color: currentColor;
- border-radius: ${tlLineHeight / 2}px;
- }
- .tween-block-item {
- height: ${tlLineHeight}px;
- }
- .tween-background-block {
- position: absolute;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- background-color: ${blackAlpha1Color};
- border-radius: ${tlLineHeight / 2}px;
- }
- .tween-duration-block {
- overflow: hidden;
- justify-content: space-between;
- background-color: currentColor;
- border-radius: ${tlLineHeight / 2}px;
- }
- .tween-skipped-duration-block {
- position: absolute;
- top: 0;
- right: 0;
- border-radius: 0px 7px 7px 0px;
- background-image: linear-gradient(
- 45deg,
- transparent 25%, ${blackAlpha2Color} 25%, ${blackAlpha2Color} 50%,
- transparent 50%, transparent 75%, ${blackAlpha2Color} 75%,
- ${blackAlpha2Color} 100%
- );
- background-size: 3px 3px;
- }
- .label-block {
- pointer-events: none;
- z-index: 1;
- align-items: center;
- height: 100%;
- margin-top: 0px;
- padding-left: 4px;
- padding-right: 4px;
- font-size: 10px;
- font-weight: bold;
- letter-spacing: .05em;
- white-space: pre;
- }
- .tl-label-block {
- pointer-events: auto;
- position: absolute;
- z-index: 1;
- top: 0px;
- height: 100%;
- background-color: ${colors[0]}77;
- backdrop-filter: blur(8px);
- cursor: pointer;
- }
- .tl-label-block:after {
- pointer-events: none;
- content: "";
- display: block;
- position: absolute;
- top: 0px;
- left: -1px;
- width: 0px;
- height: var(--anime-gui-tl-height);
- border-left: 1px dotted ${colors[0]}77;
- }
- .tl-label-block .label-block {
- color: ${whiteAlpha3Color};
- }
- .tl-label-block:hover .label-block {
- color: ${whiteColor};
- }
- .tween-line-block .label-block {
- opacity: 0;
- }
- .tween-block-item > .label-block {
- color: ${blackColor};
- }
- .iteration-line-block > .label-block,
- .tween-block > .label-block {
- opacity: .4;
- position: absolute;
- left: 0;
- top: 0;
- color: currentColor;
- transform: translateX(calc(-100% + 4px));
- }
- .iterations-block:first-child:hover > .iteration-block-item > .iteration-line-block .label-block,
- .animation-block:hover > .iterations-block:first-child .tween-line-block:hover .label-block,
- .tween-line-block:hover .label-block {
- opacity: 1!important;
- transition-duration: 0s;
- }
- .iteration-block:before {
- content: "";
- position: absolute;
- opacity: 0;
- left: 0;
- top: 0;
- right: 0;
- bottom: 0;
- background-color: currentColor;
- transition: opacity .25s ease-out;
- }
- .is-highlighted {
- filter: brightness(2);
- }
- .highlight {
- opacity: 0;
- position: absolute;
- zIndex: 9999;
- box-shadow: 0 0 0 1px #0008, 0 0 0 3px currentColor, 0 0 0 4px #0008;
- border-radius: 2px;
- }
- .highlight:before {
- content: "";
- opacity: .25;
- display: block;
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- zIndex: 9999;
- border-radius: 3px;
- background-color: currentColor;
- }
-`;
-
-const dom = initDOM();
-const targetsIdMap = new Map();
-const idsTargetMap = new Map();
-
-let targetId = 0;
-
-function registerTarget($target) {
- const id = targetsIdMap.get($target);
- if (id !== undefined) {
- return id;
- } else {
- targetsIdMap.set($target, ++targetId);
- idsTargetMap.set(targetId, $target);
- return targetId;
- }
-}
-
-function highlightTarget(targetId, color) {
- const $target = idsTargetMap.get(targetId);
- if (!$target) return;
- const { left, top, width, height } = $target.getBoundingClientRect();
- if (width + height === 0) return;
- let $highlight = utils.$(`.${prefix}highlight.${prefix}${targetId}`)[0];
- if (!$highlight) {
- $highlight = createBlock(['highlight', targetId]);
- document.body.appendChild($highlight);
- }
- utils.set($highlight, { left, top, width, height, opacity: 1, color: color });
-}
-
-function clearHighlight() {
- utils.$(`.${prefix}highlight`).forEach($highlight => $highlight.remove());
-}
-
-function createLabel(text, css) {
- const el = createBlock('label-block', css);
- el.innerHTML = text;
- return el;
-}
-
-/**
- * @param {Tween} tween
- * @param {Target} previousTweenEl
- * @param {HTMLElement} animationEl
- * @param {Boolean} isFirstIteration
- * @return {Target|HTMLElement}
- */
-function createTweenBlock(tween, previousTweenEl, animationEl, isFirstIteration) {
- const el = createBlock(['line-block', 'tween-line-block']);
- const tweenEl = createBlock(['tween-block']);
- const backgroundEl = createBlock(['tween-background-block']);
- const delayEl = createBlock(['tween-delay-block', 'tween-block-item']);
- const durationEl = createBlock(['tween-duration-block', 'tween-block-item']);
- const skippedDurationEl = createBlock(['tween-skipped-duration-block', 'tween-block-item']);
- const fromValueLabelEl = createLabel(tween._fromNumbers ? tween._fromNumbers[0] : tween._fromNumber, `padding-right: 1px;`);
- const fromToLabelEl = createLabel(tween._toNumbers ? tween._toNumbers[0] : tween._toNumber, `padding-left: 1px;`);
- tweenEl.setAttribute('data-tween', `${tween.id}`);
- if (tween._prevRep) tweenEl.setAttribute('data-previous-tween', `${tween._prevRep.id}`);
- if (tween._nextRep) tweenEl.setAttribute('data-next-tween', `${tween._nextRep.id}`);
- if (tween._isOverridden) tweenEl.style.opacity = `${.5}`;
- durationEl.appendChild(fromValueLabelEl);
- if (parameters.showTweenId) durationEl.appendChild(createLabel(tween.id, `justify-content: center; position: absolute; left: 0; right: 0; text-align: center;`));
- durationEl.appendChild(fromToLabelEl);
- tweenEl.appendChild(backgroundEl);
- // const tweenDelay = (tween.parent._offset + tween._startTime) - tween._absoluteStartTime;
- const tweenDelay = tween._delay;
- if (tweenDelay || tween.parent._delay) {
- delayEl.style.width = msToEm(previousTweenEl ? tweenDelay : tween.parent._delay + tweenDelay);
- tweenEl.appendChild(delayEl);
- }
- // if (tween._changeDuration) {
- durationEl.style.width = msToEm(tween._updateDuration);
- if (tween._updateDuration <= minValue) {
- durationEl.style.width = msToEm(10);
- }
- skippedDurationEl.style.width = msToEm(tween._updateDuration - tween._changeDuration);
- durationEl.appendChild(skippedDurationEl);
- tweenEl.appendChild(durationEl);
- // }
- if (!previousTweenEl) {
- if (isFirstIteration) {
- const propertyLabelEl = createLabel(tween.property + '—');
- tweenEl.appendChild(propertyLabelEl);
- }
- el.appendChild(tweenEl);
- return el;
- } else {
- previousTweenEl.appendChild(tweenEl);
- return previousTweenEl;
- }
-}
-
-function createTimelineLabel(labels, name, tlOffset) {
- const startTime = tlOffset + labels[name];
- const el = createBlock('tl-label-block', `left: ${msToEm(startTime)};`);
- el.dataset.startTime = startTime;
- el.appendChild(createLabel(name));
- return el;
-}
-
-/**
- * @param {Timer&Timeline&Animation} animation
- * @param {Number} i
- * @param {HTMLElement} iterationsEl
- * @param {String} color
- * @param {HTMLElement} $tlScrubber
- * @return {HTMLElement}
- */
-function createIterationBlock(animation, i, iterationsEl, color, $tlScrubber) {
- const { _reversed, _alternate, _delay, _loopDelay, iterationDuration, _offset, labels } = animation;
- const isFirstIteration = !i;
- // const isOdd = i % 2;
- // const isInverted = _direction > 0 && (_direction === 1 || _direction === 2 && isOdd || _direction === 3 && !isOdd);
- const isOdd = i % 2;
- // const isInverted = ~~(_direction === -1 || _direction === 2 && isOdd || _direction === -2 && !isOdd);
- const isReversed = _reversed ^ (_alternate && isOdd);
- const iterationEl = createBlock(['iteration-block', 'iteration-block-item']);
- const iterationLineEl = createBlock(['line-block', 'iteration-line-block']);
- const backgroundEl = createBlock(['iteration-background-block']);
- const delayEl = createBlock(['iteration-delay-block', 'iteration-block-item']);
- const durationEl = createBlock(['iteration-duration-block', 'iteration-block-item']);
- const loopDelayEl = createBlock(['iteration-loopDelay-block', 'iteration-block-item']);
- iterationLineEl.appendChild(backgroundEl);
- if (isFirstIteration) {
- const labelPrefix = isNaN(+animation.id) ? '' : animation._hasChildren ? 'Timeline ' : 'Animation ';
- const labelEl = createLabel(labelPrefix + animation.id + '—');
- iterationLineEl.appendChild(labelEl);
- }
- if (_delay) {
- delayEl.style.width = msToEm(_delay);
- iterationLineEl.appendChild(delayEl);
- }
- const isSet = iterationDuration <= minValue;
- // TODO: REMOVE?
- if (iterationDuration === Infinity || iterationDuration === maxValue) {
- // durationEl.style.width = msToEm(iterationDuration);
- durationEl.appendChild(createLabel('∞', `
- font-size: 16px;
- margin-left: auto;
- margin-right: auto;
- `));
- } else if (isSet) {
- durationEl.style.width = msToEm(10);
- } else {
- durationEl.style.width = msToEm(iterationDuration);
- }
- iterationLineEl.appendChild(durationEl);
- if (_loopDelay) {
- loopDelayEl.style.width = msToEm(_loopDelay);
- iterationLineEl.appendChild(loopDelayEl);
- }
-
- if (isSet) {
- iterationEl.style.width = msToEm(10);
- } else {
- iterationEl.style.width = msToEm(animation.iterationDuration + animation._loopDelay);
- }
-
- // if (!animation._hasChildren) {
- // iterationEl.appendChild(iterationLineEl);
- // }
-
- iterationEl.appendChild(iterationLineEl);
-
- if (isReversed) {
- iterationEl.classList.add(`${prefix}is-reversed`);
- }
-
- if (!animation._hasChildren) {
- let currentTarget;
- let currentProperty;
- let previousTargetTweenEl;
- forEachChildren(animation, tween => {
- const target = tween.target;
- const property = tween.property;
- let hasPreviousTween = (property === currentProperty && currentTarget === target);
- if (currentTarget !== target) {
- currentTarget = target;
- }
- const tweenBLockEl = createTweenBlock(tween, hasPreviousTween ? previousTargetTweenEl : false, iterationsEl, isFirstIteration);
- previousTargetTweenEl = tweenBLockEl;
- currentProperty = property;
- tweenBLockEl.dataset.color = color;
- tweenBLockEl.dataset.targetId = registerTarget(target);
- iterationEl.appendChild(tweenBLockEl);
- });
- }
-
- if (labels) {
- for (let name in labels) {
- const timelineLabelEl = createTimelineLabel(labels, name, _offset);
- $tlScrubber.appendChild(timelineLabelEl);
- }
- }
-
- return iterationEl;
-}
-
-/**
- * @param {Timer&Timeline&Animation} animation
- * @param {String} color
- * @return {HTMLElement}
- */
-function createIterationsBlock(animation, color) {
- const { $tlScrubber } = dom;
- const $el = createBlock('iterations-block');
- // const iterationCount = 1;
- const iterationCount = animation.iterationCount === Infinity ? 1 : animation.iterationCount;
- const visualOffsetMs = animation._offset;
- for (let i = 0; i < iterationCount; i++) {
- const iterationEl = createIterationBlock(animation, i, $el, color, $tlScrubber);
- if (animation._hasChildren) {
- forEachChildren(animation, child => {
- // Do not display tl.set() animations
- // if (child.duration > 1) {
- const childAnimationEl = createAnimationBlock(child);
- childAnimationEl.style.marginLeft = msToEm(-visualOffsetMs);
- iterationEl.appendChild(childAnimationEl);
- // }
- });
- }
- $el.appendChild(iterationEl);
- }
- $el.style.marginLeft = msToEm(visualOffsetMs);
- $el.dataset.startTime = visualOffsetMs;
- $el.dataset.endTime = visualOffsetMs + animation.duration;
- $el.dataset.color = color;
- return $el;
-}
-
-function createAnimationBlock(animation) {
- const color = getColor(animation.id);
- const el = createBlock('animation-block', `color: ${color};`);
- const iterationsBLockEl = createIterationsBlock(animation, color);
- el.setAttribute('data-animation', animation.id);
- el.appendChild(iterationsBLockEl);
- return el;
-}
-
-function clearHighlightTweens() {
- const $tweens = dom.$wrapper.querySelectorAll(`.${prefix}tween-block`);
- for (let i = 0, l = $tweens.length; i < l; i++) {
- $tweens[i].classList.remove(`${prefix}is-highlighted`);
- }
-}
-
-function highlightSiblings($tween) {
- clearHighlightTweens();
- const nextId = $tween.getAttribute('data-next-tween');
- const prevId = $tween.getAttribute('data-previous-tween');
- if (nextId) {
- const $nextTween = dom.$wrapper.querySelector(`.${prefix}tween-block[data-tween="${nextId}"]`);
- if ($nextTween) $nextTween.classList.add(`${prefix}is-highlighted`);
- }
- if (prevId) {
- const $prevTween = dom.$wrapper.querySelector(`.${prefix}tween-block[data-tween="${prevId}"]`);
- if ($prevTween) $prevTween.classList.add(`${prefix}is-highlighted`);
- }
-}
-
-function updateCurrentTimeParam() {
- const activeInstance = getActiveInstance();
- setParameter('time', utils.round(activeInstance.currentTime, 0));
-}
-
-function generateScrubberTL(progressAnimation) {
- const activeInstance = getActiveInstance();
- const { duration } = activeInstance;
- const { clamped } = parameters;
- const scrubberDuration = clamped ? parameters.endTime - parameters.startTime : duration;
- const scrubberStart = clamped ? parameters.startTime : 0;
- const scrubberEnd = clamped ? parameters.endTime : duration;
- const minProgress = clamped ? scrubberStart / duration : 0;
- const maxProgress = clamped ? scrubberEnd / duration : 1;
-
- const tl = createTimeline({
- autoplay: false,
- onBegin: () => setPlaybackStatus(false),
- onComplete: () => setPlaybackStatus(true),
- playbackRate: parameters.speed,
- loop: parameters.loop,
- defaults: {
- duration: scrubberDuration,
- ease: 'linear',
- },
- })
- .add({
- frameRate: 1,
- duration: scrubberDuration,
- onUpdate: updateCurrentTimeParam,
- }, 0)
- .add([activeInstance, progressAnimation], {
- progress: [minProgress, maxProgress],
- // onUpdate: () => {
- // console.log(activeInstance.progress, progressAnimation.progress);
- // }
- }, 0)
- .add(`.${prefix}time-scrubber`, {
- value: [minProgress, maxProgress],
- }, 0)
- .add(dom.$currentTime, {
- innerHTML: [scrubberStart, scrubberEnd],
- modifier: utils.round(0)
- }, 0)
- .add(dom.$currentTimeShadow, {
- innerHTML: [scrubberStart, scrubberEnd],
- modifier: utils.round(0).padStart(6, '0')
- }, 0);
-
- return tl.seek(parameters.time);
-}
-
-function createMMMap($tlBlock, duration, loopDelay) {
- const $map = createBlock('mm-tl');
- const $tlIterationsBlock = $tlBlock.querySelector(`:scope > .${prefix}iterations-block`);
- const $tlIterationBlocks = $tlIterationsBlock.querySelectorAll(`:scope > .${prefix}iteration-block`);
- const totalIterations = $tlIterationBlocks.length;
- const iterationTotalDuration = (duration + loopDelay) / totalIterations;
- const loopDelayScale = iterationTotalDuration / (duration / totalIterations) * 100;
- const iterationLoopDelayPercent = (loopDelay * totalIterations) / (duration + loopDelay);
- const iterationDurationPercent = 1 - iterationLoopDelayPercent;
-
- $tlIterationBlocks.forEach(($iterationBlock, i) => {
- const $tlIterationsBlocks = $iterationBlock.querySelectorAll(`.${prefix}iterations-block`);
- const isReversed = $iterationBlock.classList.contains(`${prefix}is-reversed`);
- const $mmScroll = createBlock('mm-tl-scroll', `
- width: ${((iterationDurationPercent / totalIterations) * loopDelayScale)}%;
- margin-right: ${ totalIterations - 1 === i ? 0 : ((iterationLoopDelayPercent / totalIterations) * loopDelayScale)}%;
- transform: scaleX(${isReversed ? -1 : 1});
- `);
- const $iterationEl = createBlock('mm-tl-line', `
- left: 0%;
- width: 100%;
- color: ${$tlIterationsBlock.dataset.color};
- `);
- $mmScroll.appendChild($iterationEl);
- $tlIterationsBlocks.forEach($block => {
- const startTime = ((+$block.dataset.startTime / (duration - (loopDelay * (totalIterations - 1)))) * totalIterations) * 100;
- const endTime = ((+$block.dataset.endTime / (duration - (loopDelay * (totalIterations - 1)))) * totalIterations) * 100;
- const $el = createBlock('mm-tl-line', `
- left: ${startTime}%;
- width: ${(endTime - startTime)}%;
- color: ${$block.dataset.color};
- `);
- $mmScroll.appendChild($el);
- });
- $map.appendChild($mmScroll);
- });
- return $map;
-}
-
-function cteateTimeRuller(duration) {
- const $timeRuller = createBlock(['time-ruller', 'ruller-bg'], `
- width: ${msToEm(duration)}
- `);
-
- for (let i = 0, l = utils.round(duration / 500, 0) + 1; i < l; i++) {
- const timeRullerDigitEl = createBlock('time-ruller-digit');
- timeRullerDigitEl.innerHTML = `<span>${i / 2}</span>`;
- $timeRuller.appendChild(timeRullerDigitEl);
- }
-
- return $timeRuller;
-}
-
-function renderTL() {
- const activeInstance = getActiveInstance();
- const { $tl, $mmScrubber, $tlScrubber, $totalDuration } = dom;
- let duration = activeInstance.duration;
- // TODO: REMOVE?
- if (duration === maxValue) {
- duration = activeInstance.iterationDuration;
- }
- const $tlBlock = createAnimationBlock(activeInstance);
- const $timeRuller = cteateTimeRuller(duration);
- const $mmMap = createMMMap($tlBlock, duration, activeInstance._loopDelay);
-
- $tlScrubber.appendChild($timeRuller);
- $tl.appendChild($tlBlock);
- $mmScrubber.appendChild($mmMap);
-
- utils.set(`.${prefix}scrubber`, { step: utils.round(1 / duration, 8) });
- utils.set($tl, { width: `calc(${msToEm(duration)} + ${sideBarWidth}px)` });
- utils.set($totalDuration, { innerHTML: `${duration}<br>ms` });
- utils.set(`.${prefix}toggle-button svg`, { rotate: parameters.minified !== false ? 0 : 180 });
-
- // Events
-
- const $iterationLines = $tlBlock.querySelectorAll(`.${prefix}iteration-line-block`);
- const $tweenLines = $tlBlock.querySelectorAll(`.${prefix}tween-line-block`);
- const $tweens = $tlBlock.querySelectorAll(`.${prefix}tween-block`);
-
- $iterationLines.forEach($iterationLine => {
- $iterationLine.onmouseenter = () => {
- const $tweenLines = $iterationLine.parentNode.querySelectorAll(`.${prefix}tween-line-block`);
- $tweenLines.forEach($tweenLine => {
- const iterationColor = utils.get($tweenLine.parentNode, 'color');
- highlightTarget(+$tweenLine.dataset.targetId, iterationColor);
- });
- };
- $iterationLine.onmouseleave = clearHighlight;
- });
-
- $tweenLines.forEach($tweenLine => {
- const { targetId, color } = $tweenLine.dataset;
- $tweenLine.onmouseenter = () => highlightTarget(+targetId, color);
- $tweenLine.onmouseleave = clearHighlight;
- });
-
- if (parameters.highlightSiblings) {
- for (let i = 0, l = $tweens.length; i < l; i++) {
- const $tween = $tweens[i];
- $tween.onmouseenter = () => highlightSiblings($tween);
- $tween.onmouseleave = () => highlightSiblings($tween);
- }
- }
-
- return $tlBlock;
-}
-
-function appendDOM($wrapper) {
- utils.set(parameters.$container, {
- '--anime-gui-height': `${parameters.height}px`,
- '--anime-gui-tl-height': `calc(var(--anime-gui-height) - ${toolbarHeight}px)`,
- paddingBottom: 'var(--anime-gui-height)',
- });
- parameters.$container.appendChild($wrapper);
-}
-
-let wrapperWasOpen;
-
-function setWrapperSize(newH) {
- const height = utils.clamp(toolbarHeight, window.innerHeight).round(0)(newH);
- const isOpen = height > toolbarHeight;
- setParameter('height', height);
- utils.set(parameters.$container, { '--anime-gui-height': height + 'px' });
- if (wrapperWasOpen !== isOpen) {
- animate(`.${prefix}toggle-button svg`, { rotate: !wrapperWasOpen ? 180 : 0, duration: 250 });
- }
- wrapperWasOpen = isOpen;
-}
-
-function resizeSrubberRange(duration) {
- const { startTime, endTime } = parameters;
- utils.set(dom.$mmBox, {
- left: `calc(${(startTime / duration) * 100}% - 3px)`,
- right: `calc(${((duration - endTime) / duration) * 100}% - 3px)`,
- modifier: utils.round(1),
- });
-}
-
-function setPlaybackStatus(paused) {
- const playbackMode = paused ? 'play' : 'pause';
- const classMode = paused ? 'remove' : 'add';
- utils.set(`.${prefix}playback-button`, { innerHTML: getIconCode(playbackMode) });
- document.body.classList[classMode](`${prefix}is-playing`);
- updateCurrentTimeParam();
-}
-
-function togglePlayback(scrubberTL) {
- const { paused } = scrubberTL;
- scrubberTL[paused ? 'play' : 'pause']();
- setPlaybackStatus(!paused);
-}
-
-function inspect(instance, userParams = {}) {
- instance.pause();
- if (instance.iterationCount === Infinity) {
- instance.iterationCount = 1;
- instance.duration = instance.iterationDuration;
- parameters.loop = true;
- }
- parseParameters(userParams);
- instances.push(instance);
- const { height } = parameters;
- if (isNil(parameters.endTime)) parameters.endTime = instance.duration;
- if (isNil(parameters.active)) parameters.active = instances.length - 1;
- if (isNil(parameters.minified)) parameters.minified = height === toolbarHeight ? false : height;
- dom.$speedButton.value = parameters.speed;
-
- appendStyles(styles);
- appendDOM(dom.$wrapper);
- renderTL();
-
- const progressAnimation = animate(svg.createDrawable(`.${prefix}progress-circle path`), {
- draw: '0 1',
- ease: 'linear',
- autoplay: false
- });
-
- let scrubberTL = generateScrubberTL(progressAnimation);
-
- function updateClamp() {
- const { clamped } = parameters;
- const { paused } = scrubberTL;
- const { currentTime } = instance;
- const className = clamped ? 'add' : 'remove';
- dom.$clampButton.classList[className](`${prefix}is-active`);
- dom.$wrapper.classList[className](`${prefix}is-clamped`);
- scrubberTL.cancel();
- scrubberTL = generateScrubberTL(progressAnimation);
- scrubberTL.pause().seek(clamped ? 0 : currentTime);
- if (!paused) scrubberTL.play();
- }
-
- function toggleClamp() {
- parameters.clamped = !parameters.clamped;
- setParameter('clamped', parameters.clamped);
- updateClamp();
- }
-
- setPlaybackStatus(scrubberTL.paused);
- updateClamp();
-
- function updateTimeScrubberValue(timeValue, duration) {
- clearHighlight();
- updateCurrentTimeParam();
- const minProgress = parameters.clamped ? parameters.startTime / duration : 0;
- const maxProgress = parameters.clamped ? parameters.endTime / duration : 1;
- const value = utils.clamp(timeValue, minProgress, maxProgress);
- utils.set(`.${prefix}time-scrubber`, { value });
- scrubberTL.completed = false;
- scrubberTL.progress = utils.mapRange(value, minProgress, maxProgress, 0, 1);
- }
-
- function seekToRange(startTime, endTime) {
- if (parameters.clamped) {
- setParameter('startTime', startTime);
- setParameter('endTime', endTime);
- scrubberTL.cancel();
- scrubberTL = generateScrubberTL(progressAnimation);
- createTimeline({ defaults: { duration: 250, ease: 'out(3)', composition: 'add' } })
- .add(`.${prefix}min-scrubber`, { value: startTime / instance.duration }, 0)
- .add(`.${prefix}max-scrubber`, { value: endTime / instance.duration }, 0)
- .add(dom.$mmBox, {
- left: `calc(${(startTime / instance.duration) * 100}% - 3px)`,
- right: `calc(${((instance.duration-endTime) / instance.duration) * 100}% - 3px)`,
- modifier: utils.round(1),
- }, 0);
- updateTimeScrubberValue(startTime, instance.duration);
- resizeSrubberRange(instance.duration);
- scrubberTL.play();
- } else {
- scrubberTL.pause().seek(startTime).play();
- }
- }
-
- const $timeScrubbers = utils.$(`.${prefix}time-scrubber`);
- const $minScrubbers = utils.$(`.${prefix}min-scrubber`);
- const $maxScrubbers = utils.$(`.${prefix}max-scrubber`);
-
- utils.set($timeScrubbers, { value: parameters.time / instance.duration });
- utils.set($minScrubbers, { value: parameters.startTime / instance.duration });
- utils.set($maxScrubbers, { value: parameters.endTime / instance.duration });
-
- resizeSrubberRange(instance.duration);
-
- $timeScrubbers.forEach($timeScrubber => {
- $timeScrubber.onmousedown = () => {
- scrubberTL.pause();
- setPlaybackStatus(scrubberTL.paused);
- };
- $timeScrubber.oninput = () => updateTimeScrubberValue($timeScrubber.value, instance.duration);
- });
-
- const onMinScrubberInput = function() {
- const startTime = utils
- .clamp(0, parameters.endTime).round(0)
- (this.value * instance.duration);
- setParameter('startTime', startTime);
- scrubberTL.cancel();
- scrubberTL = generateScrubberTL(progressAnimation);
- scrubberTL.pause().seek(0);
- setPlaybackStatus(scrubberTL.paused);
- utils.set($minScrubbers, { value: startTime / instance.duration });
- resizeSrubberRange(instance.duration);
- };
-
- const onMaxScrubberInput = function() {
- const endTime = utils
- .clamp(parameters.startTime, instance.duration).round(0)
- (this.value * instance.duration);
- setParameter('endTime', endTime);
- scrubberTL.cancel();
- scrubberTL = generateScrubberTL(progressAnimation);
- scrubberTL.pause().seek(scrubberTL.duration);
- setPlaybackStatus(scrubberTL.paused);
- utils.set($maxScrubbers, { value: endTime / instance.duration });
- resizeSrubberRange(instance.duration);
- };
-
- $minScrubbers.forEach($scrubber => $scrubber.oninput = onMinScrubberInput);
- $maxScrubbers.forEach($scrubber => $scrubber.oninput = onMaxScrubberInput);
-
- dom.$speedButton.addEventListener('change', () => {
- const speed = dom.$speedButton.value;
- setParameter('speed', dom.$speedButton.value);
- scrubberTL.playbackRate = speed;
- });
-
- window.addEventListener('keydown', (e) => {
- if (e.code === 'Space') {
- e.preventDefault();
- togglePlayback(scrubberTL);
- }
- if (e.code === 'KeyB') {
- scrubberTL.progress = 0;
- }
- if (e.code === 'KeyR') {
- scrubberTL.progress = 0;
- scrubberTL.play();
- }
- });
-
- document.addEventListener('click', (e) => {
- const $closestIterationsBlock = e.target.closest(`.${prefix}iterations-block`);
- if ($closestIterationsBlock) {
- const startTime = utils.round($closestIterationsBlock.dataset.startTime, 0);
- const endTime = utils.round($closestIterationsBlock.dataset.endTime, 0);
- seekToRange(startTime, endTime);
- }
- const $closestTlLabelBlock = e.target.closest(`.${prefix}tl-label-block`);
- if ($closestTlLabelBlock) {
- const $nextSlibling = $closestTlLabelBlock.nextElementSibling ? $closestTlLabelBlock.nextElementSibling.matches(`.${prefix}tl-label-block`) ? $closestTlLabelBlock.nextElementSibling : null : null;
- const startTime = utils.round($closestTlLabelBlock.dataset.startTime, 0);
- const endTime = $nextSlibling ? utils.round($nextSlibling.dataset.startTime, 0) : parameters.endTime <= startTime ? instance.duration : parameters.endTime;
- seekToRange(startTime, endTime);
- }
- const $closestToggleButton = e.target.closest(`.${prefix}toggle-button`);
- if ($closestToggleButton) {
- const isOpen = parameters.minified === false;
- createTimeline({
- onRender: () => setWrapperSize(parameters.height),
- defaults: { duration: 350, ease: 'out(4)' },
- })
- .add(parameters, { height: isOpen ? toolbarHeight : parameters.minified }, 0);
- setParameter('minified', isOpen ? parameters.height : false);
- }
- const $closestPlaybackButton = e.target.closest(`.${prefix}playback-button`);
- if ($closestPlaybackButton) {
- togglePlayback(scrubberTL);
- }
- const $closestBackButton = e.target.closest(`.${prefix}back-button`);
- if ($closestBackButton) {
- scrubberTL.progress = 0;
- }
- const $closestClampButton = e.target.closest(`.${prefix}clamp-button`);
- if ($closestClampButton) {
- toggleClamp();
- }
- });
-
- dom.$tlWrapper.scrollLeft = parameters.scrollX;
- dom.$tlWrapper.scrollTop = parameters.scrollY;
-
- dom.$tlWrapper.addEventListener('scroll', () => {
- setParameter('scrollX', dom.$tlWrapper.scrollLeft);
- setParameter('scrollY', dom.$tlWrapper.scrollTop);
- });
-
- // Resize
-
- let startY = 0;
- let startHeight = window.innerHeight;
-
- function resizeWrapper(diffY) {
- const newH = parameters.height + diffY;
- setWrapperSize(newH);
- setParameter('minified', newH > toolbarHeight ? false : utils.round(window.innerHeight * .33, 0));
- }
-
- function onWrapperResize(e) {
- const diffY = startY - e.y;
- resizeWrapper(diffY);
- startY = e.y;
- }
-
- function onWindowResize() {
- const diffY = window.innerHeight - startHeight;
- resizeWrapper(diffY);
- startHeight = window.innerHeight;
- }
-
- dom.$resizer.addEventListener('mousedown', e => {
- startY = e.y;
- document.addEventListener('mousemove', onWrapperResize, false);
- }, false);
-
- dom.$mmScrubber.addEventListener('wheel', e => {
- e.preventDefault();
- const speed = instance.duration / scrubberTL.duration / 10000;
- scrubberTL.progress += e.deltaY * speed;
- scrubberTL.progress += e.deltaX * -speed;
- }, {passive: false});
-
- document.addEventListener('mouseup', () => {
- document.removeEventListener('mousemove', onWrapperResize, false);
- }, false);
-
- window.onresize = onWindowResize;
-
- // Play if the active instance has autplay defined
-
- scrubberTL[instance._autoplay ? 'play' : 'pause']();
-
-}
-
-export { inspect };
diff --git a/package.json b/package.json
index 259368d9..e5756570 100644
--- a/package.json
+++ b/package.json
@@ -1,63 +1,159 @@
{
"name": "animejs",
- "version": "4.1.3",
+ "version": "4.2.0-beta.0",
+ "description": "JavaScript animation engine",
"homepage": "https://animejs.com",
+ "author": "Julian Garnier <[email protected]>",
+ "license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/juliangarnier/anime.git"
},
- "description": "JavaScript animation engine",
- "main": "lib/anime.umd.js",
- "module": "lib/anime.esm.js",
- "types": "types/index.d.ts",
- "type": "module",
- "exports": {
- ".": {
- "types": "./types/index.d.ts",
- "import": "./lib/anime.esm.js",
- "require": "./lib/anime.cjs"
- },
- "./package.json": "./package.json"
- },
- "license": "MIT",
- "author": "Julian Garnier <[email protected]>",
- "sideEffects": false,
"bugs": {
"url": "https://github.com/juliangarnier/anime/issues"
},
- "files": [
- "lib",
- "types"
- ],
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/juliangarnier"
+ },
"keywords": [
"anime",
+ "animejs",
"anime.js",
"animation",
+ "timeline",
+ "easings",
+ "spring",
+ "scroll",
+ "drag",
+ "text",
"JavaScript",
"CSS",
- "transforms",
"SVG",
- "canvas"
+ "WAAPI",
+ "Canvas",
+ "WebGL"
],
+ "files": [
+ "dist"
+ ],
+ "sideEffects": false,
+ "type": "module",
+ "main": "./dist/modules/index.cjs",
+ "module": "./dist/modules/index.js",
+ "types": "./dist/modules/index.d.ts",
+ "jsdelivr": "./dist/bundles/anime.umd.min.js",
+ "unpkg": "./dist/bundles/anime.umd.min.js",
+ "exports": {
+ "./package.json": "./package.json",
+ ".": {
+ "types": "./dist/modules/index.d.ts",
+ "require": "./dist/modules/index.cjs",
+ "import": "./dist/modules/index.js",
+ "default": "./dist/modules/index.cjs"
+ },
+ "./timer": {
+ "types": "./dist/modules/timer/index.d.ts",
+ "require": "./dist/modules/timer/index.cjs",
+ "import": "./dist/modules/timer/index.js",
+ "default": "./dist/modules/timer/index.cjs"
+ },
+ "./animation": {
+ "types": "./dist/modules/animation/index.d.ts",
+ "require": "./dist/modules/animation/index.cjs",
+ "import": "./dist/modules/animation/index.js",
+ "default": "./dist/modules/animation/index.cjs"
+ },
+ "./timeline": {
+ "types": "./dist/modules/timeline/index.d.ts",
+ "require": "./dist/modules/timeline/index.cjs",
+ "import": "./dist/modules/timeline/index.js",
+ "default": "./dist/modules/timeline/index.cjs"
+ },
+ "./animatable": {
+ "types": "./dist/modules/animatable/index.d.ts",
+ "require": "./dist/modules/animatable/index.cjs",
+ "import": "./dist/modules/animatable/index.js",
+ "default": "./dist/modules/animatable/index.cjs"
+ },
+ "./draggable": {
+ "types": "./dist/modules/draggable/index.d.ts",
+ "require": "./dist/modules/draggable/index.cjs",
+ "import": "./dist/modules/draggable/index.js",
+ "default": "./dist/modules/draggable/index.cjs"
+ },
+ "./scope": {
+ "types": "./dist/modules/scope/index.d.ts",
+ "require": "./dist/modules/scope/index.cjs",
+ "import": "./dist/modules/scope/index.js",
+ "default": "./dist/modules/scope/index.cjs"
+ },
+ "./engine": {
+ "types": "./dist/modules/engine/index.d.ts",
+ "require": "./dist/modules/engine/index.cjs",
+ "import": "./dist/modules/engine/index.js",
+ "default": "./dist/modules/engine/index.cjs"
+ },
+ "./events": {
+ "types": "./dist/modules/events/index.d.ts",
+ "require": "./dist/modules/events/index.cjs",
+ "import": "./dist/modules/events/index.js",
+ "default": "./dist/modules/events/index.cjs"
+ },
+ "./spring": {
+ "types": "./dist/modules/spring/index.d.ts",
+ "require": "./dist/modules/spring/index.cjs",
+ "import": "./dist/modules/spring/index.js",
+ "default": "./dist/modules/spring/index.cjs"
+ },
+ "./easings": {
+ "types": "./dist/modules/easings/index.d.ts",
+ "require": "./dist/modules/easings/index.cjs",
+ "import": "./dist/modules/easings/index.js",
+ "default": "./dist/modules/easings/index.cjs"
+ },
+ "./utils": {
+ "types": "./dist/modules/utils/index.d.ts",
+ "require": "./dist/modules/utils/index.cjs",
+ "import": "./dist/modules/utils/index.js",
+ "default": "./dist/modules/utils/index.cjs"
+ },
+ "./svg": {
+ "types": "./dist/modules/svg/index.d.ts",
+ "require": "./dist/modules/svg/index.cjs",
+ "import": "./dist/modules/svg/index.js",
+ "default": "./dist/modules/svg/index.cjs"
+ },
+ "./text": {
+ "types": "./dist/modules/text/index.d.ts",
+ "require": "./dist/modules/text/index.cjs",
+ "import": "./dist/modules/text/index.js",
+ "default": "./dist/modules/text/index.cjs"
+ },
+ "./waapi": {
+ "types": "./dist/modules/waapi/index.d.ts",
+ "require": "./dist/modules/waapi/index.cjs",
+ "import": "./dist/modules/waapi/index.js",
+ "default": "./dist/modules/waapi/index.cjs"
+ }
+ },
"devDependencies": {
"@rollup/plugin-terser": "^0.4.4",
"@types/node": "^24.3.0",
"browser-sync": "^2.29.3",
"chai": "^4.3.10",
"mocha": "^10.2.0",
+ "nodemon": "^3.1.10",
"rollup": "^4.9.1",
- "rollup-plugin-filesize": "^10.0.0",
- "rollup-plugin-ts": "^3.4.5",
"three": "^0.160.0",
- "typescript": "5.1.6"
+ "typescript": "^5.9.2"
},
"scripts": {
- "dev": "rollup -c -w",
- "dev-types": "types=true rollup -c -w",
- "build": "build=true types=true rollup -c",
- "release": "build=true release=true types=true rollup -c",
- "open-examples": "browser-sync start --startPath examples --server --no-notify --directory --files '**/*.js'",
- "test-browser": "browser-sync start --startPath tests/index.html --server --files '**/*.js' --no-notify --directory",
- "test-node": "node --allow-natives-syntax \"node_modules/.bin/mocha\" -u tdd --timeout 20000 \"./tests/suites/node.test.js\""
+ "dev": "nodemon --quiet --watch src --ext js --exec \"rollup -c && tsc -p tsconfig.types.json && echo '\\n\\033[32m✓ modules and types compiled\\n\\033[36m⊙ watching for changes...\\n\\033[0m'\"",
+ "dev:test": "npm run dev & npm run test:browser",
+ "build": "rm -rf dist && build=true rollup -c && tsc -p tsconfig.types.json && echo '\\n\\033[32m✓ build completed\\n\\033[0m'",
+ "test:browser": "browser-sync start --startPath tests/index.html --server --files 'dist/modules/**/*.js' 'tests/suites/**/*.js' --no-notify --directory",
+ "test:node": "node --allow-natives-syntax \"node_modules/.bin/mocha\" -u tdd --timeout 20000 \"./tests/suites/node.test.js\"",
+ "open:examples": "browser-sync start --startPath examples --server --no-notify --directory --files '**/*.js'"
}
}
diff --git a/rollup.config.js b/rollup.config.js
index f654e59b..fbc1028d 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -1,185 +1,92 @@
import terser from '@rollup/plugin-terser';
-import filesize from 'rollup-plugin-filesize';
-import ts from 'rollup-plugin-ts';
-import pkg from './package.json' assert { type: 'json' };
import fs from 'fs';
-const inputPath = 'src/anime.js';
-const outputName = 'anime';
-const jsDocTypes = fs.readFileSync('./src/types.js', 'utf-8').split('/* Exports */')[1];
+const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));
-/**
- * @param {String} format
- * @param {Boolean} [addTypes]
- * @return {String}
- */
-const banner = (format, addTypes) => {
+const banner = (format, content = '') => chunk => {
const date = new Date();
+ const moduleName = chunk.fileName.split('/')[0] || '';
return `/**
- * anime.js - ${ format }
+ * Anime.js${ moduleName.includes('.') ? '' : ' - ' + moduleName } - ${ format }
* @version v${ pkg.version }
- * @author Julian Garnier
* @license MIT
- * @copyright (c) ${ date.getFullYear() } Julian Garnier
- * @see https://animejs.com
- */${addTypes ? jsDocTypes : ''}
+ * @copyright ${ date.getFullYear() } - Julian Garnier
+ */${content}
`
}
-const terserModuleOptions = {
- compress: {
- passes: 10,
- module: true,
- },
- mangle: true,
-}
-
-const terserScriptOptions = {
- compress: {
- passes: 10,
- module: false,
- },
- mangle: true,
-}
-
-const terserStripComments = {
- compress: false,
- mangle: false,
-}
-
-const tasks = [];
-
-const cleanupOptions = {
- // Replace "import('./file.js')."
- "import\\('\\.\\/[^']+\\.js'\\)\\.": '',
- "/// <reference path='./types.js' />": '',
- __packageVersion__: pkg.version.toString()
-};
-
-const cleanup = {
- name: 'cleanup',
- generateBundle(_, bundle) {
- Object.keys(bundle).forEach((fileName) => {
- const file = bundle[fileName];
- let code = file.code;
- for (const [find, replacement] of Object.entries(cleanupOptions)) {
- const regExp = new RegExp(find, 'g');
- code = code.replace(regExp, replacement);
- }
- file.code = code;
- });
- },
-};
-
-const prependTypes = {
- name: 'prepend-file',
- transform(code, id) {
- if (id.includes('anime.js')) {
- return {
- code: `${jsDocTypes}\n${code}`,
- map: null // If you're not handling source maps
- };
+const replace = (rgx, string = '') => {
+ return {
+ name: 'replace',
+ generateBundle(_, bundle) {
+ Object.keys(bundle).forEach((fileName) => {
+ const file = bundle[fileName];
+ let code = file.code;
+ code = code.replace(rgx, string);
+ file.code = code;
+ });
}
- return null;
}
-};
-
-tasks.push( // ESM
- {
- input: inputPath,
- output: { file: pkg.module, format: 'esm', banner: banner('ESM', true) },
- plugins: [prependTypes, cleanup]
- },
-);
-
-if (process.env.types) {
- tasks.push( // TYPES
- {
- input: inputPath,
- output: { file: './types/index.js', format: 'esm', banner: banner('ESM') },
- plugins: [prependTypes, cleanup, ts()]
- }
- );
}
-if (process.env.build || process.env.npm_config_minify) {
- tasks.push( // ESM minified
- {
- input: inputPath,
- output: { file: pkg.files[0] + '/anime.esm.min.js', format: 'esm', banner: banner('ESM') },
- plugins: [cleanup, terser(terserModuleOptions), filesize({ showMinifiedSize: false })]
- }
- );
-}
+const updatePackageVersion = replace(/__packageVersion__/g, pkg.version);
-if (process.env.build) {
- tasks.push( // UMD
- {
- input: inputPath,
- output: { file: pkg.main, format: 'umd', name: outputName, banner: banner('UMD') },
- plugins: [cleanup, terser(terserStripComments)]
- }
- );
+// Extracts module input paths from the package.json 'exports' field
+const inputs = Object.keys(pkg.exports).filter(k => k !== './package.json').map(k => `src${k.replace('.', '')}/index.js`);
- tasks.push( // IIFE
+const tasks = [{
+ input: inputs,
+ output: [
{
- input: inputPath,
- output: { file: pkg.files[0] + '/anime.iife.js', format: 'iife', name: outputName, banner: banner('IIFE') },
- plugins: [cleanup, terser(terserStripComments)]
- }
- );
-
- tasks.push( // CJS
+ dir: 'dist/modules/',
+ format: 'esm',
+ preserveModules: true,
+ preserveModulesRoot: 'src',
+ banner: banner('ESM'),
+ },
{
- input: inputPath,
- output: { file: pkg.exports['.'].require, format: 'cjs', name: outputName, banner: banner('CJS') },
- plugins: [cleanup, terser(terserStripComments)]
+ dir: 'dist/modules/',
+ format: 'cjs',
+ entryFileNames: '[name].cjs',
+ preserveModules: true,
+ preserveModulesRoot: 'src',
+ banner: banner('CJS'),
}
- );
+ ],
+ plugins: [updatePackageVersion],
+}];
- tasks.push( // UMD, CJS & IIFE minified
- {
- input: inputPath,
- output: [
- { file: pkg.files[0] + '/anime.umd.min.js', format: 'umd', name: outputName, banner: banner('UMD') },
- { file: pkg.files[0] + '/anime.min.cjs', format: 'cjs', name: outputName, banner: banner('CJS') },
- { file: pkg.files[0] + '/anime.iife.min.js', format: 'iife', name: outputName, banner: banner('IIFE') },
- ],
- plugins: [cleanup, terser(terserScriptOptions)]
- }
- );
+if (process.env.build) {
- // tasks.push( // ES5
- // {
- // input: inputPath,
- // output: { file: pkg.files[0] + '/anime.es5.iife.js', format: 'iife', name: outputName, banner: banner('ES5 IIFE') },
- // plugins: [prependTypes, cleanup, babel({
- // presets: ['@babel/preset-env'],
- // babelHelpers: 'bundled',
- // comments: false,
- // parserOpts: {
- // // @ts-ignore
- // plugins: ['v8intrinsic', '@babel/plugin-transform-arrow-functions']
- // }
- // })]
- // }
- // );
+ // Gets global JSDoc type definitions from src/types to be inserted in the banner of the bundles after tree shaking
+ const JSDocTypes = fs.readFileSync('./src/types/index.js', 'utf-8').split('// Exported types')[1];
+
+ // Removes comments containing JSDoc @import tags to avoid duplicated type definitions in bundles
+ const cleanupJSDocImports = replace(/\/\*\*(?:(?!\*\/|\/\*\*)[\s\S])*?@import(?:(?!\*\/|\/\*\*)[\s\S])*?\*\//g);
+
+ const minify = terser({
+ compress: { passes: 10, module: false },
+ mangle: true,
+ });
+
+ tasks.push({
+ input: 'src/index.js',
+ output: [
+ { file: 'dist/bundles/anime.esm.js', format: 'esm', name: 'anime', banner: banner('ESM bundle', JSDocTypes) },
+ { file: 'dist/bundles/anime.umd.js', format: 'umd', name: 'anime', banner: banner('UMD bundle', JSDocTypes) }
+ ],
+ plugins: [updatePackageVersion, cleanupJSDocImports]
+ });
+
+ tasks.push({
+ input: 'src/index.js',
+ output: [
+ { file: 'dist/bundles/anime.esm.min.js', format: 'esm', name: 'anime', banner: banner('ESM minified bundle') },
+ { file: 'dist/bundles/anime.umd.min.js', format: 'umd', name: 'anime', banner: banner('UMD minified bundle') }
+ ],
+ plugins: [updatePackageVersion, minify]
+ });
- // tasks.push( // ES5 Minified
- // {
- // input: inputPath,
- // output: { file: pkg.files[0] + '/anime.es5.iife.min.js', format: 'iife', name: outputName, banner: banner('ES5 IIFE') },
- // plugins: [cleanup, babel({
- // presets: ['@babel/preset-env'],
- // babelHelpers: 'bundled',
- // comments: false,
- // parserOpts: {
- // // @ts-ignore
- // plugins: ['v8intrinsic', '@babel/plugin-transform-arrow-functions']
- // }
- // })]
- // }
- // );
}
export default tasks;
diff --git a/src/animatable.js b/src/animatable/animatable.js
similarity index 91%
rename from src/animatable.js
rename to src/animatable/animatable.js
index 717ccdbd..862f0c5a 100644
--- a/src/animatable.js
+++ b/src/animatable/animatable.js
@@ -1,13 +1,11 @@
-/// <reference path='./types.js' />
-
import {
compositionTypes,
noop
-} from './consts.js';
+} from '../core/consts.js';
import {
scope,
-} from './globals.js';
+} from '../core/globals.js';
import {
isKey,
@@ -18,15 +16,27 @@ import {
forEachChildren,
isArr,
stringStartsWith,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
JSAnimation,
-} from './animation.js';
+} from '../animation/animation.js';
import {
- parseEasings,
-} from './eases.js';
+ parseEase,
+} from '../easings/eases.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * AnimatableParams,
+ * AnimationParams,
+ * TweenParamsOptions,
+ * Tween,
+ * AnimatableProperty,
+ * AnimatableObject,
+ * } from '../types/index.js';
+ */
export class Animatable {
/**
@@ -119,7 +129,7 @@ export class Animatable {
tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number));
tween._toNumber = /** @type {Number} */(to);
}
- if (!isUnd(ease)) tween._ease = parseEasings(ease);
+ if (!isUnd(ease)) tween._ease = parseEase(ease);
tween._currentTime = 0;
});
if (!isUnd(duration)) animation.stretch(duration);
diff --git a/src/animatable/index.js b/src/animatable/index.js
new file mode 100644
index 00000000..0d1e38f8
--- /dev/null
+++ b/src/animatable/index.js
@@ -0,0 +1 @@
+export * from './animatable.js';
\ No newline at end of file
diff --git a/src/additive.js b/src/animation/additive.js
similarity index 91%
rename from src/additive.js
rename to src/animation/additive.js
index 27679f5a..eae9b795 100644
--- a/src/additive.js
+++ b/src/animation/additive.js
@@ -1,25 +1,30 @@
-/// <reference path='./types.js' />
-
import {
minValue,
noop,
valueTypes,
tickModes,
-} from './consts.js';
+} from '../core/consts.js';
import {
cloneArray,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
render,
-} from './render.js';
+} from '../core/render.js';
export const additive = {
animation: null,
update: noop,
}
+/**
+ * @import {
+ * Tween,
+ * TweenAdditiveLookups,
+ * } from '../types/index.js'
+ */
+
/**
* @typedef AdditiveAnimation
* @property {Number} duration
diff --git a/src/animation.js b/src/animation/animation.js
similarity index 90%
rename from src/animation.js
rename to src/animation/animation.js
index 136049bb..a5ec23ff 100644
--- a/src/animation.js
+++ b/src/animation/animation.js
@@ -1,16 +1,10 @@
-/// <reference path='./types.js' />
-
import {
K,
minValue,
tweenTypes,
valueTypes,
compositionTypes,
- isDomSymbol,
- transformsSymbol,
- emptyString,
- transformsFragmentStrings,
-} from './consts.js';
+} from '../core/consts.js';
import {
mergeObjects,
@@ -25,19 +19,15 @@ import {
normalizeTime,
isNum,
round,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
globals,
-} from './globals.js';
+} from '../core/globals.js';
import {
registerTargets,
-} from './targets.js';
-
-import {
- parseEasings,
-} from './eases.js';
+} from '../core/targets.js';
import {
getRelativeValue,
@@ -49,85 +39,63 @@ import {
decomposeTweenValue,
decomposedOriginalValue,
createDecomposedValueTargetObject,
-} from './values.js';
+} from '../core/values.js';
import {
sanitizePropertyName,
-} from './properties.js';
+ cleanInlineStyles,
+} from '../core/styles.js';
import {
convertValueUnit,
-} from './units.js';
+} from '../core/units.js';
+
+import {
+ parseEase,
+} from '../easings/eases.js';
+
+import {
+ Timer,
+} from '../timer/timer.js';
import {
composeTween,
getTweenSiblings,
overrideTween,
-} from './compositions.js';
+} from './composition.js';
import {
additive,
} from './additive.js';
-import {
- Timer,
-} from './timer.js';
-
/**
- * @template {Renderable} T
- * @param {T} renderable
- * @return {T}
+ * @import {
+ * Tween,
+ * TweenKeyValue,
+ * TweenParamsOptions,
+ * TweenValues,
+ * DurationKeyframes,
+ * PercentageKeyframes,
+ * AnimationParams,
+ * TweenPropValue,
+ * ArraySyntaxValue,
+ * TargetsParam,
+ * TimerParams,
+ * TweenParamValue,
+ * DOMTarget,
+ * TargetsArray,
+ * Callback,
+ * EasingFunction,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+ *
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
*/
-export const cleanInlineStyles = renderable => {
- // Allow cleanInlineStyles() to be called on timelines
- if (renderable._hasChildren) {
- forEachChildren(renderable, cleanInlineStyles, true);
- } else {
- const animation = /** @type {JSAnimation} */(renderable);
- animation.pause();
- forEachChildren(animation, (/** @type {Tween} */tween) => {
- const tweenProperty = tween.property;
- const tweenTarget = tween.target;
- if (tweenTarget[isDomSymbol]) {
- const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
- const originalInlinedValue = animation._inlineStyles[tweenProperty];
- if (tween._tweenType === tweenTypes.TRANSFORM) {
- const cachedTransforms = tweenTarget[transformsSymbol];
- if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
- delete cachedTransforms[tweenProperty];
- } else {
- cachedTransforms[tweenProperty] = originalInlinedValue;
- }
- if (tween._renderTransforms) {
- if (!Object.keys(cachedTransforms).length) {
- targetStyle.removeProperty('transform');
- } else {
- let str = emptyString;
- for (let key in cachedTransforms) {
- str += transformsFragmentStrings[key] + cachedTransforms[key] + ') ';
- }
- targetStyle.transform = str;
- }
- }
- } else {
- if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
- targetStyle.removeProperty(tweenProperty);
- } else {
- targetStyle[tweenProperty] = originalInlinedValue;
- }
- }
- if (animation._tail === tween) {
- animation.targets.forEach(t => {
- if (t.getAttribute && t.getAttribute('style') === emptyString) {
- t.removeAttribute('style');
- };
- });
- }
- }
- })
- }
- return renderable;
-}
// Defines decomposed values target objects only once and mutate their properties later to avoid GC
// TODO: Maybe move the objects creation to values.js and use the decompose function to create the base object
@@ -252,7 +220,7 @@ export class JSAnimation extends Timer {
length = 0
) {
- super(/** @type {TimerParams&AnimationParams} */(parameters), parent, parentPosition);
+ super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
const parsedTargets = registerTargets(targets);
const targetsLength = parsedTargets.length;
@@ -274,7 +242,7 @@ export class JSAnimation extends Timer {
const animDefaults = parent ? parent.defaults : globals.defaults;
const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
- const animEase = animaPlaybackEase ? parseEasings(animaPlaybackEase) : null;
+ const animEase = animaPlaybackEase ? parseEase(animaPlaybackEase) : null;
const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease);
const tDuration = hasSpring ? /** @type {Spring} */(ease).duration : setValue(duration, animDefaults.duration);
@@ -522,7 +490,7 @@ export class JSAnimation extends Timer {
const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject;
const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject;
// TODO: Check if n should be used instead of 0 for default complex values
- shortestValue.d = longestValue.d.map((_, i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
+ shortestValue.d = longestValue.d.map((/** @type {Number} */_, /** @type {Number} */i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
shortestValue.s = cloneArray(longestValue.s);
}
@@ -539,7 +507,7 @@ export class JSAnimation extends Timer {
target: target,
_value: null,
_func: toFunctionStore.func,
- _ease: parseEasings(tweenEasing),
+ _ease: parseEase(tweenEasing),
_fromNumbers: cloneArray(fromTargetObject.d),
_toNumbers: cloneArray(toTargetObject.d),
_strings: cloneArray(toTargetObject.s),
@@ -735,4 +703,4 @@ export class JSAnimation extends Timer {
* @param {AnimationParams} parameters
* @return {JSAnimation}
*/
-export const animate = (targets, parameters) => new JSAnimation(targets, parameters, null, 0, false).init();
\ No newline at end of file
+export const animate = (targets, parameters) => new JSAnimation(targets, parameters, null, 0, false).init();
diff --git a/src/compositions.js b/src/animation/composition.js
similarity index 68%
rename from src/compositions.js
rename to src/animation/composition.js
index bb0f410e..695120ef 100644
--- a/src/compositions.js
+++ b/src/animation/composition.js
@@ -1,9 +1,8 @@
-/// <reference path='./types.js' />
-
import {
compositionTypes,
minValue,
-} from './consts.js';
+ tweenTypes,
+} from '../core/consts.js';
import {
cloneArray,
@@ -11,13 +10,38 @@ import {
removeChild,
forEachChildren,
round,
-} from './helpers.js';
+ isUnd,
+} from '../core/helpers.js';
+
+import {
+ sanitizePropertyName,
+} from '../core/styles.js';
+
+import {
+ engine,
+} from '../engine/engine.js';
import {
additive,
addAdditiveAnimation,
} from './additive.js';
+/**
+ * @import {
+ * TweenReplaceLookups,
+ * TweenAdditiveLookups,
+ * TweenPropertySiblings,
+ * Tween,
+ * Target,
+ * TargetsArray,
+ * Renderable,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
const lookups = {
/** @type {TweenReplaceLookups} */
_rep: new WeakMap(),
@@ -277,3 +301,90 @@ export const removeTweenSliblings = tween => {
}
return tween;
}
+
+/**
+ * @param {TargetsArray} targetsArray
+ * @param {JSAnimation} animation
+ * @param {String} [propertyName]
+ * @return {Boolean}
+ */
+const removeTargetsFromJSAnimation = (targetsArray, animation, propertyName) => {
+ let tweensMatchesTargets = false;
+ forEachChildren(animation, (/**@type {Tween} */tween) => {
+ const tweenTarget = tween.target;
+ if (targetsArray.includes(tweenTarget)) {
+ const tweenName = tween.property;
+ const tweenType = tween._tweenType;
+ const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
+ if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
+ // Make sure to flag the previous CSS transform tween to renderTransform
+ if (tween.parent._tail === tween &&
+ tween._tweenType === tweenTypes.TRANSFORM &&
+ tween._prev &&
+ tween._prev._tweenType === tweenTypes.TRANSFORM
+ ) {
+ tween._prev._renderTransforms = 1;
+ }
+ // Removes the tween from the selected animation
+ removeChild(animation, tween);
+ // Detach the tween from its siblings to make sure blended tweens are correctlly removed
+ removeTweenSliblings(tween);
+ tweensMatchesTargets = true;
+ }
+ }
+ }, true);
+ return tweensMatchesTargets;
+}
+
+/**
+ * @param {TargetsArray} targetsArray
+ * @param {Renderable} [renderable]
+ * @param {String} [propertyName]
+ */
+export const removeTargetsFromRenderable = (targetsArray, renderable, propertyName) => {
+ const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine);
+ let removeMatches;
+ if (parent._hasChildren) {
+ let iterationDuration = 0;
+ forEachChildren(parent, (/** @type {Renderable} */child) => {
+ if (!child._hasChildren) {
+ removeMatches = removeTargetsFromJSAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName);
+ // Remove the child from its parent if no tweens and no children left after the removal
+ if (removeMatches && !child._head) {
+ child.cancel();
+ removeChild(parent, child);
+ } else {
+ // Calculate the new iterationDuration value to handle onComplete with last child in render()
+ const childTLOffset = child._offset + child._delay;
+ const childDur = childTLOffset + child.duration;
+ if (childDur > iterationDuration) {
+ iterationDuration = childDur;
+ }
+ }
+ }
+ // Make sure to also remove engine's children targets
+ // NOTE: Avoid recursion?
+ if (child._head) {
+ removeTargetsFromRenderable(targetsArray, child, propertyName);
+ } else {
+ child._hasChildren = false;
+ }
+ }, true);
+ // Update iterationDuration value to handle onComplete with last child in render()
+ if (!isUnd(/** @type {Renderable} */(parent).iterationDuration)) {
+ /** @type {Renderable} */(parent).iterationDuration = iterationDuration;
+ }
+ } else {
+ removeMatches = removeTargetsFromJSAnimation(
+ targetsArray,
+ /** @type {JSAnimation} */(parent),
+ propertyName
+ );
+ }
+ if (removeMatches && !parent._head) {
+ parent._hasChildren = false;
+ // Cancel the parent if there are no tweens and no children left after the removal
+ // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
+ if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel();
+ }
+}
diff --git a/src/animation/index.js b/src/animation/index.js
new file mode 100644
index 00000000..5b150817
--- /dev/null
+++ b/src/animation/index.js
@@ -0,0 +1 @@
+export * from './animation.js';
\ No newline at end of file
diff --git a/src/anime.js b/src/anime.js
deleted file mode 100644
index 9597ae87..00000000
--- a/src/anime.js
+++ /dev/null
@@ -1,15 +0,0 @@
-export { engine } from './engine.js';
-export { createTimer, Timer } from './timer.js';
-export { animate, JSAnimation } from './animation.js';
-export { createTimeline, Timeline } from './timeline.js';
-export { createAnimatable, Animatable } from './animatable.js';
-export { createDraggable, Draggable } from './draggable.js';
-export { createScope, Scope } from './scope.js';
-export { onScroll, ScrollObserver, scrollContainers } from './scroll.js';
-export { createSpring, Spring } from './spring.js';
-export { waapi, WAAPIAnimation } from './waapi.js';
-export { utils } from './utils.js';
-export { svg } from './svg.js';
-export { text, TextSplitter } from './text.js';
-export { stagger } from './stagger.js';
-export { eases } from './eases.js';
\ No newline at end of file
diff --git a/src/clock.js b/src/core/clock.js
similarity index 97%
rename from src/clock.js
rename to src/core/clock.js
index 913113cd..620598bc 100644
--- a/src/clock.js
+++ b/src/core/clock.js
@@ -9,6 +9,13 @@ import {
round,
} from './helpers.js';
+/**
+ * @import {
+ * Tickable,
+ * Tween,
+ * } from '../types/index.js'
+*/
+
/*
* Base class to control framerate and playback rate.
* Inherited by Engine, Timer, Animation and Timeline.
diff --git a/src/colors.js b/src/core/colors.js
similarity index 97%
rename from src/colors.js
rename to src/core/colors.js
index 5328af6d..2a83459d 100644
--- a/src/colors.js
+++ b/src/core/colors.js
@@ -1,5 +1,3 @@
-/// <reference path='./types.js' />
-
import {
rgbExecRgx,
rgbaExecRgx,
@@ -15,6 +13,12 @@ import {
isUnd,
} from './helpers.js';
+/**
+ * @import {
+ * ColorArray,
+ * } from '../types/index.js'
+*/
+
/**
* RGB / RGBA Color value string -> RGBA values array
* @param {String} rgbValue
diff --git a/src/consts.js b/src/core/consts.js
similarity index 100%
rename from src/consts.js
rename to src/core/consts.js
diff --git a/src/globals.js b/src/core/globals.js
similarity index 88%
rename from src/globals.js
rename to src/core/globals.js
index 042fc4f4..a026d030 100644
--- a/src/globals.js
+++ b/src/core/globals.js
@@ -1,5 +1,3 @@
-/// <reference path='./types.js' />
-
import {
K,
noop,
@@ -10,6 +8,17 @@ import {
isBrowser,
} from './consts.js';
+/**
+ * @import {
+ * DefaultsParams,
+ * DOMTarget,
+ * } from '../types/index.js'
+ *
+ * @import {
+ * Scope,
+ * } from '../scope/index.js'
+*/
+
/** @type {DefaultsParams} */
export const defaults = {
id: null,
diff --git a/src/helpers.js b/src/core/helpers.js
similarity index 70%
rename from src/helpers.js
rename to src/core/helpers.js
index 8206cb02..944f3c52 100644
--- a/src/helpers.js
+++ b/src/core/helpers.js
@@ -4,13 +4,19 @@ import {
hexTestRgx,
maxValue,
minValue,
- noop,
} from './consts.js';
import {
globals,
} from './globals.js';
+/**
+ * @import {
+ * Target,
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
// Strings
/**
@@ -58,6 +64,30 @@ export const isCol = a => isHex(a) || isRgb(a) || isHsl(a);
/**@param {any} a @return {Boolean} */
export const isKey = a => !globals.defaults.hasOwnProperty(a);
+// SVG
+
+// Consider the following as CSS animation
+// CSS opacity animation has better default values (opacity: 1 instead of 0))
+// rotate is more commonly intended to be used as a transform
+const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
+
+/**
+ * @param {Target} el
+ * @param {String} propertyName
+ * @return {Boolean}
+ */
+export const isValidSVGAttribute = (el, propertyName) => {
+ if (svgCssReservedProperties.includes(propertyName)) return false;
+ if (el.getAttribute(propertyName) || propertyName in el) {
+ if (propertyName === 'scale') { // Scale
+ const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
+ // Only consider scale as a valid SVG attribute on filter element
+ return elParentNode && elParentNode.tagName === 'filter';
+ }
+ return true;
+ }
+}
+
// Number
/**
@@ -85,9 +115,11 @@ export const PI = Math.PI;
export const _round = Math.round;
/**
- * @param {Number} v
- * @param {Number} min
- * @param {Number} max
+ * Clamps a value between min and max bounds
+ *
+ * @param {Number} v - Value to clamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
* @return {Number}
*/
export const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
@@ -95,8 +127,10 @@ export const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
const powCache = {};
/**
- * @param {Number} v
- * @param {Number} decimalLength
+ * Rounds a number to specified decimal places
+ *
+ * @param {Number} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
* @return {Number}
*/
export const round = (v, decimalLength) => {
@@ -108,47 +142,36 @@ export const round = (v, decimalLength) => {
};
/**
- * @param {Number} v
- * @param {Number|Array<Number>} increment
+ * Snaps a value to nearest increment or array value
+ *
+ * @param {Number} v - Value to snap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
* @return {Number}
*/
export const snap = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
/**
- * @param {Number} start
- * @param {Number} end
- * @param {Number} progress
- * @return {Number}
- */
-export const interpolate = (start, end, progress) => start + (end - start) * progress;
-
-/**
- * @param {Number} min
- * @param {Number} max
- * @param {Number} [decimalLength]
- * @return {Number}
- */
-export const random = (min, max, decimalLength) => { const m = 10 ** (decimalLength || 0); return floor((Math.random() * (max - min + (1 / m)) + min) * m) / m };
-
-/**
- * Adapted from https://bost.ocks.org/mike/shuffle/
- * @param {Array} items
- * @return {Array}
+ * Linear interpolation between two values
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
*/
-export const shuffle = items => {
- let m = items.length, t, i;
- while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; }
- return items;
-}
+export const lerp = (start, end, factor) => start + (end - start) * factor;
/**
- * @param {Number} v
+ * Replaces infinity with maximum safe value
+ *
+ * @param {Number} v - Value to check
* @return {Number}
*/
export const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v;
/**
- * @param {Number} v
+ * Normalizes time value with minimum threshold
+ *
+ * @param {Number} v - Time value to normalize
* @return {Number}
*/
export const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round(v, 11));
@@ -157,8 +180,8 @@ export const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round
/**
* @template T
- * @param {T[]} a
- * @return {T[]}
+ * @param {T[]} a
+ * @return {T[]}
*/
export const cloneArray = a => isArr(a) ? [ ...a ] : a;
@@ -167,9 +190,9 @@ export const cloneArray = a => isArr(a) ? [ ...a ] : a;
/**
* @template T
* @template U
- * @param {T} o1
- * @param {U} o2
- * @return {T & U}
+ * @param {T} o1
+ * @param {U} o2
+ * @return {T & U}
*/
export const mergeObjects = (o1, o2) => {
const merged = /** @type {T & U} */({ ...o1 });
@@ -183,11 +206,11 @@ export const mergeObjects = (o1, o2) => {
// Linked lists
/**
- * @param {Object} parent
- * @param {Function} callback
- * @param {Boolean} [reverse]
- * @param {String} [prevProp]
- * @param {String} [nextProp]
+ * @param {Object} parent
+ * @param {Function} callback
+ * @param {Boolean} [reverse]
+ * @param {String} [prevProp]
+ * @param {String} [nextProp]
* @return {void}
*/
export const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => {
@@ -237,29 +260,3 @@ export const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp
child[prevProp] = prev;
child[nextProp] = next;
}
-
-/**
- * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor
- * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)}
- */
-export const createRefreshable = constructor => {
- /** @type {Tickable} */
- let tracked;
- return (...args) => {
- let currentIteration, currentIterationProgress, reversed, alternate;
- if (tracked) {
- currentIteration = tracked.currentIteration;
- currentIterationProgress = tracked.iterationProgress;
- reversed = tracked.reversed;
- alternate = tracked._alternate;
- tracked.revert();
- }
- const cleanup = constructor(...args);
- if (cleanup && !isFnc(cleanup) && cleanup.revert) tracked = cleanup;
- if (!isUnd(currentIterationProgress)) {
- /** @type {Tickable} */(tracked).currentIteration = currentIteration;
- /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress;
- }
- return cleanup || noop;
- }
-}
diff --git a/src/render.js b/src/core/render.js
similarity index 95%
rename from src/render.js
rename to src/core/render.js
index fbd1dbcd..01fa67d2 100644
--- a/src/render.js
+++ b/src/core/render.js
@@ -1,5 +1,3 @@
-/// <reference path='./types.js' />
-
import {
globals,
} from './globals.js';
@@ -19,10 +17,32 @@ import {
now,
clamp,
round,
- interpolate,
+ lerp,
forEachChildren,
} from './helpers.js';
+/**
+ * @import {
+ * Tickable,
+ * Renderable,
+ * CallbackArgument,
+ * Tween,
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
+
/**
* @param {Tickable} tickable
* @param {Number} time
@@ -171,18 +191,18 @@ export const render = (tickable, time, muteCallbacks, internalRender, tickMode)
let number;
if (tweenIsNumber) {
- value = number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
+ value = number = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
} else if (tweenValueType === valueTypes.UNIT) {
// Rounding the values speed up string composition
- number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
+ number = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
value = `${number}${tween._unit}`;
} else if (tweenValueType === valueTypes.COLOR) {
const fn = tween._fromNumbers;
const tn = tween._toNumbers;
- const r = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[0], tn[0], tweenProgress))), 0, 255), 0);
- const g = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[1], tn[1], tweenProgress))), 0, 255), 0);
- const b = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[2], tn[2], tweenProgress))), 0, 255), 0);
- const a = clamp(/** @type {Number} */(tweenModifier(round(interpolate(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
+ const r = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[0], tn[0], tweenProgress))), 0, 255), 0);
+ const g = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[1], tn[1], tweenProgress))), 0, 255), 0);
+ const b = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[2], tn[2], tweenProgress))), 0, 255), 0);
+ const a = clamp(/** @type {Number} */(tweenModifier(round(lerp(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
value = `rgba(${r},${g},${b},${a})`;
if (tweenHasComposition) {
const ns = tween._numbers;
@@ -194,7 +214,7 @@ export const render = (tickable, time, muteCallbacks, internalRender, tickMode)
} else if (tweenValueType === valueTypes.COMPLEX) {
value = tween._strings[0];
for (let j = 0, l = tween._toNumbers.length; j < l; j++) {
- const n = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
+ const n = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
const s = tween._strings[j + 1];
value += `${s ? n + s : n}`;
if (tweenHasComposition) {
diff --git a/src/core/styles.js b/src/core/styles.js
new file mode 100644
index 00000000..24892406
--- /dev/null
+++ b/src/core/styles.js
@@ -0,0 +1,118 @@
+import {
+ tweenTypes,
+ shortTransforms,
+ isDomSymbol,
+ transformsSymbol,
+ emptyString,
+ transformsFragmentStrings,
+} from './consts.js';
+
+import {
+ forEachChildren,
+ isSvg,
+ isUnd,
+ toLowerCase,
+} from './helpers.js';
+
+const propertyNamesCache = {};
+
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+* @import {
+* Target,
+* DOMTarget,
+* Renderable,
+* Tween,
+* } from '../types/index.js'
+*/
+
+/**
+ * @param {String} propertyName
+ * @param {Target} target
+ * @param {tweenTypes} tweenType
+ * @return {String}
+ */
+export const sanitizePropertyName = (propertyName, target, tweenType) => {
+ if (tweenType === tweenTypes.TRANSFORM) {
+ const t = shortTransforms.get(propertyName);
+ return t ? t : propertyName;
+ } else if (
+ tweenType === tweenTypes.CSS ||
+ // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
+ // but properties like "baseFrequency" should stay in lowerCamelCase
+ (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
+ ) {
+ const cachedPropertyName = propertyNamesCache[propertyName];
+ if (cachedPropertyName) {
+ return cachedPropertyName;
+ } else {
+ const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
+ propertyNamesCache[propertyName] = lowerCaseName;
+ return lowerCaseName;
+ }
+ } else {
+ return propertyName;
+ }
+}
+
+/**
+ * @template {Renderable} T
+ * @param {T} renderable
+ * @return {T}
+ */
+export const cleanInlineStyles = renderable => {
+ // Allow cleanInlineStyles() to be called on timelines
+ if (renderable._hasChildren) {
+ forEachChildren(renderable, cleanInlineStyles, true);
+ } else {
+ const animation = /** @type {JSAnimation} */(renderable);
+ animation.pause();
+ forEachChildren(animation, (/** @type {Tween} */tween) => {
+ const tweenProperty = tween.property;
+ const tweenTarget = tween.target;
+ if (tweenTarget[isDomSymbol]) {
+ const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
+ const originalInlinedValue = animation._inlineStyles[tweenProperty];
+ if (tween._tweenType === tweenTypes.TRANSFORM) {
+ const cachedTransforms = tweenTarget[transformsSymbol];
+ if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
+ delete cachedTransforms[tweenProperty];
+ } else {
+ cachedTransforms[tweenProperty] = originalInlinedValue;
+ }
+ if (tween._renderTransforms) {
+ if (!Object.keys(cachedTransforms).length) {
+ targetStyle.removeProperty('transform');
+ } else {
+ let str = emptyString;
+ for (let key in cachedTransforms) {
+ str += transformsFragmentStrings[key] + cachedTransforms[key] + ') ';
+ }
+ targetStyle.transform = str;
+ }
+ }
+ } else {
+ if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
+ targetStyle.removeProperty(tweenProperty);
+ } else {
+ targetStyle[tweenProperty] = originalInlinedValue;
+ }
+ }
+ if (animation._tail === tween) {
+ animation.targets.forEach(t => {
+ if (t.getAttribute && t.getAttribute('style') === emptyString) {
+ t.removeAttribute('style');
+ };
+ });
+ }
+ }
+ })
+ }
+ return renderable;
+}
diff --git a/src/targets.js b/src/core/targets.js
similarity index 94%
rename from src/targets.js
rename to src/core/targets.js
index 1a1a35a3..71bc0305 100644
--- a/src/targets.js
+++ b/src/core/targets.js
@@ -1,5 +1,3 @@
-/// <reference path='./types.js' />
-
import {
scope,
} from './globals.js';
@@ -19,6 +17,18 @@ import {
isStr,
} from './helpers.js';
+/**
+* @import {
+* DOMTarget,
+* DOMTargetsParam,
+* JSTargetsArray,
+* TargetsParam,
+* JSTargetsParam,
+* TargetsArray,
+* DOMTargetsArray,
+* } from '../types/index.js'
+*/
+
/**
* @param {DOMTargetsParam|TargetsParam} v
* @return {NodeList|HTMLCollection}
diff --git a/src/transforms.js b/src/core/transforms.js
similarity index 95%
rename from src/transforms.js
rename to src/core/transforms.js
index 0db2da19..f963e299 100644
--- a/src/transforms.js
+++ b/src/core/transforms.js
@@ -1,5 +1,3 @@
-/// <reference path='./types.js' />
-
import {
transformsExecRgx,
transformsSymbol,
@@ -10,6 +8,12 @@ import {
stringStartsWith,
} from './helpers.js';
+/**
+* @import {
+* DOMTarget,
+* } from '../types/index.js'
+*/
+
/**
* @param {DOMTarget} target
* @param {String} propName
diff --git a/src/units.js b/src/core/units.js
similarity index 95%
rename from src/units.js
rename to src/core/units.js
index 8296d0e2..8f3d640d 100644
--- a/src/units.js
+++ b/src/core/units.js
@@ -1,5 +1,3 @@
-/// <reference path='./types.js' />
-
import {
doc,
valueTypes,
@@ -13,6 +11,13 @@ import {
const angleUnitsMap = { 'deg': 1, 'rad': 180 / PI, 'turn': 360 };
const convertedValuesCache = {};
+/**
+* @import {
+* DOMTarget,
+* TweenDecomposedValue,
+* } from '../types/index.js'
+*/
+
/**
* @param {DOMTarget} el
* @param {TweenDecomposedValue} decomposedValue
diff --git a/src/values.js b/src/core/values.js
similarity index 97%
rename from src/values.js
rename to src/core/values.js
index af1466b2..1357f59a 100644
--- a/src/values.js
+++ b/src/core/values.js
@@ -1,5 +1,3 @@
-/// <reference path='./types.js' />
-
import {
shortTransforms,
validTransforms,
@@ -18,20 +16,27 @@ import {
isFnc,
isUnd,
isCol,
+ isValidSVGAttribute,
} from './helpers.js';
import {
parseInlineTransforms,
} from './transforms.js';
-import {
- isValidSVGAttribute,
-} from './svg.js';
-
import {
convertColorStringValuesToRgbaArray
} from './colors.js';
+/**
+* @import {
+* Target,
+* DOMTarget,
+* Tween,
+* TweenPropValue,
+* TweenDecomposedValue,
+* } from '../types/index.js'
+*/
+
/**
* @template T, D
* @param {T|undefined} targetValue
diff --git a/src/draggable.js b/src/draggable/draggable.js
similarity index 95%
rename from src/draggable.js
rename to src/draggable/draggable.js
index 9e6fe3be..b462f547 100644
--- a/src/draggable.js
+++ b/src/draggable/draggable.js
@@ -1,17 +1,7 @@
-/// <reference path='./types.js' />
-
import {
scope,
globals,
-} from './globals.js';
-
-import {
- JSAnimation,
-} from './animation.js';
-
-import {
- Animatable,
-} from './animatable.js';
+} from '../core/globals.js';
import {
win,
@@ -19,11 +9,11 @@ import {
maxValue,
noop,
compositionTypes,
-} from './consts.js';
+} from '../core/consts.js';
import {
parseTargets,
-} from './targets.js';
+} from '../core/targets.js';
import {
snap,
@@ -40,38 +30,74 @@ import {
sin,
abs,
now,
-} from './helpers.js';
+} from '../core/helpers.js';
+
+import {
+ setValue,
+} from '../core/values.js';
import {
- getTargetValue,
- setTargetValues,
- remove,
mapRange,
-} from './utils.js';
+} from '../utils/number.js';
import {
Timer,
-} from './timer.js';
+} from '../timer/timer.js';
import {
- setValue,
-} from './values.js';
+ JSAnimation,
+} from '../animation/animation.js';
+
+import {
+ removeTargetsFromRenderable,
+} from '../animation/composition.js';
+
+import {
+ Animatable,
+} from '../animatable/animatable.js';
import {
eases,
- parseEasings,
-} from './eases.js';
+ parseEase,
+} from '../easings/eases.js';
import {
createSpring,
-} from './spring.js';
+} from '../spring/spring.js'
+
+import {
+ get,
+ set,
+} from '../utils/target.js';
+
+/**
+ * @import {
+ * DOMTarget,
+ * DOMTargetSelector,
+ * DraggableCursorParams,
+ * TargetsParam,
+ * DraggableParams,
+ * EasingFunction,
+ * Callback,
+ * AnimatableParams,
+ * DraggableAxisParam,
+ * AnimatableObject,
+ * EasingParam,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
/**
* @param {Event} e
*/
const preventDefault = e => {
if (e.cancelable) e.preventDefault();
-};
+}
class DOMProxy {
/** @param {Object} el */
@@ -184,7 +210,7 @@ class Transforms {
* @param {Draggable} draggable
* @return {T}
*/
-const parseDraggableFunctionParameter = (value, draggable) => value && isFnc(value) ? /** @type {Function} */(value)(draggable) : value;
+const parseDraggableFunctionParameter = (value, draggable) => value && isFnc(value) ? /** @type {Function} */(value)(draggable) : /** @type {T} */(value);
let zIndex = 0;
@@ -201,7 +227,7 @@ export class Draggable {
const trigger = parameters.trigger;
const modifier = parameters.modifier;
const ease = parameters.releaseEase;
- const customEase = ease && parseEasings(ease);
+ const customEase = ease && parseEase(ease);
const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
const xProp = /** @type {String} */(isObj(paramX) && !isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX');
const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY');
@@ -213,7 +239,7 @@ export class Draggable {
this.$scrollContainer = this.useWin ? win : this.$container;
this.$target = /** @type {HTMLElement} */(isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]);
this.$trigger = /** @type {HTMLElement} */(parseTargets(trigger ? trigger : target)[0]);
- this.fixed = getTargetValue(this.$target, 'position') === 'fixed';
+ this.fixed = get(this.$target, 'position') === 'fixed';
// Refreshable parameters
this.isFinePointer = true;
/** @type {[Number, Number, Number, Number]} */
@@ -577,7 +603,7 @@ export class Draggable {
const { width, height, left, top, right, bottom } = $container.getBoundingClientRect();
this.dragArea[2] = round(uw ? clamp(width, iw, iw) : width, 0);
this.dragArea[3] = round(uw ? clamp(height, ih, ih) : height, 0);
- const containerOverflow = getTargetValue($container, 'overflow');
+ const containerOverflow = get($container, 'overflow');
const visibleOverflow = containerOverflow === 'visible';
const hiddenOverflow = containerOverflow === 'hidden';
this.canScroll = fx ? false :
@@ -761,12 +787,12 @@ export class Draggable {
this.overshootTicker.pause();
// Pauses the in bounds onRelease animations
for (let prop in this.animate.animations) this.animate.animations[prop].pause();
- remove(this, null, 'x');
- remove(this, null, 'y');
- remove(this, null, 'progressX');
- remove(this, null, 'progressY');
- remove(this.scroll); // Removes any active animations on the container scroll
- remove(this.overshootCoords); // Removes active overshoot animations
+ removeTargetsFromRenderable([this], null, 'x');
+ removeTargetsFromRenderable([this], null, 'y');
+ removeTargetsFromRenderable([this], null, 'progressX');
+ removeTargetsFromRenderable([this], null, 'progressY');
+ removeTargetsFromRenderable([this.scroll]); // Removes any active animations on the container scroll
+ removeTargetsFromRenderable([this.overshootCoords]); // Removes active overshoot animations
return this;
}
@@ -807,7 +833,7 @@ export class Draggable {
handleHover() {
if (this.isFinePointer && this.cursor && !this.cursorStyles) {
- this.cursorStyles = setTargetValues(this.$trigger, {
+ this.cursorStyles = set(this.$trigger, {
cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover
});
}
@@ -884,9 +910,9 @@ export class Draggable {
this.targetStyles.revert();
this.targetStyles = null;
}
- const z = /** @type {Number} */(getTargetValue(this.$target, 'zIndex', false));
+ const z = /** @type {Number} */(get(this.$target, 'zIndex', false));
zIndex = (z > zIndex ? z : zIndex) + 1;
- this.targetStyles = setTargetValues(this.$target, { zIndex });
+ this.targetStyles = set(this.$target, { zIndex });
if (this.triggerStyles) {
this.triggerStyles.revert();
this.triggerStyles = null;
@@ -896,7 +922,7 @@ export class Draggable {
this.cursorStyles = null;
}
if (this.isFinePointer && this.cursor) {
- this.bodyStyles = setTargetValues(doc.body, {
+ this.bodyStyles = set(doc.body, {
cursor: /** @type {DraggableCursorParams} */(this.cursor).onGrab
});
}
@@ -929,7 +955,7 @@ export class Draggable {
let canTouchScroll = false;
while (touches && $parent && $parent !== this.$trigger) {
- const overflowY = getTargetValue($parent, 'overflow-y');
+ const overflowY = get($parent, 'overflow-y');
if (overflowY !== 'hidden' && overflowY !== 'visible') {
const { scrollTop, scrollHeight, clientHeight } = $parent;
if (scrollHeight > clientHeight) {
@@ -958,7 +984,7 @@ export class Draggable {
preventDefault(e);
// Needed to prevents click on handleUp
- if (!this.triggerStyles) this.triggerStyles = setTargetValues(this.$trigger, { pointerEvents: 'none' });
+ if (!this.triggerStyles) this.triggerStyles = set(this.$trigger, { pointerEvents: 'none' });
// Needed to prevent page scroll while dragging on touch devvice
this.$trigger.addEventListener('touchstart', preventDefault, { passive: false });
this.$trigger.addEventListener('touchmove', preventDefault, { passive: false });
@@ -1143,7 +1169,7 @@ export class Draggable {
if (!this.enabled) {
this.enabled = true;
this.$target.classList.remove('is-disabled');
- this.touchActionStyles = setTargetValues(this.$trigger, {
+ this.touchActionStyles = set(this.$trigger, {
touchAction: this.disabled[0] ? 'pan-x' : this.disabled[1] ? 'pan-y' : 'none'
});
this.$trigger.addEventListener('touchstart', this, { passive: true });
diff --git a/src/draggable/index.js b/src/draggable/index.js
new file mode 100644
index 00000000..6f86dc8d
--- /dev/null
+++ b/src/draggable/index.js
@@ -0,0 +1 @@
+export * from './draggable.js';
\ No newline at end of file
diff --git a/src/eases.js b/src/eases.js
deleted file mode 100644
index f39f64bf..00000000
--- a/src/eases.js
+++ /dev/null
@@ -1,319 +0,0 @@
-/// <reference path='./types.js' />
-
-import {
- minValue,
- emptyString,
-} from './consts.js';
-
-import {
- isUnd,
- isStr,
- isFnc,
- parseNumber,
- clamp,
- sqrt,
- cos,
- sin,
- ceil,
- floor,
- abs,
- asin,
- PI,
- pow,
-} from './helpers.js';
-
-/** @type {EasingFunction} */
-export const none = t => t;
-
-// Cubic Bezier solver adapted from https://github.com/gre/bezier-ease © Gaëtan Renaudeau
-
-/**
- * @param {Number} aT
- * @param {Number} aA1
- * @param {Number} aA2
- * @return {Number}
- */
-const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT;
-
-/**
- * @param {Number} aX
- * @param {Number} mX1
- * @param {Number} mX2
- * @return {Number}
- */
-const binarySubdivide = (aX, mX1, mX2) => {
- let aA = 0, aB = 1, currentX, currentT, i = 0;
- do {
- currentT = aA + (aB - aA) / 2;
- currentX = calcBezier(currentT, mX1, mX2) - aX;
- if (currentX > 0) {
- aB = currentT;
- } else {
- aA = currentT;
- }
- } while (abs(currentX) > .0000001 && ++i < 100);
- return currentT;
-}
-
-/**
- * @param {Number} [mX1] The x coordinate of the first point
- * @param {Number} [mY1] The y coordinate of the first point
- * @param {Number} [mX2] The x coordinate of the second point
- * @param {Number} [mY2] The y coordinate of the second point
- * @return {EasingFunction}
- */
-
-export const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none :
- t => t === 0 || t === 1 ? t :
- calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
-
-/**
- * Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
- * Only covers 'end' and 'start' jumpterms
- * @param {Number} steps
- * @param {Boolean} [fromStart]
- * @return {EasingFunction}
- */
-export const steps = (steps = 10, fromStart) => {
- const roundMethod = fromStart ? ceil : floor;
- return t => roundMethod(clamp(t, 0, 1) * steps) * (1 / steps);
-}
-
-/**
- * Without parameters, the linear function creates a non-eased transition.
- * Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points.
- * @param {...(String|Number)} args - Points
- * @return {EasingFunction}
- */
-const linear = (...args) => {
- const argsLength = args.length;
- if (!argsLength) return none;
- const totalPoints = argsLength - 1;
- const firstArg = args[0];
- const lastArg = args[totalPoints];
- const xPoints = [0];
- const yPoints = [parseNumber(firstArg)];
- for (let i = 1; i < totalPoints; i++) {
- const arg = args[i];
- const splitValue = isStr(arg) ?
- /** @type {String} */(arg).trim().split(' ') :
- [arg];
- const value = splitValue[0];
- const percent = splitValue[1];
- xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints);
- yPoints.push(parseNumber(value));
- }
- yPoints.push(parseNumber(lastArg));
- xPoints.push(1);
- return function easeLinear(t) {
- for (let i = 1, l = xPoints.length; i < l; i++) {
- const currentX = xPoints[i];
- if (t <= currentX) {
- const prevX = xPoints[i - 1];
- const prevY = yPoints[i - 1];
- return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX);
- }
- }
- return yPoints[yPoints.length - 1];
- }
-}
-
-/**
- * Generate random steps
- * @param {Number} [length] - The number of steps
- * @param {Number} [randomness] - How strong the randomness is
- * @return {EasingFunction}
- */
-const irregular = (length = 10, randomness = 1) => {
- const values = [0];
- const total = length - 1;
- for (let i = 1; i < total; i++) {
- const previousValue = values[i - 1];
- const spacing = i / total;
- const segmentEnd = (i + 1) / total;
- const randomVariation = spacing + (segmentEnd - spacing) * Math.random();
- // Mix the even spacing and random variation based on the randomness parameter
- const randomValue = spacing * (1 - randomness) + randomVariation * randomness;
- values.push(clamp(randomValue, previousValue, 1));
- }
- values.push(1);
- return linear(...values);
-}
-
-// Easing functions adapted from http://www.robertpenner.com/ease © Robert Penner
-
-/**
- * @callback PowerEasing
- * @param {Number|String} [power=1.675]
- * @return {EasingFunction}
- */
-
-/**
- * @callback BackEasing
- * @param {Number|String} [overshoot=1.70158]
- * @return {EasingFunction}
- */
-
-/**
- * @callback ElasticEasing
- * @param {Number|String} [amplitude=1]
- * @param {Number|String} [period=.3]
- * @return {EasingFunction}
- */
-
-/**
- * @callback EaseFactory
- * @param {Number|String} [paramA]
- * @param {Number|String} [paramB]
- * @return {EasingFunction|Number}
- */
-
-/** @typedef {PowerEasing|BackEasing|ElasticEasing} EasesFactory */
-
-const halfPI = PI / 2;
-const doublePI = PI * 2;
-/** @type {PowerEasing} */
-export const easeInPower = (p = 1.68) => t => pow(t, +p);
-
-/** @type {Record<String, EasesFactory|EasingFunction>} */
-const easeInFunctions = {
- [emptyString]: easeInPower,
- Quad: easeInPower(2),
- Cubic: easeInPower(3),
- Quart: easeInPower(4),
- Quint: easeInPower(5),
- /** @type {EasingFunction} */
- Sine: t => 1 - cos(t * halfPI),
- /** @type {EasingFunction} */
- Circ: t => 1 - sqrt(1 - t * t),
- /** @type {EasingFunction} */
- Expo: t => t ? pow(2, 10 * t - 10) : 0,
- /** @type {EasingFunction} */
- Bounce: t => {
- let pow2, b = 4;
- while (t < ((pow2 = pow(2, --b)) - 1) / 11);
- return 1 / pow(4, 3 - b) - 7.5625 * pow((pow2 * 3 - 2) / 22 - t, 2);
- },
- /** @type {BackEasing} */
- Back: (overshoot = 1.70158) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t,
- /** @type {ElasticEasing} */
- Elastic: (amplitude = 1, period = .3) => {
- const a = clamp(+amplitude, 1, 10);
- const p = clamp(+period, minValue, 2);
- const s = (p / doublePI) * asin(1 / a);
- const e = doublePI / p;
- return t => t === 0 || t === 1 ? t : -a * pow(2, -10 * (1 - t)) * sin(((1 - t) - s) * e);
- }
-}
-
-/**
- * @callback EaseType
- * @param {EasingFunction} Ease
- * @return {EasingFunction}
- */
-
-/** @type {Record<String, EaseType>} */
-export const easeTypes = {
- in: easeIn => t => easeIn(t),
- out: easeIn => t => 1 - easeIn(1 - t),
- inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2,
- outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2,
-}
-
-/**
- * @param {String} string
- * @param {Record<String, EasesFactory|EasingFunction>} easesFunctions
- * @param {Object} easesLookups
- * @return {EasingFunction}
- */
-export const parseEaseString = (string, easesFunctions, easesLookups) => {
- if (easesLookups[string]) return easesLookups[string];
- if (string.indexOf('(') <= -1) {
- const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic');
- const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasesFactory} */(easesFunctions[string])() : easesFunctions[string]);
- return parsedFn ? easesLookups[string] = parsedFn : none;
- } else {
- const split = string.slice(0, -1).split('(');
- const parsedFn = /** @type {EasesFactory} */(easesFunctions[split[0]]);
- return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none;
- }
-}
-
-/**
- * @typedef {Object} EasesFunctions
- * @property {typeof linear} linear
- * @property {typeof irregular} irregular
- * @property {typeof steps} steps
- * @property {typeof cubicBezier} cubicBezier
- * @property {PowerEasing} in
- * @property {PowerEasing} out
- * @property {PowerEasing} inOut
- * @property {PowerEasing} outIn
- * @property {EasingFunction} inQuad
- * @property {EasingFunction} outQuad
- * @property {EasingFunction} inOutQuad
- * @property {EasingFunction} outInQuad
- * @property {EasingFunction} inCubic
- * @property {EasingFunction} outCubic
- * @property {EasingFunction} inOutCubic
- * @property {EasingFunction} outInCubic
- * @property {EasingFunction} inQuart
- * @property {EasingFunction} outQuart
- * @property {EasingFunction} inOutQuart
- * @property {EasingFunction} outInQuart
- * @property {EasingFunction} inQuint
- * @property {EasingFunction} outQuint
- * @property {EasingFunction} inOutQuint
- * @property {EasingFunction} outInQuint
- * @property {EasingFunction} inSine
- * @property {EasingFunction} outSine
- * @property {EasingFunction} inOutSine
- * @property {EasingFunction} outInSine
- * @property {EasingFunction} inCirc
- * @property {EasingFunction} outCirc
- * @property {EasingFunction} inOutCirc
- * @property {EasingFunction} outInCirc
- * @property {EasingFunction} inExpo
- * @property {EasingFunction} outExpo
- * @property {EasingFunction} inOutExpo
- * @property {EasingFunction} outInExpo
- * @property {EasingFunction} inBounce
- * @property {EasingFunction} outBounce
- * @property {EasingFunction} inOutBounce
- * @property {EasingFunction} outInBounce
- * @property {BackEasing} inBack
- * @property {BackEasing} outBack
- * @property {BackEasing} inOutBack
- * @property {BackEasing} outInBack
- * @property {ElasticEasing} inElastic
- * @property {ElasticEasing} outElastic
- * @property {ElasticEasing} inOutElastic
- * @property {ElasticEasing} outInElastic
- */
-
-export const eases = (/*#__PURE__*/ (() => {
- const list = { linear, irregular, steps, cubicBezier };
- for (let type in easeTypes) {
- for (let name in easeInFunctions) {
- const easeIn = easeInFunctions[name];
- const easeType = easeTypes[type];
- list[type + name] = /** @type {EasesFactory|EasingFunction} */(
- name === emptyString || name === 'Back' || name === 'Elastic' ?
- (a, b) => easeType(/** @type {EasesFactory} */(easeIn)(a, b)) :
- easeType(/** @type {EasingFunction} */(easeIn))
- );
- }
- }
- return /** @type {EasesFunctions} */(list);
-})());
-
-/** @type {Record<String, EasingFunction>} */
-const JSEasesLookups = { linear: none };
-
-/**
- * @param {EasingParam} ease
- * @return {EasingFunction}
- */
-export const parseEasings = ease => isFnc(ease) ? ease :
- isStr(ease) ? parseEaseString(/** @type {String} */(ease), eases, JSEasesLookups) :
- none;
diff --git a/src/easings/cubic-bezier.js b/src/easings/cubic-bezier.js
new file mode 100644
index 00000000..d2442478
--- /dev/null
+++ b/src/easings/cubic-bezier.js
@@ -0,0 +1,59 @@
+import {
+ abs,
+} from '../core/helpers.js';
+
+import {
+ none,
+} from './none.js';
+
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Cubic Bezier solver adapted from https://github.com/gre/bezier-easing
+ * (c) 2014 Gaëtan Renaudeau
+ */
+
+/**
+ * @param {Number} aT
+ * @param {Number} aA1
+ * @param {Number} aA2
+ * @return {Number}
+ */
+const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT;
+
+/**
+ * @param {Number} aX
+ * @param {Number} mX1
+ * @param {Number} mX2
+ * @return {Number}
+ */
+const binarySubdivide = (aX, mX1, mX2) => {
+ let aA = 0, aB = 1, currentX, currentT, i = 0;
+ do {
+ currentT = aA + (aB - aA) / 2;
+ currentX = calcBezier(currentT, mX1, mX2) - aX;
+ if (currentX > 0) {
+ aB = currentT;
+ } else {
+ aA = currentT;
+ }
+ } while (abs(currentX) > .0000001 && ++i < 100);
+ return currentT;
+}
+
+/**
+ * @param {Number} [mX1] The x coordinate of the first point
+ * @param {Number} [mY1] The y coordinate of the first point
+ * @param {Number} [mX2] The x coordinate of the second point
+ * @param {Number} [mY2] The y coordinate of the second point
+ * @return {EasingFunction}
+ */
+
+export const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none :
+ t => t === 0 || t === 1 ? t :
+ calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
diff --git a/src/easings/eases.js b/src/easings/eases.js
new file mode 100644
index 00000000..aca3767a
--- /dev/null
+++ b/src/easings/eases.js
@@ -0,0 +1,157 @@
+import {
+ minValue,
+ emptyString,
+} from '../core/consts.js';
+
+import {
+ isStr,
+ isFnc,
+ clamp,
+ sqrt,
+ cos,
+ sin,
+ asin,
+ PI,
+ pow,
+} from '../core/helpers.js';
+
+import {
+ easeInPower,
+ easeTypes,
+ parseEaseString,
+} from './parser.js';
+
+import { none } from './none.js';
+import { cubicBezier } from './cubic-bezier.js';
+import { steps } from './steps.js';
+import { linear } from './linear.js';
+import { irregular } from './irregular.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * EasingFunctionWithParams,
+ * EasingParam,
+ * BackEasing,
+ * ElasticEasing,
+ * PowerEasing,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Easing functions adapted and simplified from https://robertpenner.com/easing/
+ * (c) 2001 Robert Penner
+ */
+
+const halfPI = PI / 2;
+const doublePI = PI * 2;
+
+/** @type {Record<String, EasingFunctionWithParams|EasingFunction>} */
+const easeInFunctions = {
+ [emptyString]: easeInPower,
+ Quad: easeInPower(2),
+ Cubic: easeInPower(3),
+ Quart: easeInPower(4),
+ Quint: easeInPower(5),
+ /** @type {EasingFunction} */
+ Sine: t => 1 - cos(t * halfPI),
+ /** @type {EasingFunction} */
+ Circ: t => 1 - sqrt(1 - t * t),
+ /** @type {EasingFunction} */
+ Expo: t => t ? pow(2, 10 * t - 10) : 0,
+ /** @type {EasingFunction} */
+ Bounce: t => {
+ let pow2, b = 4;
+ while (t < ((pow2 = pow(2, --b)) - 1) / 11);
+ return 1 / pow(4, 3 - b) - 7.5625 * pow((pow2 * 3 - 2) / 22 - t, 2);
+ },
+ /** @type {BackEasing} */
+ Back: (overshoot = 1.70158) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t,
+ /** @type {ElasticEasing} */
+ Elastic: (amplitude = 1, period = .3) => {
+ const a = clamp(+amplitude, 1, 10);
+ const p = clamp(+period, minValue, 2);
+ const s = (p / doublePI) * asin(1 / a);
+ const e = doublePI / p;
+ return t => t === 0 || t === 1 ? t : -a * pow(2, -10 * (1 - t)) * sin(((1 - t) - s) * e);
+ }
+}
+
+/**
+ * @typedef {Object} EasesFunctions
+ * @property {typeof linear} linear
+ * @property {typeof irregular} irregular
+ * @property {typeof steps} steps
+ * @property {typeof cubicBezier} cubicBezier
+ * @property {PowerEasing} in
+ * @property {PowerEasing} out
+ * @property {PowerEasing} inOut
+ * @property {PowerEasing} outIn
+ * @property {EasingFunction} inQuad
+ * @property {EasingFunction} outQuad
+ * @property {EasingFunction} inOutQuad
+ * @property {EasingFunction} outInQuad
+ * @property {EasingFunction} inCubic
+ * @property {EasingFunction} outCubic
+ * @property {EasingFunction} inOutCubic
+ * @property {EasingFunction} outInCubic
+ * @property {EasingFunction} inQuart
+ * @property {EasingFunction} outQuart
+ * @property {EasingFunction} inOutQuart
+ * @property {EasingFunction} outInQuart
+ * @property {EasingFunction} inQuint
+ * @property {EasingFunction} outQuint
+ * @property {EasingFunction} inOutQuint
+ * @property {EasingFunction} outInQuint
+ * @property {EasingFunction} inSine
+ * @property {EasingFunction} outSine
+ * @property {EasingFunction} inOutSine
+ * @property {EasingFunction} outInSine
+ * @property {EasingFunction} inCirc
+ * @property {EasingFunction} outCirc
+ * @property {EasingFunction} inOutCirc
+ * @property {EasingFunction} outInCirc
+ * @property {EasingFunction} inExpo
+ * @property {EasingFunction} outExpo
+ * @property {EasingFunction} inOutExpo
+ * @property {EasingFunction} outInExpo
+ * @property {EasingFunction} inBounce
+ * @property {EasingFunction} outBounce
+ * @property {EasingFunction} inOutBounce
+ * @property {EasingFunction} outInBounce
+ * @property {BackEasing} inBack
+ * @property {BackEasing} outBack
+ * @property {BackEasing} inOutBack
+ * @property {BackEasing} outInBack
+ * @property {ElasticEasing} inElastic
+ * @property {ElasticEasing} outElastic
+ * @property {ElasticEasing} inOutElastic
+ * @property {ElasticEasing} outInElastic
+ */
+
+export const eases = (/*#__PURE__ */ (() => {
+ const list = { linear, irregular, steps, cubicBezier };
+ for (let type in easeTypes) {
+ for (let name in easeInFunctions) {
+ const easeIn = easeInFunctions[name];
+ const easeType = easeTypes[type];
+ list[type + name] = /** @type {EasingFunctionWithParams|EasingFunction} */(
+ name === emptyString || name === 'Back' || name === 'Elastic' ?
+ (a, b) => easeType(/** @type {EasingFunctionWithParams} */(easeIn)(a, b)) :
+ easeType(/** @type {EasingFunction} */(easeIn))
+ );
+ }
+ }
+ return /** @type {EasesFunctions} */(list);
+})());
+
+/** @type {Record<String, EasingFunction>} */
+const JSEasesLookups = { linear: none };
+
+/**
+ * @param {EasingParam} ease
+ * @return {EasingFunction}
+ */
+export const parseEase = ease => isFnc(ease) ? ease :
+ isStr(ease) ? parseEaseString(/** @type {String} */(ease), eases, JSEasesLookups) :
+ none;
diff --git a/src/easings/index.js b/src/easings/index.js
new file mode 100644
index 00000000..22ce441c
--- /dev/null
+++ b/src/easings/index.js
@@ -0,0 +1,6 @@
+export { none } from './none.js';
+export { cubicBezier } from './cubic-bezier.js';
+export { steps } from './steps.js';
+export { linear } from './linear.js';
+export { irregular } from './irregular.js';
+export { eases } from './eases.js';
\ No newline at end of file
diff --git a/src/easings/irregular.js b/src/easings/irregular.js
new file mode 100644
index 00000000..43451a53
--- /dev/null
+++ b/src/easings/irregular.js
@@ -0,0 +1,36 @@
+import {
+ clamp,
+} from "../core/helpers.js";
+
+import {
+ linear,
+} from "./linear.js";
+
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Generate random steps
+ * @param {Number} [length] - The number of steps
+ * @param {Number} [randomness] - How strong the randomness is
+ * @return {EasingFunction}
+ */
+export const irregular = (length = 10, randomness = 1) => {
+ const values = [0];
+ const total = length - 1;
+ for (let i = 1; i < total; i++) {
+ const previousValue = values[i - 1];
+ const spacing = i / total;
+ const segmentEnd = (i + 1) / total;
+ const randomVariation = spacing + (segmentEnd - spacing) * Math.random();
+ // Mix the even spacing and random variation based on the randomness parameter
+ const randomValue = spacing * (1 - randomness) + randomVariation * randomness;
+ values.push(clamp(randomValue, previousValue, 1));
+ }
+ values.push(1);
+ return linear(...values);
+}
\ No newline at end of file
diff --git a/src/easings/linear.js b/src/easings/linear.js
new file mode 100644
index 00000000..05a2f227
--- /dev/null
+++ b/src/easings/linear.js
@@ -0,0 +1,55 @@
+import {
+ isStr,
+ isUnd,
+ parseNumber,
+} from '../core/helpers.js';
+
+import {
+ none,
+} from './none.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Without parameters, the linear function creates a non-eased transition.
+ * Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points.
+ *
+ * @param {...(String|Number)} args - Points
+ * @return {EasingFunction}
+ */
+export const linear = (...args) => {
+ const argsLength = args.length;
+ if (!argsLength) return none;
+ const totalPoints = argsLength - 1;
+ const firstArg = args[0];
+ const lastArg = args[totalPoints];
+ const xPoints = [0];
+ const yPoints = [parseNumber(firstArg)];
+ for (let i = 1; i < totalPoints; i++) {
+ const arg = args[i];
+ const splitValue = isStr(arg) ?
+ /** @type {String} */(arg).trim().split(' ') :
+ [arg];
+ const value = splitValue[0];
+ const percent = splitValue[1];
+ xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints);
+ yPoints.push(parseNumber(value));
+ }
+ yPoints.push(parseNumber(lastArg));
+ xPoints.push(1);
+ return function easeLinear(t) {
+ for (let i = 1, l = xPoints.length; i < l; i++) {
+ const currentX = xPoints[i];
+ if (t <= currentX) {
+ const prevX = xPoints[i - 1];
+ const prevY = yPoints[i - 1];
+ return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX);
+ }
+ }
+ return yPoints[yPoints.length - 1];
+ }
+}
diff --git a/src/easings/none.js b/src/easings/none.js
new file mode 100644
index 00000000..42847733
--- /dev/null
+++ b/src/easings/none.js
@@ -0,0 +1,8 @@
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/** @type {EasingFunction} */
+export const none = t => t;
\ No newline at end of file
diff --git a/src/easings/parser.js b/src/easings/parser.js
new file mode 100644
index 00000000..938aa4c3
--- /dev/null
+++ b/src/easings/parser.js
@@ -0,0 +1,46 @@
+import { pow } from "../core/helpers.js";
+import { none } from "./none.js";
+
+/**
+ * @import {
+ * EasingFunction,
+ * PowerEasing,
+ * EasingFunctionWithParams,
+ * } from '../types/index.js'
+*/
+
+/** @type {PowerEasing} */
+export const easeInPower = (p = 1.68) => t => pow(t, +p);
+
+/**
+ * @callback EaseType
+ * @param {EasingFunction} Ease
+ * @return {EasingFunction}
+ */
+
+/** @type {Record<String, EaseType>} */
+export const easeTypes = {
+ in: easeIn => t => easeIn(t),
+ out: easeIn => t => 1 - easeIn(1 - t),
+ inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2,
+ outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2,
+}
+
+/**
+ * @param {String} string
+ * @param {Record<String, EasingFunctionWithParams|EasingFunction>} easesFunctions
+ * @param {Object} easesLookups
+ * @return {EasingFunction}
+ */
+export const parseEaseString = (string, easesFunctions, easesLookups) => {
+ if (easesLookups[string]) return easesLookups[string];
+ if (string.indexOf('(') <= -1) {
+ const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic');
+ const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasingFunctionWithParams} */(easesFunctions[string])() : easesFunctions[string]);
+ return parsedFn ? easesLookups[string] = parsedFn : none;
+ } else {
+ const split = string.slice(0, -1).split('(');
+ const parsedFn = /** @type {EasingFunctionWithParams} */(easesFunctions[split[0]]);
+ return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none;
+ }
+}
\ No newline at end of file
diff --git a/src/easings/steps.js b/src/easings/steps.js
new file mode 100644
index 00000000..cf1f1879
--- /dev/null
+++ b/src/easings/steps.js
@@ -0,0 +1,23 @@
+import {
+ ceil,
+ clamp,
+ floor,
+} from "../core/helpers.js";
+
+/**
+ * @import {
+ * EasingFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
+ * Only covers 'end' and 'start' jumpterms
+ * @param {Number} steps
+ * @param {Boolean} [fromStart]
+ * @return {EasingFunction}
+ */
+export const steps = (steps = 10, fromStart) => {
+ const roundMethod = fromStart ? ceil : floor;
+ return t => roundMethod(clamp(t, 0, 1) * steps) * (1 / steps);
+}
diff --git a/src/engine.js b/src/engine/engine.js
similarity index 87%
rename from src/engine.js
rename to src/engine/engine.js
index 92ed0aba..4bcbe429 100644
--- a/src/engine.js
+++ b/src/engine/engine.js
@@ -2,37 +2,49 @@ import {
defaults,
globals,
globalVersions,
-} from './globals.js';
+} from '../core/globals.js';
import {
tickModes,
isBrowser,
K,
doc,
-} from './consts.js';
+} from '../core/consts.js';
import {
now,
forEachChildren,
removeChild,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
Clock,
-} from './clock.js';
+} from '../core/clock.js';
import {
- additive,
-} from './additive.js';
+ tick,
+} from '../core/render.js';
import {
- tick,
-} from './render.js';
+ additive,
+} from '../animation/additive.js';
-export const engineTickMethod = /*#__PURE__*/ (() => isBrowser ? requestAnimationFrame : setImmediate)();
-export const engineCancelMethod = /*#__PURE__*/ (() => isBrowser ? cancelAnimationFrame : clearImmediate)();
+/**
+ * @import {
+ * DefaultsParams,
+ * } from '../types/index.js'
+*/
-export class Engine extends Clock {
+/**
+ * @import {
+ * Tickable,
+ * } from '../types/index.js'
+*/
+
+const engineTickMethod = /*#__PURE__*/ (() => isBrowser ? requestAnimationFrame : setImmediate)();
+const engineCancelMethod = /*#__PURE__*/ (() => isBrowser ? cancelAnimationFrame : clearImmediate)();
+
+class Engine extends Clock {
/** @param {Number} [initTime] */
constructor(initTime) {
@@ -113,7 +125,7 @@ export class Engine extends Clock {
// Getter and setter for timeUnit
get timeUnit() {
return globals.timeScale === 1 ? 'ms' : 's';
- };
+ }
set timeUnit(unit) {
const secondsScale = 0.001;
@@ -138,7 +150,7 @@ export class Engine extends Clock {
globals.precision = precision;
}
-};
+}
export const engine = /*#__PURE__*/(() => {
const engine = new Engine(now());
@@ -160,10 +172,10 @@ const tickEngine = () => {
} else {
engine.reqId = 0;
}
-};
+}
const killEngine = () => {
engineCancelMethod(/** @type {NodeJS.Immediate & Number} */(engine.reqId));
engine.reqId = 0;
return engine;
-};
+}
diff --git a/src/engine/index.js b/src/engine/index.js
new file mode 100644
index 00000000..0a522f49
--- /dev/null
+++ b/src/engine/index.js
@@ -0,0 +1 @@
+export * from './engine.js';
\ No newline at end of file
diff --git a/src/events/index.js b/src/events/index.js
new file mode 100644
index 00000000..8c4c6b58
--- /dev/null
+++ b/src/events/index.js
@@ -0,0 +1 @@
+export * from './scroll.js';
\ No newline at end of file
diff --git a/src/scroll.js b/src/events/scroll.js
similarity index 95%
rename from src/scroll.js
rename to src/events/scroll.js
index 6b187fc8..163d7218 100644
--- a/src/scroll.js
+++ b/src/events/scroll.js
@@ -4,23 +4,18 @@ import {
noop,
isDomSymbol,
relativeValuesExecRgx,
-} from './consts.js';
+} from '../core/consts.js';
import {
scope,
globals,
-} from './globals.js';
-
-import {
- none,
- parseEasings,
-} from './eases.js';
+} from '../core/globals.js';
import {
addChild,
removeChild,
forEachChildren,
- interpolate,
+ lerp,
clamp,
round,
isFnc,
@@ -28,33 +23,75 @@ import {
isObj,
isStr,
isUnd,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
parseTargets,
-} from './targets.js';
+} from '../core/targets.js';
import {
- Timer,
-} from './timer.js';
+ decomposeRawValue,
+ decomposedOriginalValue,
+ getRelativeValue,
+ setValue,
+} from '../core/values.js';
import {
convertValueUnit,
-} from './units.js';
+} from '../core/units.js';
+
+import {
+ Timer,
+} from '../timer/timer.js';
+
+import {
+ get,
+ set,
+} from '../utils/target.js';
import {
- lerp,
- getTargetValue,
- setTargetValues,
sync,
-} from './utils.js';
+} from '../utils/time.js';
import {
- decomposeRawValue,
- decomposedOriginalValue,
- getRelativeValue,
- setValue,
-} from './values.js';
+ none,
+} from '../easings/none.js';
+
+import {
+ parseEase,
+} from '../easings/eases.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * EasingFunction,
+ * Callback,
+ * EasingParam,
+ * ScrollThresholdValue,
+ * ScrollObserverParams,
+ * Tickable,
+ * ScrollThresholdParam,
+ * ScrollThresholdCallback,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * JSAnimation,
+ * } from '../animation/animation.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
/**
* @return {Number}
@@ -74,7 +111,7 @@ const getMaxViewHeight = () => {
* @param {ScrollObserver} scroller
* @return {T}
*/
-const parseScrollObserverFunctionParameter = (value, scroller) => value && isFnc(value) ? /** @type {Function} */(value)(scroller) : value;
+const parseScrollObserverFunctionParameter = (value, scroller) => value && isFnc(value) ? /** @type {Function} */(value)(scroller) : /** @type {T} */(value);
export const scrollContainers = new Map();
@@ -133,7 +170,7 @@ class ScrollContainer {
this.dataTimer = new Timer({
autoplay: false,
frameRate: 30,
- onUpdate: self => {
+ onUpdate: (/** @type {Timer} */self) => {
const dt = self.deltaTime;
const px = this.prevScrollX;
const py = this.prevScrollY;
@@ -373,7 +410,7 @@ export class ScrollObserver {
constructor(parameters = {}) {
if (scope.current) scope.current.register(this);
const syncMode = setValue(parameters.sync, 'play pause');
- const ease = syncMode ? parseEasings(/** @type {EasingParam} */(syncMode)) : null;
+ const ease = syncMode ? parseEase(/** @type {EasingParam} */(syncMode)) : null;
const isLinear = syncMode && (syncMode === 'linear' || syncMode === none);
const isEase = syncMode && !(ease === none && !isLinear);
const isSmooth = syncMode && (isNum(syncMode) || syncMode === true || isLinear);
@@ -676,9 +713,9 @@ export class ScrollObserver {
if (!$existingDebug) $debug.classList.add('animejs-onscroll-debug');
this.$debug = $debug;
- const containerPosition = getTargetValue(container.element, 'position');
+ const containerPosition = get(container.element, 'position');
if (containerPosition === 'static') {
- this.debugStyles = setTargetValues(container.element, { position: 'relative '});
+ this.debugStyles = set(container.element, { position: 'relative '});
}
}
@@ -703,10 +740,10 @@ export class ScrollObserver {
linked.seek(0, true);
}
/* Old implementation to get offset and targetSize before fixing https://github.com/juliangarnier/anime/issues/1021
- // const isContainerStatic = getTargetValue(container.element, 'position') === 'static' ? setTargetValues(container.element, { position: 'relative '}) : false;
+ // const isContainerStatic = get(container.element, 'position') === 'static' ? set(container.element, { position: 'relative '}) : false;
// while ($el && $el !== container.element && $el !== doc.body) {
- // const isSticky = getTargetValue($el, 'position') === 'sticky' ?
- // setTargetValues($el, { position: 'static' }) :
+ // const isSticky = get($el, 'position') === 'sticky' ?
+ // set($el, { position: 'static' }) :
// false;
// if ($el === $offsetParent) {
// offsetX += $el.offsetLeft || 0;
@@ -724,7 +761,7 @@ export class ScrollObserver {
// const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight;
while ($el && $el !== container.element && $el !== doc.body) {
- const isSticky = getTargetValue($el, 'position') === 'sticky' ? setTargetValues($el, { position: 'static' }) : false;
+ const isSticky = get($el, 'position') === 'sticky' ? set($el, { position: 'static' }) : false;
$el = $el.parentElement;
if (isSticky) {
if (!stickys) stickys = [];
@@ -834,7 +871,7 @@ export class ScrollObserver {
if (/** @type {Number} */(syncSmooth) < 1) {
const step = 0.0001;
const snap = lp < p && p === 1 ? step : lp > p && !p ? -step : 0;
- p = round(lerp(lp, p, interpolate(.01, .2, /** @type {Number} */(syncSmooth)), false) + snap, 6);
+ p = round(lerp(lp, p, lerp(.01, .2, /** @type {Number} */(syncSmooth))) + snap, 6);
}
} else if (syncEase) {
p = syncEase(p);
diff --git a/src/index.js b/src/index.js
new file mode 100644
index 00000000..cfb5666b
--- /dev/null
+++ b/src/index.js
@@ -0,0 +1,19 @@
+export * from './timer/index.js';
+export * from './animation/index.js';
+export * from './timeline/index.js';
+export * from './animatable/index.js';
+export * from './draggable/index.js';
+export * from './scope/index.js';
+export * from './events/index.js';
+export * from './spring/index.js';
+export * from './engine/index.js';
+export * from './easings/index.js';
+export * as easings from './easings/index.js';
+export * from './utils/index.js';
+export * as utils from './utils/index.js';
+export * from './svg/index.js';
+export * as svg from './svg/index.js';
+export * from './text/index.js';
+export * as text from './text/index.js';
+export * from './waapi/index.js';
+export * from './types/index.js';
diff --git a/src/properties.js b/src/properties.js
deleted file mode 100644
index 1163fca2..00000000
--- a/src/properties.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/// <reference path='./types.js' />
-
-import {
- tweenTypes,
- shortTransforms,
-} from './consts.js';
-
-import {
- isSvg,
- toLowerCase,
-} from './helpers.js';
-
-const propertyNamesCache = {};
-
-/**
- * @param {String} propertyName
- * @param {Target} target
- * @param {tweenTypes} tweenType
- * @return {String}
- */
-export const sanitizePropertyName = (propertyName, target, tweenType) => {
- if (tweenType === tweenTypes.TRANSFORM) {
- const t = shortTransforms.get(propertyName);
- return t ? t : propertyName;
- } else if (
- tweenType === tweenTypes.CSS ||
- // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
- // but properties like "baseFrequency" should stay in lowerCamelCase
- (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
- ) {
- const cachedPropertyName = propertyNamesCache[propertyName];
- if (cachedPropertyName) {
- return cachedPropertyName;
- } else {
- const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
- propertyNamesCache[propertyName] = lowerCaseName;
- return lowerCaseName;
- }
- } else {
- return propertyName;
- }
-}
diff --git a/src/scope/index.js b/src/scope/index.js
new file mode 100644
index 00000000..96192c64
--- /dev/null
+++ b/src/scope/index.js
@@ -0,0 +1 @@
+export * from './scope.js';
\ No newline at end of file
diff --git a/src/scope.js b/src/scope/scope.js
similarity index 93%
rename from src/scope.js
rename to src/scope/scope.js
index c9d7f416..eecb7db9 100644
--- a/src/scope.js
+++ b/src/scope/scope.js
@@ -1,25 +1,42 @@
-/// <reference path='./types.js' />
-
import {
doc,
win,
- noop,
-} from './consts.js';
+} from '../core/consts.js';
import {
scope,
globals,
-} from './globals.js';
+} from '../core/globals.js';
import {
- createRefreshable,
isFnc,
mergeObjects,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
parseTargets,
-} from './targets.js';
+} from '../core/targets.js';
+
+import {
+ keepTime,
+} from '../utils/time.js';
+
+/**
+ * @import {
+ * Tickable,
+ * ScopeParams,
+ * DOMTarget,
+ * ReactRef,
+ * AngularRef,
+ * DOMTargetSelector,
+ * DefaultsParams,
+ * ScopeConstructorCallback,
+ * ScopeCleanupCallback,
+ * Revertible,
+ * ScopeMethod,
+ * ScopedCallback,
+ * } from '../types/index.js'
+*/
export class Scope {
/** @param {ScopeParams} [parameters] */
@@ -186,7 +203,7 @@ export class Scope {
const currentIndex = this.onceIndex++;
const tracked = /** @type {(scope: this) => Tickable} */(this.constructorsOnce[currentIndex]);
if (isFnc(tracked)) return tracked(this);
- const constructor = /** @type {(scope: this) => Tickable} */(createRefreshable(cb));
+ const constructor = /** @type {(scope: this) => Tickable} */(keepTime(cb));
this.constructorsOnce[currentIndex] = constructor;
let trackedTickable;
this.execute(() => {
diff --git a/src/spring/index.js b/src/spring/index.js
new file mode 100644
index 00000000..5e16fd58
--- /dev/null
+++ b/src/spring/index.js
@@ -0,0 +1 @@
+export * from './spring.js';
\ No newline at end of file
diff --git a/src/spring.js b/src/spring/spring.js
similarity index 88%
rename from src/spring.js
rename to src/spring/spring.js
index 07fe2a21..04650316 100644
--- a/src/spring.js
+++ b/src/spring/spring.js
@@ -1,13 +1,11 @@
-/// <reference path='./types.js' />
-
import {
- minValue,
K,
-} from './consts.js';
+ minValue,
+} from '../core/consts.js';
import {
globals,
-} from './globals.js';
+} from '../core/globals.js';
import {
round,
@@ -17,26 +15,26 @@ import {
cos,
sin,
abs,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
setValue,
-} from './values.js';
+} from '../core/values.js';
+
+/**
+ * @import {
+ * EasingFunction,
+ * SpringParams,
+ * } from '../types/index.js'
+*/
/*
* Spring ease solver adapted from https://webkit.org/demos/spring/spring.js
- * Webkit Copyright © 2016 Apple Inc
+ * (c) 2016 Webkit - Apple Inc
*/
const maxSpringParamValue = K * 10;
-/**
- * @typedef {Object} SpringParams
- * @property {Number} [mass=1] - Mass, default 1
- * @property {Number} [stiffness=100] - Stiffness, default 100
- * @property {Number} [damping=10] - Damping, default 10
- * @property {Number} [velocity=0] - Initial velocity, default 0
- */
export class Spring {
/**
* @param {SpringParams} [parameters]
diff --git a/src/svg.js b/src/svg.js
deleted file mode 100644
index 273d9e1f..00000000
--- a/src/svg.js
+++ /dev/null
@@ -1,251 +0,0 @@
-/// <reference path='./types.js' />
-
-import {
- K,
- isSvgSymbol,
- morphPointsSymbol,
- proxyTargetSymbol,
-} from './consts.js';
-
-import {
- round,
- isSvg,
- atan2,
- sqrt,
- PI,
- isFnc,
-} from './helpers.js';
-
-import {
- parseTargets
-} from './targets.js';
-
-/**
- * @param {TargetsParam} path
- * @return {SVGGeometryElement|undefined}
- */
-const getPath = path => {
- const parsedTargets = parseTargets(path);
- const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
- if (!$parsedSvg || !isSvg($parsedSvg)) return;
- return $parsedSvg;
-}
-
-/**
- * @param {TargetsParam} path2
- * @param {Number} [precision]
- * @return {FunctionValue}
- */
-const morphTo = (path2, precision = .33) => ($path1) => {
- const $path2 = /** @type {SVGGeometryElement} */(getPath(path2));
- if (!$path2) return;
- const isPath = $path1.tagName === 'path';
- const separator = isPath ? ' ' : ',';
- const previousPoints = $path1[morphPointsSymbol];
- if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
-
- let v1 = '', v2 = '';
-
- if (!precision) {
- v1 = $path1.getAttribute(isPath ? 'd' : 'points');
- v2 = $path2.getAttribute(isPath ? 'd' : 'points');
- } else {
- const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
- const length2 = $path2.getTotalLength();
- const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
- for (let i = 0; i < maxPoints; i++) {
- const t = i / (maxPoints - 1);
- const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
- const pointOnPath2 = $path2.getPointAtLength(length2 * t);
- const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
- v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
- v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
- }
- }
-
- $path1[morphPointsSymbol] = v2;
-
- return [v1, v2];
-}
-
-/**
- * @param {SVGGeometryElement} [$el]
- * @return {Number}
- */
-const getScaleFactor = $el => {
- let scaleFactor = 1;
- if ($el && $el.getCTM) {
- const ctm = $el.getCTM();
- if (ctm) {
- const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
- const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
- scaleFactor = (scaleX + scaleY) / 2;
- }
- }
- return scaleFactor;
-}
-
-/**
- * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
- * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
- * @param {number} start - Starting position (0-1)
- * @param {number} end - Ending position (0-1)
- * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
- */
-const createDrawableProxy = ($el, start, end) => {
- const pathLength = K;
- const computedStyles = getComputedStyle($el);
- const strokeLineCap = computedStyles.strokeLinecap;
- // @ts-ignore
- const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
- let currentCap = strokeLineCap;
-
- const proxy = new Proxy($el, {
- get(target, property) {
- const value = target[property];
- if (property === proxyTargetSymbol) return target;
- if (property === 'setAttribute') {
- return (...args) => {
- if (args[0] === 'draw') {
- const value = args[1];
- const values = value.split(' ');
- const v1 = +values[0];
- const v2 = +values[1];
- // TOTO: Benchmark if performing two slices is more performant than one split
- // const spaceIndex = value.indexOf(' ');
- // const v1 = round(+value.slice(0, spaceIndex), precision);
- // const v2 = round(+value.slice(spaceIndex + 1), precision);
- const scaleFactor = getScaleFactor($scalled);
- const os = v1 * -pathLength * scaleFactor;
- const d1 = (v2 * pathLength * scaleFactor) + os;
- const d2 = (pathLength * scaleFactor +
- ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
- if (strokeLineCap !== 'butt') {
- const newCap = v1 === v2 ? 'butt' : strokeLineCap;
- if (currentCap !== newCap) {
- target.style.strokeLinecap = `${newCap}`;
- currentCap = newCap;
- }
- }
- target.setAttribute('stroke-dashoffset', `${os}`);
- target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
- }
- return Reflect.apply(value, target, args);
- };
- }
-
- if (isFnc(value)) {
- return (...args) => Reflect.apply(value, target, args);
- } else {
- return value;
- }
- }
- });
-
- if ($el.getAttribute('pathLength') !== `${pathLength}`) {
- $el.setAttribute('pathLength', `${pathLength}`);
- proxy.setAttribute('draw', `${start} ${end}`);
- }
-
- return /** @type {DrawableSVGGeometry} */(proxy);
-}
-
-/**
- * Creates drawable proxies for multiple SVG elements.
- * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
- * @param {number} [start=0] - Starting position (0-1)
- * @param {number} [end=0] - Ending position (0-1)
- * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
- */
-const createDrawable = (selector, start = 0, end = 0) => {
- const els = parseTargets(selector);
- return els.map($el => createDrawableProxy(
- /** @type {SVGGeometryElement} */($el),
- start,
- end
- ));
-};
-
-// Motion path animation
-
-/**
- * @param {SVGGeometryElement} $path
- * @param {Number} progress
- * @param {Number}lookup
- * @return {DOMPoint}
- */
-const getPathPoint = ($path, progress, lookup = 0) => {
- return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0);
-}
-
-/**
- * @param {SVGGeometryElement} $path
- * @param {String} pathProperty
- * @return {FunctionValue}
- */
-const getPathProgess = ($path, pathProperty) => {
- return $el => {
- const totalLength = +($path.getTotalLength());
- const inSvg = $el[isSvgSymbol];
- const ctm = $path.getCTM();
- /** @type {TweenObjectValue} */
- return {
- from: 0,
- to: totalLength,
- /** @type {TweenModifier} */
- modifier: progress => {
- if (pathProperty === 'a') {
- const p0 = getPathPoint($path, progress, -1);
- const p1 = getPathPoint($path, progress, +1);
- return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI;
- } else {
- const p = getPathPoint($path, progress, 0);
- return pathProperty === 'x' ?
- inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
- inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
- }
- }
- }
- }
-}
-
-/**
- * @param {TargetsParam} path
- */
-const createMotionPath = path => {
- const $path = getPath(path);
- if (!$path) return;
- return {
- translateX: getPathProgess($path, 'x'),
- translateY: getPathProgess($path, 'y'),
- rotate: getPathProgess($path, 'a'),
- }
-}
-
-// Check for valid SVG attribute
-
-const cssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
-
-/**
- * @param {Target} el
- * @param {String} propertyName
- * @return {Boolean}
- */
-export const isValidSVGAttribute = (el, propertyName) => {
- // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform
- if (cssReservedProperties.includes(propertyName)) return false;
- if (el.getAttribute(propertyName) || propertyName in el) {
- if (propertyName === 'scale') { // Scale
- const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
- // Only consider scale as a valid SVG attribute on filter element
- return elParentNode && elParentNode.tagName === 'filter';
- }
- return true;
- }
-}
-
-export const svg = {
- morphTo,
- createMotionPath,
- createDrawable,
-}
diff --git a/src/svg/drawable.js b/src/svg/drawable.js
new file mode 100644
index 00000000..8600be90
--- /dev/null
+++ b/src/svg/drawable.js
@@ -0,0 +1,118 @@
+import {
+ K,
+ proxyTargetSymbol,
+} from '../core/consts.js';
+
+import {
+ sqrt,
+ isFnc,
+} from '../core/helpers.js';
+
+import {
+ parseTargets,
+} from '../core/targets.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * DrawableSVGGeometry,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {SVGGeometryElement} [$el]
+ * @return {Number}
+ */
+const getScaleFactor = $el => {
+ let scaleFactor = 1;
+ if ($el && $el.getCTM) {
+ const ctm = $el.getCTM();
+ if (ctm) {
+ const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
+ const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
+ scaleFactor = (scaleX + scaleY) / 2;
+ }
+ }
+ return scaleFactor;
+}
+
+/**
+ * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
+ * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
+ * @param {number} start - Starting position (0-1)
+ * @param {number} end - Ending position (0-1)
+ * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
+ */
+const createDrawableProxy = ($el, start, end) => {
+ const pathLength = K;
+ const computedStyles = getComputedStyle($el);
+ const strokeLineCap = computedStyles.strokeLinecap;
+ // @ts-ignore
+ const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
+ let currentCap = strokeLineCap;
+
+ const proxy = new Proxy($el, {
+ get(target, property) {
+ const value = target[property];
+ if (property === proxyTargetSymbol) return target;
+ if (property === 'setAttribute') {
+ return (...args) => {
+ if (args[0] === 'draw') {
+ const value = args[1];
+ const values = value.split(' ');
+ const v1 = +values[0];
+ const v2 = +values[1];
+ // TOTO: Benchmark if performing two slices is more performant than one split
+ // const spaceIndex = value.indexOf(' ');
+ // const v1 = round(+value.slice(0, spaceIndex), precision);
+ // const v2 = round(+value.slice(spaceIndex + 1), precision);
+ const scaleFactor = getScaleFactor($scalled);
+ const os = v1 * -pathLength * scaleFactor;
+ const d1 = (v2 * pathLength * scaleFactor) + os;
+ const d2 = (pathLength * scaleFactor +
+ ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
+ if (strokeLineCap !== 'butt') {
+ const newCap = v1 === v2 ? 'butt' : strokeLineCap;
+ if (currentCap !== newCap) {
+ target.style.strokeLinecap = `${newCap}`;
+ currentCap = newCap;
+ }
+ }
+ target.setAttribute('stroke-dashoffset', `${os}`);
+ target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
+ }
+ return Reflect.apply(value, target, args);
+ };
+ }
+
+ if (isFnc(value)) {
+ return (...args) => Reflect.apply(value, target, args);
+ } else {
+ return value;
+ }
+ }
+ });
+
+ if ($el.getAttribute('pathLength') !== `${pathLength}`) {
+ $el.setAttribute('pathLength', `${pathLength}`);
+ proxy.setAttribute('draw', `${start} ${end}`);
+ }
+
+ return /** @type {DrawableSVGGeometry} */(proxy);
+}
+
+/**
+ * Creates drawable proxies for multiple SVG elements.
+ * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
+ * @param {number} [start=0] - Starting position (0-1)
+ * @param {number} [end=0] - Ending position (0-1)
+ * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
+ */
+export const createDrawable = (selector, start = 0, end = 0) => {
+ const els = parseTargets(selector);
+ return els.map($el => createDrawableProxy(
+ /** @type {SVGGeometryElement} */($el),
+ start,
+ end
+ ));
+}
diff --git a/src/svg/helpers.js b/src/svg/helpers.js
new file mode 100644
index 00000000..9ce07b12
--- /dev/null
+++ b/src/svg/helpers.js
@@ -0,0 +1,24 @@
+import {
+ isSvg,
+} from '../core/helpers.js';
+
+import {
+ parseTargets
+} from '../core/targets.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {TargetsParam} path
+ * @return {SVGGeometryElement|void}
+ */
+export const getPath = path => {
+ const parsedTargets = parseTargets(path);
+ const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
+ if (!$parsedSvg || !isSvg($parsedSvg)) return console.warn(`${path} is not a valid SVGGeometryElement`);
+ return $parsedSvg;
+}
diff --git a/src/svg/index.js b/src/svg/index.js
new file mode 100644
index 00000000..41f13e04
--- /dev/null
+++ b/src/svg/index.js
@@ -0,0 +1,3 @@
+export { createMotionPath } from "./motionpath.js";
+export { createDrawable } from "./drawable.js";
+export { morphTo } from "./morphto.js";
\ No newline at end of file
diff --git a/src/svg/morphto.js b/src/svg/morphto.js
new file mode 100644
index 00000000..abda105a
--- /dev/null
+++ b/src/svg/morphto.js
@@ -0,0 +1,55 @@
+import {
+ morphPointsSymbol,
+} from '../core/consts.js';
+
+import {
+ round,
+} from '../core/helpers.js';
+
+import {
+ getPath,
+} from './helpers.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * FunctionValue
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {TargetsParam} path2
+ * @param {Number} [precision]
+ * @return {FunctionValue}
+ */
+export const morphTo = (path2, precision = .33) => ($path1) => {
+ const $path2 = /** @type {SVGGeometryElement} */(getPath(path2));
+ if (!$path2) return;
+ const isPath = $path1.tagName === 'path';
+ const separator = isPath ? ' ' : ',';
+ const previousPoints = $path1[morphPointsSymbol];
+ if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
+
+ let v1 = '', v2 = '';
+
+ if (!precision) {
+ v1 = $path1.getAttribute(isPath ? 'd' : 'points');
+ v2 = $path2.getAttribute(isPath ? 'd' : 'points');
+ } else {
+ const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
+ const length2 = $path2.getTotalLength();
+ const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
+ for (let i = 0; i < maxPoints; i++) {
+ const t = i / (maxPoints - 1);
+ const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
+ const pointOnPath2 = $path2.getPointAtLength(length2 * t);
+ const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
+ v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
+ v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
+ }
+ }
+
+ $path1[morphPointsSymbol] = v2;
+
+ return [v1, v2];
+}
diff --git a/src/svg/motionpath.js b/src/svg/motionpath.js
new file mode 100644
index 00000000..2a1e6273
--- /dev/null
+++ b/src/svg/motionpath.js
@@ -0,0 +1,77 @@
+import {
+ isSvgSymbol,
+} from '../core/consts.js';
+
+import {
+ atan2,
+ PI,
+} from '../core/helpers.js';
+
+import {
+ getPath,
+} from './helpers.js';
+
+/**
+ * @import {
+ * TargetsParam,
+ * FunctionValue,
+ * TweenObjectValue,
+ * TweenModifier,
+ * } from '../types/index.js'
+*/
+
+// Motion path animation
+
+/**
+ * @param {SVGGeometryElement} $path
+ * @param {Number} progress
+ * @param {Number}lookup
+ * @return {DOMPoint}
+ */
+const getPathPoint = ($path, progress, lookup = 0) => {
+ return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0);
+}
+
+/**
+ * @param {SVGGeometryElement} $path
+ * @param {String} pathProperty
+ * @return {FunctionValue}
+ */
+const getPathProgess = ($path, pathProperty) => {
+ return $el => {
+ const totalLength = +($path.getTotalLength());
+ const inSvg = $el[isSvgSymbol];
+ const ctm = $path.getCTM();
+ /** @type {TweenObjectValue} */
+ return {
+ from: 0,
+ to: totalLength,
+ /** @type {TweenModifier} */
+ modifier: progress => {
+ if (pathProperty === 'a') {
+ const p0 = getPathPoint($path, progress, -1);
+ const p1 = getPathPoint($path, progress, +1);
+ return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI;
+ } else {
+ const p = getPathPoint($path, progress, 0);
+ return pathProperty === 'x' ?
+ inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
+ inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
+ }
+ }
+ }
+ }
+}
+
+/**
+ * @param {TargetsParam} path
+ */
+export const createMotionPath = path => {
+ const $path = getPath(path);
+ if (!$path) return;
+ return {
+ translateX: getPathProgess($path, 'x'),
+ translateY: getPathProgess($path, 'y'),
+ rotate: getPathProgess($path, 'a'),
+ }
+}
diff --git a/src/text/index.js b/src/text/index.js
new file mode 100644
index 00000000..5e8c649d
--- /dev/null
+++ b/src/text/index.js
@@ -0,0 +1 @@
+export * from './split.js';
\ No newline at end of file
diff --git a/src/text.js b/src/text/split.js
similarity index 93%
rename from src/text.js
rename to src/text/split.js
index 0ea832d3..60cd016f 100644
--- a/src/text.js
+++ b/src/text/split.js
@@ -1,14 +1,11 @@
-/// <reference path='./types.js' />
-
import {
doc,
- noop,
isBrowser,
-} from './consts.js';
+} from '../core/consts.js';
import {
scope,
-} from './globals.js';
+} from '../core/globals.js';
import {
isFnc,
@@ -17,16 +14,29 @@ import {
isObj,
isUnd,
isArr,
- createRefreshable,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
getNodeList,
-} from './targets.js';
+} from '../core/targets.js';
import {
setValue,
-} from './values.js';
+} from '../core/values.js';
+
+import {
+ keepTime,
+} from '../utils/time.js';
+
+/**
+ * @import {
+ * Tickable,
+ * DOMTarget,
+ * SplitTemplateParams,
+ * SplitFunctionValue,
+ * TextSplitterParams,
+ * } from '../types/index.js'
+*/
const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter;
const valueRgx = /\{value\}/g;
@@ -62,7 +72,7 @@ let $splitTemplate = null;
const isSegmentWordLike = seg => {
return seg.isWordLike ||
seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later
- isNum(+seg.segment); // Safari doesn't considers numbers as words
+ isNum(+seg.segment); // Safari doesn't considers numbers as words
}
/**
@@ -106,7 +116,7 @@ const filterLineElements = ($el, lineIndex, bin) => {
/**
* @param {'line'|'word'|'char'} type
- * @param {splitTemplateParams} params
+ * @param {SplitTemplateParams} params
* @return {String}
*/
const generateTemplate = (type, params = {}) => {
@@ -224,11 +234,11 @@ export class TextSplitter {
this.accessible = setValue(accessible, true);
this.linesOnly = lineParams && (!wordParams && !charParams);
/** @type {String|false|SplitFunctionValue} */
- this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {splitTemplateParams} */(lineParams)) : lineParams;
+ this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams;
/** @type {String|false|SplitFunctionValue} */
- this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {splitTemplateParams} */(wordParams)) : wordParams;
+ this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams;
/** @type {String|false|SplitFunctionValue} */
- this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {splitTemplateParams} */(charParams)) : charParams;
+ this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams;
this.$target = $target;
this.html = $target && $target.innerHTML;
this.lines = [];
@@ -267,7 +277,7 @@ export class TextSplitter {
*/
addEffect(effect) {
if (!isFnc(effect)) return console.warn('Effect must return a function.');
- const refreshableEffect = createRefreshable(effect);
+ const refreshableEffect = keepTime(effect);
this.effects.push(refreshableEffect);
if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this);
return this;
@@ -473,8 +483,16 @@ export class TextSplitter {
* @param {TextSplitterParams} [parameters]
* @return {TextSplitter}
*/
-export const split = (target, parameters) => new TextSplitter(target, parameters);
+export const splitText = (target, parameters) => new TextSplitter(target, parameters);
-export const text = {
- split,
+/**
+ * @deprecated text.split() is deprecated, import splitText() directly, or text.splitText()
+ *
+ * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
+ * @param {TextSplitterParams} [parameters]
+ * @return {TextSplitter}
+ */
+export const split = (target, parameters) => {
+ console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()');
+ return new TextSplitter(target, parameters);
}
diff --git a/src/timeline/index.js b/src/timeline/index.js
new file mode 100644
index 00000000..efa6efcc
--- /dev/null
+++ b/src/timeline/index.js
@@ -0,0 +1 @@
+export * from './timeline.js';
\ No newline at end of file
diff --git a/src/timeline/position.js b/src/timeline/position.js
new file mode 100644
index 00000000..982a8d65
--- /dev/null
+++ b/src/timeline/position.js
@@ -0,0 +1,73 @@
+import {
+ minValue,
+ relativeValuesExecRgx,
+} from "../core/consts.js";
+
+import {
+ isNil,
+ isNum,
+ isUnd,
+ stringStartsWith,
+} from "../core/helpers.js";
+
+import {
+ getRelativeValue,
+} from "../core/values.js";
+
+/**
+ * @import {
+ * Tickable,
+ * TimelinePosition,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from './timeline.js'
+*/
+
+/**
+ * Timeline's children offsets positions parser
+ * @param {Timeline} timeline
+ * @param {String} timePosition
+ * @return {Number}
+ */
+const getPrevChildOffset = (timeline, timePosition) => {
+ if (stringStartsWith(timePosition, '<')) {
+ const goToPrevAnimationOffset = timePosition[1] === '<';
+ const prevAnimation = /** @type {Tickable} */(timeline._tail);
+ const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
+ return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
+ }
+}
+
+/**
+ * @param {Timeline} timeline
+ * @param {TimelinePosition} [timePosition]
+ * @return {Number}
+ */
+export const parseTimelinePosition = (timeline, timePosition) => {
+ let tlDuration = timeline.iterationDuration;
+ if (tlDuration === minValue) tlDuration = 0;
+ if (isUnd(timePosition)) return tlDuration;
+ if (isNum(+timePosition)) return +timePosition;
+ const timePosStr = /** @type {String} */(timePosition);
+ const tlLabels = timeline ? timeline.labels : null;
+ const hasLabels = !isNil(tlLabels);
+ const prevOffset = getPrevChildOffset(timeline, timePosStr);
+ const hasSibling = !isUnd(prevOffset);
+ const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
+ if (matchedRelativeOperator) {
+ const fullOperator = matchedRelativeOperator[0];
+ const split = timePosStr.split(fullOperator);
+ const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
+ const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
+ const parsedNumericalOffset = +split[1];
+ return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
+ } else {
+ return hasSibling ? prevOffset :
+ hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
+ tlDuration : tlDuration;
+ }
+}
\ No newline at end of file
diff --git a/src/timeline.js b/src/timeline/timeline.js
similarity index 79%
rename from src/timeline.js
rename to src/timeline/timeline.js
index d6121e74..82152b1e 100644
--- a/src/timeline.js
+++ b/src/timeline/timeline.js
@@ -1,104 +1,83 @@
-/// <reference path='./types.js' />
-
import {
globals,
-} from './globals.js';
+} from '../core/globals.js';
import {
- relativeValuesExecRgx,
minValue,
tickModes,
compositionTypes,
-} from './consts.js';
+} from '../core/consts.js';
import {
isObj,
isFnc,
isUnd,
- isNil,
isNum,
+ isStr,
addChild,
forEachChildren,
- stringStartsWith,
mergeObjects,
clampInfinity,
normalizeTime,
- isStr,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
- getRelativeValue, setValue,
-} from './values.js';
+ setValue,
+} from '../core/values.js';
import {
parseTargets,
-} from './targets.js';
+} from '../core/targets.js';
import {
- Timer,
-} from './timer.js';
+ tick,
+} from '../core/render.js';
import {
- JSAnimation,
cleanInlineStyles,
-} from './animation.js';
+} from '../utils/target.js';
import {
- tick,
-} from './render.js';
+ Timer,
+} from '../timer/timer.js';
import {
- parseEasings,
-} from './eases.js';
+ removeTargetsFromRenderable,
+} from '../animation/composition.js';
+
+import {
+ JSAnimation,
+} from '../animation/animation.js';
import {
- remove,
-} from './utils.js';
+ parseEase,
+} from '../easings/eases.js';
+
+import {
+ parseTimelinePosition,
+} from './position.js';
/**
- * Timeline's children offsets positions parser
- * @param {Timeline} timeline
- * @param {String} timePosition
- * @return {Number}
- */
-const getPrevChildOffset = (timeline, timePosition) => {
- if (stringStartsWith(timePosition, '<')) {
- const goToPrevAnimationOffset = timePosition[1] === '<';
- const prevAnimation = /** @type {Tickable} */(timeline._tail);
- const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
- return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
- }
-}
+ * @import {
+ * TargetsParam,
+ * Callback,
+ * Tickable,
+ * TimerParams,
+ * AnimationParams,
+ * Target,
+ * Renderable,
+ * TimelineParams,
+ * DefaultsParams,
+ * TimelinePosition,
+ * StaggerFunction,
+ * } from '../types/index.js'
+*/
/**
- * @param {Timeline} timeline
- * @param {TimelinePosition} [timePosition]
- * @return {Number}
- */
-export const parseTimelinePosition = (timeline, timePosition) => {
- let tlDuration = timeline.iterationDuration;
- if (tlDuration === minValue) tlDuration = 0;
- if (isUnd(timePosition)) return tlDuration;
- if (isNum(+timePosition)) return +timePosition;
- const timePosStr = /** @type {String} */(timePosition);
- const tlLabels = timeline ? timeline.labels : null;
- const hasLabels = !isNil(tlLabels);
- const prevOffset = getPrevChildOffset(timeline, timePosStr);
- const hasSibling = !isUnd(prevOffset);
- const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
- if (matchedRelativeOperator) {
- const fullOperator = matchedRelativeOperator[0];
- const split = timePosStr.split(fullOperator);
- const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
- const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
- const parsedNumericalOffset = +split[1];
- return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
- } else {
- return hasSibling ? prevOffset :
- hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
- tlDuration : tlDuration;
- }
-}
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
/**
* @param {Timeline} tl
@@ -169,7 +148,7 @@ export class Timeline extends Timer {
/** @type {Callback<this>} */
this.onRender = parameters.onRender || globalDefaults.onRender;
const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase);
- this._ease = tlPlaybackEase ? parseEasings(tlPlaybackEase) : null;
+ this._ease = tlPlaybackEase ? parseEase(tlPlaybackEase) : null;
/** @type {Number} */
this.iterationDuration = 0;
}
@@ -314,7 +293,7 @@ export class Timeline extends Timer {
* @return {this}
*/
remove(targets, propertyName) {
- remove(targets, this, propertyName);
+ removeTargetsFromRenderable(parseTargets(targets), this, propertyName);
return this;
}
diff --git a/src/timer/index.js b/src/timer/index.js
new file mode 100644
index 00000000..56e8c50a
--- /dev/null
+++ b/src/timer/index.js
@@ -0,0 +1 @@
+export * from './timer.js';
\ No newline at end of file
diff --git a/src/timer.js b/src/timer/timer.js
similarity index 96%
rename from src/timer.js
rename to src/timer/timer.js
index 320fe4b2..a4e9757c 100644
--- a/src/timer.js
+++ b/src/timer/timer.js
@@ -1,12 +1,10 @@
-/// <reference path='./types.js' />
-
import {
minValue,
compositionTypes,
tickModes,
noop,
maxValue,
-} from './consts.js';
+} from '../core/consts.js';
import {
now,
@@ -19,34 +17,55 @@ import {
isFnc,
clamp,
floor,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
scope,
globals,
-} from './globals.js';
+} from '../core/globals.js';
import {
setValue,
-} from './values.js';
+} from '../core/values.js';
import {
tick,
-} from './render.js';
+} from '../core/render.js';
import {
composeTween,
getTweenSiblings,
removeTweenSliblings,
-} from './compositions.js';
+} from '../animation/composition.js';
import {
- engine,
-} from './engine.js';
+ Clock,
+} from '../core/clock.js';
import {
- Clock,
-} from './clock.js';
+ engine,
+} from '../engine/engine.js';
+
+/**
+ * @import {
+ * Callback,
+ * TimerParams,
+ * Renderable,
+ * Tween,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * ScrollObserver,
+ * } from '../events/scroll.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
/**
* @param {Timer} timer
@@ -214,7 +233,6 @@ export class Timer extends Clock {
return !!this._cancelled;
}
- /** @param {Boolean} cancelled */
set cancelled(cancelled) {
cancelled ? this.cancel() : this.reset(1).play();
}
@@ -223,7 +241,6 @@ export class Timer extends Clock {
return clamp(round(this._currentTime, globals.precision), -this._delay, this.duration);
}
- /** @param {Number} time */
set currentTime(time) {
const paused = this.paused;
// Pausing the timer is necessary to avoid time jumps on a running instance
@@ -235,7 +252,6 @@ export class Timer extends Clock {
return round(this._iterationTime, globals.precision);
}
- /** @param {Number} time */
set iterationCurrentTime(time) {
this.currentTime = (this.iterationDuration * this._currentIteration) + time;
}
@@ -244,7 +260,6 @@ export class Timer extends Clock {
return clamp(round(this._currentTime / this.duration, 10), 0, 1);
}
- /** @param {Number} progress */
set progress(progress) {
this.currentTime = this.duration * progress;
}
@@ -253,7 +268,6 @@ export class Timer extends Clock {
return clamp(round(this._iterationTime / this.iterationDuration, 10), 0, 1);
}
- /** @param {Number} progress */
set iterationProgress(progress) {
const iterationDuration = this.iterationDuration;
this.currentTime = (iterationDuration * this._currentIteration) + (iterationDuration * progress);
@@ -263,7 +277,6 @@ export class Timer extends Clock {
return this._currentIteration;
}
- /** @param {Number} iterationCount */
set currentIteration(iterationCount) {
this.currentTime = (this.iterationDuration * clamp(+iterationCount, 0, this.iterationCount - 1));
}
@@ -272,7 +285,6 @@ export class Timer extends Clock {
return !!this._reversed;
}
- /** @param {Boolean} reverse */
set reversed(reverse) {
reverse ? this.reverse() : this.play();
}
@@ -281,7 +293,6 @@ export class Timer extends Clock {
return super.speed;
}
- /** @param {Number} playbackRate */
set speed(playbackRate) {
super.speed = playbackRate;
this.resetTime();
diff --git a/src/types.js b/src/types/index.js
similarity index 87%
rename from src/types.js
rename to src/types/index.js
index 5e5d1d1a..5e3704a5 100644
--- a/src/types.js
+++ b/src/types/index.js
@@ -1,20 +1,26 @@
-/* #__PURE__ */
+// Needed to transform this file as an valid ESM module
-/* Private */
+export {}
-/** @typedef {import('./animation.js').JSAnimation} JSAnimation */
-/** @typedef {import('./waapi.js').WAAPIAnimation} WAAPIAnimation */
-/** @typedef {import('./timer.js').Timer} Timer */
-/** @typedef {import('./timeline.js').Timeline} Timeline */
-/** @typedef {import('./draggable.js').Draggable} Draggable */
-/** @typedef {import('./scroll.js').ScrollObserver} ScrollObserver */
-/** @typedef {import('./scope.js').Scope} Scope */
-/** @typedef {import('./text.js').TextSplitter} TextSplitter */
-/** @typedef {import('./spring.js').Spring} Spring */
+// Private types
-/* Exports */
+/**
+ * @import { ScrollObserver } from '../events/scroll.js';
+ * @import { JSAnimation } from '../animation/animation.js';
+ * @import { Animatable } from '../animatable/animatable.js';
+ * @import { Timeline } from '../timeline/timeline.js';
+ * @import { Timer } from '../timer/timer.js';
+ * @import { WAAPIAnimation } from '../waapi/waapi.js';
+ * @import { Draggable } from '../draggable/draggable.js';
+ * @import { TextSplitter } from '../text/split.js';
+ * @import { Scope } from '../scope/scope.js';
+ * @import { Spring } from '../spring/spring.js';
+ * @import { compositionTypes, tweenTypes, valueTypes } from '../core/consts.js';
+ */
+
+// Exported types
-// Global types ////////////////////////////////////////////////////////////////
+// Global types
/**
* @typedef {Object} DefaultsParams
@@ -31,7 +37,7 @@
* @property {Number|FunctionValue} [delay]
* @property {Number} [loopDelay]
* @property {EasingParam} [ease]
- * @property {'none'|'replace'|'blend'|import('./consts.js').compositionTypes} [composition]
+ * @property {'none'|'replace'|'blend'|compositionTypes} [composition]
* @property {(v: any) => any} [modifier]
* @property {(tickable: Tickable) => void} [onBegin]
* @property {(tickable: Tickable) => void} [onBeforeUpdate]
@@ -45,9 +51,9 @@
/** @typedef {JSAnimation|Timeline} Renderable */
/** @typedef {Timer|Renderable} Tickable */
/** @typedef {Timer&JSAnimation&Timeline} CallbackArgument */
-/** @typedef {import('./animatable.js').Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */
+/** @typedef {Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */
-// Stagger types ///////////////////////////////////////////////////////////////
+// Stagger types
/**
* @template T
@@ -72,7 +78,21 @@
* @property {TweenModifier} [modifier]
*/
-// Eases types /////////////////////////////////////////////////////////////////
+// Targets types
+
+/** @typedef {HTMLElement|SVGElement} DOMTarget */
+/** @typedef {Record<String, any>} JSTarget */
+/** @typedef {DOMTarget|JSTarget} Target */
+/** @typedef {Target|NodeList|String} TargetSelector */
+/** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */
+/** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */
+/** @typedef {Array.<DOMTarget>} DOMTargetsArray */
+/** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */
+/** @typedef {Array.<JSTarget>} JSTargetsArray */
+/** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */
+/** @typedef {Array.<Target>} TargetsArray */
+
+// Eases types
/**
* @callback EasingFunction
@@ -84,23 +104,32 @@
* @typedef {('linear'|'linear(x1, x2 25%, x3)'|'in'|'out'|'inOut'|'inQuad'|'outQuad'|'inOutQuad'|'inCubic'|'outCubic'|'inOutCubic'|'inQuart'|'outQuart'|'inOutQuart'|'inQuint'|'outQuint'|'inOutQuint'|'inSine'|'outSine'|'inOutSine'|'inCirc'|'outCirc'|'inOutCirc'|'inExpo'|'outExpo'|'inOutExpo'|'inBounce'|'outBounce'|'inOutBounce'|'inBack'|'outBack'|'inOutBack'|'inElastic'|'outElastic'|'inOutElastic'|'irregular'|'cubicBezier'|'steps'|'in(p = 1.675)'|'out(p = 1.675)'|'inOut(p = 1.675)'|'inBack(overshoot = 1.70158)'|'outBack(overshoot = 1.70158)'|'inOutBack(overshoot = 1.70158)'|'inElastic(amplitude = 1, period = .3)'|'outElastic(amplitude = 1, period = .3)'|'inOutElastic(amplitude = 1, period = .3)'|'irregular(length = 10, randomness = 1)'|'cubicBezier(x1, y1, x2, y2)'|'steps(steps = 10)')} EaseStringParamNames
*/
+/**
+ * @callback PowerEasing
+ * @param {Number|String} [power=1.675]
+ * @return {EasingFunction}
+ */
+
+/**
+ * @callback BackEasing
+ * @param {Number|String} [overshoot=1.70158]
+ * @return {EasingFunction}
+ */
+
+/**
+ * @callback ElasticEasing
+ * @param {Number|String} [amplitude=1]
+ * @param {Number|String} [period=.3]
+ * @return {EasingFunction}
+ */
+
+/** @typedef {PowerEasing|BackEasing|ElasticEasing} EasingFunctionWithParams */
+
// A hack to get both ease names suggestions AND allow any strings
// https://github.com/microsoft/TypeScript/issues/29729#issuecomment-460346421
/** @typedef {(String & {})|EaseStringParamNames|EasingFunction|Spring} EasingParam */
-/** @typedef {HTMLElement|SVGElement} DOMTarget */
-/** @typedef {Record<String, any>} JSTarget */
-/** @typedef {DOMTarget|JSTarget} Target */
-/** @typedef {Target|NodeList|String} TargetSelector */
-/** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */
-/** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */
-/** @typedef {Array.<DOMTarget>} DOMTargetsArray */
-/** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */
-/** @typedef {Array.<JSTarget>} JSTargetsArray */
-/** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */
-/** @typedef {Array.<Target>} TargetsArray */
-
-// Spring types ////////////////////////////////////////////////////////////////
+// Spring types
/**
* @typedef {Object} SpringParams
@@ -110,7 +139,7 @@
* @property {Number} [velocity=0] - Initial velocity, default 0
*/
- // Callback types //////////////////////////////////////////////////////////////
+ // Callback types
/**
* @template T
@@ -137,7 +166,7 @@
* @property {Callback<T>} [onRender]
*/
-// Timer types /////////////////////////////////////////////////////////////////
+// Timer types
/**
* @typedef {Object} TimerOptions
@@ -153,13 +182,11 @@
* @property {Number} [playbackRate]
*/
-/**
-
/**
* @typedef {TimerOptions & TickableCallbacks<Timer>} TimerParams
*/
-// Tween types /////////////////////////////////////////////////////////////////
+// Tween types
/**
* @callback FunctionValue
@@ -201,8 +228,8 @@
* @property {Number} _startTime
* @property {Number} _changeDuration
* @property {Number} _absoluteStartTime
- * @property {import('./consts.js').tweenTypes} _tweenType
- * @property {import('./consts.js').valueTypes} _valueType
+ * @property {tweenTypes} _tweenType
+ * @property {valueTypes} _valueType
* @property {Number} _composition
* @property {Number} _isOverlapped
* @property {Number} _isOverridden
@@ -230,7 +257,7 @@
/** @typedef {WeakMap.<Target, TweenLookups>} TweenReplaceLookups */
/** @typedef {Map.<Target, TweenLookups>} TweenAdditiveLookups */
-// JSAnimation types ///////////////////////////////////////////////////////////
+// JSAnimation types
/**
* @typedef {Number|String|FunctionValue} TweenParamValue
@@ -241,7 +268,7 @@
*/
/**
- * @typedef {(String & {})|'none'|'replace'|'blend'|import('./consts.js').compositionTypes} TweenComposition
+ * @typedef {(String & {})|'none'|'replace'|'blend'|compositionTypes} TweenComposition
*/
/**
@@ -304,7 +331,7 @@
* @typedef {Record<String, TweenOptions | Callback<JSAnimation> | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & TickableCallbacks<JSAnimation> & RenderableCallbacks<JSAnimation>} AnimationParams
*/
-// Timeline types //////////////////////////////////////////////////////////////
+// Timeline types
/**
* Accepts:<br>
@@ -345,7 +372,7 @@
* @typedef {TimerOptions & TimelineOptions & TickableCallbacks<Timeline> & RenderableCallbacks<Timeline>} TimelineParams
*/
-// WAAPIAnimation types ////////////////////////////////////////////////////////
+// WAAPIAnimation types
/**
* @typedef {String|Number|Array<String>|Array<Number>} WAAPITweenValue
@@ -395,7 +422,7 @@
* @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | WAAPICallback | EasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams
*/
-// Animatable types ////////////////////////////////////////////////////////////
+// Animatable types
/**
* @callback AnimatablePropertySetter
@@ -415,7 +442,7 @@
*/
/**
- * @typedef {import('./animatable.js').Animatable & Record<String, AnimatableProperty>} AnimatableObject
+ * @typedef {Animatable & Record<String, AnimatableProperty>} AnimatableObject
*/
/**
@@ -431,7 +458,7 @@
* @typedef {Record<String, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions} AnimatableParams
*/
-// Scope types /////////////////////////////////////////////////////////////////
+// Scope types
/**
* @typedef {Object} ReactRef
@@ -474,7 +501,7 @@
* @return {ScopeCleanupCallback|void}
*/
-// Scroll types ////////////////////////////////////////////////////////////////
+// Scroll types
/**
* @typedef {String|Number} ScrollThresholdValue
@@ -519,7 +546,7 @@
* @property {Callback<ScrollObserver>} [onSyncComplete]
*/
-// Draggable types /////////////////////////////////////////////////////////////
+// Draggable types
/**
* @typedef {Object} DraggableAxisParam
@@ -568,10 +595,10 @@
* @property {Callback<Draggable>} [onAfterResize]
*/
-// Text types //////////////////////////////////////////////////////////////////
+// Text types
/**
- * @typedef {Object} splitTemplateParams
+ * @typedef {Object} SplitTemplateParams
* @property {false|String} [class]
* @property {Boolean|'hidden'|'clip'|'visible'|'scroll'|'auto'} [wrap]
* @property {Boolean|'top'|'right'|'bottom'|'left'|'center'} [clone]
@@ -589,15 +616,15 @@
/**
* @typedef {Object} TextSplitterParams
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [lines]
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [words]
- * @property {SplitValue|splitTemplateParams|SplitFunctionValue} [chars]
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [lines]
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [words]
+ * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [chars]
* @property {Boolean} [accessible]
* @property {Boolean} [includeSpaces]
* @property {Boolean} [debug]
*/
-// SVG types ///////////////////////////////////////////////////////////////////
+// SVG types
/**
* @typedef {SVGGeometryElement & {
diff --git a/src/utils.js b/src/utils.js
deleted file mode 100644
index 29a6fe58..00000000
--- a/src/utils.js
+++ /dev/null
@@ -1,458 +0,0 @@
-/// <reference path='./types.js' />
-
-import {
- globals,
-} from './globals.js';
-
-import {
- noop,
- minValue,
- compositionTypes,
- valueTypes,
- K,
- tweenTypes,
-} from './consts.js';
-
-import {
- isUnd,
- PI,
- snap,
- clamp,
- round,
- random,
- interpolate,
- shuffle,
- removeChild,
- forEachChildren,
- createRefreshable,
-} from './helpers.js';
-
-import {
- engine,
-} from './engine.js';
-
-import {
- Timer,
-} from './timer.js';
-
-import {
- JSAnimation,
- cleanInlineStyles,
-} from './animation.js';
-
-import {
- removeWAAPIAnimation,
-} from './waapi.js';
-
-import {
- parseTargets,
- registerTargets,
-} from './targets.js';
-
-import {
- sanitizePropertyName,
-} from './properties.js';
-
-import {
- setValue,
- getTweenType,
- getOriginalAnimatableValue,
- decomposeRawValue,
- decomposedOriginalValue,
-} from './values.js';
-
-import {
- convertValueUnit,
-} from './units.js';
-
-import {
- removeTweenSliblings,
-} from './compositions.js';
-
-/**
- * @param {Callback<Timer>} [callback]
- * @return {Timer}
- */
-export const sync = (callback = noop) => {
- return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
-}
-
-/**
- * @overload
- * @param {DOMTargetSelector} targetSelector
- * @param {String} propName
- * @return {String}
- *
- * @overload
- * @param {JSTargetsParam} targetSelector
- * @param {String} propName
- * @return {Number|String}
- *
- * @overload
- * @param {DOMTargetsParam} targetSelector
- * @param {String} propName
- * @param {String} unit
- * @return {String}
- *
- * @overload
- * @param {TargetsParam} targetSelector
- * @param {String} propName
- * @param {Boolean} unit
- * @return {Number}
- *
- * @param {TargetsParam} targetSelector
- * @param {String} propName
- * @param {String|Boolean} [unit]
- */
-export function getTargetValue(targetSelector, propName, unit) {
- const targets = registerTargets(targetSelector);
- if (!targets.length) return;
- const [ target ] = targets;
- const tweenType = getTweenType(target, propName);
- const normalizePropName = sanitizePropertyName(propName, target, tweenType);
- let originalValue = getOriginalAnimatableValue(target, normalizePropName);
- if (isUnd(unit)) {
- return originalValue;
- } else {
- decomposeRawValue(originalValue, decomposedOriginalValue);
- if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) {
- if (unit === false) {
- return decomposedOriginalValue.n;
- } else {
- const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false);
- return `${round(convertedValue.n, globals.precision)}${convertedValue.u}`;
- }
- }
- }
-}
-
-/**
- * @param {TargetsParam} targets
- * @param {AnimationParams} parameters
- * @return {JSAnimation}
- */
-export const setTargetValues = (targets, parameters) => {
- if (isUnd(parameters)) return;
- parameters.duration = minValue;
- // Do not overrides currently active tweens by default
- parameters.composition = setValue(parameters.composition, compositionTypes.none);
- // Skip init() and force rendering by playing the animation
- return new JSAnimation(targets, parameters, null, 0, true).resume();
-}
-
-/**
- * @param {TargetsArray} targetsArray
- * @param {JSAnimation} animation
- * @param {String} [propertyName]
- * @return {Boolean}
- */
-const removeTargetsFromAnimation = (targetsArray, animation, propertyName) => {
- let tweensMatchesTargets = false;
- forEachChildren(animation, (/**@type {Tween} */tween) => {
- const tweenTarget = tween.target;
- if (targetsArray.includes(tweenTarget)) {
- const tweenName = tween.property;
- const tweenType = tween._tweenType;
- const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
- if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
- // Make sure to flag the previous CSS transform tween to renderTransform
- if (tween.parent._tail === tween &&
- tween._tweenType === tweenTypes.TRANSFORM &&
- tween._prev &&
- tween._prev._tweenType === tweenTypes.TRANSFORM
- ) {
- tween._prev._renderTransforms = 1;
- }
- // Removes the tween from the selected animation
- removeChild(animation, tween);
- // Detach the tween from its siblings to make sure blended tweens are correctlly removed
- removeTweenSliblings(tween);
- tweensMatchesTargets = true;
- }
- }
- }, true);
- return tweensMatchesTargets;
-}
-
-/**
- * @param {TargetsParam} targets
- * @param {Renderable|WAAPIAnimation} [renderable]
- * @param {String} [propertyName]
- * @return {TargetsArray}
- */
-export const remove = (targets, renderable, propertyName) => {
- const targetsArray = parseTargets(targets);
- const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine);
- const waapiAnimation = renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable);
- for (let i = 0, l = targetsArray.length; i < l; i++) {
- const $el = /** @type {DOMTarget} */(targetsArray[i]);
- removeWAAPIAnimation($el, propertyName, waapiAnimation);
- }
- let removeMatches;
- if (parent._hasChildren) {
- let iterationDuration = 0;
- forEachChildren(parent, (/** @type {Renderable} */child) => {
- if (!child._hasChildren) {
- removeMatches = removeTargetsFromAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName);
- // Remove the child from its parent if no tweens and no children left after the removal
- if (removeMatches && !child._head) {
- child.cancel();
- removeChild(parent, child);
- } else {
- // Calculate the new iterationDuration value to handle onComplete with last child in render()
- const childTLOffset = child._offset + child._delay;
- const childDur = childTLOffset + child.duration;
- if (childDur > iterationDuration) {
- iterationDuration = childDur;
- }
- }
- }
- // Make sure to also remove engine's children targets
- // NOTE: Avoid recursion?
- if (child._head) {
- remove(targets, child, propertyName);
- } else {
- child._hasChildren = false;
- }
- }, true);
- // Update iterationDuration value to handle onComplete with last child in render()
- if (!isUnd(/** @type {Renderable} */(parent).iterationDuration)) {
- /** @type {Renderable} */(parent).iterationDuration = iterationDuration;
- }
- } else {
- removeMatches = removeTargetsFromAnimation(
- targetsArray,
- /** @type {JSAnimation} */(parent),
- propertyName
- );
- }
-
- if (removeMatches && !parent._head) {
- parent._hasChildren = false;
- // Cancel the parent if there are no tweens and no children left after the removal
- // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
- if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel();
- }
-
- return targetsArray;
-}
-
-/**
- * @param {(...args: any[]) => Tickable} constructor
- * @return {(...args: any[]) => Tickable}
- */
-export const keepTime = createRefreshable;
-
-/**
- * @param {String|Array} items
- * @return {any}
- */
-const randomPick = items => items[random(0, items.length - 1)];
-
-/**
- * @param {Number|String} v
- * @param {Number} decimalLength
- * @return {String}
- */
-const roundPad = (v, decimalLength) => (+v).toFixed(decimalLength);
-
-/**
- * @param {Number} v
- * @param {Number} totalLength
- * @param {String} padString
- * @return {String}
- */
-const padStart = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString);
-
-/**
- * @param {Number} v
- * @param {Number} totalLength
- * @param {String} padString
- * @return {String}
- */
-const padEnd = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString);
-
-/**
- * @param {Number} v
- * @param {Number} min
- * @param {Number} max
- * @return {Number}
- */
-const wrap = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min;
-
-/**
- * @param {Number} value
- * @param {Number} inLow
- * @param {Number} inHigh
- * @param {Number} outLow
- * @param {Number} outHigh
- * @return {Number}
- */
-export const mapRange = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow);
-
-/**
- * @param {Number} degrees
- * @return {Number}
- */
-const degToRad = degrees => degrees * PI / 180;
-
-/**
- * @param {Number} radians
- * @return {Number}
- */
-const radToDeg = radians => radians * 180 / PI;
-
-/**
- * https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
- * @param {Number} start
- * @param {Number} end
- * @param {Number} amount
- * @param {Renderable|Boolean} [renderable]
- * @return {Number}
- */
-export const lerp = (start, end, amount, renderable) => {
- let dt = K / globals.defaults.frameRate;
- if (renderable !== false) {
- const ticker = /** @type Renderable */
- (renderable) ||
- (engine._hasChildren && engine);
- if (ticker && ticker.deltaTime) {
- dt = ticker.deltaTime;
- }
- }
- const t = 1 - Math.exp(-amount * dt * .1);
- return !amount ? start : amount === 1 ? end : (1 - t) * start + t * end;
-}
-
-// Chain-able utilities
-
-/**
- * @callback UtilityFunction
- * @param {...*} args
- * @return {Number|String}
- *
- * @param {UtilityFunction} fn
- * @param {Number} [last=0]
- * @return {function(...(Number|String)): function(Number|String): (Number|String)}
- */
-const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args);
-
-/**
- * @param {Function} fn
- * @return {function(...(Number|String))}
- */
-const chain = fn => {
- return (...args) => {
- const result = fn(...args);
- return new Proxy(noop, {
- apply: (_, __, [v]) => result(v),
- get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => {
- const nextResult = utils[prop](...nextArgs);
- return (/**@type {Number|String} */v) => nextResult(result(v));
- })
- });
- }
-}
-
-/**
- * @param {UtilityFunction} fn
- * @param {Number} [right]
- * @return {function(...(Number|String)): UtilityFunction}
- */
-const makeChainable = (fn, right = 0) => (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args);
-
-/**
- * @callback ChainedUtilsResult
- * @param {Number} value
- * @return {Number}
- *
- * @typedef {Object} ChainableUtils
- * @property {ChainedClamp} clamp
- * @property {ChainedRound} round
- * @property {ChainedSnap} snap
- * @property {ChainedWrap} wrap
- * @property {ChainedInterpolate} interpolate
- * @property {ChainedMapRange} mapRange
- * @property {ChainedRoundPad} roundPad
- * @property {ChainedPadStart} padStart
- * @property {ChainedPadEnd} padEnd
- * @property {ChainedDegToRad} degToRad
- * @property {ChainedRadToDeg} radToDeg
- *
- * @typedef {ChainableUtils & ChainedUtilsResult} ChainableUtil
- *
- * @callback ChainedClamp
- * @param {Number} min
- * @param {Number} max
- * @return {ChainableUtil}
- *
- * @callback ChainedRound
- * @param {Number} decimalLength
- * @return {ChainableUtil}
- *
- * @callback ChainedSnap
- * @param {Number} increment
- * @return {ChainableUtil}
- *
- * @callback ChainedWrap
- * @param {Number} min
- * @param {Number} max
- * @return {ChainableUtil}
- *
- * @callback ChainedInterpolate
- * @param {Number} start
- * @param {Number} end
- * @return {ChainableUtil}
- *
- * @callback ChainedMapRange
- * @param {Number} inLow
- * @param {Number} inHigh
- * @param {Number} outLow
- * @param {Number} outHigh
- * @return {ChainableUtil}
- *
- * @callback ChainedRoundPad
- * @param {Number} decimalLength
- * @return {ChainableUtil}
- *
- * @callback ChainedPadStart
- * @param {Number} totalLength
- * @param {String} padString
- * @return {ChainableUtil}
- *
- * @callback ChainedPadEnd
- * @param {Number} totalLength
- * @param {String} padString
- * @return {ChainableUtil}
- *
- * @callback ChainedDegToRad
- * @return {ChainableUtil}
- *
- * @callback ChainedRadToDeg
- * @return {ChainableUtil}
- */
-
-export const utils = {
- $: registerTargets,
- get: getTargetValue,
- set: setTargetValues,
- remove,
- cleanInlineStyles,
- random,
- randomPick,
- shuffle,
- lerp,
- sync,
- keepTime,
- clamp: /** @type {typeof clamp & ChainedClamp} */(makeChainable(clamp)),
- round: /** @type {typeof round & ChainedRound} */(makeChainable(round)),
- snap: /** @type {typeof snap & ChainedSnap} */(makeChainable(snap)),
- wrap: /** @type {typeof wrap & ChainedWrap} */(makeChainable(wrap)),
- interpolate: /** @type {typeof interpolate & ChainedInterpolate} */(makeChainable(interpolate, 1)),
- mapRange: /** @type {typeof mapRange & ChainedMapRange} */(makeChainable(mapRange)),
- roundPad: /** @type {typeof roundPad & ChainedRoundPad} */(makeChainable(roundPad)),
- padStart: /** @type {typeof padStart & ChainedPadStart} */(makeChainable(padStart)),
- padEnd: /** @type {typeof padEnd & ChainedPadEnd} */(makeChainable(padEnd)),
- degToRad: /** @type {typeof degToRad & ChainedDegToRad} */(makeChainable(degToRad)),
- radToDeg: /** @type {typeof radToDeg & ChainedRadToDeg} */(makeChainable(radToDeg)),
-}
diff --git a/src/utils/chainable.js b/src/utils/chainable.js
new file mode 100644
index 00000000..453dfed1
--- /dev/null
+++ b/src/utils/chainable.js
@@ -0,0 +1,171 @@
+import {
+ noop,
+} from '../core/consts.js';
+
+import * as numberImports from './number.js';
+
+// Chain-able utilities
+
+const numberUtils = numberImports; // Needed to keep the import when bundling
+
+const chainables = {};
+
+/**
+ * @callback UtilityFunction
+ * @param {...*} args
+ * @return {Number|String}
+ *
+ * @param {UtilityFunction} fn
+ * @param {Number} [last=0]
+ * @return {function(...(Number|String)): function(Number|String): (Number|String)}
+ */
+const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args);
+
+/**
+ * @param {Function} fn
+ * @return {function(...(Number|String))}
+ */
+const chain = fn => {
+ return (...args) => {
+ const result = fn(...args);
+ return new Proxy(noop, {
+ apply: (_, __, [v]) => result(v),
+ get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => {
+ const nextResult = chainables[prop](...nextArgs);
+ return (/**@type {Number|String} */v) => nextResult(result(v));
+ })
+ });
+ }
+}
+
+/**
+ * @param {UtilityFunction} fn
+ * @param {String} name
+ * @param {Number} [right]
+ * @return {function(...(Number|String)): UtilityFunction}
+ */
+const makeChainable = (name, fn, right = 0) => {
+ const chained = (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args);
+ if (!chainables[name]) chainables[name] = chained;
+ return chained;
+}
+
+/**
+ * @typedef {Object} ChainablesMap
+ * @property {ChainedClamp} clamp
+ * @property {ChainedRound} round
+ * @property {ChainedSnap} snap
+ * @property {ChainedWrap} wrap
+ * @property {ChainedLerp} lerp
+ * @property {ChainedDamp} damp
+ * @property {ChainedMapRange} mapRange
+ * @property {ChainedRoundPad} roundPad
+ * @property {ChainedPadStart} padStart
+ * @property {ChainedPadEnd} padEnd
+ * @property {ChainedDegToRad} degToRad
+ * @property {ChainedRadToDeg} radToDeg
+ */
+
+/**
+ * @callback ChainedUtilsResult
+ * @param {Number} value - The value to process through the chained operations
+ * @return {Number} The processed result
+ */
+
+/**
+ * @typedef {ChainablesMap & ChainedUtilsResult} ChainableUtil
+ */
+
+// Chainable
+
+/**
+ * @callback ChainedRoundPad
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+export const roundPad = /** @type {typeof numberUtils.roundPad & ChainedRoundPad} */(makeChainable('roundPad', numberUtils.roundPad));
+
+/**
+ * @callback ChainedPadStart
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+export const padStart = /** @type {typeof numberUtils.padStart & ChainedPadStart} */(makeChainable('padStart', numberUtils.padStart));
+
+/**
+ * @callback ChainedPadEnd
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {ChainableUtil}
+ */
+export const padEnd = /** @type {typeof numberUtils.padEnd & ChainedPadEnd} */(makeChainable('padEnd', numberUtils.padEnd));
+
+/**
+ * @callback ChainedWrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+export const wrap = /** @type {typeof numberUtils.wrap & ChainedWrap} */(makeChainable('wrap', numberUtils.wrap));
+
+/**
+ * @callback ChainedMapRange
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {ChainableUtil}
+ */
+export const mapRange = /** @type {typeof numberUtils.mapRange & ChainedMapRange} */(makeChainable('mapRange', numberUtils.mapRange));
+
+/**
+ * @callback ChainedDegToRad
+ * @return {ChainableUtil}
+ */
+export const degToRad = /** @type {typeof numberUtils.degToRad & ChainedDegToRad} */(makeChainable('degToRad', numberUtils.degToRad));
+
+/**
+ * @callback ChainedRadToDeg
+ * @return {ChainableUtil}
+ */
+export const radToDeg = /** @type {typeof numberUtils.radToDeg & ChainedRadToDeg} */(makeChainable('radToDeg', numberUtils.radToDeg));
+
+/**
+ * @callback ChainedSnap
+ * @param {Number|Array<Number>} increment - Step size or array of snap points
+ * @return {ChainableUtil}
+ */
+export const snap = /** @type {typeof numberUtils.snap & ChainedSnap} */(makeChainable('snap', numberUtils.snap));
+
+/**
+ * @callback ChainedClamp
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {ChainableUtil}
+ */
+export const clamp = /** @type {typeof numberUtils.clamp & ChainedClamp} */(makeChainable('clamp', numberUtils.clamp));
+
+/**
+ * @callback ChainedRound
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {ChainableUtil}
+ */
+export const round = /** @type {typeof numberUtils.round & ChainedRound} */(makeChainable('round', numberUtils.round));
+
+/**
+ * @callback ChainedLerp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Ending value
+ * @return {ChainableUtil}
+ */
+export const lerp = /** @type {typeof numberUtils.lerp & ChainedLerp} */(makeChainable('lerp', numberUtils.lerp, 1));
+
+/**
+ * @callback ChainedDamp
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @return {ChainableUtil}
+ */
+export const damp = /** @type {typeof numberUtils.damp & ChainedDamp} */(makeChainable('damp', numberUtils.damp, 1));
diff --git a/src/utils/index.js b/src/utils/index.js
new file mode 100644
index 00000000..3229c0eb
--- /dev/null
+++ b/src/utils/index.js
@@ -0,0 +1,5 @@
+export * from './chainable.js';
+export * from './random.js';
+export * from './time.js';
+export * from './target.js';
+export * from './stagger.js';
\ No newline at end of file
diff --git a/src/utils/number.js b/src/utils/number.js
new file mode 100644
index 00000000..ad454b5d
--- /dev/null
+++ b/src/utils/number.js
@@ -0,0 +1,84 @@
+import {
+ lerp,
+} from '../core/helpers.js';
+
+export {
+ snap,
+ clamp,
+ round,
+ lerp,
+} from '../core/helpers.js';
+
+/**
+ * Rounds a number to fixed decimal places
+ * @param {Number|String} v - Value to round
+ * @param {Number} decimalLength - Number of decimal places
+ * @return {String}
+ */
+export const roundPad = (v, decimalLength) => (+v).toFixed(decimalLength);
+
+/**
+ * Pads the start of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {String}
+ */
+export const padStart = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString);
+
+/**
+ * Pads the end of a value with a string
+ * @param {Number} v - Value to pad
+ * @param {Number} totalLength - Target length
+ * @param {String} padString - String to pad with
+ * @return {String}
+ */
+export const padEnd = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString);
+
+/**
+ * Wraps a value within a range
+ * @param {Number} v - Value to wrap
+ * @param {Number} min - Minimum boundary
+ * @param {Number} max - Maximum boundary
+ * @return {Number}
+ */
+export const wrap = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min;
+
+/**
+ * Maps a value from one range to another
+ * @param {Number} value - Input value
+ * @param {Number} inLow - Input range minimum
+ * @param {Number} inHigh - Input range maximum
+ * @param {Number} outLow - Output range minimum
+ * @param {Number} outHigh - Output range maximum
+ * @return {Number}
+ */
+export const mapRange = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow);
+
+/**
+ * Converts degrees to radians
+ * @param {Number} degrees - Angle in degrees
+ * @return {Number}
+ */
+export const degToRad = degrees => degrees * Math.PI / 180;
+
+/**
+ * Converts radians to degrees
+ * @param {Number} radians - Angle in radians
+ * @return {Number}
+ */
+export const radToDeg = radians => radians * 180 / Math.PI;
+
+/**
+ * Frame rate independent damped lerp
+ * Based on: https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
+ *
+ * @param {Number} start - Starting value
+ * @param {Number} end - Target value
+ * @param {Number} deltaTime - Delta time in ms
+ * @param {Number} factor - Interpolation factor in the range [0, 1]
+ * @return {Number} The interpolated value
+ */
+export const damp = (start, end, deltaTime, factor) => {
+ return !factor ? start : factor === 1 ? end : lerp(start, end, 1 - Math.exp(-factor * deltaTime * .1));
+}
diff --git a/src/utils/random.js b/src/utils/random.js
new file mode 100644
index 00000000..8cbe31e7
--- /dev/null
+++ b/src/utils/random.js
@@ -0,0 +1,63 @@
+/**
+ * Generate a random number between optional min and max (inclusive) and decimal precision
+ *
+ * @callback RandomNumberGenerator
+ * @param {Number} [min=0] - The minimum value (inclusive)
+ * @param {Number} [max=1] - The maximum value (inclusive)
+ * @param {Number} [decimalLength=0] - Number of decimal places to round to
+ * @return {Number} A random number between min and max
+ */
+
+/**
+ * Generates a random number between min and max (inclusive) with optional decimal precision
+ *
+ * @type {RandomNumberGenerator}
+ */
+export const random = (min = 0, max = 1, decimalLength = 0) => {
+ const m = 10 ** decimalLength;
+ return Math.floor((Math.random() * (max - min + (1 / m)) + min) * m) / m;
+}
+
+let _seed = 0;
+
+/**
+ * Creates a seeded pseudorandom number generator function
+ *
+ * @param {Number} [seed] - The seed value for the random number generator
+ * @param {Number} [seededMin=0] - The minimum default value (inclusive) of the returned function
+ * @param {Number} [seededMax=1] - The maximum default value (inclusive) of the returned function
+ * @param {Number} [seededDecimalLength=0] - Default number of decimal places to round to of the returned function
+ * @return {RandomNumberGenerator} A function to generate a random number between optional min and max (inclusive) and decimal precision
+ */
+export const createSeededRandom = (seed, seededMin = 0, seededMax = 1, seededDecimalLength = 0) => {
+ let t = seed === undefined ? _seed++ : seed;
+ return (min = seededMin, max = seededMax, decimalLength = seededDecimalLength) => {
+ t += 0x6D2B79F5;
+ t = Math.imul(t ^ t >>> 15, t | 1);
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
+ const m = 10 ** decimalLength;
+ return Math.floor(((((t ^ t >>> 14) >>> 0) / 4294967296) * (max - min + (1 / m)) + min) * m) / m;
+ }
+}
+
+/**
+ * Picks a random element from an array or a string
+ *
+ * @template T
+ * @param {String|Array<T>} items - The array or string to pick from
+ * @return {String|T} A random element from the array or character from the string
+ */
+export const randomPick = items => items[random(0, items.length - 1)];
+
+/**
+ * Shuffles an array in-place using the Fisher-Yates algorithm
+ * Adapted from https://bost.ocks.org/mike/shuffle/
+ *
+ * @param {Array} items - The array to shuffle (will be modified in-place)
+ * @return {Array} The same array reference, now shuffled
+ */
+export const shuffle = items => {
+ let m = items.length, t, i;
+ while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; }
+ return items;
+}
diff --git a/src/stagger.js b/src/utils/stagger.js
similarity index 90%
rename from src/stagger.js
rename to src/utils/stagger.js
index 1717246e..b761dac8 100644
--- a/src/stagger.js
+++ b/src/utils/stagger.js
@@ -1,9 +1,7 @@
-/// <reference path='./types.js' />
-
import {
emptyString,
unitsExecRgx,
-} from './consts.js';
+} from '../core/consts.js';
import {
isArr,
@@ -17,24 +15,40 @@ import {
max,
isStr,
isFnc,
- shuffle,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
- parseEasings,
-} from './eases.js';
+ parseEase,
+} from '../easings/eases.js';
import {
parseTimelinePosition,
-} from './timeline.js';
+} from '../timeline/position.js';
import {
getOriginalAnimatableValue,
-} from './values.js';
+} from '../core/values.js';
import {
registerTargets,
-} from './targets.js';
+} from '../core/targets.js';
+
+import {
+ shuffle,
+} from './random.js';
+
+/**
+ * @import {
+ * StaggerParams,
+ * StaggerFunction,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
/**
* @overload
@@ -73,7 +87,7 @@ export const stagger = (val, params = {}) => {
const ease = params.ease;
const hasEasing = !isUnd(ease);
const hasSpring = hasEasing && !isUnd(/** @type {Spring} */(ease).ease);
- const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEasings(ease) : null;
+ const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEase(ease) : null;
const grid = params.grid;
const axis = params.axis;
const customTotal = params.total;
diff --git a/src/utils/target.js b/src/utils/target.js
new file mode 100644
index 00000000..c8be4e0f
--- /dev/null
+++ b/src/utils/target.js
@@ -0,0 +1,156 @@
+import {
+ globals,
+} from '../core/globals.js';
+
+import {
+ minValue,
+ compositionTypes,
+ valueTypes,
+} from '../core/consts.js';
+
+import {
+ isUnd,
+ round,
+} from '../core/helpers.js';
+
+import {
+ parseTargets,
+ registerTargets,
+} from '../core/targets.js';
+
+import {
+ sanitizePropertyName,
+} from '../core/styles.js';
+
+import {
+ setValue,
+ getTweenType,
+ getOriginalAnimatableValue,
+ decomposeRawValue,
+ decomposedOriginalValue,
+} from '../core/values.js';
+
+import {
+ convertValueUnit,
+} from '../core/units.js';
+
+import {
+ removeWAAPIAnimation,
+} from '../waapi/composition.js';
+
+import {
+ removeTargetsFromRenderable,
+} from '../animation/composition.js';
+
+import {
+ JSAnimation,
+} from '../animation/animation.js';
+
+export { registerTargets as $ };
+
+/**
+ * @import {
+ * Renderable,
+ * DOMTargetSelector,
+ * JSTargetsParam,
+ * DOMTargetsParam,
+ * TargetsParam,
+ * DOMTarget,
+ * AnimationParams,
+ * TargetsArray,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @overload
+ * @param {DOMTargetSelector} targetSelector
+ * @param {String} propName
+ * @return {String}
+ *
+ * @overload
+ * @param {JSTargetsParam} targetSelector
+ * @param {String} propName
+ * @return {Number|String}
+ *
+ * @overload
+ * @param {DOMTargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String} unit
+ * @return {String}
+ *
+ * @overload
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {Boolean} unit
+ * @return {Number}
+ *
+ * @param {TargetsParam} targetSelector
+ * @param {String} propName
+ * @param {String|Boolean} [unit]
+ */
+export function get(targetSelector, propName, unit) {
+ const targets = registerTargets(targetSelector);
+ if (!targets.length) return;
+ const [ target ] = targets;
+ const tweenType = getTweenType(target, propName);
+ const normalizePropName = sanitizePropertyName(propName, target, tweenType);
+ let originalValue = getOriginalAnimatableValue(target, normalizePropName);
+ if (isUnd(unit)) {
+ return originalValue;
+ } else {
+ decomposeRawValue(originalValue, decomposedOriginalValue);
+ if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) {
+ if (unit === false) {
+ return decomposedOriginalValue.n;
+ } else {
+ const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false);
+ return `${round(convertedValue.n, globals.precision)}${convertedValue.u}`;
+ }
+ }
+ }
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {AnimationParams} parameters
+ * @return {JSAnimation}
+ */
+export const set = (targets, parameters) => {
+ if (isUnd(parameters)) return;
+ parameters.duration = minValue;
+ // Do not overrides currently active tweens by default
+ parameters.composition = setValue(parameters.composition, compositionTypes.none);
+ // Skip init() and force rendering by playing the animation
+ return new JSAnimation(targets, parameters, null, 0, true).resume();
+}
+
+/**
+ * @param {TargetsParam} targets
+ * @param {Renderable|WAAPIAnimation} [renderable]
+ * @param {String} [propertyName]
+ * @return {TargetsArray}
+ */
+export const remove = (targets, renderable, propertyName) => {
+ const targetsArray = parseTargets(targets);
+ for (let i = 0, l = targetsArray.length; i < l; i++) {
+ removeWAAPIAnimation(
+ /** @type {DOMTarget} */(targetsArray[i]),
+ propertyName,
+ renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable),
+ )
+ }
+ removeTargetsFromRenderable(
+ targetsArray,
+ /** @type {Renderable} */(renderable),
+ propertyName
+ )
+ return targetsArray;
+}
+
+export { cleanInlineStyles } from '../core/styles.js';
diff --git a/src/utils/time.js b/src/utils/time.js
new file mode 100644
index 00000000..8e3b6f8b
--- /dev/null
+++ b/src/utils/time.js
@@ -0,0 +1,57 @@
+import {
+ noop,
+} from '../core/consts.js';
+
+import {
+ globals,
+} from '../core/globals.js';
+
+import {
+ isFnc,
+ isUnd,
+} from '../core/helpers.js';
+
+import {
+ Timer,
+} from '../timer/timer.js';
+
+/**
+ * @import {
+ * Callback,
+ * Tickable,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @param {Callback<Timer>} [callback]
+ * @return {Timer}
+ */
+export const sync = (callback = noop) => {
+ return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
+}
+
+/**
+ * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor
+ * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)}
+ */
+export const keepTime = constructor => {
+ /** @type {Tickable} */
+ let tracked;
+ return (...args) => {
+ let currentIteration, currentIterationProgress, reversed, alternate;
+ if (tracked) {
+ currentIteration = tracked.currentIteration;
+ currentIterationProgress = tracked.iterationProgress;
+ reversed = tracked.reversed;
+ alternate = tracked._alternate;
+ tracked.revert();
+ }
+ const cleanup = constructor(...args);
+ if (cleanup && !isFnc(cleanup) && cleanup.revert) tracked = cleanup;
+ if (!isUnd(currentIterationProgress)) {
+ /** @type {Tickable} */(tracked).currentIteration = currentIteration;
+ /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress;
+ }
+ return cleanup || noop;
+ }
+}
diff --git a/src/waapi/composition.js b/src/waapi/composition.js
new file mode 100644
index 00000000..1178e2bf
--- /dev/null
+++ b/src/waapi/composition.js
@@ -0,0 +1,78 @@
+import { addChild, removeChild } from "../core/helpers.js";
+
+/**
+ * @import {
+ * DOMTarget,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation,
+ * } from '../waapi/waapi.js'
+*/
+
+const WAAPIAnimationsLookups = {
+ _head: null,
+ _tail: null,
+}
+
+/**
+ * @param {DOMTarget} $el
+ * @param {String} [property]
+ * @param {WAAPIAnimation} [parent]
+ */
+export const removeWAAPIAnimation = ($el, property, parent) => {
+ let nextLookup = WAAPIAnimationsLookups._head;
+ while (nextLookup) {
+ const next = nextLookup._next;
+ const matchTarget = nextLookup.$el === $el;
+ const matchProperty = !property || nextLookup.property === property;
+ const matchParent = !parent || nextLookup.parent === parent;
+ if (matchTarget && matchProperty && matchParent) {
+ const anim = nextLookup.animation;
+ try { anim.commitStyles(); } catch {};
+ anim.cancel();
+ removeChild(WAAPIAnimationsLookups, nextLookup);
+ const lookupParent = nextLookup.parent;
+ if (lookupParent) {
+ lookupParent._completed++;
+ if (lookupParent.animations.length === lookupParent._completed) {
+ lookupParent.completed = true;
+ if (!lookupParent.muteCallbacks) {
+ lookupParent.paused = true;
+ lookupParent.onComplete(lookupParent);
+ lookupParent._resolve(lookupParent);
+ }
+ }
+ }
+ }
+ nextLookup = next;
+ }
+}
+
+/**
+ * @param {WAAPIAnimation} parent
+ * @param {DOMTarget} $el
+ * @param {String} property
+ * @param {PropertyIndexedKeyframes} keyframes
+ * @param {KeyframeAnimationOptions} params
+ * @retun {Animation}
+ */
+export const addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
+ const animation = $el.animate(keyframes, params);
+ const animTotalDuration = params.delay + (+params.duration * params.iterations);
+ animation.playbackRate = parent._speed;
+ if (parent.paused) animation.pause();
+ if (parent.duration < animTotalDuration) {
+ parent.duration = animTotalDuration;
+ parent.controlAnimation = animation;
+ }
+ parent.animations.push(animation);
+ removeWAAPIAnimation($el, property);
+ addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null });
+ const handleRemove = () => { removeWAAPIAnimation($el, property, parent); };
+ animation.onremove = handleRemove;
+ animation.onfinish = handleRemove;
+ return animation;
+}
diff --git a/src/waapi/index.js b/src/waapi/index.js
new file mode 100644
index 00000000..2407fd5b
--- /dev/null
+++ b/src/waapi/index.js
@@ -0,0 +1 @@
+export * from './waapi.js';
\ No newline at end of file
diff --git a/src/waapi.js b/src/waapi/waapi.js
similarity index 86%
rename from src/waapi.js
rename to src/waapi/waapi.js
index bd926e7e..9d864e1a 100644
--- a/src/waapi.js
+++ b/src/waapi/waapi.js
@@ -1,5 +1,3 @@
-/// <reference path='./types.js' />
-
import {
isArr,
isKey,
@@ -8,33 +6,24 @@ import {
isStr,
isUnd,
isFnc,
- addChild,
- removeChild,
stringStartsWith,
toLowerCase,
isNil,
-} from './helpers.js';
+} from '../core/helpers.js';
import {
scope,
globals,
-} from './globals.js';
+} from '../core/globals.js';
import {
registerTargets,
-} from './targets.js';
+} from '../core/targets.js';
import {
getFunctionValue,
setValue,
-} from './values.js';
-
-import {
- none,
- easeTypes,
- easeInPower,
- parseEaseString,
-} from './eases.js';
+} from '../core/values.js';
import {
isBrowser,
@@ -45,7 +34,49 @@ import {
transformsFragmentStrings,
transformsSymbol,
validTransforms,
-} from './consts.js';
+} from '../core/consts.js';
+
+import {
+ none,
+} from '../easings/none.js';
+
+import {
+ easeTypes,
+ easeInPower,
+ parseEaseString,
+} from '../easings/parser.js';
+
+import {
+ addWAAPIAnimation,
+} from './composition.js';
+
+/**
+ * @import {
+ * Callback,
+ * EasingFunction,
+ * EasingParam,
+ * DOMTarget,
+ * DOMTargetsParam,
+ * DOMTargetsArray,
+ * WAAPIAnimationParams,
+ * WAAPITweenOptions,
+ * WAAPIKeyframeValue,
+ * WAAPICallback,
+ * WAAPITweenValue
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Spring,
+ * } from '../spring/spring.js'
+*/
+
+/**
+ * @import {
+ * ScrollObserver,
+ * } from '../events/scroll.js'
+*/
/**
* Converts an easing function into a valid CSS linear() timing function string
@@ -124,71 +155,6 @@ const validIndividualTransforms = /*#__PURE__*/ (() => [...transformsShorthands,
let transformsPropertiesRegistered = null;
-const WAAPIAnimationsLookups = {
- _head: null,
- _tail: null,
-};
-
-/**
- * @param {DOMTarget} $el
- * @param {String} [property]
- * @param {WAAPIAnimation} [parent]
- */
-export const removeWAAPIAnimation = ($el, property, parent) => {
- let nextLookup = WAAPIAnimationsLookups._head;
- while (nextLookup) {
- const next = nextLookup._next;
- const matchTarget = nextLookup.$el === $el;
- const matchProperty = !property || nextLookup.property === property;
- const matchParent = !parent || nextLookup.parent === parent;
- if (matchTarget && matchProperty && matchParent) {
- const anim = nextLookup.animation;
- try { anim.commitStyles(); } catch {};
- anim.cancel();
- removeChild(WAAPIAnimationsLookups, nextLookup);
- const lookupParent = nextLookup.parent;
- if (lookupParent) {
- lookupParent._completed++;
- if (lookupParent.animations.length === lookupParent._completed) {
- lookupParent.completed = true;
- if (!lookupParent.muteCallbacks) {
- lookupParent.paused = true;
- lookupParent.onComplete(lookupParent);
- lookupParent._resolve(lookupParent);
- }
- }
- }
- }
- nextLookup = next;
- }
-}
-
-/**
- * @param {WAAPIAnimation} parent
- * @param {DOMTarget} $el
- * @param {String} property
- * @param {PropertyIndexedKeyframes} keyframes
- * @param {KeyframeAnimationOptions} params
- * @retun {Animation}
- */
-const addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
- const animation = $el.animate(keyframes, params);
- const animTotalDuration = params.delay + (+params.duration * params.iterations);
- animation.playbackRate = parent._speed;
- if (parent.paused) animation.pause();
- if (parent.duration < animTotalDuration) {
- parent.duration = animTotalDuration;
- parent.controlAnimation = animation;
- }
- parent.animations.push(animation);
- removeWAAPIAnimation($el, property);
- addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null });
- const handleRemove = () => { removeWAAPIAnimation($el, property, parent); };
- animation.onremove = handleRemove;
- animation.onfinish = handleRemove;
- return animation;
-}
-
/**
* @param {String} propName
* @param {WAAPIKeyframeValue} value
@@ -411,7 +377,6 @@ export class WAAPIAnimation {
return this._speed;
}
- /** @param {Number} speed */
set speed(speed) {
this._speed = +speed;
this.forEach(anim => anim.playbackRate = speed);
@@ -423,7 +388,6 @@ export class WAAPIAnimation {
return this.completed ? this.duration : controlAnimation ? +controlAnimation.currentTime * (timeScale === 1 ? 1 : timeScale) : 0;
}
- /** @param {Number} time */
set currentTime(time) {
const t = time * (globals.timeScale === 1 ? 1 : K);
this.forEach(anim => {
@@ -439,7 +403,6 @@ export class WAAPIAnimation {
return this.currentTime / this.duration;
}
- /** @param {Number} progress */
set progress(progress) {
this.forEach(anim => anim.currentTime = progress * this.duration || 0);
}
diff --git a/tests/index.html b/tests/index.html
index ff43c0bc..3163fb09 100644
--- a/tests/index.html
+++ b/tests/index.html
@@ -286,6 +286,7 @@
<div id="tests"></div>
<div id="mocha"></div>
<button id="open-in-popup"></button>
+ <script src="../dist/bundles/anime.umd.min.js"></script>
<script type="module" src="../tests/setup.js"></script>
<script type="module" src="../tests/run.js"></script>
<script type="text/javascript">
diff --git a/tests/playground/additive-animations-2.html b/tests/playground/additive-animations-2.html
index 3035c98c..85d79fcf 100644
--- a/tests/playground/additive-animations-2.html
+++ b/tests/playground/additive-animations-2.html
@@ -95,7 +95,7 @@
<body>
<script type="module">
- import { animate, createTimer, createTimeline, stagger, utils, engine } from '../../lib/anime.esm.js';
+ import { animate, createTimer, createTimeline, stagger, utils, engine } from '../../../dist/modules/index.js';
const maxParticles = 200;
const activeRadius = 100;
diff --git a/tests/playground/advanced-staggering-demos.html b/tests/playground/advanced-staggering-demos.html
index 8c838131..895980cd 100644
--- a/tests/playground/advanced-staggering-demos.html
+++ b/tests/playground/advanced-staggering-demos.html
@@ -232,7 +232,7 @@
</section>
</div>
<script type="module">
- import { createTimeline, stagger } from '../../lib/anime.esm.js';
+ import { createTimeline, stagger } from '../../../dist/modules/index.js';
const red = '#F64E4D';
diff --git a/tests/playground/animejs-mgs-logo-animation.html b/tests/playground/animejs-mgs-logo-animation.html
index def83ea8..e7e0051e 100644
--- a/tests/playground/animejs-mgs-logo-animation.html
+++ b/tests/playground/animejs-mgs-logo-animation.html
@@ -152,7 +152,7 @@
</section>
<script type="module">
- import { animate, createTimeline, utils, stagger } from '../../lib/anime.esm.js';
+ import { animate, createTimeline, utils, stagger } from '../../../dist/modules/index.js';
const logoAnimation = createTimeline({
alternate: true,
diff --git a/tests/playground/animejs-v2-logo-animation.html b/tests/playground/animejs-v2-logo-animation.html
index c47795b8..764e950c 100644
--- a/tests/playground/animejs-v2-logo-animation.html
+++ b/tests/playground/animejs-v2-logo-animation.html
@@ -188,8 +188,8 @@
</div>
<script type="module">
- import { createTimeline, utils, stagger, svg } from '../../lib/anime.esm.js';
- import { inspect } from '../../lib/gui/index.js';
+ import { createTimeline, utils, stagger, svg } from '../../../dist/modules/index.js';
+
utils.set(['.fill.out', '.line.out'], { opacity: 0 });
diff --git a/tests/playground/animejs-v3-logo-animation.html b/tests/playground/animejs-v3-logo-animation.html
index 7d297920..741e73f4 100644
--- a/tests/playground/animejs-v3-logo-animation.html
+++ b/tests/playground/animejs-v3-logo-animation.html
@@ -200,8 +200,8 @@
</div>
<script type="module">
- import { createTimeline, utils, stagger, svg, createSpring } from '../../../lib/anime.esm.js';
- import { inspect } from '../../lib/gui/index.js';
+ import { createTimeline, utils, stagger, svg, createSpring } from '../../../dist/modules/index.js';
+
function fitElementToParent(el, padding, exception) {
var timeout = null;
diff --git a/tests/playground/benchmark/index.js b/tests/playground/benchmark/index.js
index 5251e00f..1cece012 100644
--- a/tests/playground/benchmark/index.js
+++ b/tests/playground/benchmark/index.js
@@ -1,4 +1,4 @@
-import { waapi, animate, createTimer, utils, engine } from '../../../lib/anime.esm.js';
+import { waapi, animate, createTimer, utils, engine } from '../../../dist/modules/index.js';
import {
Object3D,
diff --git a/tests/playground/color-conversion.html b/tests/playground/color-conversion.html
index 95fde22f..65a7f6c4 100644
--- a/tests/playground/color-conversion.html
+++ b/tests/playground/color-conversion.html
@@ -88,7 +88,7 @@
</div>
</section>
<script type="module">
- import { animate } from '../../lib/anime.esm.js';
+ import { animate } from '../../../dist/modules/index.js';
const colorTestEls = document.querySelectorAll('.color-test');
diff --git a/tests/playground/draggables/callbacks/index.js b/tests/playground/draggables/callbacks/index.js
index dd583f48..46806264 100644
--- a/tests/playground/draggables/callbacks/index.js
+++ b/tests/playground/draggables/callbacks/index.js
@@ -3,7 +3,7 @@ import {
createDraggable,
utils,
Draggable
-} from '../../../../lib/anime.esm.js';
+} from '../../../../dist/modules/index.js';
const [ $log1, $log2 ] = utils.$('.log');
const [ $container ] = /** @type {Array<HTMLElement>} */(utils.$('#container '));
diff --git a/tests/playground/keyframes/index.js b/tests/playground/keyframes/index.js
index 14bb9ba0..4588d725 100644
--- a/tests/playground/keyframes/index.js
+++ b/tests/playground/keyframes/index.js
@@ -1,6 +1,6 @@
import {
animate,
-} from '../../../lib/anime.esm.js';
+} from '../../../dist/modules/index.js';
const easeOut = 'cubicBezier(0, 0, 0.58, 1)';
const easeIn = 'cubicBezier(0.42, 0, 1, 1)';
diff --git a/tests/playground/lerp/index.html b/tests/playground/lerp/index.html
new file mode 100644
index 00000000..934596b8
--- /dev/null
+++ b/tests/playground/lerp/index.html
@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Lerp tests / Anime.js</title>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
+ <link href="../assets/css/styles.css" rel="stylesheet">
+ <style>
+ body {
+ display: flex;
+ flex-direction: column;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+ }
+
+ .container {
+ display: flex;
+ flex-wrap: wrap;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ gap: .5rem;
+ padding: 1rem;
+ }
+
+ .square {
+ width: 100px;
+ height: 100px;
+ background: var(--red);
+ border-radius: 1rem;
+ padding: 1rem;
+ }
+
+ .button {
+ border-radius: 1rem;
+ padding: 1rem;
+ }
+
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h2>input</h2>
+ <div class="square input"></div>
+ </div>
+ <div class="container">
+ <h2>lerped</h2>
+ <div class="square lerped"></div>
+ </div>
+ <div class="container">
+ <h2>damped</h2>
+ <div class="square damped"></div>
+ </div>
+ <script type="module" src="./index.js"></script>
+</body>
+</html>
diff --git a/tests/playground/lerp/index.js b/tests/playground/lerp/index.js
new file mode 100644
index 00000000..85410e87
--- /dev/null
+++ b/tests/playground/lerp/index.js
@@ -0,0 +1,111 @@
+import {
+ animate,
+ createTimer,
+ utils,
+} from '../../../dist/modules/index.js';
+
+const [ $input ] = utils.$('.input');
+const [ $damped ] = utils.$('.damped');
+const [ $lerped ] = utils.$('.lerped');
+
+animate($input, {
+ x: [-200, 200],
+ modifier: utils.snap(100),
+ duration: 2000,
+ loop: true,
+ alternate: true,
+ ease: 'linear',
+});
+
+createTimer({
+ frameRate: 10,
+ onUpdate: clock => {
+ const sourceX = utils.get($input, 'x', false);
+ const lerpedX = utils.get($lerped, 'x', false);
+ utils.set($lerped, {
+ x: utils.lerp(lerpedX, sourceX, .075)
+ });
+ }
+});
+
+createTimer({
+ frameRate: 10,
+ onUpdate: clock => {
+ const sourceX = utils.get($input, 'x', false);
+ const lerpedX = utils.get($damped, 'x', false);
+ utils.set($damped, {
+ x: utils.damp(lerpedX, sourceX, clock.deltaTime, .075)
+ });
+ }
+});
+
+let seededRandom = utils.createSeededRandom(0);
+
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+console.log(utils.random() * -1);
+
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+seededRandom = utils.createSeededRandom(0);
+console.log('RESET');
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
+console.log(seededRandom(0, 10));
\ No newline at end of file
diff --git a/tests/playground/onscroll/assets/debug.js b/tests/playground/onscroll/assets/debug.js
index 8529bc0e..2655fc83 100644
--- a/tests/playground/onscroll/assets/debug.js
+++ b/tests/playground/onscroll/assets/debug.js
@@ -3,7 +3,7 @@ import {
onScroll,
createTimeline,
animate,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
animate('#edges .target', {
rotate: 360,
diff --git a/tests/playground/onscroll/assets/function-based-values.js b/tests/playground/onscroll/assets/function-based-values.js
index 717ce606..120622e8 100644
--- a/tests/playground/onscroll/assets/function-based-values.js
+++ b/tests/playground/onscroll/assets/function-based-values.js
@@ -3,7 +3,7 @@ import {
animate,
onScroll,
stagger,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
const isLandscapeMedia = matchMedia('(orientation: landscape)');
diff --git a/tests/playground/onscroll/assets/horizontal-container.js b/tests/playground/onscroll/assets/horizontal-container.js
index 0007b4d0..5f9e0ef4 100644
--- a/tests/playground/onscroll/assets/horizontal-container.js
+++ b/tests/playground/onscroll/assets/horizontal-container.js
@@ -3,7 +3,7 @@ import {
onScroll,
createTimeline,
animate,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
const tl = createTimeline({
autoplay: onScroll({
diff --git a/tests/playground/onscroll/assets/min-max.js b/tests/playground/onscroll/assets/min-max.js
index 26f1d517..0406811e 100644
--- a/tests/playground/onscroll/assets/min-max.js
+++ b/tests/playground/onscroll/assets/min-max.js
@@ -3,7 +3,7 @@ import {
animate,
onScroll,
stagger,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
// Sync
diff --git a/tests/playground/onscroll/assets/standalone.js b/tests/playground/onscroll/assets/standalone.js
index 116b5d7f..f3a41c93 100644
--- a/tests/playground/onscroll/assets/standalone.js
+++ b/tests/playground/onscroll/assets/standalone.js
@@ -2,7 +2,7 @@ import {
utils,
onScroll,
animate,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
const $logs = utils.$('.log');
diff --git a/tests/playground/onscroll/assets/sticky-snap.js b/tests/playground/onscroll/assets/sticky-snap.js
index 0d5834b7..7136a507 100644
--- a/tests/playground/onscroll/assets/sticky-snap.js
+++ b/tests/playground/onscroll/assets/sticky-snap.js
@@ -2,7 +2,7 @@ import {
utils,
onScroll,
createTimeline,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
const tl = createTimeline({
defaults: {
diff --git a/tests/playground/onscroll/assets/svg-target.js b/tests/playground/onscroll/assets/svg-target.js
index 0d95cbfd..40999d91 100644
--- a/tests/playground/onscroll/assets/svg-target.js
+++ b/tests/playground/onscroll/assets/svg-target.js
@@ -2,7 +2,7 @@ import {
animate,
onScroll,
utils,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
utils.set('.section', {
rotate: () => utils.random(-45, 45),
diff --git a/tests/playground/onscroll/assets/sync-methods.js b/tests/playground/onscroll/assets/sync-methods.js
index 230e9b10..5c1ee31c 100644
--- a/tests/playground/onscroll/assets/sync-methods.js
+++ b/tests/playground/onscroll/assets/sync-methods.js
@@ -3,7 +3,7 @@ import {
animate,
onScroll,
stagger,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
// Sync
diff --git a/tests/playground/onscroll/assets/sync-modes.js b/tests/playground/onscroll/assets/sync-modes.js
index a7cf1bd5..fca351b1 100644
--- a/tests/playground/onscroll/assets/sync-modes.js
+++ b/tests/playground/onscroll/assets/sync-modes.js
@@ -3,7 +3,7 @@ import {
animate,
onScroll,
stagger,
-} from '../../../../src/anime.js';
+} from '../../../../dist/modules/index.js';
const $logs = utils.$('.log');
diff --git a/tests/playground/playback/index.js b/tests/playground/playback/index.js
index 46f037b4..0dadd582 100644
--- a/tests/playground/playback/index.js
+++ b/tests/playground/playback/index.js
@@ -3,7 +3,7 @@ import {
stagger,
utils,
engine,
-} from '../../../lib/anime.esm.js';
+} from '../../../dist/modules/index.js';
const [$animPlay] = utils.$('#animation-play');
const [$animPause] = utils.$('#animation-pause');
diff --git a/tests/playground/sandbox/index.js b/tests/playground/sandbox/index.js
index 16be5e52..c3e0d32a 100644
--- a/tests/playground/sandbox/index.js
+++ b/tests/playground/sandbox/index.js
@@ -1,17 +1,16 @@
-import {
- animate,
- createTimeline,
- utils,
-} from '../../../lib/anime.esm.js';
+import { animate, clamp, createTimer, onScroll, random } from '../../../dist/modules/index.js';
-utils.set('.square', {
- y: 0,
- rotate: 45,
-})
+animate('square', {
+ x: 100,
+ duration: 200,
+ autoplay: onScroll({
+ target: '.container',
+ sync: 1,
+ })
+});
animate('.square', {
- y: '+=50',
- rotate: () => '+=10',
- loop: true,
- onLoop: self => self.refresh()
+ duration: () => random(1, 200)
});
+
+const value = clamp()
\ No newline at end of file
diff --git a/tests/playground/scope/index.js b/tests/playground/scope/index.js
index f2608c2f..a4e44b69 100644
--- a/tests/playground/scope/index.js
+++ b/tests/playground/scope/index.js
@@ -2,7 +2,7 @@ import {
animate,
utils,
createScope,
-} from '../../../lib/anime.esm.js';
+} from '../../../dist/modules/index.js';
const scope = createScope({
mediaQueries: { isSmall: '(max-width: 800px)' },
diff --git a/tests/playground/sprite-animation.html b/tests/playground/sprite-animation.html
index 3da92b63..4d13732b 100644
--- a/tests/playground/sprite-animation.html
+++ b/tests/playground/sprite-animation.html
@@ -43,7 +43,7 @@
<script type="module">
- import { animate } from '../../lib/anime.esm.js';
+ import { animate } from '../../../dist/modules/index.js';
const ryu = animate('.ryu', {
backgroundPosition: '100% 0px',
diff --git a/tests/playground/stagger-demo.html b/tests/playground/stagger-demo.html
index 79e413c0..92013de7 100644
--- a/tests/playground/stagger-demo.html
+++ b/tests/playground/stagger-demo.html
@@ -40,7 +40,7 @@
</body>
<script type="module">
- import { animate, createTimeline, utils, stagger, svg } from '../../lib/anime.esm.js';
+ import { animate, createTimeline, utils, stagger, svg } from '../../../dist/modules/index.js';
const staggerVisualizerEl = document.querySelector('.stagger-visualizer');
const fragment = document.createDocumentFragment();
diff --git a/tests/playground/stagger-grid-demo.html b/tests/playground/stagger-grid-demo.html
index ecd0f150..567c9a3a 100644
--- a/tests/playground/stagger-grid-demo.html
+++ b/tests/playground/stagger-grid-demo.html
@@ -43,7 +43,7 @@
</body>
<script type="module">
- import { animate, createTimeline, utils, stagger, svg } from '../../lib/anime.esm.js';
+ import { animate, createTimeline, utils, stagger, svg } from '../../../dist/modules/index.js';
const staggerVisualizerEl = document.querySelector('.stagger-visualizer');
const fragment = document.createDocumentFragment();
diff --git a/tests/playground/svg-motion-path/index.js b/tests/playground/svg-motion-path/index.js
index 00e3b58f..4ec6ba15 100644
--- a/tests/playground/svg-motion-path/index.js
+++ b/tests/playground/svg-motion-path/index.js
@@ -1,4 +1,4 @@
-import { animate, svg } from '../../../lib/anime.esm.js';
+import { animate, svg } from '../../../dist/modules/index.js';
animate(['.no-specified-width .dom-el', '.no-specified-width .rect-el'], {
duration: 3000,
diff --git a/tests/playground/svg-path-animation.html b/tests/playground/svg-path-animation.html
index d6575aba..b7c0cc1f 100644
--- a/tests/playground/svg-path-animation.html
+++ b/tests/playground/svg-path-animation.html
@@ -29,7 +29,7 @@
</div>
<script type="module">
- import { animate, createTimeline, utils, stagger, svg } from '../../lib/anime.esm.js';
+ import { animate, createTimeline, utils, stagger, svg } from '../../../dist/modules/index.js';
createTimeline()
.add(svg.createDrawable('path'), {
diff --git a/tests/playground/threejs/instanced-mesh/index.js b/tests/playground/threejs/instanced-mesh/index.js
index d40e5744..f4c6efcb 100644
--- a/tests/playground/threejs/instanced-mesh/index.js
+++ b/tests/playground/threejs/instanced-mesh/index.js
@@ -1,4 +1,4 @@
-import { animate, createTimer, createTimeline, utils, engine, stagger } from '../../../lib/anime.esm.js';
+import { animate, createTimer, createTimeline, utils, engine, stagger } from '../../../../dist/modules/index.js';
import {
Object3D,
diff --git a/tests/playground/timekeeper/index.html b/tests/playground/timekeeper/index.html
index ae162100..708ff6d1 100644
--- a/tests/playground/timekeeper/index.html
+++ b/tests/playground/timekeeper/index.html
@@ -18,10 +18,14 @@
display: flex;
flex-wrap: wrap;
justify-content: center;
+ flex-direction: column;
align-items: center;
gap: .5rem;
padding: 1rem;
}
+ .is-min-m .container {
+ flex-direction: row;
+ }
.square {
width: 100px;
height: 100px;
diff --git a/tests/playground/timekeeper/index.js b/tests/playground/timekeeper/index.js
index 68b8b2f8..70a0b38e 100644
--- a/tests/playground/timekeeper/index.js
+++ b/tests/playground/timekeeper/index.js
@@ -3,23 +3,23 @@ import {
createScope,
createTimeline,
stagger
-} from '../../../lib/anime.esm.js';
-
-const timekeeper = utils.keepTime(scope => {
- const isMinM = scope.matches.minM;
- return createTimeline().add('.square', {
- y: 200,
- rotate: -90,
- scale: utils.random(.8, .9, 2),
- background: isMinM ? '#0FF' : '#FF0',
- alternate: true,
- loop: true,
- ease: 'inOutQuad',
- }, stagger(200));
-});
+} from '../../../dist/modules/index.js';
createScope({
mediaQueries: { minM: '(min-width: 800px)' }
+}).add(self => {
+ self.keepTime(scope => {
+ const isMinM = scope.matches.minM;
+ document.body.classList.toggle('is-min-m', isMinM);
+ return createTimeline().add('.square', {
+ x: isMinM ? 0 : [-50, 50],
+ y: isMinM ? [-50, 50] : 0,
+ rotate: -90,
+ scale: .75,
+ alternate: true,
+ loop: true,
+ ease: 'inOutQuad',
+ mediaQueries: { minM: '(min-width: 800px)' }
}).add(self => {
self.preserve(timekeeper);
-});
+});
\ No newline at end of file
diff --git a/tests/playground/timeline/nested/index.js b/tests/playground/timeline/nested/index.js
index 8760b764..4a9320f3 100644
--- a/tests/playground/timeline/nested/index.js
+++ b/tests/playground/timeline/nested/index.js
@@ -1,4 +1,4 @@
-import { animate, createTimer, createTimeline, eases, stagger, utils } from '../../../../lib/anime.esm.js';
+import { animate, createTimer, createTimeline, eases, stagger, utils } from '../../../../dist/modules/index.js';
// import { inspect } from '../../../lib/gui/index.js';
diff --git a/tests/playground/timeline/test-sets/index.js b/tests/playground/timeline/test-sets/index.js
index 0d4f62b0..ce3ac9f2 100644
--- a/tests/playground/timeline/test-sets/index.js
+++ b/tests/playground/timeline/test-sets/index.js
@@ -1,4 +1,4 @@
-import { createTimeline, stagger, utils, engine, animate } from '../../../../lib/anime.esm.js';
+import { createTimeline, stagger, utils, engine, animate } from '../../../../dist/modules/index.js';
// import { createTimeline, stagger, utils, engine, animate } from '../../assets/js/anime.esm.js';
// import { inspect } from '../../../lib/gui/index.js';
diff --git a/tests/playground/timeline/test/index.js b/tests/playground/timeline/test/index.js
index fe66e7ed..07a50057 100644
--- a/tests/playground/timeline/test/index.js
+++ b/tests/playground/timeline/test/index.js
@@ -1,4 +1,4 @@
-import { createTimeline, stagger } from '../../../../lib/anime.esm.js';
+import { createTimeline, stagger } from '../../../../dist/modules/index.js';
// import { inspect } from '../../../lib/gui/index.js';
const duration = 1000;
diff --git a/tests/playground/tl-seek-test/index.js b/tests/playground/tl-seek-test/index.js
index 77c376a5..1fa04388 100644
--- a/tests/playground/tl-seek-test/index.js
+++ b/tests/playground/tl-seek-test/index.js
@@ -2,7 +2,7 @@ import {
createTimeline,
stagger,
utils,
-} from '../../../lib/anime.esm.js';
+} from '../../../dist/modules/index.js';
const count = 2000;
diff --git a/tests/playground/tween-composition.html b/tests/playground/tween-composition.html
index 972160cb..977460ed 100644
--- a/tests/playground/tween-composition.html
+++ b/tests/playground/tween-composition.html
@@ -61,9 +61,7 @@
<div class="hover loop square red"></div>
</div>
<script type="module">
- import { animate, stagger, utils } from '../../../lib/anime.esm.js';
-
- // import { inspect } from '../lib/gui/index.js';
+ import { animate, stagger, utils } from '../../../dist/modules/index.js';
const black = '#252423';
const white = '#F6F4F2';
@@ -87,23 +85,14 @@
const staggered = animate($loopeds, {
autoplay: false,
x: [
- {
- to: ['-50%', 50],
- delay: stagger(120, {grid: [5, 5], from: 14}),
- endDelay: stagger(120, {grid: [5, 5], from: 14, direction: 'reverse'}),
- }, {
- to: '-50%',
- delay: stagger(120, {grid: [5, 5], from: 10}),
- endDelay: stagger(120, {grid: [5, 5], from: 10, direction: 'reverse'}),
- },
+ { to: ['-50%', 50], delay: stagger(120, {grid: [5, 5], from: 14}) },
+ { to: '-50%', delay: stagger(120, {grid: [5, 5], from: 10}) },
],
ease: 'inOutQuart',
duration: 2000,
loop: true,
});
- // // inspect(staggered);
-
// animate($loopeds, {
// scale: [0, 1],
// ease: 'inOutQuad',
@@ -111,8 +100,6 @@
// delay: stagger(120, {grid: [5, 5], from: 'center', start: 240}),
// });
- // createGUI(staggered);
-
for (let i = 0, l = $hovereds.length; i < l; i++) {
const el = $hovereds[i];
el.onmouseenter = () => {
diff --git a/tests/playground/waapi/composition/index.js b/tests/playground/waapi/composition/index.js
index 80a0d146..20f99c43 100644
--- a/tests/playground/waapi/composition/index.js
+++ b/tests/playground/waapi/composition/index.js
@@ -1,4 +1,4 @@
-import { waapi, animate, stagger, createSpring, utils, eases, engine } from '../../../../lib/anime.esm.js';
+import { waapi, animate, stagger, createSpring, utils, eases, engine } from '../../../../dist/modules/index.js';
let currentY = 0;
let alternate = false;
diff --git a/tests/playground/waapi/eases/index.js b/tests/playground/waapi/eases/index.js
index 3cb1785e..2b0ddaac 100644
--- a/tests/playground/waapi/eases/index.js
+++ b/tests/playground/waapi/eases/index.js
@@ -1,4 +1,4 @@
-import { waapi, animate, stagger, createSpring, utils } from '../../../../lib/anime.esm.js';
+import { waapi, animate, stagger, createSpring, utils } from '../../../../dist/modules/index.js';
const $animation = document.querySelector('.animation');
const total = 36;
diff --git a/tests/playground/waapi/playback/index.js b/tests/playground/waapi/playback/index.js
index f2e85503..1513a5f8 100644
--- a/tests/playground/waapi/playback/index.js
+++ b/tests/playground/waapi/playback/index.js
@@ -5,7 +5,7 @@ import {
createTimer,
createScope,
onScroll
-} from '../../../../lib/anime.esm.js';
+} from '../../../../dist/modules/index.js';
const [$animResume] = utils.$('#animation-resume');
const [$animPlay] = utils.$('#animation-play');
diff --git a/tests/playground/waapi/values/index.js b/tests/playground/waapi/values/index.js
index 83fe3e18..1c95ea75 100644
--- a/tests/playground/waapi/values/index.js
+++ b/tests/playground/waapi/values/index.js
@@ -1,4 +1,4 @@
-import { waapi, animate, stagger, utils, createTimer } from '../../../../lib/anime.esm.js';
+import { waapi, animate, stagger, utils, createTimer } from '../../../../dist/modules/index.js';
let alternate = false;
let x = utils.random(0, window.innerWidth - 800);
diff --git a/tests/run.js b/tests/run.js
index 5814c7c8..a8593b29 100644
--- a/tests/run.js
+++ b/tests/run.js
@@ -1,5 +1,6 @@
import './suites/engine.test.js';
import './suites/seconds.test.js';
+import './suites/build.test.js';
import './suites/draggables.test.js';
import './suites/scroll.test.js';
import './suites/waapi.test.js';
diff --git a/tests/suites/animatables.test.js b/tests/suites/animatables.test.js
index eaaf001b..b259cfb2 100644
--- a/tests/suites/animatables.test.js
+++ b/tests/suites/animatables.test.js
@@ -6,7 +6,7 @@ import {
createAnimatable,
createTimer,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('Animatables', () => {
diff --git a/tests/suites/animations.test.js b/tests/suites/animations.test.js
index 626daf1a..1a97333a 100644
--- a/tests/suites/animations.test.js
+++ b/tests/suites/animations.test.js
@@ -12,12 +12,12 @@ import {
animate,
createTimer,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
import {
minValue,
tweenTypes,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
suite('Animations', () => {
diff --git a/tests/suites/build.test.js b/tests/suites/build.test.js
new file mode 100644
index 00000000..13e42737
--- /dev/null
+++ b/tests/suites/build.test.js
@@ -0,0 +1,130 @@
+import {
+ expect,
+} from '../utils.js';
+
+import * as esmModules from '../../../dist/modules/index.js';
+import * as esmBundle from '../../../dist/bundles/anime.esm.js';
+import * as minifiedEsmBundle from '../../../dist/bundles/anime.esm.min.js';
+
+const apiExports = [
+ 'animate',
+ 'createTimer',
+ 'createTimeline',
+ 'createAnimatable',
+ 'createDraggable',
+ 'createScope',
+ 'createSpring',
+ 'onScroll',
+ 'engine',
+ 'easings',
+ 'utils', 'stagger',
+ 'svg', 'createDrawable', 'createMotionPath', 'morphTo',
+ 'text', 'splitText', 'split',
+ 'waapi',
+]
+
+suite('Build', () => {
+
+ test('ESM modules exports', () => {
+ apiExports.forEach(exportName => {
+ expect(esmModules[exportName]).to.exist;
+ });
+ });
+
+ test('ESM bundle exports', () => {
+ apiExports.forEach(exportName => {
+ expect(esmBundle[exportName]).to.exist;
+ })
+ });
+
+ test('ESM bundle minified exports', () => {
+ apiExports.forEach(exportName => {
+ expect(minifiedEsmBundle[exportName]).to.exist;
+ })
+ });
+
+ test('UMD bundle exports', () => {
+ apiExports.forEach(exportName => {
+ expect(window.anime[exportName]).to.exist;
+ })
+ });
+
+ test('ESM sub modules exports', resolve => {
+ fetch('../../../package.json')
+ .then((response) => response.json())
+ .then((data) => {
+ const inputs = Object.keys(data.exports)
+ .filter(k => k !== './package.json')
+ .map(k => `../../../dist/modules${k.replace('.', '')}/index.js`);
+
+ const fetchPromises = inputs.map(path =>
+ fetch(path)
+ .then((response) => {
+ expect(response.ok).to.equal(true, `Failed to fetch ${path}`);
+ return response.text();
+ })
+ .then((content) => {
+ expect(content).to.exist;
+ expect(content).to.not.be.empty;
+ const hasExport = content.includes('export');
+ expect(hasExport).to.equal(true, `Module at ${path} has no exports`);
+ return { path, success: true };
+ })
+ .catch((error) => {
+ throw new Error(`Error loading module ${path}: ${error.message}`);
+ })
+ );
+ return Promise.all(fetchPromises);
+ })
+ .then((results) => {
+ expect(results).to.have.length.greaterThan(0);
+ resolve();
+ })
+ .catch((error) => {
+ resolve(error);
+ });
+ });
+
+ test('CJS sub modules exports', resolve => {
+ fetch('../../../package.json')
+ .then((response) => response.json())
+ .then((data) => {
+ const inputs = Object.keys(data.exports)
+ .filter(k => k !== './package.json')
+ .map(k => `../../../dist/modules${k.replace('.', '')}/index.cjs`);
+
+ const fetchPromises = inputs.map(path =>
+ fetch(path)
+ .then((response) => {
+ expect(response.ok).to.equal(true, `Failed to fetch ${path}`);
+ return response.text();
+ })
+ .then((content) => {
+ expect(content).to.exist;
+ expect(content).to.not.be.empty;
+ const hasExport = content.includes('exports.');
+ expect(hasExport).to.equal(true, `Module at ${path} has no exports`);
+ return { path, success: true };
+ })
+ .catch((error) => {
+ throw new Error(`Error loading module ${path}: ${error.message}`);
+ })
+ );
+ return Promise.all(fetchPromises);
+ })
+ .then((results) => {
+ expect(results).to.have.length.greaterThan(0);
+ resolve();
+ })
+ .catch((error) => {
+ resolve(error);
+ });
+ });
+
+ test('Package version', () => {
+ window.AnimeJS.forEach(instance => {
+ expect(instance.version).to.not.equal('__packageVersion__');
+ })
+ });
+
+});
diff --git a/tests/suites/callbacks.test.js b/tests/suites/callbacks.test.js
index 768a8c76..7161496b 100644
--- a/tests/suites/callbacks.test.js
+++ b/tests/suites/callbacks.test.js
@@ -6,7 +6,7 @@ import {
animate,
createTimeline,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
function setupAnimationCallBack(callbackName, callbackFunc) {
const parameters = {
diff --git a/tests/suites/colors.test.js b/tests/suites/colors.test.js
index 3b29ed18..27e18ff8 100644
--- a/tests/suites/colors.test.js
+++ b/tests/suites/colors.test.js
@@ -6,11 +6,11 @@ import {
import {
animate,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
import {
valueTypes,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
const colors = {
from: {
diff --git a/tests/suites/controls.test.js b/tests/suites/controls.test.js
index c9b4395f..51bd0e03 100644
--- a/tests/suites/controls.test.js
+++ b/tests/suites/controls.test.js
@@ -10,11 +10,11 @@ import {
createTimer,
utils,
engine,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
import {
minValue,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
suite('Controls', () => {
test('Alternate the direction of an animation', resolve => {
diff --git a/tests/suites/directions.test.js b/tests/suites/directions.test.js
index daa56d23..374fae99 100644
--- a/tests/suites/directions.test.js
+++ b/tests/suites/directions.test.js
@@ -5,7 +5,7 @@ import {
import {
animate,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('Directions', () => {
test('Direction normal should update from 0 to 1', resolve => {
diff --git a/tests/suites/draggables.test.js b/tests/suites/draggables.test.js
index ab0751ba..1060b915 100644
--- a/tests/suites/draggables.test.js
+++ b/tests/suites/draggables.test.js
@@ -1,14 +1,12 @@
import {
expect,
- getChildAtIndex,
- forEachChildren,
} from '../utils.js';
import {
createTimer,
createDraggable,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
const createMouseEvent = ($target, name, x, y) => $target.dispatchEvent(new MouseEvent('mouse' + name, {
clientX: x,
@@ -194,3 +192,4 @@ suite('Draggables', () => {
});
});
+
diff --git a/tests/suites/eases.test.js b/tests/suites/eases.test.js
index 29ff3d5d..1ee220d2 100644
--- a/tests/suites/eases.test.js
+++ b/tests/suites/eases.test.js
@@ -7,7 +7,7 @@ import {
utils,
eases,
createSpring,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
function createEasingParam(ease) {
return {
diff --git a/tests/suites/engine.test.js b/tests/suites/engine.test.js
index 13e63a6e..16349775 100644
--- a/tests/suites/engine.test.js
+++ b/tests/suites/engine.test.js
@@ -6,7 +6,7 @@ import {
animate,
engine,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
const defaultEnginePauseState = engine.paused;
const defaultEngineReqId = engine.reqId;
diff --git a/tests/suites/function-based-values.test.js b/tests/suites/function-based-values.test.js
index 735308df..ed01518b 100644
--- a/tests/suites/function-based-values.test.js
+++ b/tests/suites/function-based-values.test.js
@@ -4,12 +4,12 @@ import {
getTweenDelay,
} from '../utils.js';
-import { animate, stagger, utils } from '../../src/anime.js';
+import { animate, stagger, utils } from '../../../dist/modules/index.js';
import {
valueTypes,
minValue,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
suite('Function based values', () => {
diff --git a/tests/suites/keyframes.test.js b/tests/suites/keyframes.test.js
index 6ae71b76..19fdd9a5 100644
--- a/tests/suites/keyframes.test.js
+++ b/tests/suites/keyframes.test.js
@@ -4,11 +4,11 @@ import {
getTweenDelay,
} from '../utils.js';
-import { animate, utils } from '../../src/anime.js';
+import { animate, utils } from '../../../dist/modules/index.js';
import {
valueTypes,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
suite('Keyframes', () => {
test('An array of one raw value should be considered as a simple value', () => {
diff --git a/tests/suites/leaks.test.js b/tests/suites/leaks.test.js
index 2b3b3c5d..0aa8c2cc 100644
--- a/tests/suites/leaks.test.js
+++ b/tests/suites/leaks.test.js
@@ -4,7 +4,7 @@ import {
import {
engine,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('Leaks', () => {
test('Engine should not contain any active tickable', resolve => {
diff --git a/tests/suites/node.test.js b/tests/suites/node.test.js
index f0eee378..f10850d1 100644
--- a/tests/suites/node.test.js
+++ b/tests/suites/node.test.js
@@ -1,6 +1,6 @@
import { expect } from 'chai';
-import { animate, createTimer, createTimeline, engine } from '../../src/anime.js';
-import { render } from '../../src/render.js';
+import { animate, createTimer, createTimeline, engine } from '../../dist/modules/index.js';
+import { render } from '../../dist/modules/core/render.js';
// import { animate } from '../visual/assets/anime.4.0.0.beta-29.js';
const totalInstances = 10000;
@@ -172,7 +172,38 @@ suite('Node tests', () => {
expect(animationHasFastProperties).to.equal(true);
});
- test('test if the render() function can be optimized', () => {
+ const generateInstances = () => {
+ let anim, tl, timer;
+ for (let i = 0; i < totalInstances; i++) {
+ anim = animate(targets[i], {
+ prop: Math.random(),
+ delay: Math.random() * 1.5,
+ duration: Math.random() * 2,
+ loopDelay: Math.random() * 3
+ });
+ tl = createTimeline()
+ .add(targets[i], {
+ prop: Math.random(),
+ delay: Math.random() * 1.5,
+ duration: Math.random() * 2,
+ loopDelay: Math.random() * 3
+ })
+ .add(targets[i], {
+ prop: Math.random(),
+ delay: Math.random() * 1.5,
+ duration: Math.random() * 2,
+ loopDelay: Math.random() * 3,
+ })
+ timer = createTimer({
+ delay: Math.random() * 1.5,
+ duration: Math.random() * 2,
+ loopDelay: Math.random() * 3
+ });
+ }
+ return { anim, tl, timer }
+ }
+
+ test('test if the render() function can be optimized', resolve => {
// First test a normal run
@@ -180,35 +211,42 @@ suite('Node tests', () => {
animate(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
- duration: Math.random() * 2,
+ duration: Math.random() * 100,
loopDelay: Math.random() * 3
})
}
- expect(getOptimizationStatus(render)).to.equal(49);
+ setTimeout(() => {
+ expect(getOptimizationStatus(render)).to.equal(49);
- // Then mix animation types an manually render them
+ // Then mix animation types an manually render them
- const animations = [];
+ const animations = [];
- // animations.push(globalClock._additiveAnimation);
+ // animations.push(globalClock._additiveAnimation);
- for (let i = 0; i < totalInstances / 3; i++) {
- animations.push(animate(targets[i], {prop: Math.random(), duration: Math.random() * 2, autoplay: false}));
- animations.push(createTimer({duration: Math.random() * 10, autoplay: false}));
- }
+ for (let i = 0; i < totalInstances / 3; i++) {
+ animations.push(animate(targets[i], {prop: Math.random(), duration: Math.random() * 100, autoplay: false}));
+ animations.push(createTimer({duration: Math.random() * 100, autoplay: false}));
+ }
- // animations.push(globalClock._additiveAnimation);
+ // animations.push(globalClock._additiveAnimation);
- const start = Date.now();
+ const start = Date.now();
- for (let i = 0; i < animations.length; i++) {
- const time = Date.now() - start;
- const tickMode = Math.random() < .5 ? 0 : -1;
- render(animations[i], time, 0, 0, tickMode);
- }
+ for (let i = 0; i < animations.length; i++) {
+ const time = Date.now() - start;
+ const tickMode = Math.random() < .5 ? 0 : -1;
+ render(animations[i], time, 0, 0, tickMode);
+ }
+
+ setTimeout(() => {
+ expect(getOptimizationStatus(render)).to.equal(49);
+ resolve();
+ }, 200)
+
+ }, 200)
- expect(getOptimizationStatus(render)).to.equal(49);
});
test('test if the engine.update() function can be optimized', resolve => {
@@ -235,37 +273,6 @@ suite('Node tests', () => {
}, 200)
});
- const generateInstances = () => {
- let anim, tl, timer;
- for (let i = 0; i < totalInstances; i++) {
- anim = animate(targets[i], {
- prop: Math.random(),
- delay: Math.random() * 1.5,
- duration: Math.random() * 2,
- loopDelay: Math.random() * 3
- });
- tl = createTimeline()
- .add(targets[i], {
- prop: Math.random(),
- delay: Math.random() * 1.5,
- duration: Math.random() * 2,
- loopDelay: Math.random() * 3
- })
- .add(targets[i], {
- prop: Math.random(),
- delay: Math.random() * 1.5,
- duration: Math.random() * 2,
- loopDelay: Math.random() * 3,
- })
- timer = createTimer({
- delay: Math.random() * 1.5,
- duration: Math.random() * 2,
- loopDelay: Math.random() * 3
- });
- }
- return { anim, tl, timer }
- }
-
test('test if engine has fast properties', () => {
const { anim, tl, timer } = generateInstances();
expect(%HasFastProperties(engine)).to.equal(true);
diff --git a/tests/suites/parameters.test.js b/tests/suites/parameters.test.js
index ecf27f61..944f898d 100644
--- a/tests/suites/parameters.test.js
+++ b/tests/suites/parameters.test.js
@@ -8,8 +8,8 @@ import {
testObject,
} from '../setup.js';
-import { animate, createTimeline, createTimer, utils } from '../../src/anime.js';
-import { minValue } from '../../src/consts.js';
+import { animate, createTimeline, createTimer, utils } from '../../../dist/modules/index.js';
+import { minValue } from '../../dist/modules/core/consts.js';
suite('Parameters', () => {
const duration = 10;
diff --git a/tests/suites/promises.test.js b/tests/suites/promises.test.js
index 694d02fd..c51bfcea 100644
--- a/tests/suites/promises.test.js
+++ b/tests/suites/promises.test.js
@@ -2,7 +2,7 @@ import {
expect,
} from '../utils.js';
-import { animate, createTimeline, createTimer, utils } from '../../src/anime.js';
+import { animate, createTimeline, createTimer, utils } from '../../../dist/modules/index.js';
suite('Promises', () => {
diff --git a/tests/suites/scope.test.js b/tests/suites/scope.test.js
index a3b80829..aeab7e46 100644
--- a/tests/suites/scope.test.js
+++ b/tests/suites/scope.test.js
@@ -4,7 +4,7 @@ import {
import {
createScope,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('Scope', () => {
diff --git a/tests/suites/scroll.test.js b/tests/suites/scroll.test.js
index 51768e6f..d1a9abda 100644
--- a/tests/suites/scroll.test.js
+++ b/tests/suites/scroll.test.js
@@ -7,7 +7,7 @@ import {
scrollContainers,
animate,
utils
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('Scroll', () => {
test('Reverting an animation with onScroll should also revert the ScrollObserver', () => {
diff --git a/tests/suites/seconds.test.js b/tests/suites/seconds.test.js
index 54600c0e..40178e81 100644
--- a/tests/suites/seconds.test.js
+++ b/tests/suites/seconds.test.js
@@ -5,14 +5,14 @@ import {
import {
minValue,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
import {
animate,
createTimeline,
createTimer,
engine,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('Seconds', () => {
diff --git a/tests/suites/stagger.test.js b/tests/suites/stagger.test.js
index 6ae19428..e1bed7e9 100644
--- a/tests/suites/stagger.test.js
+++ b/tests/suites/stagger.test.js
@@ -4,7 +4,7 @@ import {
getTweenDelay,
} from '../utils.js';
-import { animate, stagger, createTimeline } from '../../src/anime.js';
+import { animate, stagger, createTimeline } from '../../../dist/modules/index.js';
suite('Stagger', () => {
test('Increase each values by a specific value for each elements', () => {
diff --git a/tests/suites/svg.test.js b/tests/suites/svg.test.js
index d2c711e6..92f88fc5 100644
--- a/tests/suites/svg.test.js
+++ b/tests/suites/svg.test.js
@@ -7,7 +7,7 @@ import {
animate,
utils,
svg,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('SVG', () => {
test('svg.createDrawable', resolve => {
diff --git a/tests/suites/targets.test.js b/tests/suites/targets.test.js
index f60b6694..aa72cece 100644
--- a/tests/suites/targets.test.js
+++ b/tests/suites/targets.test.js
@@ -10,7 +10,7 @@ import {
import {
animate,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('Targets', () => {
test('Single element from CSS selector', () => {
diff --git a/tests/suites/text.test.js b/tests/suites/text.test.js
index ab5dc117..6425ae77 100644
--- a/tests/suites/text.test.js
+++ b/tests/suites/text.test.js
@@ -5,9 +5,9 @@ import {
import {
utils,
- text,
+ splitText,
animate,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
// Firefox detect Japanse words differently
const wordsLength = browserIs.firefox ? 44 : 45;
@@ -15,7 +15,7 @@ const charsLength = 229;
suite('Text', () => {
test('Defaults text split (words only)', () => {
- const split = text.split('#split-text p');
+ const split = splitText('#split-text p');
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(0);
@@ -23,7 +23,7 @@ suite('Text', () => {
});
test('Split chars only', () => {
- const split = text.split('#split-text p', { words: false, chars: true });
+ const split = splitText('#split-text p', { words: false, chars: true });
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(charsLength);
@@ -31,7 +31,7 @@ suite('Text', () => {
});
test('Split lines only', resolve => {
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: true,
words: false,
})
@@ -50,7 +50,7 @@ suite('Text', () => {
});
test('Split words and chars', () => {
- const split = text.split('#split-text p', { chars: true });
+ const split = splitText('#split-text p', { chars: true });
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(charsLength);
@@ -58,7 +58,7 @@ suite('Text', () => {
});
test('Split words and lines', resolve => {
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: true,
});
split.addEffect((split) => {
@@ -76,7 +76,7 @@ suite('Text', () => {
});
test('Split lines and chars', resolve => {
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: true,
words: false,
chars: true,
@@ -95,7 +95,7 @@ suite('Text', () => {
});
test('Split lines words and chars', resolve => {
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: true,
chars: true,
})
@@ -114,7 +114,7 @@ suite('Text', () => {
});
test('Custom css classes', resolve => {
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: { class: 'split-line' },
words: { class: 'split-word' },
chars: { class: 'split-char' },
@@ -133,7 +133,7 @@ suite('Text', () => {
});
test('Wrap text', resolve => {
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: { wrap: 'clip' },
words: { wrap: 'clip' },
chars: { wrap: 'clip' },
@@ -151,7 +151,7 @@ suite('Text', () => {
});
test('Clone text', resolve => {
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: { clone: true },
words: { clone: true },
chars: { clone: true },
@@ -166,7 +166,7 @@ suite('Text', () => {
});
test('Custom template', resolve => {
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: '<span class="split-line split-line-{i}">{value}</span>',
words: '<span class="split-word split-word-{i}">{value}</span>',
chars: '<span class="split-char split-char-{i}">{value}</span>',
@@ -185,7 +185,7 @@ suite('Text', () => {
test('Init in a document.fonts.ready Promise', resolve => {
document.fonts.ready.then(() => {
- text.split('#split-text p', {
+ splitText('#split-text p', {
lines: true,
words: true,
chars: true,
@@ -204,7 +204,7 @@ suite('Text', () => {
test('addEffect() should only triggers once on load', resolve => {
let calls = 0, timeout;
- text.split('#split-text p', {
+ splitText('#split-text p', {
lines: true,
})
.addEffect((split) => {
@@ -221,7 +221,7 @@ suite('Text', () => {
test('addEffect() should properly track the time of an animation', resolve => {
let animation;
const [ $p ] = utils.$('#split-text p');
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: true,
})
.addEffect((split) => {
@@ -248,7 +248,7 @@ suite('Text', () => {
let cleanups = 0;
let lines = 0;
const [ $p ] = utils.$('#split-text p');
- const split = text.split($p, {
+ const split = splitText($p, {
lines: true,
})
.addEffect(() => {
@@ -284,7 +284,7 @@ suite('Text', () => {
test('addEffect() should only triggers once on load inside a document.fonts.ready Promise', resolve => {
document.fonts.ready.then(() => {
let calls = 0, timeout;
- text.split('#split-text p', {
+ splitText('#split-text p', {
lines: true,
})
.addEffect((split) => {
@@ -304,7 +304,7 @@ suite('Text', () => {
let calls = 0;
let cleanups = 0;
const [ $p ] = utils.$('#split-text p');
- const split = text.split($p, {
+ const split = splitText($p, {
lines: true,
})
.addEffect(() => {
@@ -331,7 +331,7 @@ suite('Text', () => {
let calls = 0;
let cleanups = 0;
const [ $p ] = utils.$('#split-text p');
- const split = text.split($p, {
+ const split = splitText($p, {
lines: false,
})
.addEffect(() => {
@@ -353,7 +353,7 @@ suite('Text', () => {
let calls = 0;
let cleanups = 0;
const [ $p ] = utils.$('#split-text p');
- const split = text.split($p, {
+ const split = splitText($p, {
lines: true,
})
.addEffect(self => {
@@ -383,7 +383,7 @@ suite('Text', () => {
test('revert() should properly revert animations effects', resolve => {
let animation;
const [ $p ] = utils.$('#split-text p');
- const split = text.split('#split-text p', {
+ const split = splitText('#split-text p', {
lines: true,
})
.addEffect((split) => {
@@ -405,7 +405,7 @@ suite('Text', () => {
let calls = 0;
let cleanups = 0;
const [ $p ] = utils.$('#split-text p');
- const split = text.split($p, {
+ const split = splitText($p, {
lines: true,
})
.addEffect(self => {
diff --git a/tests/suites/timelines.test.js b/tests/suites/timelines.test.js
index a03278c2..5f2b1162 100644
--- a/tests/suites/timelines.test.js
+++ b/tests/suites/timelines.test.js
@@ -9,12 +9,12 @@ import {
utils,
createTimer,
animate,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
import {
compositionTypes,
minValue,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
suite('Timelines', () => {
function createTL() {
diff --git a/tests/suites/timings.test.js b/tests/suites/timings.test.js
index 6c0f5074..5324c624 100644
--- a/tests/suites/timings.test.js
+++ b/tests/suites/timings.test.js
@@ -6,7 +6,7 @@ import {
import {
animate,
utils
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('Timings', () => {
test('Specified timings parameters', resolve => {
diff --git a/tests/suites/tweens.test.js b/tests/suites/tweens.test.js
index d7e545c3..8143627e 100644
--- a/tests/suites/tweens.test.js
+++ b/tests/suites/tweens.test.js
@@ -11,12 +11,12 @@ import {
createTimer,
createTimeline,
engine,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
import {
compositionTypes,
valueTypes,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
suite('Tweens', () => {
test('Single tween timings', () => {
diff --git a/tests/suites/types.test.js b/tests/suites/types.test.js
index 7c8311f1..d0e188b3 100644
--- a/tests/suites/types.test.js
+++ b/tests/suites/types.test.js
@@ -1,4 +1,4 @@
-import { animate, createTimer, createTimeline, utils } from '../../src/anime.js';
+import { animate, createTimer, createTimeline, utils } from '../../../dist/modules/index.js';
animate('.anime-css', {
keyframes: {
diff --git a/tests/suites/units.test.js b/tests/suites/units.test.js
index c784f905..b5c7ff1f 100644
--- a/tests/suites/units.test.js
+++ b/tests/suites/units.test.js
@@ -6,7 +6,7 @@ import {
import {
animate,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
const validUnits = ['cm','mm','in','pc','pt','px','em','ex','ch','rem','vw','vh','vmin','vmax','q','lh','rlh','vb','vi','svw','svh','lvw','lvh','dvw','dvh'];
diff --git a/tests/suites/utils.test.js b/tests/suites/utils.test.js
index b3afa0c6..f0abd219 100644
--- a/tests/suites/utils.test.js
+++ b/tests/suites/utils.test.js
@@ -2,7 +2,7 @@ import {
utils,
animate,
createTimeline,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
import {
expect,
@@ -140,7 +140,7 @@ suite('Utils', () => {
});
test('Set Object properties to specific unit', () => {
- const anim = utils.set(testObject, {
+ utils.set(testObject, {
plainValue: '42px',
valueWithUnit: '42rem',
multiplePLainValues: '40% 41px 42rem 43vh',
@@ -459,7 +459,7 @@ suite('Utils', () => {
animation.pause();
});
- test('Remove specific tween property and cancel the animation if not tweens are left', () => {
+ test('Remove specific tween property and cancel the animation if no tweens are left', () => {
const animation = animate('#target-id', { x: 100, y: 100 });
expect(getChildLength(animation)).to.equal(2);
@@ -503,4 +503,10 @@ suite('Utils', () => {
animation.pause();
});
+ test('Chained utility functions', () => {
+ const chain = utils.mapRange(0, 100, 0, 1000).clamp(0, 100);
+ expect(chain(1)).to.equal(10);
+ expect(chain(5)).to.equal(50);
+ expect(chain(50)).to.equal(100);
+ });
});
diff --git a/tests/suites/values.test.js b/tests/suites/values.test.js
index f42a92c1..c4b41f88 100644
--- a/tests/suites/values.test.js
+++ b/tests/suites/values.test.js
@@ -7,12 +7,12 @@ import {
import {
animate,
utils,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
import {
unitsExecRgx,
valueTypes,
-} from '../../src/consts.js';
+} from '../../dist/modules/core/consts.js';
suite('Values', () => {
diff --git a/tests/suites/waapi.test.js b/tests/suites/waapi.test.js
index 3e084cc4..4a9aafeb 100644
--- a/tests/suites/waapi.test.js
+++ b/tests/suites/waapi.test.js
@@ -7,7 +7,7 @@ import {
utils,
stagger,
eases,
-} from '../../src/anime.js';
+} from '../../../dist/modules/index.js';
suite('WAAPI', () => {
diff --git a/tests/utils.js b/tests/utils.js
index e00957c6..529d10e4 100644
--- a/tests/utils.js
+++ b/tests/utils.js
@@ -4,7 +4,7 @@ import {
addChild,
removeChild,
forEachChildren,
-} from '../src/helpers.js';
+} from '../dist/modules/core/helpers.js';
export const { expect } = chai;
diff --git a/tsconfig.json b/tsconfig.json
index f614d552..2b1dccf3 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,14 +1,12 @@
{
"compilerOptions": {
"lib": ["ESNext", "DOM"],
+ "module": "ESNext",
"target": "ESNext",
- "strict": false,
+ "moduleResolution": "nodenext",
"allowJs": true,
"checkJs": true,
- "noEmit": true,
- "declarationDir": "types",
- "declaration": true
+ "noEmit": true
},
- "include": ["src/**/*.js"],
- "exclude": ["node_modules", "tests", "lib", "documentation", "src/gui/*.js"]
-}
+ "include": ["src/**/*.js"]
+}
\ No newline at end of file
diff --git a/tsconfig.types.json b/tsconfig.types.json
new file mode 100644
index 00000000..8031b1cf
--- /dev/null
+++ b/tsconfig.types.json
@@ -0,0 +1,33 @@
+{
+ "compilerOptions": {
+ "lib": ["ESNext", "DOM"],
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "target": "esnext",
+ "allowJs": true,
+ "checkJs": true,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "skipLibCheck": true,
+ "outDir": "./dist/modules/"
+ },
+ "include": [
+ "./src/index.js",
+ "./src/timer/index.js",
+ "./src/animation/index.js",
+ "./src/timeline/index.js",
+ "./src/animatable/index.js",
+ "./src/draggable/index.js",
+ "./src/scope/index.js",
+ "./src/events/index.js",
+ "./src/spring/index.js",
+ "./src/engine/index.js",
+ "./src/easings/index.js",
+ "./src/utils/index.js",
+ "./src/svg/index.js",
+ "./src/text/index.js",
+ "./src/waapi/index.js",
+ "./src/types/index.js",
+ ],
+ "exclude": [] // Needed to allow include and outDir to be the same
+}
\ No newline at end of file