Skip to content

armgit / anime

Public Imported from GitHub
0

JavaScript animation engine

4.3.0-beta.0

Julian Garnierfddf8f50961c
diff --git a/package.json b/package.json
index ae59cc99..4db8cb77 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,8 @@
{
"name": "animejs",
- "version": "4.2.2",
- "homepage": "https://animejs.com",
+ "version": "4.3.0-beta.0",
"description": "JavaScript animation engine",
+ "homepage": "https://animejs.com",
"author": "Julian Garnier <[email protected]>",
"license": "MIT",
"repository": {
@@ -104,6 +104,12 @@
"import": "./dist/modules/events/index.js",
"default": "./dist/modules/events/index.cjs"
},
+ "./layout": {
+ "types": "./dist/modules/layout/index.d.ts",
+ "require": "./dist/modules/layout/index.cjs",
+ "import": "./dist/modules/layout/index.js",
+ "default": "./dist/modules/layout/index.cjs"
+ },
"./easings": {
"types": "./dist/modules/easings/index.d.ts",
"require": "./dist/modules/easings/index.cjs",
diff --git a/src/animation/animation.js b/src/animation/animation.js
index 83e0983c..291a8d0e 100644
--- a/src/animation/animation.js
+++ b/src/animation/animation.js
@@ -110,6 +110,7 @@ const fastSetValuesArray = [null, null];
const keyObjectTarget = { to: null };
let tweenId = 0;
+let JSAnimationId = 0;
let keyframes;
/** @type {TweenParamsOptions & TweenValues} */
let key;
@@ -224,6 +225,8 @@ export class JSAnimation extends Timer {
super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
+ ++JSAnimationId;
+
const parsedTargets = registerTargets(targets);
const targetsLength = parsedTargets.length;
@@ -233,6 +236,7 @@ export class JSAnimation extends Timer {
const params = /** @type {AnimationParams} */(kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters);
const {
+ id,
delay,
duration,
ease,
@@ -243,11 +247,12 @@ export class JSAnimation extends Timer {
} = 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).settlingDuration : setValue(duration, animDefaults.duration);
+ const animEase = setValue(ease, animDefaults.ease);
+ const animPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
+ const parsedAnimPlaybackEase = animPlaybackEase ? parseEase(animPlaybackEase) : null;
+ const hasSpring = !isUnd(/** @type {Spring} */(animEase).ease);
+ const tEasing = hasSpring ? /** @type {Spring} */(animEase).ease : setValue(ease, parsedAnimPlaybackEase ? 'linear' : animDefaults.ease);
+ const tDuration = hasSpring ? /** @type {Spring} */(animEase).settlingDuration : 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
@@ -255,7 +260,7 @@ export class JSAnimation extends Timer {
// const absoluteOffsetTime = this._offset;
const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0);
// This allows targeting the current animation in the spring onComplete callback
- if (hasSpring) /** @type {Spring} */(ease).parent = this;
+ if (hasSpring) /** @type {Spring} */(animEase).parent = this;
let iterationDuration = NaN;
let iterationDelay = NaN;
@@ -399,6 +404,8 @@ export class JSAnimation extends Timer {
if (isFromToValue) {
decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject);
decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject);
+ // Needed to force an inline style registration
+ const originalValue = getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore);
if (fromTargetObject.t === valueTypes.NUMBER) {
if (prevSibling) {
if (prevSibling._valueType === valueTypes.UNIT) {
@@ -407,7 +414,7 @@ export class JSAnimation extends Timer {
}
} else {
decomposeRawValue(
- getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore),
+ originalValue,
decomposedOriginalValue
);
if (decomposedOriginalValue.t === valueTypes.UNIT) {
@@ -626,12 +633,14 @@ export class JSAnimation extends Timer {
}
/** @type {TargetsArray} */
this.targets = parsedTargets;
+ /** @type {String|Number} */
+ this.id = !isUnd(id) ? id : JSAnimationId;
/** @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;
+ this._ease = parsedAnimPlaybackEase;
/** @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.
diff --git a/src/core/clock.js b/src/core/clock.js
index 620598bc..0f43f93f 100644
--- a/src/core/clock.js
+++ b/src/core/clock.js
@@ -6,8 +6,8 @@ import {
} from './consts.js';
import {
- round,
-} from './helpers.js';
+ defaults,
+} from './globals.js';
/**
* @import {
@@ -29,7 +29,7 @@ export class Clock {
/** @type {Number} */
this._currentTime = initTime;
/** @type {Number} */
- this._elapsedTime = initTime;
+ this._lastTickTime = initTime;
/** @type {Number} */
this._startTime = initTime;
/** @type {Number} */
@@ -37,7 +37,7 @@ export class Clock {
/** @type {Number} */
this._scheduledTime = 0;
/** @type {Number} */
- this._frameDuration = round(K / maxFps, 0);
+ this._frameDuration = K / maxFps;
/** @type {Number} */
this._fps = maxFps;
/** @type {Number} */
@@ -58,7 +58,8 @@ export class Clock {
const previousFrameDuration = this._frameDuration;
const fr = +frameRate;
const fps = fr < minValue ? minValue : fr;
- const frameDuration = round(K / fps, 0);
+ const frameDuration = K / fps;
+ if (fps > defaults.frameRate) defaults.frameRate = fps;
this._fps = fps;
this._frameDuration = frameDuration;
this._scheduledTime += frameDuration - previousFrameDuration;
@@ -79,14 +80,13 @@ export class Clock {
*/
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._lastTickTime = time;
+ // If the current 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;
+ if (time < scheduledTime) return tickModes.NONE;
const frameDuration = this._frameDuration;
- const frameDelta = elapsedTime - scheduledTime;
+ const frameDelta = time - 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;
diff --git a/src/core/consts.js b/src/core/consts.js
index 5fed2fd7..63ba17a6 100644
--- a/src/core/consts.js
+++ b/src/core/consts.js
@@ -3,8 +3,10 @@
// TODO: Do we need to check if we're running inside a worker ?
export const isBrowser = typeof window !== 'undefined';
-/** @type {Window & {AnimeJS: Array}|null} */
-export const win = isBrowser ? /** @type {Window & {AnimeJS: Array}} */(/** @type {unknown} */(window)) : null;
+/** @typedef {Window & {AnimeJS: Array} & {AnimeJSDevTools: any}|null} AnimeJSWindow
+
+/** @type {AnimeJSWindow} */
+export const win = isBrowser ? /** @type {AnimeJSWindow} */(/** @type {unknown} */(window)) : null;
/** @type {Document|null} */
export const doc = isBrowser ? document : null;
@@ -56,7 +58,7 @@ export const proxyTargetSymbol = Symbol();
export const minValue = 1e-11;
export const maxValue = 1e12;
export const K = 1e3;
-export const maxFps = 120;
+export const maxFps = 240;
// Strings
diff --git a/src/core/globals.js b/src/core/globals.js
index c9199eb3..a35d7617 100644
--- a/src/core/globals.js
+++ b/src/core/globals.js
@@ -64,6 +64,8 @@ export const globals = {
tickThreshold: 200,
}
+export const devTools = isBrowser && win.AnimeJSDevTools;
+
export const globalVersions = { version: '__packageVersion__', engine: null };
if (isBrowser) {
diff --git a/src/core/styles.js b/src/core/styles.js
index 9c94ce7d..3c82e1e3 100644
--- a/src/core/styles.js
+++ b/src/core/styles.js
@@ -11,7 +11,6 @@ import {
forEachChildren,
isNil,
isSvg,
- isUnd,
toLowerCase,
} from './helpers.js';
diff --git a/src/engine/engine.js b/src/engine/engine.js
index 4bcbe429..be23ef3f 100644
--- a/src/engine/engine.js
+++ b/src/engine/engine.js
@@ -92,7 +92,7 @@ class Engine extends Clock {
wake() {
if (this.useDefaultMainLoop && !this.reqId) {
- // Imediatly request a tick to update engine._elapsedTime and get accurate offsetPosition calculation in timer.js
+ // Imediatly request a tick to update engine._lastTickTime and get accurate offsetPosition calculation in timer.js
this.requestTick(now());
this.reqId = engineTickMethod(tickEngine);
}
diff --git a/src/index.js b/src/index.js
index f331d709..d2fc079a 100644
--- a/src/index.js
+++ b/src/index.js
@@ -7,6 +7,7 @@ export * from './scope/index.js';
export * from './events/index.js';
export * from './engine/index.js';
export * from './easings/index.js';
+export * from './layout/index.js';
export * as easings from './easings/index.js';
export * from './utils/index.js';
export * as utils from './utils/index.js';
diff --git a/src/layout/index.js b/src/layout/index.js
new file mode 100644
index 00000000..23780baf
--- /dev/null
+++ b/src/layout/index.js
@@ -0,0 +1 @@
+export * from './layout.js';
\ No newline at end of file
diff --git a/src/layout/layout.js b/src/layout/layout.js
new file mode 100644
index 00000000..0b6d9353
--- /dev/null
+++ b/src/layout/layout.js
@@ -0,0 +1,1398 @@
+import {
+ isStr,
+ isArr,
+ isUnd,
+ isFnc,
+ isSvg,
+ mergeObjects,
+} from '../core/helpers.js';
+
+import {
+ registerTargets,
+} from '../core/targets.js';
+
+import {
+ getFunctionValue,
+ setValue,
+} from '../core/values.js';
+
+import {
+ noop,
+} from '../core/consts.js';
+
+import {
+ createTimeline,
+} from '../timeline/timeline.js';
+
+import {
+ waapi,
+} from '../waapi/waapi.js';
+
+import {
+ scope,
+} from '../core/globals.js';
+
+/**
+ * @import {
+ * AnimationParams,
+ * } from '../types/index.js'
+*/
+
+/**
+ * @import {
+ * Timeline,
+ * } from '../timeline/timeline.js'
+*/
+
+/**
+ * @import {
+ * WAAPIAnimation
+ * } from '../waapi/waapi.js'
+*/
+
+/**
+ * @import {
+ * DOMTarget,
+ * DOMTargetSelector,
+ * FunctionValue,
+ * EasingParam,
+ * Callback,
+ } from '../types/index.js'
+*/
+
+/**
+ * @typedef {DOMTargetSelector|Array<DOMTargetSelector>} LayoutChildrenParam
+ */
+
+/**
+ * @typedef {Record<String, Number|String>} LayoutStateParams
+ */
+
+/**
+ * @typedef {Object} LayoutAnimationParams
+ * @property {Number} [duration]
+ * @property {Number|FunctionValue} [delay]
+ * @property {EasingParam} [ease]
+ * @property {LayoutStateParams} [frozen]
+ * @property {LayoutStateParams} [added]
+ * @property {LayoutStateParams} [removed]
+ * @property {Callback<AutoLayout>} [onComplete]
+ */
+
+/**
+ * @typedef {LayoutAnimationParams & {
+ * children?: LayoutChildrenParam,
+ * properties?: Array<String>,
+ * }} AutoLayoutParams
+ */
+
+/**
+ * @typedef {Record<String, Number|String> & {
+ * transform: String,
+ * x: Number,
+ * y: Number,
+ * left: Number,
+ * top: Number,
+ * clientLeft: Number,
+ * clientTop: Number,
+ * width: Number,
+ * height: Number,
+ * }} LayoutNodeProperties
+ */
+
+/**
+ * @typedef {Object} LayoutNode
+ * @property {String} id
+ * @property {DOMTarget} $el
+ * @property {Number} index
+ * @property {Number} total
+ * @property {Number} delay
+ * @property {Number} duration
+ * @property {DOMTarget} $measure
+ * @property {LayoutSnapshot} state
+ * @property {AutoLayout} layout
+ * @property {LayoutNode|null} parentNode
+ * @property {Boolean} isTarget
+ * @property {Boolean} hasTransform
+ * @property {Boolean} isAnimated
+ * @property {Array<String>} inlineStyles
+ * @property {String|null} inlineTransforms
+ * @property {String|null} inlineTransition
+ * @property {Boolean} branchAdded
+ * @property {Boolean} branchRemoved
+ * @property {Boolean} branchNotRendered
+ * @property {Boolean} sizeChanged
+ * @property {Boolean} isInlined
+ * @property {Boolean} hasVisibilitySwap
+ * @property {Boolean} hasDisplayNone
+ * @property {Boolean} hasVisibilityHidden
+ * @property {String|null} measuredInlineTransform
+ * @property {String|null} measuredInlineTransition
+ * @property {String|null} measuredDisplay
+ * @property {String|null} measuredVisibility
+ * @property {String|null} measuredPosition
+ * @property {Boolean} measuredHasDisplayNone
+ * @property {Boolean} measuredHasVisibilityHidden
+ * @property {Boolean} measuredIsVisible
+ * @property {Boolean} measuredIsRemoved
+ * @property {Boolean} measuredIsInsideRoot
+ * @property {LayoutNodeProperties} properties
+ * @property {LayoutNode|null} _head
+ * @property {LayoutNode|null} _tail
+ * @property {LayoutNode|null} _prev
+ * @property {LayoutNode|null} _next
+ */
+
+/**
+ * @callback LayoutNodeIterator
+ * @param {LayoutNode} node
+ * @param {Number} index
+ * @return {void}
+ */
+
+let layoutId = 0;
+let nodeId = 0;
+
+/**
+ * @param {DOMTarget} root
+ * @param {DOMTarget} $el
+ * @return {Boolean}
+ */
+const isElementInRoot = (root, $el) => {
+ if (!root || !$el) return false;
+ return root === $el || root.contains($el);
+}
+
+/**
+ * @param {Node} node
+ * @param {'previousSibling'|'nextSibling'} direction
+ * @return {Boolean}
+ */
+const hasTextSibling = (node, direction) => {
+ let sibling = node[direction];
+ while (sibling && sibling.nodeType === Node.TEXT_NODE && !sibling.textContent.trim()) {
+ sibling = sibling[direction];
+ }
+ return sibling && sibling.nodeType === Node.TEXT_NODE;
+}
+
+/**
+ * @param {DOMTarget} $el
+ * @return {Boolean}
+ */
+const isElementSurroundedByText = $el => hasTextSibling($el, 'previousSibling') || hasTextSibling($el, 'nextSibling');
+
+/**
+ * @param {DOMTarget|null} $el
+ * @return {String|null}
+ */
+const muteElementTransition = $el => {
+ if (!$el) return null;
+ const style = $el.style;
+ const transition = style.transition || '';
+ style.setProperty('transition', 'none', 'important');
+ return transition;
+}
+
+/**
+ * @param {DOMTarget|null} $el
+ * @param {String|null} transition
+ */
+const restoreElementTransition = ($el, transition) => {
+ if (!$el) return;
+ const style = $el.style;
+ if (transition) {
+ style.transition = transition;
+ } else {
+ style.removeProperty('transition');
+ }
+}
+
+/**
+ * @param {LayoutNode} node
+ */
+const muteNodeTransition = node => {
+ const store = node.layout.transitionMuteStore;
+ const $el = node.$el;
+ const $measure = node.$measure;
+ if ($el && !store.has($el)) store.set($el, muteElementTransition($el));
+ if ($measure && !store.has($measure)) store.set($measure, muteElementTransition($measure));
+}
+
+/**
+ * @param {Map<DOMTarget, String|null>} store
+ */
+const restoreLayoutTransition = store => {
+ store.forEach((value, $el) => restoreElementTransition($el, value));
+ store.clear();
+}
+
+const hiddenComputedStyle = /** @type {CSSStyleDeclaration} */({
+ display: 'none',
+ visibility: 'hidden',
+ opacity: '0',
+ transform: 'none',
+ position: 'static',
+});
+
+/**
+ * @param {LayoutNode|null} node
+ */
+const detachNode = node => {
+ if (!node) return;
+ const parent = node.parentNode;
+ if (!parent) return;
+ if (parent._head === node) parent._head = node._next;
+ if (parent._tail === node) parent._tail = node._prev;
+ if (node._prev) node._prev._next = node._next;
+ if (node._next) node._next._prev = node._prev;
+ node._prev = null;
+ node._next = null;
+ node.parentNode = null;
+}
+
+/**
+ * @param {DOMTarget} $el
+ * @param {LayoutNode|null} parentNode
+ * @param {LayoutSnapshot} state
+ * @param {LayoutNode} [recycledNode]
+ * @return {LayoutNode}
+ */
+const createNode = ($el, parentNode, state, recycledNode) => {
+ let dataId = $el.dataset.layoutId;
+ if (!dataId) dataId = $el.dataset.layoutId = `node-${nodeId++}`;
+ const node = recycledNode ? recycledNode : /** @type {LayoutNode} */({});
+ node.$el = $el;
+ node.$measure = $el;
+ node.id = dataId;
+ node.index = 0;
+ node.total = 1;
+ node.delay = 0;
+ node.duration = 0;
+ node.state = state;
+ node.layout = state.layout;
+ node.parentNode = parentNode || null;
+ node.isTarget = false;
+ node.hasTransform = false;
+ node.isAnimated = false;
+ node.inlineStyles = [];
+ node.inlineTransforms = null;
+ node.inlineTransition = null;
+ node.branchAdded = false;
+ node.branchRemoved = false;
+ node.branchNotRendered = false;
+ node.sizeChanged = false;
+ node.isInlined = false;
+ node.hasVisibilitySwap = false;
+ node.hasDisplayNone = false;
+ node.hasVisibilityHidden = false;
+ node.measuredInlineTransform = null;
+ node.measuredInlineTransition = null;
+ node.measuredDisplay = null;
+ node.measuredVisibility = null;
+ node.measuredPosition = null;
+ node.measuredHasDisplayNone = false;
+ node.measuredHasVisibilityHidden = false;
+ node.measuredIsVisible = false;
+ node.measuredIsRemoved = false;
+ node.measuredIsInsideRoot = false;
+ node.properties = /** @type {LayoutNodeProperties} */({
+ transform: 'none',
+ x: 0,
+ y: 0,
+ left: 0,
+ top: 0,
+ clientLeft: 0,
+ clientTop: 0,
+ width: 0,
+ height: 0,
+ });
+ node.layout.properties.forEach(prop => node.properties[prop] = 0);
+ node._head = null;
+ node._tail = null;
+ node._prev = null;
+ node._next = null;
+ return node;
+}
+
+/**
+ * @param {LayoutNode} node
+ * @param {DOMTarget} $measure
+ * @param {CSSStyleDeclaration} computedStyle
+ * @param {Boolean} skipMeasurements
+ * @return {LayoutNode}
+ */
+const recordNodeState = (node, $measure, computedStyle, skipMeasurements) => {
+ const $el = node.$el;
+ const root = node.layout.root;
+ const isRoot = root === $el;
+ const properties = node.properties;
+ const rootNode = node.state.rootNode;
+ const parentNode = node.parentNode;
+ const computedTransforms = computedStyle.transform;
+ const inlineTransforms = $el.style.transform;
+ const parentNotRendered = parentNode ? parentNode.measuredIsRemoved : false;
+ const position = computedStyle.position;
+ if (isRoot) node.layout.absoluteCoords = position === 'fixed' || position === 'absolute';
+ node.$measure = $measure;
+ node.inlineTransforms = inlineTransforms;
+ node.hasTransform = computedTransforms && computedTransforms !== 'none';
+ node.measuredIsInsideRoot = isElementInRoot(root, $measure);
+ node.measuredInlineTransform = null;
+ node.measuredDisplay = computedStyle.display;
+ node.measuredVisibility = computedStyle.visibility;
+ node.measuredPosition = position;
+ node.measuredHasDisplayNone = computedStyle.display === 'none';
+ node.measuredHasVisibilityHidden = computedStyle.visibility === 'hidden';
+ node.measuredIsVisible = !(node.measuredHasDisplayNone || node.measuredHasVisibilityHidden);
+ node.measuredIsRemoved = node.measuredHasDisplayNone || node.measuredHasVisibilityHidden || parentNotRendered;
+ node.isInlined = node.measuredDisplay.includes('inline') && isElementSurroundedByText($el);
+
+ // Mute transforms (and transition to avoid triggering an animation) before the position calculation
+ if (node.hasTransform && !skipMeasurements) {
+ const transitionMuteStore = node.layout.transitionMuteStore;
+ if (!transitionMuteStore.get($el)) node.inlineTransition = muteElementTransition($el);
+ if ($measure === $el) {
+ $el.style.transform = 'none';
+ } else {
+ if (!transitionMuteStore.get($measure)) node.measuredInlineTransition = muteElementTransition($measure);
+ node.measuredInlineTransform = $measure.style.transform;
+ $measure.style.transform = 'none';
+ }
+ }
+
+ let left = 0;
+ let top = 0;
+ let width = 0;
+ let height = 0;
+
+ if (!skipMeasurements) {
+ const rect = $measure.getBoundingClientRect();
+ left = rect.left;
+ top = rect.top;
+ width = rect.width;
+ height = rect.height;
+ }
+
+ for (let name in properties) {
+ const computedProp = name === 'transform' ? computedTransforms : computedStyle[name] || (computedStyle.getPropertyValue && computedStyle.getPropertyValue(name));
+ if (!isUnd(computedProp)) properties[name] = computedProp;
+ }
+
+ properties.left = left;
+ properties.top = top;
+ properties.clientLeft = skipMeasurements ? 0 : $measure.clientLeft;
+ properties.clientTop = skipMeasurements ? 0 : $measure.clientTop;
+ // Compute local x/y relative to parent
+ let absoluteLeft, absoluteTop;
+ if (isRoot) {
+ if (!node.layout.absoluteCoords) {
+ absoluteLeft = 0;
+ absoluteTop = 0;
+ } else {
+ absoluteLeft = left;
+ absoluteTop = top;
+ }
+ } else {
+ const p = parentNode || rootNode;
+ const parentLeft = p.properties.left;
+ const parentTop = p.properties.top;
+ const borderLeft = p.properties.clientLeft;
+ const borderTop = p.properties.clientTop;
+ if (!node.layout.absoluteCoords) {
+ if (p === rootNode) {
+ const rootLeft = rootNode.properties.left;
+ const rootTop = rootNode.properties.top;
+ const rootBorderLeft = rootNode.properties.clientLeft;
+ const rootBorderTop = rootNode.properties.clientTop;
+ absoluteLeft = left - rootLeft - rootBorderLeft;
+ absoluteTop = top - rootTop - rootBorderTop;
+ } else {
+ absoluteLeft = left - parentLeft - borderLeft;
+ absoluteTop = top - parentTop - borderTop;
+ }
+ } else {
+ absoluteLeft = left - parentLeft - borderLeft;
+ absoluteTop = top - parentTop - borderTop;
+ }
+ }
+ properties.x = absoluteLeft;
+ properties.y = absoluteTop;
+ properties.width = width;
+ properties.height = height;
+ return node;
+}
+
+/**
+ * @param {LayoutNode} node
+ * @param {LayoutStateParams} [props]
+ */
+const updateNodeProperties = (node, props) => {
+ if (!props) return;
+ for (let name in props) {
+ node.properties[name] = props[name];
+ }
+}
+
+/**
+ * @param {LayoutNode} node
+ */
+const recordNodeInlineStyles = node => {
+ const style = node.$el.style;
+ const stylesStore = node.inlineStyles;
+ stylesStore.length = 0;
+ node.layout.recordedProperties.forEach(prop => {
+ stylesStore.push(prop, style[prop] || '');
+ });
+}
+
+/**
+ * @param {LayoutNode} node
+ */
+const restoreNodeInlineStyles = node => {
+ const style = node.$el.style;
+ const stylesStore = node.inlineStyles;
+ for (let i = 0, l = stylesStore.length; i < l; i += 2) {
+ const property = stylesStore[i];
+ const styleValue = stylesStore[i + 1];
+ if (styleValue && styleValue !== '') {
+ style[property] = styleValue;
+ } else {
+ style[property] = '';
+ style.removeProperty(property);
+ }
+ }
+}
+
+/**
+ * @param {LayoutNode} node
+ */
+const restoreNodeTransform = node => {
+ const inlineTransforms = node.inlineTransforms;
+ const nodeStyle = node.$el.style;
+ if (!node.hasTransform || !inlineTransforms || (node.hasTransform && nodeStyle.transform === 'none') || (inlineTransforms && inlineTransforms === 'none')) {
+ nodeStyle.removeProperty('transform');
+ } else if (inlineTransforms) {
+ nodeStyle.transform = inlineTransforms;
+ }
+ const $measure = node.$measure;
+ if (node.hasTransform && $measure !== node.$el) {
+ const measuredStyle = $measure.style;
+ const measuredInline = node.measuredInlineTransform;
+ if (measuredInline && measuredInline !== '') {
+ measuredStyle.transform = measuredInline;
+ } else {
+ measuredStyle.removeProperty('transform');
+ }
+ }
+ node.measuredInlineTransform = null;
+ if (node.inlineTransition !== null) {
+ restoreElementTransition(node.$el, node.inlineTransition);
+ node.inlineTransition = null;
+ }
+ if ($measure !== node.$el && node.measuredInlineTransition !== null) {
+ restoreElementTransition($measure, node.measuredInlineTransition);
+ node.measuredInlineTransition = null;
+ }
+}
+
+/**
+ * @param {LayoutNode} node
+ */
+const restoreNodeVisualState = node => {
+ if (node.measuredIsRemoved || node.hasVisibilitySwap) {
+ node.$el.style.removeProperty('display');
+ node.$el.style.removeProperty('visibility');
+ if (node.hasVisibilitySwap) {
+ node.$measure.style.removeProperty('display');
+ node.$measure.style.removeProperty('visibility');
+ }
+ }
+ if (node.measuredIsRemoved) {
+ node.layout.pendingRemoved.delete(node.$el);
+ }
+}
+
+/**
+ * @param {LayoutNode} node
+ * @param {LayoutNode} targetNode
+ * @param {LayoutSnapshot} newState
+ * @return {LayoutNode}
+ */
+const cloneNodeProperties = (node, targetNode, newState) => {
+ targetNode.properties = /** @type {LayoutNodeProperties} */({ ...node.properties });
+ targetNode.state = newState;
+ targetNode.isTarget = node.isTarget;
+ targetNode.hasTransform = node.hasTransform;
+ targetNode.inlineTransforms = node.inlineTransforms;
+ targetNode.measuredIsVisible = node.measuredIsVisible;
+ targetNode.measuredDisplay = node.measuredDisplay;
+ targetNode.measuredIsRemoved = node.measuredIsRemoved;
+ targetNode.measuredHasDisplayNone = node.measuredHasDisplayNone;
+ targetNode.measuredHasVisibilityHidden = node.measuredHasVisibilityHidden;
+ targetNode.hasDisplayNone = node.hasDisplayNone;
+ targetNode.isInlined = node.isInlined;
+ targetNode.hasVisibilityHidden = node.hasVisibilityHidden;
+ return targetNode;
+}
+
+class LayoutSnapshot {
+ /**
+ * @param {AutoLayout} layout
+ */
+ constructor(layout) {
+ /** @type {AutoLayout} */
+ this.layout = layout;
+ /** @type {LayoutNode|null} */
+ this.rootNode = null;
+ /** @type {Set<LayoutNode>} */
+ this.rootNodes = new Set();
+ /** @type {Map<String, LayoutNode>} */
+ this.nodes = new Map();
+ /** @type {Number} */
+ this.scrollX = 0;
+ /** @type {Number} */
+ this.scrollY = 0;
+ }
+
+ /**
+ * @return {this}
+ */
+ revert() {
+ this.forEachNode(node => {
+ node.$el.removeAttribute('data-layout-id');
+ node.$measure.removeAttribute('data-layout-id');
+ });
+ this.rootNode = null;
+ this.rootNodes.clear();
+ this.nodes.clear();
+ return this;
+ }
+
+ /**
+ * @param {DOMTarget} $el
+ * @return {LayoutNodeProperties|undefined}
+ */
+ get($el) {
+ const node = this.nodes.get($el.dataset.layoutId);
+ if (!node) {
+ console.warn(`No node found on state`);
+ return;
+ }
+ return node.properties;
+ }
+
+ /**
+ * @param {DOMTarget} $el
+ * @param {String} prop
+ * @return {Number|String|undefined}
+ */
+ getValue($el, prop) {
+ if (!$el || !$el.dataset) {
+ console.warn(`No element found on state (${$el})`);
+ return;
+ }
+ const node = this.nodes.get($el.dataset.layoutId);
+ if (!node) {
+ console.warn(`No node found on state`);
+ return;
+ }
+ const value = node.properties[prop];
+ if (!isUnd(value)) return getFunctionValue(value, $el, node.index, node.total);
+ }
+
+ /**
+ * @param {LayoutNode|null} rootNode
+ * @param {LayoutNodeIterator} cb
+ */
+ forEach(rootNode, cb) {
+ let node = rootNode;
+ let i = 0;
+ while (node) {
+ cb(node, i++);
+ if (node._head) {
+ node = node._head;
+ } else if (node._next) {
+ node = node._next;
+ } else {
+ while (node && !node._next) {
+ node = node.parentNode;
+ }
+ if (node) node = node._next;
+ }
+ }
+ }
+
+ /**
+ * @param {LayoutNodeIterator} cb
+ */
+ forEachRootNode(cb) {
+ this.forEach(this.rootNode, cb);
+ }
+
+ /**
+ * @param {LayoutNodeIterator} cb
+ */
+ forEachNode(cb) {
+ for (const rootNode of this.rootNodes) {
+ this.forEach(rootNode, cb);
+ }
+ }
+
+ /**
+ * @param {DOMTarget} $el
+ * @param {LayoutNode|null} parentNode
+ * @return {LayoutNode|null}
+ */
+ registerElement($el, parentNode) {
+ if (!$el || $el.nodeType !== 1) return null;
+
+ if (!this.layout.transitionMuteStore.has($el)) this.layout.transitionMuteStore.set($el, muteElementTransition($el));
+
+ /** @type {Array<DOMTarget|LayoutNode|null>} */
+ const stack = [$el, parentNode];
+ const root = this.layout.root;
+ let firstNode = null;
+
+ while (stack.length) {
+ /** @type {LayoutNode|null} */
+ const $parent = /** @type {LayoutNode|null} */(stack.pop());
+ /** @type {DOMTarget|null} */
+ const $current = /** @type {DOMTarget|null} */(stack.pop());
+ if (!$current || $current.nodeType !== 1 || isSvg($current)) continue;
+
+ const skipMeasurements = $parent ? $parent.measuredIsRemoved : false;
+
+ const computedStyle = skipMeasurements ? hiddenComputedStyle : getComputedStyle($current);
+ const hasDisplayNone = skipMeasurements ? true : computedStyle.display === 'none';
+ const hasVisibilityHidden = skipMeasurements ? true : computedStyle.visibility === 'hidden';
+ const isVisible = !hasDisplayNone && !hasVisibilityHidden;
+ const existingId = $current.dataset.layoutId;
+ const isInsideRoot = isElementInRoot(root, $current);
+
+ let node = existingId ? this.nodes.get(existingId) : null;
+
+ if (node && node.$el !== $current) {
+ const nodeInsideRoot = isElementInRoot(root, node.$el);
+ const measuredVisible = node.measuredIsVisible;
+ const shouldReassignNode = !nodeInsideRoot && (isInsideRoot || (!isInsideRoot && !measuredVisible && isVisible));
+ const shouldReuseMeasurements = nodeInsideRoot && !measuredVisible && isVisible;
+ // Rebind nodes that move into the root or whose detached twin just became visible
+ if (shouldReassignNode) {
+ detachNode(node);
+ node = createNode($current, $parent, this, node);
+ // for hidden element with in-root sibling, keep the hidden node but borrow measurements from its visible in-root twin element
+ } else if (shouldReuseMeasurements) {
+ recordNodeState(node, $current, computedStyle, skipMeasurements);
+ let $child = $current.lastElementChild;
+ while ($child) {
+ stack.push(/** @type {DOMTarget} */($child), node);
+ $child = $child.previousElementSibling;
+ }
+ if (!firstNode) firstNode = node;
+ continue;
+ // No reassignment needed so keep walking descendants under the current parent
+ } else {
+ let $child = $current.lastElementChild;
+ while ($child) {
+ stack.push(/** @type {DOMTarget} */($child), $parent);
+ $child = $child.previousElementSibling;
+ }
+ if (!firstNode) firstNode = node;
+ continue;
+ }
+ } else {
+ node = createNode($current, $parent, this, node);
+ }
+
+ node.branchAdded = false;
+ node.branchRemoved = false;
+ node.branchNotRendered = false;
+ node.isTarget = false;
+ node.isAnimated = false;
+ node.hasVisibilityHidden = hasVisibilityHidden;
+ node.hasDisplayNone = hasDisplayNone;
+ node.hasVisibilitySwap = (hasVisibilityHidden && !node.measuredHasVisibilityHidden) || (hasDisplayNone && !node.measuredHasDisplayNone);
+ // node.hasVisibilitySwap = (hasVisibilityHidden !== node.measuredHasVisibilityHidden) || (hasDisplayNone !== node.measuredHasDisplayNone);
+
+ this.nodes.set(node.id, node);
+
+ node.parentNode = $parent || null;
+ node._prev = null;
+ node._next = null;
+
+ if ($parent) {
+ this.rootNodes.delete(node);
+ if (!$parent._head) {
+ $parent._head = node;
+ $parent._tail = node;
+ } else {
+ $parent._tail._next = node;
+ node._prev = $parent._tail;
+ $parent._tail = node;
+ }
+ } else {
+ this.rootNodes.add(node);
+ }
+
+ recordNodeState(node, node.$el, computedStyle, skipMeasurements);
+
+ let $child = $current.lastElementChild;
+ while ($child) {
+ stack.push(/** @type {DOMTarget} */($child), node);
+ $child = $child.previousElementSibling;
+ }
+
+ if (!firstNode) firstNode = node;
+ }
+
+ return firstNode;
+ }
+
+ /**
+ * @param {DOMTarget} $el
+ * @param {Set<DOMTarget>} candidates
+ * @return {LayoutNode|null}
+ */
+ ensureDetachedNode($el, candidates) {
+ if (!$el || $el === this.layout.root) return null;
+ const existingId = $el.dataset.layoutId;
+ const existingNode = existingId ? this.nodes.get(existingId) : null;
+ if (existingNode && existingNode.$el === $el) return existingNode;
+ let parentNode = null;
+ let $ancestor = $el.parentElement;
+ while ($ancestor && $ancestor !== this.layout.root) {
+ if (candidates.has($ancestor)) {
+ parentNode = this.ensureDetachedNode($ancestor, candidates);
+ break;
+ }
+ $ancestor = $ancestor.parentElement;
+ }
+ return this.registerElement($el, parentNode);
+ }
+
+ /**
+ * @return {this}
+ */
+ record() {
+ const { children, root } = this.layout;
+ const toParse = isArr(children) ? children : [children];
+ const scoped = [];
+ const scopeRoot = children === '*' ? root : scope.root;
+
+ for (let i = 0, l = toParse.length; i < l; i++) {
+ const child = toParse[i];
+ scoped[i] = isStr(child) ? scopeRoot.querySelectorAll(child) : child;
+ }
+
+ const parsedChildren = registerTargets(scoped);
+
+ this.nodes.clear();
+ this.rootNodes.clear();
+
+ const rootNode = this.registerElement(root, null);
+ // Root node are always targets
+ rootNode.isTarget = true;
+ this.rootNode = rootNode;
+
+ // Track ids of nodes that belong to the current root to filter detached matches
+ const inRootNodeIds = new Set();
+ this.nodes.forEach((node, id) => {
+ if (node && node.measuredIsInsideRoot) {
+ inRootNodeIds.add(id);
+ }
+ });
+
+ // Elements with a layout id outside the root that match the children selector
+ const detachedElementsLookup = new Set();
+ const orderedDetachedElements = [];
+
+ for (let i = 0, l = parsedChildren.length; i < l; i++) {
+ const $el = parsedChildren[i];
+ if (!$el || $el.nodeType !== 1 || $el === root) continue;
+ const insideRoot = isElementInRoot(root, $el);
+ if (!insideRoot) {
+ const layoutNodeId = $el.dataset.layoutId;
+ if (!layoutNodeId || !inRootNodeIds.has(layoutNodeId)) continue;
+ }
+ if (!detachedElementsLookup.has($el)) {
+ detachedElementsLookup.add($el);
+ orderedDetachedElements.push($el);
+ }
+ }
+
+ for (let i = 0, l = orderedDetachedElements.length; i < l; i++) {
+ this.ensureDetachedNode(orderedDetachedElements[i], detachedElementsLookup);
+ }
+
+ for (let i = 0, l = parsedChildren.length; i < l; i++) {
+ const $el = parsedChildren[i];
+ const node = this.nodes.get($el.dataset.layoutId);
+ if (node) {
+ let cur = node;
+ while (cur) {
+ if (cur.isTarget) break;
+ cur.isTarget = true;
+ cur = cur.parentNode;
+ }
+ }
+ }
+
+ this.scrollX = window.scrollX;
+ this.scrollY = window.scrollY;
+
+ const total = this.nodes.size;
+
+ this.forEachNode(restoreNodeTransform);
+ this.forEachNode((node, i) => {
+ node.index = i;
+ node.total = total;
+ });
+
+ return this;
+ }
+}
+
+export class AutoLayout {
+ /**
+ * @param {DOMTargetSelector} root
+ * @param {AutoLayoutParams} [params]
+ */
+ constructor(root, params = {}) {
+ if (scope.current) scope.current.register(this);
+ const frozenParams = params.frozen;
+ const addedParams = params.added;
+ const removedParams = params.removed;
+ const propsParams = params.properties;
+ /** @type {AutoLayoutParams} */
+ this.params = params;
+ /** @type {DOMTarget} */
+ this.root = /** @type {DOMTarget} */(registerTargets(root)[0]);
+ /** @type {Number} */
+ this.id = layoutId++;
+ /** @type {LayoutChildrenParam} */
+ this.children = params.children || '*';
+ /** @type {Boolean} */
+ this.absoluteCoords = false;
+ /** @type {Number} */
+ this.duration = setValue(params.duration, 500);
+ /** @type {Number|FunctionValue} */
+ this.delay = setValue(params.delay, 0);
+ /** @type {EasingParam} */
+ this.ease = setValue(params.ease, 'inOutExpo');
+ /** @type {Callback<this>} */
+ this.onComplete = setValue(params.onComplete, /** @type {Callback<this>} */(noop));
+ /** @type {LayoutStateParams} */
+ this.frozenParams = frozenParams || { opacity: 0 };
+ /** @type {LayoutStateParams} */
+ this.addedParams = addedParams || { opacity: 0 };
+ /** @type {LayoutStateParams} */
+ this.removedParams = removedParams || { opacity: 0 };
+ /** @type {Set<String>} */
+ this.properties = new Set([
+ 'opacity',
+ 'borderRadius',
+ ]);
+ if (frozenParams) for (let name in frozenParams) this.properties.add(name);
+ if (addedParams) for (let name in addedParams) this.properties.add(name);
+ if (removedParams) for (let name in removedParams) this.properties.add(name);
+ if (propsParams) for (let i = 0, l = propsParams.length; i < l; i++) this.properties.add(propsParams[i]);
+ /** @type {Set<String>} */
+ this.recordedProperties = new Set([
+ 'display',
+ 'visibility',
+ 'translate',
+ 'position',
+ 'left',
+ 'top',
+ 'marginLeft',
+ 'marginTop',
+ 'width',
+ 'height',
+ 'maxWidth',
+ 'maxHeight',
+ 'minWidth',
+ 'minHeight',
+ ]);
+ this.properties.forEach(prop => this.recordedProperties.add(prop));
+ /** @type {WeakSet<DOMTarget>} */
+ this.pendingRemoved = new WeakSet();
+ /** @type {Map<DOMTarget, String|null>} */
+ this.transitionMuteStore = new Map();
+ /** @type {LayoutSnapshot} */
+ this.oldState = new LayoutSnapshot(this);
+ /** @type {LayoutSnapshot} */
+ this.newState = new LayoutSnapshot(this);
+ /** @type {Timeline|null} */
+ this.timeline = null;
+ /** @type {WAAPIAnimation|null} */
+ this.transformAnimation = null;
+ /** @type {Array<DOMTarget>} */
+ this.frozen = [];
+ /** @type {Array<DOMTarget>} */
+ this.removed = [];
+ /** @type {Array<DOMTarget>} */
+ this.added = [];
+ // Record the current state as the old state to init the data attributes
+ this.oldState.record();
+ // And all layout transition muted during the record
+ restoreLayoutTransition(this.transitionMuteStore);
+ }
+
+ /**
+ * @return {this}
+ */
+ revert() {
+ if (this.timeline) {
+ this.timeline.complete();
+ this.timeline = null;
+ }
+ if (this.transformAnimation) {
+ this.transformAnimation.complete();
+ this.transformAnimation = null;
+ }
+ this.root.classList.remove('is-animated');
+ this.frozen.length = this.removed.length = this.added.length = 0;
+ this.oldState.revert();
+ this.newState.revert();
+ requestAnimationFrame(() => restoreLayoutTransition(this.transitionMuteStore));
+ return this;
+ }
+
+ /**
+ * @return {this}
+ */
+ record() {
+ // Commit transforms before measuring
+ if (this.transformAnimation) {
+ this.transformAnimation.cancel();
+ this.transformAnimation = null;
+ }
+ // Record the old state
+ this.oldState.record();
+ // Cancel any running timeline
+ if (this.timeline) {
+ this.timeline.cancel();
+ this.timeline = null;
+ }
+ // Restore previously captured inline styles
+ this.newState.forEachRootNode(restoreNodeInlineStyles);
+ return this;
+ }
+
+ /**
+ * @param {LayoutAnimationParams} [params]
+ * @return {Timeline}
+ */
+ animate(params = {}) {
+ const delay = setValue(params.delay, this.delay);
+ const duration = setValue(params.duration, this.duration);
+ const onComplete = setValue(params.onComplete, this.onComplete);
+ const frozenParams = params.frozen ? mergeObjects(params.frozen, this.frozenParams) : this.frozenParams;
+ const addedParams = params.added ? mergeObjects(params.added, this.addedParams) : this.addedParams;
+ const removedParams = params.removed ? mergeObjects(params.removed, this.removedParams) : this.removedParams;
+ const oldState = this.oldState;
+ const newState = this.newState;
+ const added = this.added;
+ const removed = this.removed;
+ const frozen = this.frozen;
+ const pendingRemoved = this.pendingRemoved;
+
+ added.length = removed.length = frozen.length = 0;
+
+ // Mute old state CSS transitions to prevent wrong properties calculation
+ oldState.forEachRootNode(muteNodeTransition);
+ // Capture the new state before animation
+ newState.record();
+ newState.forEachRootNode(recordNodeInlineStyles);
+
+ const targets = [];
+ const animated = [];
+ const transformed = [];
+ const animatedFrozen = [];
+ const root = newState.rootNode.$el;
+
+ newState.forEachRootNode(node => {
+ const $el = node.$el;
+ const id = node.id;
+ const parent = node.parentNode;
+ const parentAdded = parent ? parent.branchAdded : false;
+ const parentRemoved = parent ? parent.branchRemoved : false;
+ const parentNotRendered = parent ? parent.branchNotRendered : false;
+
+ // Delay and duration must be calculated in the animate() call to support delay override
+ node.delay = +(isFnc(delay) ? delay($el, node.index, node.total) : delay);
+ node.duration = +(isFnc(duration) ? duration($el, node.index, node.total) : duration);
+
+ let oldStateNode = oldState.nodes.get(id);
+
+ const hasNoOldState = !oldStateNode;
+
+ if (hasNoOldState) {
+ oldStateNode = cloneNodeProperties(node, /** @type {LayoutNode} */({}), oldState);
+ oldState.nodes.set(id, oldStateNode);
+ oldStateNode.measuredIsRemoved = true;
+ } else if (oldStateNode.measuredIsRemoved && !node.measuredIsRemoved) {
+ cloneNodeProperties(node, oldStateNode, oldState);
+ oldStateNode.measuredIsRemoved = true;
+ }
+
+ const oldParentNode = oldStateNode.parentNode;
+ const oldParentId = oldParentNode ? oldParentNode.id : null;
+ const newParentId = parent ? parent.id : null;
+ const parentChanged = oldParentId !== newParentId;
+ const elementChanged = oldStateNode.$el !== node.$el;
+ const wasRemovedBefore = oldStateNode.measuredIsRemoved;
+ const isRemovedNow = node.measuredIsRemoved;
+
+ // Recalculate postion relative to their parent for elements that have been moved
+ if (!oldStateNode.measuredIsRemoved && !isRemovedNow && !hasNoOldState && (parentChanged || elementChanged)) {
+ let offsetX = 0;
+ let offsetY = 0;
+ let current = node.parentNode;
+ while (current) {
+ offsetX += current.properties.x || 0;
+ offsetY += current.properties.y || 0;
+ if (current.parentNode === newState.rootNode) break;
+ current = current.parentNode;
+ }
+ let oldOffsetX = 0;
+ let oldOffsetY = 0;
+ let oldCurrent = oldStateNode.parentNode;
+ while (oldCurrent) {
+ oldOffsetX += oldCurrent.properties.x || 0;
+ oldOffsetY += oldCurrent.properties.y || 0;
+ if (oldCurrent.parentNode === oldState.rootNode) break;
+ oldCurrent = oldCurrent.parentNode;
+ }
+ oldStateNode.properties.x += oldOffsetX - offsetX;
+ oldStateNode.properties.y += oldOffsetY - offsetY;
+ }
+
+ if (node.hasVisibilitySwap) {
+ if (node.hasVisibilityHidden) {
+ node.$el.style.visibility = 'visible';
+ node.$measure.style.visibility = 'hidden';
+ }
+ if (node.hasDisplayNone) {
+ node.$el.style.display = oldStateNode.measuredDisplay || node.measuredDisplay || '';
+ // Setting visibility 'hidden' instead of display none to avoid calculation issues
+ node.$measure.style.visibility = 'hidden';
+ // @TODO: check why setting display here can cause calculation issues
+ // node.$measure.style.display = 'none';
+ }
+ }
+
+ const wasPendingRemoval = pendingRemoved.has($el);
+ const wasVisibleBefore = oldStateNode.measuredIsVisible;
+ const isVisibleNow = node.measuredIsVisible;
+ const becomeVisible = !wasVisibleBefore && isVisibleNow && !parentNotRendered;
+ const topLevelAdded = !isRemovedNow && (wasRemovedBefore || wasPendingRemoval) && !parentAdded;
+ const newlyRemoved = isRemovedNow && !wasRemovedBefore && !parentRemoved;
+ const topLevelRemoved = newlyRemoved || isRemovedNow && wasPendingRemoval && !parentRemoved;
+
+ if (node.measuredIsRemoved && wasVisibleBefore) {
+ node.$el.style.display = oldStateNode.measuredDisplay;
+ node.$el.style.visibility = 'visible';
+ cloneNodeProperties(oldStateNode, node, newState);
+ }
+
+ if (newlyRemoved) {
+ removed.push($el);
+ pendingRemoved.add($el);
+ } else if (!isRemovedNow && wasPendingRemoval) {
+ pendingRemoved.delete($el);
+ }
+
+ // Node is added
+ if ((topLevelAdded && !parentNotRendered) || becomeVisible) {
+ updateNodeProperties(oldStateNode, addedParams);
+ added.push($el);
+ // Node is removed
+ } else if (topLevelRemoved && !parentNotRendered) {
+ updateNodeProperties(node, removedParams);
+ }
+
+ // Compute function based propety values before cheking for changes
+ for (let name in node.properties) {
+ node.properties[name] = newState.getValue(node.$el, name);
+ // NOTE: I'm using node.$el to get the value of old state, make sure this is valid instead of oldStateNode.$el
+ oldStateNode.properties[name] = oldState.getValue(node.$el, name);
+ }
+
+ const hiddenStateChanged = (topLevelAdded || newlyRemoved) && wasRemovedBefore !== isRemovedNow;
+ let propertyChanged = false;
+
+
+ if (node.isTarget && (!node.measuredIsRemoved && wasVisibleBefore || node.measuredIsRemoved && isVisibleNow)) {
+ if (!node.isInlined && (node.properties.transform !== 'none' || oldStateNode.properties.transform !== 'none')) {
+ node.hasTransform = true;
+ propertyChanged = true;
+ transformed.push($el);
+ }
+ for (let name in node.properties) {
+ if (name !== 'transform' && (node.properties[name] !== oldStateNode.properties[name] || hiddenStateChanged)) {
+ propertyChanged = true;
+ animated.push($el);
+ break;
+ }
+ }
+ }
+
+ const nodeHasChanged = (propertyChanged || topLevelAdded || topLevelRemoved || becomeVisible);
+ const nodeIsAnimated = node.isTarget && nodeHasChanged;
+
+ node.isAnimated = nodeIsAnimated;
+ node.branchAdded = parentAdded || topLevelAdded;
+ node.branchRemoved = parentRemoved || topLevelRemoved;
+ node.branchNotRendered = parentNotRendered || node.measuredIsRemoved;
+
+ const sizeTolerance = 1;
+ const widthChanged = Math.abs(node.properties.width - oldStateNode.properties.width) > sizeTolerance;
+ const heightChanged = Math.abs(node.properties.height - oldStateNode.properties.height) > sizeTolerance;
+
+ node.sizeChanged = (widthChanged || heightChanged);
+
+ targets.push($el);
+
+ if (!node.isTarget) {
+ frozen.push($el);
+ if ((nodeHasChanged || node.sizeChanged) && parent && parent.isTarget && parent.isAnimated && parent.sizeChanged) {
+ animatedFrozen.push($el);
+ }
+ }
+ });
+
+ const defaults = {
+ ease: setValue(params.ease, this.ease),
+ duration: (/** @type {HTMLElement} */$el) => newState.nodes.get($el.dataset.layoutId).duration,
+ delay: (/** @type {HTMLElement} */$el) => newState.nodes.get($el.dataset.layoutId).delay,
+ }
+
+ this.timeline = createTimeline({
+ onComplete: () => {
+ // Make sure to call .cancel() after restoreNodeInlineStyles(node); otehrwise the commited styles get reverted
+ if (this.transformAnimation) this.transformAnimation.cancel();
+ newState.forEachRootNode(node => {
+ restoreNodeVisualState(node);
+ restoreNodeInlineStyles(node);
+ });
+ for (let i = 0, l = transformed.length; i < l; i++) {
+ const $el = transformed[i];
+ $el.style.transform = newState.getValue($el, 'transform');
+ }
+ this.root.classList.remove('is-animated');
+ if (onComplete) onComplete(this);
+ // Avoid CSS transitions at the end of the animation by restoring them on the next frame
+ requestAnimationFrame(() => {
+ if (this.root.classList.contains('is-animated')) return;
+ restoreLayoutTransition(this.transitionMuteStore);
+ });
+ },
+ onPause: () => {
+ if (this.transformAnimation) this.transformAnimation.cancel();
+ newState.forEachRootNode(restoreNodeVisualState);
+ this.root.classList.remove('is-animated');
+ if (onComplete) onComplete(this);
+ },
+ composition: false,
+ defaults,
+ });
+
+ if (targets.length) {
+
+ this.root.classList.add('is-animated');
+
+ for (let i = 0, l = targets.length; i < l; i++) {
+ const $el = targets[i];
+ const id = $el.dataset.layoutId;
+ const oldNode = oldState.nodes.get(id);
+ const newNode = newState.nodes.get(id);
+ const oldNodeState = oldNode.properties;
+
+ // Make sure to mute all CSS transition before applying the oldState styles back
+ muteNodeTransition(newNode);
+
+ // Don't animate dimensions and positions of inlined elements
+ if (!newNode.isInlined) {
+ // Display grid can mess with the absolute positioning, so set it to block during transition
+ // if (oldNode.measuredDisplay === 'grid' || newNode.measuredDisplay === 'grid') $el.style.display = 'block';
+ $el.style.display = 'block';
+ // All children must be in position absolue
+ if ($el !== root || this.absoluteCoords) {
+ $el.style.position = this.absoluteCoords ? 'fixed' : 'absolute';
+ $el.style.left = '0px';
+ $el.style.top = '0px';
+ $el.style.marginLeft = '0px';
+ $el.style.marginTop = '0px';
+ $el.style.translate = `${oldNodeState.x}px ${oldNodeState.y}px`;
+ }
+ if ($el === root && newNode.measuredPosition === 'static') {
+ $el.style.position = 'relative';
+ // Cancel left / trop in case the static element had muted values now activated by potision relative
+ $el.style.left = '0px';
+ $el.style.top = '0px';
+ }
+ $el.style.width = `${oldNodeState.width}px`;
+ $el.style.height = `${oldNodeState.height}px`;
+ // Overrides user defined min and max to prevents width and height clamping
+ $el.style.minWidth = `auto`;
+ $el.style.minHeight = `auto`;
+ $el.style.maxWidth = `none`;
+ $el.style.maxHeight = `none`;
+ }
+ }
+
+ // Restore the scroll position if the oldState differs from the current state
+ if (oldState.scrollX !== window.scrollX || oldState.scrollY !== window.scrollY) {
+ // Restoring in the next frame avoids race conditions if for example a waapi animation commit styles that affect the root height
+ requestAnimationFrame(() => {
+ window.scrollTo(oldState.scrollX, oldState.scrollY);
+ });
+ }
+
+ for (let i = 0, l = animated.length; i < l; i++) {
+ const $el = animated[i];
+ const id = $el.dataset.layoutId;
+ const oldNode = oldState.nodes.get(id);
+ const newNode = newState.nodes.get(id);
+ const oldNodeState = oldNode.properties;
+ const newNodeState = newNode.properties;
+ let hasChanged = false;
+ const animatedProps = {
+ composition: 'none',
+ // delay: (/** @type {HTMLElement} */$el) => newState.nodes.get($el.dataset.layoutId).delay,
+ }
+ if (!newNode.isInlined) {
+ if (oldNodeState.width !== newNodeState.width) {
+ animatedProps.width = [oldNodeState.width, newNodeState.width];
+ hasChanged = true;
+ }
+ if (oldNodeState.height !== newNodeState.height) {
+ animatedProps.height = [oldNodeState.height, newNodeState.height];
+ hasChanged = true;
+ }
+ // If the node has transforms we handle the translate animation in wappi otherwise translate and other transforms can be out of sync
+ // Always animate translate
+ if (!newNode.hasTransform) {
+ animatedProps.translate = [`${oldNodeState.x}px ${oldNodeState.y}px`, `${newNodeState.x}px ${newNodeState.y}px`];
+ hasChanged = true;
+ }
+ }
+ this.properties.forEach(prop => {
+ const oldVal = oldNodeState[prop];
+ const newVal = newNodeState[prop];
+ if (prop !== 'transform' && oldVal !== newVal) {
+ animatedProps[prop] = [oldVal, newVal];
+ hasChanged = true;
+ }
+ });
+ if (hasChanged) {
+ this.timeline.add($el, animatedProps, 0);
+ }
+ }
+
+ }
+
+ if (frozen.length) {
+
+ for (let i = 0, l = frozen.length; i < l; i++) {
+ const $el = frozen[i];
+ const oldNode = oldState.nodes.get($el.dataset.layoutId);
+ if (!oldNode.isInlined) {
+ const oldNodeState = oldState.get($el);
+ $el.style.width = `${oldNodeState.width}px`;
+ $el.style.height = `${oldNodeState.height}px`;
+ // Overrides user defined min and max to prevents width and height clamping
+ $el.style.minWidth = `auto`;
+ $el.style.minHeight = `auto`;
+ $el.style.maxWidth = `none`;
+ $el.style.maxHeight = `none`;
+ $el.style.translate = `${oldNodeState.x}px ${oldNodeState.y}px`;
+ }
+ this.properties.forEach(prop => {
+ if (prop !== 'transform') {
+ $el.style[prop] = `${oldState.getValue($el, prop)}`;
+ }
+ });
+ }
+
+ for (let i = 0, l = frozen.length; i < l; i++) {
+ const $el = frozen[i];
+ const newNode = newState.nodes.get($el.dataset.layoutId);
+ const newNodeState = newState.get($el);
+ this.timeline.call(() => {
+ if (!newNode.isInlined) {
+ $el.style.width = `${newNodeState.width}px`;
+ $el.style.height = `${newNodeState.height}px`;
+ // Overrides user defined min and max to prevents width and height clamping
+ $el.style.minWidth = `auto`;
+ $el.style.minHeight = `auto`;
+ $el.style.maxWidth = `none`;
+ $el.style.maxHeight = `none`;
+ $el.style.translate = `${newNodeState.x}px ${newNodeState.y}px`;
+ }
+ this.properties.forEach(prop => {
+ if (prop !== 'transform') {
+ $el.style[prop] = `${newState.getValue($el, prop)}`;
+ }
+ });
+ }, newNode.delay + newNode.duration / 2);
+ }
+
+ if (animatedFrozen.length) {
+ const animatedFrozenParams = /** @type {AnimationParams} */({});
+ if (frozenParams) {
+ for (let prop in frozenParams) {
+ animatedFrozenParams[prop] = [
+ { from: (/** @type {HTMLElement} */$el) => oldState.getValue($el, prop), ease: 'in(1.75)', to: frozenParams[prop] },
+ { from: frozenParams[prop], to: (/** @type {HTMLElement} */$el) => newState.getValue($el, prop), ease: 'out(1.75)' }
+ ]
+ }
+ }
+ this.timeline.add(animatedFrozen, animatedFrozenParams, 0);
+ }
+
+ }
+
+ const transformedLength = transformed.length;
+
+ if (transformedLength) {
+ // We only need to set the transform property here since translate is alread defined the targets loop
+ for (let i = 0; i < transformedLength; i++) {
+ const $el = transformed[i];
+ $el.style.translate = `${oldState.get($el).x}px ${oldState.get($el).y}px`,
+ $el.style.transform = oldState.getValue($el, 'transform');
+ }
+ this.transformAnimation = waapi.animate(transformed, {
+ translate: (/** @type {HTMLElement} */$el) => `${newState.get($el).x}px ${newState.get($el).y}px`,
+ transform: (/** @type {HTMLElement} */$el) => newState.getValue($el, 'transform'),
+ autoplay: false,
+ persist: true,
+ ...defaults,
+ });
+ this.timeline.sync(this.transformAnimation, 0);
+ }
+
+ return this.timeline.init();
+ }
+
+ /**
+ * @param {(layout: this) => void} callback
+ * @param {LayoutAnimationParams} [params]
+ * @return {this}
+ */
+ update(callback, params = {}) {
+ this.record();
+ callback(this);
+ this.animate(params);
+ return this;
+ }
+}
+
+/**
+ * @param {DOMTargetSelector} root
+ * @param {AutoLayoutParams} [params]
+ * @return {AutoLayout}
+ */
+export const createLayout = (root, params) => new AutoLayout(root, params);
diff --git a/src/text/split.js b/src/text/split.js
index 60cd016f..3e4ffa3f 100644
--- a/src/text/split.js
+++ b/src/text/split.js
@@ -103,12 +103,23 @@ const filterEmptyElements = $el => {
/**
* @param {HTMLElement} $el
* @param {Number} lineIndex
- * @param {Set<HTMLElement>} bin
- * @returns {Set<HTMLElement>}
+ * @param {Set<HTMLElement|Node>} bin
+ * @returns {Set<HTMLElement|Node>}
*/
const filterLineElements = ($el, lineIndex, bin) => {
const dataLineAttr = $el.getAttribute(dataLine);
- if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') bin.add($el);
+ if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') {
+ bin.add($el);
+ // Also remove adjacent whitespace-only text nodes
+ const prev = $el.previousSibling;
+ const next = $el.nextSibling;
+ if (prev && prev.nodeType === 3 && whiteSpaceRgx.test(prev.textContent)) {
+ bin.add(prev);
+ }
+ if (next && next.nodeType === 3 && whiteSpaceRgx.test(next.textContent)) {
+ bin.add(next);
+ }
+ }
let i = $el.childElementCount;
while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin);
return bin;
@@ -323,7 +334,7 @@ export class TextSplitter {
// 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(' ')) {
+ if (!whiteSpaceGroupRgx.test(lastWord) && !whiteSpaceGroupRgx.test(segment)) {
tempWords[lastWordIndex] += segment;
} else {
tempWords.push(segment);
@@ -416,7 +427,7 @@ export class TextSplitter {
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++;
+ if (!isUnd(y) && top - y > height * .5) linesCount++;
$el.setAttribute(dataLine, `${linesCount}`);
const nested = $el.querySelectorAll(`[${dataLine}]`);
let c = nested.length;
@@ -430,9 +441,11 @@ export class TextSplitter {
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();
+ const $parent = $el.parentNode;
+ if ($parent) {
+ if ($el.nodeType === 1) parents.add(/** @type {HTMLElement} */($parent));
+ $parent.removeChild($el);
+ }
});
clones.push($clone);
}
@@ -445,6 +458,7 @@ export class TextSplitter {
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;
diff --git a/src/timeline/timeline.js b/src/timeline/timeline.js
index ef62d7d2..ec2a1010 100644
--- a/src/timeline/timeline.js
+++ b/src/timeline/timeline.js
@@ -114,11 +114,11 @@ 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);
+ if (tl.composition) 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(true);
+ if (tl.composition) tlChild.init(true);
// TODO: Might be better to insert at a position relative to startTime?
addChild(tl, tlChild);
forEachChildren(tl, (/** @type {Renderable} */child) => {
@@ -130,6 +130,8 @@ function addTlChild(childParams, tl, timePosition, targets, index, length) {
return tl;
}
+let TLId = 0;
+
export class Timeline extends Timer {
/**
@@ -137,6 +139,9 @@ export class Timeline extends Timer {
*/
constructor(parameters = {}) {
super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0);
+ ++TLId;
+ /** @type {String|Number} */
+ this.id = !isUnd(parameters.id) ? parameters.id : TLId;
/** @type {Number} */
this.duration = 0; // TL duration starts at 0 and grows when adding children
/** @type {Record<String, Number>} */
@@ -145,6 +150,8 @@ export class Timeline extends Timer {
const globalDefaults = globals.defaults;
/** @type {DefaultsParams} */
this.defaults = defaultsParams ? mergeObjects(defaultsParams, globalDefaults) : globalDefaults;
+ /** @type {Boolean} */
+ this.composition = setValue(parameters.composition, true);
/** @type {Callback<this>} */
this.onRender = parameters.onRender || globalDefaults.onRender;
const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase);
@@ -222,7 +229,8 @@ export class Timeline extends Timer {
parseTimelinePosition(this,a2),
);
}
- return this.init(true);
+ if (this.composition) this.init(true);
+ return this;
}
}
@@ -249,7 +257,7 @@ export class Timeline extends Timer {
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);
+ return this.add(synced, { currentTime: [0, duration], duration, delay: 0, ease: 'linear', playbackEase: 'linear' }, position);
}
/**
@@ -272,7 +280,7 @@ export class Timeline extends Timer {
*/
call(callback, position) {
if (isUnd(callback) || callback && !isFnc(callback)) return this;
- return this.add({ duration: 0, onComplete: () => callback(this) }, position);
+ return this.add({ duration: 0, delay: 0, onComplete: () => callback(this) }, position);
}
/**
diff --git a/src/timer/timer.js b/src/timer/timer.js
index 87fda73f..bac40bdb 100644
--- a/src/timer/timer.js
+++ b/src/timer/timer.js
@@ -22,6 +22,7 @@ import {
import {
scope,
globals,
+ devTools,
} from '../core/globals.js';
import {
@@ -112,6 +113,8 @@ export class Timer extends Clock {
super(0);
+ ++timerId;
+
const {
id,
delay,
@@ -133,31 +136,42 @@ export class Timer extends Clock {
if (scope.current) scope.current.register(this);
- const timerInitTime = parent ? 0 : engine._elapsedTime;
+ const timerInitTime = parent ? 0 : engine._lastTickTime;
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 timerIterationCount = timerLoop === true ||
+ timerLoop === Infinity ||
+ /** @type {Number} */(timerLoop) < 0 ? Infinity :
+ /** @type {Number} */(timerLoop) + 1;
+
+ if (devTools) {
+ const isInfinite = timerIterationCount === Infinity;
+ const registered = devTools.register(this, parameters, isInfinite);
+ if (registered && isInfinite) {
+ const minIterations = alternate ? 2 : 1;
+ const iterations = parent ? devTools.maxNestedInfiniteLoops : devTools.maxInfiniteLoops;
+ timerIterationCount = Math.max(iterations, minIterations);
+ }
+ }
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
+ // Make sure to tick the engine once if not currently running to get up to date engine._lastTickTime
// 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;
+ offsetPosition = (engine._lastTickTime - engine._startTime) * globals.timeScale;
}
// Timer's parameters
- this.id = !isUnd(id) ? id : ++timerId;
+ /** @type {String|Number} */
+ this.id = !isUnd(id) ? id : timerId;
/** @type {Timeline} */
this.parent = parent;
// Total duration of the timer
@@ -217,7 +231,7 @@ export class Timer extends Clock {
// Clock's parameters
/** @type {Number} */
- this._elapsedTime = timerInitTime;
+ this._lastTickTime = timerInitTime;
/** @type {Number} */
this._startTime = timerInitTime;
/** @type {Number} */
@@ -248,7 +262,7 @@ export class Timer extends Clock {
}
get iterationCurrentTime() {
- return round(this._iterationTime, globals.precision);
+ return clamp(round(this._iterationTime, globals.precision), 0, this.iterationDuration);
}
set iterationCurrentTime(time) {
@@ -346,9 +360,9 @@ export class Timer extends Clock {
/** @return {this} */
resetTime() {
const timeScale = 1 / (this._speed * engine._speed);
- // TODO: See if we can safely use engine._elapsedTime here
+ // TODO: See if we can safely use engine._lastTickTime here
// if (!engine.reqId) engine.requestTick(now())
- // this._startTime = engine._elapsedTime - (this._currentTime + this._delay) * timeScale;
+ // this._startTime = engine._lastTickTime - (this._currentTime + this._delay) * timeScale;
this._startTime = now() - (this._currentTime + this._delay) * timeScale;
return this;
}
diff --git a/src/types/index.js b/src/types/index.js
index d7c44928..e65997fb 100644
--- a/src/types/index.js
+++ b/src/types/index.js
@@ -14,6 +14,7 @@ export {}
* @import { Draggable } from '../draggable/draggable.js';
* @import { TextSplitter } from '../text/split.js';
* @import { Scope } from '../scope/scope.js';
+ * @import { AutoLayout } from '../layout/layout.js';
* @import { Spring } from '../easings/spring/index.js';
* @import { compositionTypes, tweenTypes, valueTypes } from '../core/consts.js';
*/
@@ -52,7 +53,7 @@ export {}
/** @typedef {JSAnimation|Timeline} Renderable */
/** @typedef {Timer|Renderable} Tickable */
/** @typedef {Timer&JSAnimation&Timeline} CallbackArgument */
-/** @typedef {Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */
+/** @typedef {Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope|AutoLayout} Revertible */
// Stagger types
@@ -376,6 +377,7 @@ export {}
* @typedef {Object} TimelineOptions
* @property {DefaultsParams} [defaults]
* @property {EasingParam} [playbackEase]
+ * @property {Boolean} [composition]
*/
/**
diff --git a/src/waapi/waapi.js b/src/waapi/waapi.js
index bb5e9f32..d33dc80b 100644
--- a/src/waapi/waapi.js
+++ b/src/waapi/waapi.js
@@ -35,7 +35,6 @@ import {
transformsFragmentStrings,
transformsSymbol,
validTransforms,
- cssVarPrefix,
} from '../core/consts.js';
import {
@@ -368,8 +367,10 @@ export class WAAPIAnimation {
* @return {this}
*/
forEach(callback) {
- const cb = isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback;
- this.animations.forEach(cb);
+ try {
+ const cb = isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback;
+ this.animations.forEach(cb);
+ } catch {};
return this;
}
@@ -466,14 +467,21 @@ export class WAAPIAnimation {
cancel() {
this.muteCallbacks = true; // This prevents triggering the onComplete callback and resolving the Promise
- return this.commitStyles().forEach('cancel');
+ this.commitStyles().forEach('cancel');
+ this.animations.length = 0; // Needed to release all animations from memory
+ requestAnimationFrame(() => {
+ this.targets.forEach(($el) => { // Needed to avoid unecessary inline transorms
+ if ($el.style.transform === 'none') $el.style.removeProperty('transform');
+ });
+ });
+ return this;
}
revert() {
// NOTE: We need a better way to revert the transforms, since right now the entire transform property value is reverted,
// This means if you have multiple animations animating different transforms on the same target,
// reverting one of them will also override the transform property of the other animations.
- // A better approach would be to store the original custom property values is they exist instead of the entire transform value,
+ // A better approach would be to store the original custom property values if they exist instead of the entire transform value,
// and update the CSS variables with the orignal value
this.cancel().targets.forEach(($el, i) => {
const targetStyle = $el.style;
@@ -483,7 +491,7 @@ export class WAAPIAnimation {
if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
targetStyle.removeProperty(toLowerCase(name));
} else {
- targetStyle[name] = originalInlinedValue;
+ $el.style[name] = originalInlinedValue;
}
}
// Remove style attribute if empty
diff --git a/tests/index.html b/tests/index.html
index 3163fb09..245471ae 100644
--- a/tests/index.html
+++ b/tests/index.html
@@ -25,7 +25,7 @@
--color-green: #18FF74;/* green: */
--color-darkgreen: #00D672;/* darkgreen: */
--color-turquoise: #3CFFEC;/* turquoise: */
- --color-skyblue: #61C3FF;/* skyblue: */
+ --color-blue: #61C3FF;/* blue: */
--color-kingblue: #5A87FF;/* kingblue: */
--color-lavender: #8453E3;/* lavender: */
--color-purple: #C26EFF;/* purple: */
diff --git a/tests/playground/animejs-v2-logo-animation.html b/tests/playground/animejs-v2-logo-animation.html
index 764e950c..9c346600 100644
--- a/tests/playground/animejs-v2-logo-animation.html
+++ b/tests/playground/animejs-v2-logo-animation.html
@@ -194,7 +194,6 @@
utils.set(['.fill.out', '.line.out'], { opacity: 0 });
const logoTimeline = createTimeline({
- autoplay: false,
alternate: true,
loop: 1,
defaults: {
@@ -294,8 +293,6 @@
}, 4200)
.init();
- inspect(logoTimeline);
-
// logoTimeline.seek(660);
// logoTimeline.seek(660);
diff --git a/tests/playground/assets/css/styles.css b/tests/playground/assets/css/styles.css
index 99afce33..21fca87f 100644
--- a/tests/playground/assets/css/styles.css
+++ b/tests/playground/assets/css/styles.css
@@ -1,19 +1,131 @@
:root {
- --black: #252423;
- --white: #F6F4F2;
- --red: #FF4B4B;
- --orange: #FF8F42;
- --lightorange: #FFC730;
- --yellow: #F6FF56;
- --citrus: #A4FF4F;
- --green: #18FF74;
- --darkgreen: #00D672;
- --turquoise: #3CFFEC;
- --skyblue: #61C3FF;
- --kingblue: #5A87FF;
- --lavender: #8453E3;
- --purple: #C26EFF;
- --pink: #FB89FB;
+ --black-1: #252423;
+ --black-2: #262422;
+ --black-3: #262422;
+ --black-4: #262422;
+ --black-5: #272421;
+ --black-6: #272421;
+ --white-1: #f6f4f2;
+ --white-2: #b8b6b3;
+ --white-3: #9a9593;
+ --white-4: #524f49;
+ --white-5: #413d39;
+ --white-6: #312e2b;
+ --red-1: #ff4b4b;
+ --red-2: #bf3e3e;
+ --red-3: #9e3838;
+ --red-4: #532a29;
+ --red-5: #412726;
+ --red-6: #322523;
+ --corail-1: #ff8333;
+ --corail-2: #bf672d;
+ --corail-3: #9e582b;
+ --corail-4: #533724;
+ --corail-5: #412f23;
+ --corail-6: #322922;
+ --orange-1: #ffa828;
+ --orange-2: #bf8026;
+ --orange-3: #9e6d25;
+ --orange-4: #523e23;
+ --orange-5: #413422;
+ --orange-6: #322b21;
+ --yellow-1: #ffcc2a;
+ --yellow-2: #bf9a27;
+ --yellow-3: #9e8026;
+ --yellow-4: #524723;
+ --yellow-5: #413922;
+ --yellow-6: #322d21;
+ --citrus-1: #f9f640;
+ --citrus-2: #bab836;
+ --citrus-3: #9b9932;
+ --citrus-4: #515027;
+ --citrus-5: #403f24;
+ --citrus-6: #323022;
+ --lime-1: #b7ff54;
+ --lime-2: #8bbe44;
+ --lime-3: #759d3d;
+ --lime-4: #42522b;
+ --lime-5: #384027;
+ --lime-6: #2d3123;
+ --green-1: #6aff65;
+ --green-2: #54be50;
+ --green-3: #4a9e45;
+ --green-4: #31522e;
+ --green-5: #2c4029;
+ --green-6: #273124;
+ --emerald-1: #57f695;
+ --emerald-2: #47b873;
+ --emerald-3: #409962;
+ --emerald-4: #2d5039;
+ --emerald-5: #293f30;
+ --emerald-6: #263128;
+ --turquoise-1: #66ffbc;
+ --turquoise-2: #52be8e;
+ --turquoise-3: #479e77;
+ --turquoise-4: #305242;
+ --turquoise-5: #2b4035;
+ --turquoise-6: #26312b;
+ --cyan-1: #26f2d5;
+ --cyan-2: #25b5a0;
+ --cyan-3: #259686;
+ --cyan-4: #244e48;
+ --cyan-5: #233f39;
+ --cyan-6: #23302d;
+ --sega-1: #05dbe9;
+ --sega-2: #0fa4ae;
+ --sega-3: #138990;
+ --sega-4: #1e4a4c;
+ --sega-5: #203b3c;
+ --sega-6: #212f2f;
+ --sky-1: #33b3f1;
+ --sky-2: #2e88b4;
+ --sky-3: #2c7395;
+ --sky-4: #26424e;
+ --sky-5: #25363e;
+ --sky-6: #242c2f;
+ --indigo-1: #717aff;
+ --indigo-2: #595fbe;
+ --indigo-3: #4d519e;
+ --indigo-4: #323351;
+ --indigo-5: #2c2c3f;
+ --indigo-6: #282630;
+ --lavender-1: #a369ff;
+ --lavender-2: #7d53be;
+ --lavender-3: #6a489e;
+ --lavender-4: #3e3051;
+ --lavender-5: #342a3f;
+ --lavender-6: #2b2530;
+ --purple-1: #c06ddf;
+ --purple-2: #9356a8;
+ --purple-3: #7b4a8c;
+ --purple-4: #45314b;
+ --purple-5: #392b3c;
+ --purple-6: #2f262d;
+ --magenta-1: #e962bf;
+ --magenta-2: #af4e90;
+ --magenta-3: #93447a;
+ --magenta-4: #4e2e43;
+ --magenta-5: #3f2936;
+ --magenta-6: #31252b;
+ --pink-1: #ff86a7;
+ --pink-2: #bf687f;
+ --pink-3: #9f586b;
+ --pink-4: #53363c;
+ --pink-5: #412e32;
+ --pink-6: #322729;
+ --bg-1: #252423;
+ --bg-2: #2a2928;
+ --bg-3: #2f2e2d;
+ --bg-4: #353433;
+ --bg-5: #3a3938;
+ --fg-1: #dddcda;
+ --fg-2: #c6c3c1;
+ --fg-3: #96918f;
+ --fg-4: #65655e;
+ --fg-5: #33332e;
+ --br: 1rem;
+ --padding: 1rem;
+ --border-width: 1px;
}
*, *:before, *:after {
@@ -27,16 +139,22 @@
html,
body {
- background-color: var(--black);
- color: var(--white);
- font-family: sans-serif;
+ background-color: var(--bg-1);
+ color: var(--fg-1);
+ font-family: BerkeleyMono-Regular, monospace, sans-serif;
}
-.black { color: var(--black); }
-.white { color: var(--white); }
-.red { color: var(--red); }
-.blue { color: var(--skyblue); }
-.green { color: var(--green); }
+.br { border-radius: var(--br); }
+.br .br { border-radius: calc(var(--br) * .5); }
+.br .br .br { border-radius: calc(var(--br) * .25); }
+
+.black { color: var(--bg-1); }
+.white { color: var(--fg-1); }
+.red { color: var(--red-1); }
+.orange { color: var(--corail-1); }
+.yellow { color: var(--yellow-1); }
+.blue { color: var(--sky-1); }
+.green { color: var(--green-1); }
.grid {
--one-cell: 100px;
diff --git a/tests/playground/keyframes/index.html b/tests/playground/keyframes/index.html
index 378f5690..dce0f92f 100644
--- a/tests/playground/keyframes/index.html
+++ b/tests/playground/keyframes/index.html
@@ -61,7 +61,7 @@
}
.waapi {
- background-color: var(--orange);
+ background-color: var(--orange-1);
}
.anime {
diff --git a/tests/playground/layout/index.html b/tests/playground/layout/index.html
new file mode 100644
index 00000000..1c6bfad3
--- /dev/null
+++ b/tests/playground/layout/index.html
@@ -0,0 +1,476 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Layout 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;
+ justify-content: flex-start;
+ align-items: flex-start;
+ width: 100%;
+ min-height: 100lvh;
+ padding-bottom: 28rem;
+ }
+ #controls {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ position: sticky;
+ z-index: 1000;
+ top: 0;
+ left: 0;
+ right: 0;
+ width: 100%;
+ padding: .5rem;
+ background-color: var(--bg-1);
+ border-bottom: 1px solid var(--bg-4);
+ }
+ #controls button {
+ width: 20%;
+ flex-grow: 1;
+ flex-shrink: 0;
+ height: 4ch;
+ min-width: 0;
+ margin: .5ch;
+ background-color: var(--fg-1);
+ color: var(--bg-2);
+ }
+ #controls button.is-active {
+ background-color: var(--fg-1);
+ color: var(--bg-3);
+ }
+ .tests {
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ width: 100%;
+ }
+ .test {
+ position: relative;
+ display: flex;
+ align-items: stretch;
+ justify-content: center;
+ flex-direction: column;
+ width: 100%;
+ border: 1px solid var(--white-5);
+ margin-right: -1px;
+ margin-top: -1px;
+ padding: 3rem 1rem 1rem 1rem;
+ background: var(--bg-1);
+ }
+ @media (min-width: 740px) {
+ .test {
+ width: 50%;
+ }
+ .double-container {
+ width: 100%;
+ }
+ }
+ @media (min-width: 1024px) {
+ .test {
+ width: 33.333333%;
+ }
+ .double-container {
+ width: 100%;
+ }
+ }
+ @media (min-width: 1600px) {
+ .test {
+ width: 25%;
+ }
+ .double-container {
+ width: 50%;
+ }
+ }
+ .test-header {
+ overflow: hidden;
+ display: flex;
+ justify-content: space-between;
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ padding: .5rem;
+ }
+ .test-header button {
+ padding: 0 .5rem;
+ }
+ .fixed-height{
+ height: 18rem;
+ }
+ .demo {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ container-type: inline-size;
+ padding: 0;
+ width: 100%;
+ }
+ .demo:has(.sticky) {
+ align-items: flex-start;
+ height: 100%;
+ }
+ .container {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-wrap: nowrap;
+ top: 1.5rem;
+ gap: .5rem;
+ padding: .5rem;
+ width: 100cqw;
+ margin-left: 1rem;
+ margin-right: 1rem;
+ background-color: var(--bg-2);
+ border: 1px dotted var(--white-2);
+ }
+ .double-container .container {
+ width: 50cqw;
+ margin-left: 0rem;
+ margin-right: 0rem;
+ }
+ .display-none {
+ display: none;
+ }
+ .relative {
+ position: relative;
+ top: 0rem;
+ }
+ .static {
+ position: static;
+ top: 2.5rem;
+ }
+ .absolute {
+ position: absolute;
+ top: 2.5rem;
+ }
+ .fixed {
+ position: fixed;
+ top: auto;
+ bottom: 0;
+ }
+ .sticky {
+ position: sticky;
+ top: 3.5rem;
+ }
+ .vertical {
+ flex-direction: column;
+ }
+ .horizontal {
+ flex-direction: row;
+ }
+ .target-container .child {
+ display: none;
+ }
+ .child {
+ border: 1px dashed var(--white-3);
+ width: 100%;
+ padding: .5rem;
+ border-radius: 1rem;
+ background-color: var(--bg-4);
+ transition: all 1s ease-out;
+ }
+ .child > span {
+ background: var(--white-2);
+ color: var(--bg-2);
+ }
+ .sub-child {
+ border: 1px solid var(--white-4);
+ margin-top: .5rem;
+ padding: .5rem;
+ border-radius: .5rem;
+ background-color: var(--bg-5);
+ }
+ .sub-child > span {
+ background: var(--white-2);
+ color: var(--bg-2);
+ }
+ #layout-id .child-b,
+ #layout-id .vertical .child-a {
+ visibility: hidden;
+ }
+ #layout-id .vertical .child-b {
+ visibility: visible;
+ }
+ #simple-fixed-root {
+ position: relative;
+ z-index: 10;
+ }
+ #specific-properties .vertical .child {
+ color: var(--red-1);
+ border-radius: .5rem;
+ }
+ #specific-properties .vertical .child > span {
+ background-color: var(--red-1);
+ }
+ #specific-properties .vertical .sub-child {
+ color: var(--orange-1);
+ border-radius: .25rem;
+ }
+ #specific-properties .vertical .sub-child > span {
+ background-color: var(--orange-1);
+ }
+ #simple-fixed-root {
+ position: fixed;
+ z-index: 11;
+ bottom: 0;
+ right: 0;
+ height: 14rem;
+ }
+ #swap-outside-fixed-root {
+ z-index: 10;
+ }
+ #swap-outside-fixed-root .container-b {
+ position: fixed;
+ top: inherit;
+ bottom: 2rem;
+ left: 2rem;
+ background: transparent;
+ }
+ </style>
+</head>
+<body>
+ <div id="controls">
+ <button id="animate-all">animate all</button>
+ <button id="revert-all">revert all</button>
+ </div>
+ <div class="tests">
+
+ <div id="simple-absolute-root" class="test fixed-height">
+ <div class="test-header">
+ <h2>Simple absolute root</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container absolute vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+
+ <div id="simple-sticky-root" class="test fixed-height">
+ <div class="test-header">
+ <h2>Simple sticky root</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container sticky vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+
+ <div id="simple-fixed-root" class="test fixed-height">
+ <div class="test-header">
+ <h2>Simple fixed root</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container fixed vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+
+ <div id="simple-relative-root" class="test fixed-height">
+ <div class="test-header">
+ <h2>Simple relative root</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container relative vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+
+ <div id="simple-static-root" class="test fixed-height">
+ <div class="test-header">
+ <h2>Simple static root</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container static vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="specific-children" class="test fixed-height">
+ <div class="test-header">
+ <h2>Specific children</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="specific-properties" class="test fixed-height">
+ <div class="test-header">
+ <h2>Specific properties</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="hide-display-none" class="test fixed-height">
+ <div class="test-header">
+ <h2>Remove with "display: none"</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="hide-visibility-hidden" class="test fixed-height">
+ <div class="test-header">
+ <h2>Remove with "visibility: hidden"</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="frozen-properties" class="test fixed-height">
+ <div class="test-header">
+ <h2>Custom frozen properties</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="removed-properties" class="test fixed-height">
+ <div class="test-header">
+ <h2>Custom removed properties</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="added-properties" class="test fixed-height">
+ <div class="test-header">
+ <h2>Added properties</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="custom-timings" class="test fixed-height">
+ <div class="test-header">
+ <h2>Custom timings</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="spring-ease" class="test fixed-height">
+ <div class="test-header">
+ <h2>Spring ease</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="layout-id" class="test fixed-height">
+ <div class="test-header">
+ <h2>Swap elements with id</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child child-a" data-layout-id="test-id-1">A direct <span data-layout-id="test-id-2">child</span> element. <div class="sub-child" data-layout-id="test-id-3"> And a <span data-layout-id="test-id-4">sub child</span> element</div></div>
+ <div class="child child-b" data-layout-id="test-id-1">A direct <span data-layout-id="test-id-2">child</span> element. <div class="sub-child" data-layout-id="test-id-3"> And a <span data-layout-id="test-id-4">sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="swap-outside-fixed-root" class="test fixed-height">
+ <div class="test-header">
+ <h2>Swap element outside fixed root</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container container-a">
+ <div class="child" data-layout-id="c">A direct <span data-layout-id="c-1">child</span> element. <div class="sub-child" data-layout-id="c-2"> And a <span data-layout-id="c-3">sub child</span> element</div></div>
+ <div class="child" data-layout-id="d">A direct <span data-layout-id="d-1">child</span> element. <div class="sub-child" data-layout-id="d-2"> And a <span data-layout-id="d-3">sub child</span> element</div></div>
+ </div>
+ <div class="container container-b target-container">
+ <div class="child" data-layout-id="c">A direct <span data-layout-id="c-1">child</span> element. <div class="sub-child" data-layout-id="c-2"> And a <span data-layout-id="c-3">sub child</span> element</div></div>
+ <div class="child" data-layout-id="d">A direct <span data-layout-id="d-1">child</span> element. <div class="sub-child" data-layout-id="d-2"> And a <span data-layout-id="d-3">sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ <div id="swap-inside-root" class="test fixed-height double-container">
+ <div class="test-header">
+ <h2>Swap element inside root</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container vertical">
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ <div class="child">A direct <span>child</span> element. <div class="sub-child"> And a <span>sub child</span> element</div></div>
+ </div>
+ <div class="container vertical"></div>
+ </div>
+ </div>
+ <div id="swap-outside-root" class="test fixed-height double-container">
+ <div class="test-header">
+ <h2>Swap element outside root</h2>
+ <button>Animate</button>
+ </div>
+ <div class="demo">
+ <div class="container container-a">
+ <div class="child" data-layout-id="a">A direct <span data-layout-id="a-1">child</span> element. <div class="sub-child" data-layout-id="a-2"> And a <span data-layout-id="a-3">sub child</span> element</div></div>
+ <div class="child" data-layout-id="b">A direct <span data-layout-id="b-1">child</span> element. <div class="sub-child" data-layout-id="b-2"> And a <span data-layout-id="b-3">sub child</span> element</div></div>
+ </div>
+ <div class="container container-b target-container">
+ <div class="child" data-layout-id="a">A direct <span data-layout-id="a-1">child</span> element. <div class="sub-child" data-layout-id="a-2"> And a <span data-layout-id="a-3">sub child</span> element</div></div>
+ <div class="child" data-layout-id="b">A direct <span data-layout-id="b-1">child</span> element. <div class="sub-child" data-layout-id="b-2"> And a <span data-layout-id="b-3">sub child</span> element</div></div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <script type="module" src="./index.js"></script>
+</body>
+</html>
diff --git a/tests/playground/layout/index.js b/tests/playground/layout/index.js
new file mode 100644
index 00000000..301b5117
--- /dev/null
+++ b/tests/playground/layout/index.js
@@ -0,0 +1,247 @@
+import { createLayout, utils, createScope, stagger, spring } from '../../../dist/modules/index.js';
+
+const duration = 1000;
+
+const [ $animateAll ] = utils.$('#animate-all');
+const [ $revertAll ] = utils.$('#revert-all');
+
+$animateAll.addEventListener('click', () => {
+ tests.forEach(test => {
+ test.data.$button.click();
+ })
+})
+
+$revertAll.addEventListener('click', () => {
+ tests.forEach(test => {
+ test.revert();
+ })
+})
+
+const tests = [
+ createScope({ root: '#simple-fixed-root' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container');
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#simple-absolute-root' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container');
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#simple-sticky-root' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container');
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#simple-relative-root' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container');
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#simple-static-root' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container');
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#specific-children' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ children: ['.child', '.child > span'],
+ });
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#specific-properties' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ properties: ['background-color', 'color'],
+ });
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#hide-display-none' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ children: ['.child', '.child > span'],
+ });
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ const $child = root.querySelector('.child');
+ root.classList.toggle('vertical');
+ $child.style.display = $child.style.display === 'none' ? 'block' : 'none';
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#hide-visibility-hidden' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ children: ['.child', '.child > span'],
+ });
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ const $child = root.querySelector('.child');
+ root.classList.toggle('vertical');
+ $child.style.visibility = $child.style.visibility === 'hidden' ? 'visible' : 'hidden';
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#frozen-properties' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ children: ['.child', '.child > span'],
+ frozen: {
+ color: 'var(--red-1)',
+ borderColor: 'var(--red-1)',
+ filter: 'blur(5px)',
+ }
+ });
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration, frozen: { color: 'var(--green-1)' } })
+ });
+ }),
+ createScope({ root: '#removed-properties' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ children: ['.child', '.child > span'],
+ properties: ['background-color'],
+ removed: {
+ transform: 'rotate(45deg) scale(0)',
+ },
+ });
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ const $child = root.querySelector('.child');
+ root.classList.toggle('vertical');
+ $child.style.display = $child.style.display === 'none' ? 'block' : 'none';
+ }, { duration, removed: { 'background-color': 'var(--red-1)' } })
+ });
+ }),
+ createScope({ root: '#added-properties' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ properties: ['background-color'],
+ children: ['.child', '.child > span'],
+ added: {
+ transform: 'rotate(-45deg) scale(0)',
+ },
+ });
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ const $child = root.querySelector('.child');
+ $child.style.display = $child.style.display === 'none' ? 'block' : 'none';
+ }, { duration, added: { 'background-color': 'var(--green-1)' } })
+ });
+ }),
+ createScope({ root: '#custom-timings' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ duration: 1000,
+ ease: 'outExpo',
+ });
+ data.$button.addEventListener('click', () => {
+ const isVertical = data.layout.root.classList.contains('vertical');
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, {
+ delay: stagger([0, 400], { from: isVertical ? 'last' : 'first' }),
+ duration,
+ })
+ });
+ }),
+ createScope({ root: '#spring-ease' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container', {
+ duration: 1000,
+ ease: spring(),
+ delay: stagger(25)
+ });
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#layout-id' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container');
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.classList.toggle('vertical');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#swap-outside-fixed-root' }).add(({ root, data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.demo', {
+ delay: stagger([0, 100]),
+ });
+ data.$button.addEventListener('click', () => {
+ const $newContainer = root.querySelector('.container.target-container');
+ const $oldContainer = root.querySelector('.container:not(.target-container)');
+ data.layout.update(({root}) => {
+ $newContainer.classList.remove('target-container');
+ $oldContainer.classList.add('target-container');
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#swap-inside-root' }).add(({ data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.demo');
+ data.$button.addEventListener('click', () => {
+ data.layout.update(({ root }) => {
+ root.querySelectorAll('.container').forEach($container => $container.classList.toggle('vertical'));
+ const $child = root.querySelector('.child');
+ const $parent = $child.parentElement;
+ const $nextParent = $parent.nextElementSibling || $parent.previousElementSibling;
+ $parent.style.zIndex = '0';
+ $nextParent.style.zIndex = '1';
+ $nextParent.appendChild($child);
+ }, { duration })
+ });
+ }),
+ createScope({ root: '#swap-outside-root' }).add(({ root, data }) => {
+ data.$button = utils.$('button')[0];
+ data.layout = createLayout('.container-b', {
+ children: ['.container', '.child', '.child > span'],
+ delay: stagger([0, 100]),
+ });
+ data.$button.addEventListener('click', () => {
+ const $newContainer = root.querySelector('.container.target-container');
+ const $oldContainer = root.querySelector('.container:not(.target-container)');
+ data.layout.update(({root}) => {
+ root.classList.toggle('vertical');
+ $newContainer.classList.remove('target-container');
+ $oldContainer.classList.add('target-container');
+ }, { duration })
+ });
+ }),
+]
\ No newline at end of file
diff --git a/tests/playground/onscroll/assets/onscroll.css b/tests/playground/onscroll/assets/onscroll.css
index d990efc8..dbf611b0 100644
--- a/tests/playground/onscroll/assets/onscroll.css
+++ b/tests/playground/onscroll/assets/onscroll.css
@@ -66,14 +66,14 @@ h2 {
z-index: 0;
background-image: url(card-back.svg);
transform: rotateY(180deg);
- background-color: var(--white);
+ background-color: var(--white-1);
}
.front {
z-index: 1;
backface-visibility: hidden;
background-image: url(card.svg);
- background-color: var(--white);
+ background-color: var(--white-1);
background-size: 89%;
background-repeat: no-repeat;
}
diff --git a/tests/playground/onscroll/function-based-values.html b/tests/playground/onscroll/function-based-values.html
index cbfb90f3..79887a34 100644
--- a/tests/playground/onscroll/function-based-values.html
+++ b/tests/playground/onscroll/function-based-values.html
@@ -39,7 +39,7 @@
flex-shrink: 0;
width: 100vw;
height: 100lvh;
- border: 1px dotted var(--green);
+ border: 1px dotted var(--green-1);
}
@media (orientation: landscape) {
diff --git a/tests/playground/onscroll/horizontal-container.html b/tests/playground/onscroll/horizontal-container.html
index ef0218ee..7bc03304 100644
--- a/tests/playground/onscroll/horizontal-container.html
+++ b/tests/playground/onscroll/horizontal-container.html
@@ -26,8 +26,8 @@
transform-style: preserve-3d;
overflow-x: auto;
overflow-y: hidden;
- border: 1px dotted var(--green);
- background-color: var(--black);
+ border: 1px dotted var(--green-1);
+ background-color: var(--black-1);
}
.sticky-scroller {
transform-style: preserve-3d;
diff --git a/tests/playground/onscroll/standalone.html b/tests/playground/onscroll/standalone.html
index 1cf82fb5..173af057 100644
--- a/tests/playground/onscroll/standalone.html
+++ b/tests/playground/onscroll/standalone.html
@@ -44,7 +44,7 @@
margin: 1rem;
padding: .5rem;
border-radius: 1rem;
- background-color: var(--white);
+ background-color: var(--white-1);
}
</style>
</head>
diff --git a/tests/playground/onscroll/sticky-snap.html b/tests/playground/onscroll/sticky-snap.html
index bb3a2825..2e3cb8d5 100644
--- a/tests/playground/onscroll/sticky-snap.html
+++ b/tests/playground/onscroll/sticky-snap.html
@@ -37,7 +37,7 @@
position: sticky;
top: 0;
height: 100vh;
- border: 1px dotted var(--green);
+ border: 1px dotted var(--green-1);
}
.stack {
border: 2px dashed rgba(255,255,255,.25);
diff --git a/tests/playground/onscroll/svg-target.html b/tests/playground/onscroll/svg-target.html
index 48ff8545..cd753bcc 100644
--- a/tests/playground/onscroll/svg-target.html
+++ b/tests/playground/onscroll/svg-target.html
@@ -40,7 +40,7 @@
flex-shrink: 0;
width: 100vw;
height: 100lvh;
- border: 1px dotted var(--green);
+ border: 1px dotted var(--green-1);
}
body {
diff --git a/tests/playground/sandbox/index.html b/tests/playground/sandbox/index.html
index 3a62ee88..a2399bb2 100644
--- a/tests/playground/sandbox/index.html
+++ b/tests/playground/sandbox/index.html
@@ -6,46 +6,37 @@
<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;
- justify-content: center;
- align-items: center;
- width: 100%;
- height: 500px;
-}
+ body{
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: flex-start;
+ height: 100lvh;
+ background: black;
+ }
-main {
- height: 400px;
- width: 400px;
- background-color: wheat;
- overflow-y: auto;
- scale: .8;
-}
+ div {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 300px;
+ height: 100px;
+ background: red;
+ font-size: 64px;
+ }
-.page {
- width: 100%;
- height: 1000px;
- position: relative;
-}
-
-.rectangle {
- width: 100px;
- height: 100px;
- background: purple;
- position: absolute;
- bottom: 100px;
-}
+ @keyframes x-animation {
+ to { margin-left: 90%; }
+ }
+ .css.animate {
+ animation: x-animation 1s linear forwards infinite;
+ }
</style>
</head>
<body>
- <main>
- <div class="page">
- <div class="rectangle" id="target">
- </div>
- </div>
- </main>
+ <div class="css">css</div>
+ <div class="anim">anime.js</div>
<script type="module" src="./index.js"></script>
</body>
</html>
diff --git a/tests/playground/sandbox/index.js b/tests/playground/sandbox/index.js
index 2f9aa736..63a580e5 100644
--- a/tests/playground/sandbox/index.js
+++ b/tests/playground/sandbox/index.js
@@ -1,5 +1,16 @@
-import { waapi, animate, onScroll, $, set, stagger, spring, random, utils } from '../../../dist/modules/index.js';
+import { animate, utils, stagger, engine } from '../../../dist/modules/index.js';
-async function animation() {
- await animate('test', { x: 100 });
-}
\ No newline at end of file
+// engine.fps = 120;
+// engine.defaults.frameRate = 120;
+// engine.pauseOnDocumentHidden = false;
+
+const duration = 1000;
+
+animate('.anim', {
+ marginLeft: [0,"90%"],
+ duration,
+ loop: true,
+ ease: 'linear'
+})
+
+document.querySelector('.css').classList.add('animate');
\ No newline at end of file
diff --git a/tests/playground/scope/index.js b/tests/playground/scope/index.js
index a4e44b69..1c87ec17 100644
--- a/tests/playground/scope/index.js
+++ b/tests/playground/scope/index.js
@@ -70,7 +70,7 @@ const scope = createScope({
}
self.keepTime(() => animate('.square', {
- background: ($el) => utils.get($el, utils.randomPick(['--skyblue', '--lavender', '--pink'])),
+ background: ($el) => utils.get($el, utils.randomPick(['--blue', '--lavender', '--pink'])),
loop: true,
ease: 'inOut(2)',
alternate: true,
diff --git a/tests/playground/sprite-animation.html b/tests/playground/sprite-animation.html
index 4d13732b..82473828 100644
--- a/tests/playground/sprite-animation.html
+++ b/tests/playground/sprite-animation.html
@@ -43,11 +43,11 @@
<script type="module">
- import { animate } from '../../../dist/modules/index.js';
+ import { animate, steps } from '../../../dist/modules/index.js';
const ryu = animate('.ryu', {
backgroundPosition: '100% 0px',
- ease: 'steps(9)',
+ ease: steps(9),
duration: 450,
loop: true
});
diff --git a/tests/playground/stagger-demo.html b/tests/playground/stagger-demo.html
index 92013de7..065df60b 100644
--- a/tests/playground/stagger-demo.html
+++ b/tests/playground/stagger-demo.html
@@ -28,7 +28,7 @@
width: 64px;
height: 128px;
border: 1px solid var(--red);
- background-color: var(--black);
+ background-color: var(--black-1);
}
</style>
diff --git a/tests/playground/svg-motion-path/index.html b/tests/playground/svg-motion-path/index.html
index b9d213d5..f82e403d 100644
--- a/tests/playground/svg-motion-path/index.html
+++ b/tests/playground/svg-motion-path/index.html
@@ -38,7 +38,7 @@
border: 2px solid currentColor;
}
.rect-el {
- stroke: var(--green);
+ stroke: var(--green-1);
}
</style>
</head>
diff --git a/tests/playground/tween-composition.html b/tests/playground/tween-composition.html
index 977460ed..0584650f 100644
--- a/tests/playground/tween-composition.html
+++ b/tests/playground/tween-composition.html
@@ -73,7 +73,7 @@
const green = '#18FF74';
const darkgreen = '#00D672';
const turquoise = '#3CFFEC';
- const skyblue = '#61C3FF';
+ const blue = '#61C3FF';
const kingblue = '#5A87FF';
const lavender = '#8453E3';
const purple = '#C26EFF';
@@ -108,7 +108,7 @@
scale: [{ from: 1.4, to: .5, duration: 4000 }, { to: 1.6, duration: 2000 }],
rotate: [{ to: 45, duration: 2000 }],
zIndex: { to: 999, modifier: utils.round(0), ease: 'linear', duration: 25 },
- color: { to: el.dataset.clicked ? skyblue : orange, duration: 300, ease: 'out(4)' },
+ color: { to: el.dataset.clicked ? blue : orange, duration: 300, ease: 'out(4)' },
boxShadow: '0 0 10px 0 rgba(0, 0, 0, .3)',
duration: 900,
onBegin() { el.dataset.hover = true; },
diff --git a/tests/playground/waapi/composition/index.html b/tests/playground/waapi/composition/index.html
index f9fa23a5..01cb4ad0 100644
--- a/tests/playground/waapi/composition/index.html
+++ b/tests/playground/waapi/composition/index.html
@@ -36,7 +36,7 @@
color: var(--red);
}
.container-B .square {
- color: var(--orange);
+ color: var(--orange-1);
}
.container-C .square {
color: var(--yellow);
diff --git a/tests/playground/waapi/eases/index.js b/tests/playground/waapi/eases/index.js
index 2b0ddaac..770d9dab 100644
--- a/tests/playground/waapi/eases/index.js
+++ b/tests/playground/waapi/eases/index.js
@@ -18,7 +18,7 @@ for (let i = 0; i < total; i++) {
// targets.forEach(($el, i) => {
// animations[i] = $el.animate({
// transform: `rotate(${(i / total) * 360}deg) translateY(200px) scaleX(.25)`,
-// backgroundColor: [`var(--orange)`, `var(--red)`],
+// backgroundColor: [`var(--orange-1)`, `var(--red)`],
// }, {
// easing: 'linear(0, 0.02, 0.0749, 0.1573, 0.2596, 0.3749, 0.4966, 0.6191, 0.7374, 0.8476, 0.9467, 1.0325, 1.1038, 1.16, 1.2014, 1.2285, 1.2425, 1.245, 1.2376, 1.222, 1.2003, 1.1742, 1.1453, 1.1152, 1.0854, 1.0568, 1.0304, 1.007, 0.9869, 0.9704, 0.9576, 0.9484, 0.9427, 0.9401, 0.9402, 0.9426, 0.9468, 0.9525, 0.9592, 0.9664, 0.9737, 0.981, 0.9879, 0.9942, 0.9997, 1.0044, 1.0082, 1.0111, 1.0131, 1.0143, 1.0148, 1.0146, 1.0138, 1.0127, 1.0112, 1.0095, 1.0078, 1.0059, 1.0042, 1.0025, 1.001, 0.9997, 0.9986, 0.9978, 0.9971, 0.9967, 0.9964, 0.9965, 0.9967, 0.997, 0.9974, 0.9978, 0.9982, 0.9987, 0.9991, 0.9995, 0.9998, 1.0001, 1.0004, 1.0006, 1.0007, 1.0008, 1.0009, 1.0008, 1.0007, 1.0006, 1.0005, 1.0004, 1.0003, 1.0002, 1.0001, 1, 0.9999, 0.9998, 1)',
// iterations: Infinity,
@@ -38,7 +38,7 @@ for (let i = 0; i < total; i++) {
waapi.animate('.square', {
transform: (_, i) => `rotate(${(i / total) * 360}deg) translateY(200px) scaleX(.25)`,
backgroundColor: {
- to: [`var(--orange)`, `var(--red)`],
+ to: [`var(--orange-1)`, `var(--red)`],
ease: 'linear',
duration: 3000,
},
diff --git a/tests/playground/waapi/playback/index.html b/tests/playground/waapi/playback/index.html
index 71ca90a1..36c2c51a 100644
--- a/tests/playground/waapi/playback/index.html
+++ b/tests/playground/waapi/playback/index.html
@@ -34,7 +34,7 @@
margin-bottom: 10rem;
}
.square {
- --bg: var(--green);
+ --bg: var(--green-1);
position: relative;
width: 4rem;
height: 4rem;
diff --git a/tests/suites/engine.test.js b/tests/suites/engine.test.js
index 419a358a..5261fa24 100644
--- a/tests/suites/engine.test.js
+++ b/tests/suites/engine.test.js
@@ -26,7 +26,7 @@ suite('Engine', () => {
});
expect(animation1._offset).to.be.above(50); // Above the setTimeout value
expect(animation1._offset).to.be.below(animation2._offset); // Below animation2._offset
- expect(animation2._offset).to.be.above(animation1._offset + 15);
+ expect(animation2._offset).to.be.above(animation1._offset);
resolve();
}
});