repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/animation/animation.js | src/animation/animation.js | import {
K,
minValue,
tweenTypes,
valueTypes,
compositionTypes,
} from '../core/consts.js';
import {
mergeObjects,
cloneArray,
isArr,
isObj,
isUnd,
isKey,
addChild,
forEachChildren,
clampInfinity,
normalizeTime,
isNum,
round,
isNil,
} from '../core/helpers.js';
import {
globals,
} from '../core/globals.js';
import {
registerTargets,
} from '../core/targets.js';
import {
getRelativeValue,
getFunctionValue,
getOriginalAnimatableValue,
getTweenType,
setValue,
decomposeRawValue,
decomposeTweenValue,
decomposedOriginalValue,
createDecomposedValueTargetObject,
} from '../core/values.js';
import {
sanitizePropertyName,
cleanInlineStyles,
} from '../core/styles.js';
import {
convertValueUnit,
} from '../core/units.js';
import {
parseEase,
} from '../easings/eases/parser.js';
import {
Timer,
} from '../timer/timer.js';
import {
composeTween,
getTweenSiblings,
overrideTween,
} from './composition.js';
import {
additive,
} from './additive.js';
/**
* @import {
* Tween,
* TweenKeyValue,
* TweenParamsOptions,
* TweenValues,
* DurationKeyframes,
* PercentageKeyframes,
* AnimationParams,
* TweenPropValue,
* ArraySyntaxValue,
* TargetsParam,
* TimerParams,
* TweenParamValue,
* DOMTarget,
* TargetsArray,
* Callback,
* EasingFunction,
* } from '../types/index.js'
*
* @import {
* Timeline,
* } from '../timeline/timeline.js'
*
* @import {
* Spring,
* } from '../easings/spring/index.js'
*/
// Defines decomposed values target objects only once and mutate their properties later to avoid GC
// TODO: Maybe move the objects creation to values.js and use the decompose function to create the base object
const fromTargetObject = createDecomposedValueTargetObject();
const toTargetObject = createDecomposedValueTargetObject();
const inlineStylesStore = {};
const toFunctionStore = { func: null };
const keyframesTargetArray = [null];
const fastSetValuesArray = [null, null];
/** @type {TweenKeyValue} */
const keyObjectTarget = { to: null };
let tweenId = 0;
let keyframes;
/** @type {TweenParamsOptions & TweenValues} */
let key;
/**
* @param {DurationKeyframes | PercentageKeyframes} keyframes
* @param {AnimationParams} parameters
* @return {AnimationParams}
*/
const generateKeyframes = (keyframes, parameters) => {
/** @type {AnimationParams} */
const properties = {};
if (isArr(keyframes)) {
const propertyNames = [].concat(.../** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(isKey);
for (let i = 0, l = propertyNames.length; i < l; i++) {
const propName = propertyNames[i];
const propArray = /** @type {DurationKeyframes} */(keyframes).map(key => {
/** @type {TweenKeyValue} */
const newKey = {};
for (let p in key) {
const keyValue = /** @type {TweenPropValue} */(key[p]);
if (isKey(p)) {
if (p === propName) {
newKey.to = keyValue;
}
} else {
newKey[p] = keyValue;
}
}
return newKey;
});
properties[propName] = /** @type {ArraySyntaxValue} */(propArray);
}
} else {
const totalDuration = /** @type {Number} */(setValue(parameters.duration, globals.defaults.duration));
const keys = Object.keys(keyframes)
.map(key => { return {o: parseFloat(key) / 100, p: keyframes[key]} })
.sort((a, b) => a.o - b.o);
keys.forEach(key => {
const offset = key.o;
const prop = key.p;
for (let name in prop) {
if (isKey(name)) {
let propArray = /** @type {Array} */(properties[name]);
if (!propArray) propArray = properties[name] = [];
const duration = offset * totalDuration;
let length = propArray.length;
let prevKey = propArray[length - 1];
const keyObj = { to: prop[name] };
let durProgress = 0;
for (let i = 0; i < length; i++) {
durProgress += propArray[i].duration;
}
if (length === 1) {
keyObj.from = prevKey.to;
}
if (prop.ease) {
keyObj.ease = prop.ease;
}
keyObj.duration = duration - (length ? durProgress : 0);
propArray.push(keyObj);
}
}
return key;
});
for (let name in properties) {
const propArray = /** @type {Array} */(properties[name]);
let prevEase;
// let durProgress = 0
for (let i = 0, l = propArray.length; i < l; i++) {
const prop = propArray[i];
// Emulate WAPPI easing parameter position
const currentEase = prop.ease;
prop.ease = prevEase ? prevEase : undefined;
prevEase = currentEase;
// durProgress += prop.duration;
// if (i === l - 1 && durProgress !== totalDuration) {
// propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress })
// }
}
if (!propArray[0].duration) {
propArray.shift();
}
}
}
return properties;
}
export class JSAnimation extends Timer {
/**
* @param {TargetsParam} targets
* @param {AnimationParams} parameters
* @param {Timeline} [parent]
* @param {Number} [parentPosition]
* @param {Boolean} [fastSet=false]
* @param {Number} [index=0]
* @param {Number} [length=0]
*/
constructor(
targets,
parameters,
parent,
parentPosition,
fastSet = false,
index = 0,
length = 0
) {
super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
const parsedTargets = registerTargets(targets);
const targetsLength = parsedTargets.length;
// If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties
const kfParams = /** @type {AnimationParams} */(parameters).keyframes;
const params = /** @type {AnimationParams} */(kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters);
const {
delay,
duration,
ease,
playbackEase,
modifier,
composition,
onRender,
} = params;
const animDefaults = parent ? parent.defaults : globals.defaults;
const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
const animEase = animaPlaybackEase ? parseEase(animaPlaybackEase) : null;
const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease);
const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease);
const tDuration = hasSpring ? /** @type {Spring} */(ease).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
const tComposition = isUnd(composition) && targetsLength >= K ? compositionTypes.none : !isUnd(composition) ? composition : animDefaults.composition;
// 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;
let iterationDuration = NaN;
let iterationDelay = NaN;
let animationAnimationLength = 0;
let shouldTriggerRender = 0;
for (let targetIndex = 0; targetIndex < targetsLength; targetIndex++) {
const target = parsedTargets[targetIndex];
const ti = index || targetIndex;
const tl = length || targetsLength;
let lastTransformGroupIndex = NaN;
let lastTransformGroupLength = NaN;
for (let p in params) {
if (isKey(p)) {
const tweenType = getTweenType(target, p);
const propName = sanitizePropertyName(p, target, tweenType);
let propValue = params[p];
const isPropValueArray = isArr(propValue);
if (fastSet && !isPropValueArray) {
fastSetValuesArray[0] = propValue;
fastSetValuesArray[1] = propValue;
propValue = fastSetValuesArray;
}
// TODO: Allow nested keyframes inside ObjectValue value (prop: { to: [.5, 1, .75, 2, 3] })
// Normalize property values to valid keyframe syntax:
// [x, y] to [{to: [x, y]}] or {to: x} to [{to: x}] or keep keys syntax [{}, {}, {}...]
// const keyframes = isArr(propValue) ? propValue.length === 2 && !isObj(propValue[0]) ? [{ to: propValue }] : propValue : [propValue];
if (isPropValueArray) {
const arrayLength = /** @type {Array} */(propValue).length;
const isNotObjectValue = !isObj(propValue[0]);
// Convert [x, y] to [{to: [x, y]}]
if (arrayLength === 2 && isNotObjectValue) {
keyObjectTarget.to = /** @type {TweenParamValue} */(/** @type {unknown} */(propValue));
keyframesTargetArray[0] = keyObjectTarget;
keyframes = keyframesTargetArray;
// Convert [x, y, z] to [[x, y], z]
} else if (arrayLength > 2 && isNotObjectValue) {
keyframes = [];
/** @type {Array.<Number>} */(propValue).forEach((v, i) => {
if (!i) {
fastSetValuesArray[0] = v;
} else if (i === 1) {
fastSetValuesArray[1] = v;
keyframes.push(fastSetValuesArray);
} else {
keyframes.push(v);
}
});
} else {
keyframes = /** @type {Array.<TweenKeyValue>} */(propValue);
}
} else {
keyframesTargetArray[0] = propValue;
keyframes = keyframesTargetArray;
}
let siblings = null;
let prevTween = null;
let firstTweenChangeStartTime = NaN;
let lastTweenChangeEndTime = 0;
let tweenIndex = 0;
for (let l = keyframes.length; tweenIndex < l; tweenIndex++) {
const keyframe = keyframes[tweenIndex];
if (isObj(keyframe)) {
key = keyframe;
} else {
keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe);
key = keyObjectTarget;
}
toFunctionStore.func = null;
const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore);
let tweenToValue;
// Allows function based values to return an object syntax value ({to: v})
if (isObj(computedToValue) && !isUnd(computedToValue.to)) {
key = computedToValue;
tweenToValue = computedToValue.to;
} else {
tweenToValue = computedToValue;
}
const tweenFromValue = getFunctionValue(key.from, target, ti, tl);
const keyEasing = key.ease;
const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */(keyEasing).ease);
// Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time
const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing || tEasing;
// Calculate default individual keyframe duration by dividing the tl of keyframes
const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).settlingDuration : getFunctionValue(setValue(key.duration, (l > 1 ? getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl);
// Default delay value should only be applied to the first tween
const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl);
const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl);
const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition];
// Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper
const tweenModifier = key.modifier || tModifier;
const hasFromvalue = !isUnd(tweenFromValue);
const hasToValue = !isUnd(tweenToValue);
const isFromToArray = isArr(tweenToValue);
const isFromToValue = isFromToArray || (hasFromvalue && hasToValue);
const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay;
// Rounding is necessary here to minimize floating point errors when working in seconds
const absoluteStartTime = round(absoluteOffsetTime + tweenStartTime, 12);
// Force a onRender callback if the animation contains at least one from value and autoplay is set to false
if (!shouldTriggerRender && (hasFromvalue || isFromToArray)) shouldTriggerRender = 1;
let prevSibling = prevTween;
if (tweenComposition !== compositionTypes.none) {
if (!siblings) siblings = getTweenSiblings(target, propName);
let nextSibling = siblings._head;
// Iterate trough all the next siblings until we find a sibling with an equal or inferior start time
while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) {
prevSibling = nextSibling;
nextSibling = nextSibling._nextRep;
// Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time
if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) {
while (nextSibling) {
overrideTween(nextSibling);
// This will ends both the current while loop and the upper one once all the next sibllings have been overriden
nextSibling = nextSibling._nextRep;
}
}
}
}
// Decompose values
if (isFromToValue) {
decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject);
decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject);
if (fromTargetObject.t === valueTypes.NUMBER) {
if (prevSibling) {
if (prevSibling._valueType === valueTypes.UNIT) {
fromTargetObject.t = valueTypes.UNIT;
fromTargetObject.u = prevSibling._unit;
}
} else {
decomposeRawValue(
getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore),
decomposedOriginalValue
);
if (decomposedOriginalValue.t === valueTypes.UNIT) {
fromTargetObject.t = valueTypes.UNIT;
fromTargetObject.u = decomposedOriginalValue.u;
}
}
}
} else {
if (hasToValue) {
decomposeRawValue(tweenToValue, toTargetObject);
} else {
if (prevTween) {
decomposeTweenValue(prevTween, toTargetObject);
} else {
// No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore), toTargetObject);
}
}
if (hasFromvalue) {
decomposeRawValue(tweenFromValue, fromTargetObject);
} else {
if (prevTween) {
decomposeTweenValue(prevTween, fromTargetObject);
} else {
decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
// No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore), fromTargetObject);
}
}
}
// Apply operators
if (fromTargetObject.o) {
fromTargetObject.n = getRelativeValue(
!prevSibling ? decomposeRawValue(
getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore),
decomposedOriginalValue
).n : prevSibling._toNumber,
fromTargetObject.n,
fromTargetObject.o
);
}
if (toTargetObject.o) {
toTargetObject.n = getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o);
}
// Values omogenisation in cases of type difference between "from" and "to"
if (fromTargetObject.t !== toTargetObject.t) {
if (fromTargetObject.t === valueTypes.COMPLEX || toTargetObject.t === valueTypes.COMPLEX) {
const complexValue = fromTargetObject.t === valueTypes.COMPLEX ? fromTargetObject : toTargetObject;
const notComplexValue = fromTargetObject.t === valueTypes.COMPLEX ? toTargetObject : fromTargetObject;
notComplexValue.t = valueTypes.COMPLEX;
notComplexValue.s = cloneArray(complexValue.s);
notComplexValue.d = complexValue.d.map(() => notComplexValue.n);
} else if (fromTargetObject.t === valueTypes.UNIT || toTargetObject.t === valueTypes.UNIT) {
const unitValue = fromTargetObject.t === valueTypes.UNIT ? fromTargetObject : toTargetObject;
const notUnitValue = fromTargetObject.t === valueTypes.UNIT ? toTargetObject : fromTargetObject;
notUnitValue.t = valueTypes.UNIT;
notUnitValue.u = unitValue.u;
} else if (fromTargetObject.t === valueTypes.COLOR || toTargetObject.t === valueTypes.COLOR) {
const colorValue = fromTargetObject.t === valueTypes.COLOR ? fromTargetObject : toTargetObject;
const notColorValue = fromTargetObject.t === valueTypes.COLOR ? toTargetObject : fromTargetObject;
notColorValue.t = valueTypes.COLOR;
notColorValue.s = colorValue.s;
notColorValue.d = [0, 0, 0, 1];
}
}
// Unit conversion
if (fromTargetObject.u !== toTargetObject.u) {
let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject;
valueToConvert = convertValueUnit(/** @type {DOMTarget} */(target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false);
// TODO:
// convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u);
}
// Fill in non existing complex values
if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) {
const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject;
const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject;
// TODO: Check if n should be used instead of 0 for default complex values
shortestValue.d = longestValue.d.map((/** @type {Number} */_, /** @type {Number} */i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
shortestValue.s = cloneArray(longestValue.s);
}
// Tween factory
// Rounding is necessary here to minimize floating point errors when working in seconds
const tweenUpdateDuration = round(+tweenDuration || minValue, 12);
// Copy the value of the iniline style if it exist and imediatly nullify it to prevents false positive on other targets
let inlineValue = inlineStylesStore[propName];
if (!isNil(inlineValue)) inlineStylesStore[propName] = null;
/** @type {Tween} */
const tween = {
parent: this,
id: tweenId++,
property: propName,
target: target,
_value: null,
_func: toFunctionStore.func,
_ease: parseEase(tweenEasing),
_fromNumbers: cloneArray(fromTargetObject.d),
_toNumbers: cloneArray(toTargetObject.d),
_strings: cloneArray(toTargetObject.s),
_fromNumber: fromTargetObject.n,
_toNumber: toTargetObject.n,
_numbers: cloneArray(fromTargetObject.d), // For additive tween and animatables
_number: fromTargetObject.n, // For additive tween and animatables
_unit: toTargetObject.u,
_modifier: tweenModifier,
_currentTime: 0,
_startTime: tweenStartTime,
_delay: +tweenDelay,
_updateDuration: tweenUpdateDuration,
_changeDuration: tweenUpdateDuration,
_absoluteStartTime: absoluteStartTime,
// NOTE: Investigate bit packing to stores ENUM / BOOL
_tweenType: tweenType,
_valueType: toTargetObject.t,
_composition: tweenComposition,
_isOverlapped: 0,
_isOverridden: 0,
_renderTransforms: 0,
_inlineValue: inlineValue,
_prevRep: null, // For replaced tween
_nextRep: null, // For replaced tween
_prevAdd: null, // For additive tween
_nextAdd: null, // For additive tween
_prev: null,
_next: null,
}
if (tweenComposition !== compositionTypes.none) {
composeTween(tween, siblings);
}
if (isNaN(firstTweenChangeStartTime)) {
firstTweenChangeStartTime = tween._startTime;
}
// Rounding is necessary here to minimize floating point errors when working in seconds
lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12);
prevTween = tween;
animationAnimationLength++;
addChild(this, tween);
}
// Update animation timings with the added tweens properties
if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) {
iterationDelay = firstTweenChangeStartTime;
}
if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) {
iterationDuration = lastTweenChangeEndTime;
}
// TODO: Find a way to inline tween._renderTransforms = 1 here
if (tweenType === tweenTypes.TRANSFORM) {
lastTransformGroupIndex = animationAnimationLength - tweenIndex;
lastTransformGroupLength = animationAnimationLength;
}
}
}
// Set _renderTransforms to last transform property to correctly render the transforms list
if (!isNaN(lastTransformGroupIndex)) {
let i = 0;
forEachChildren(this, (/** @type {Tween} */tween) => {
if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) {
tween._renderTransforms = 1;
if (tween._composition === compositionTypes.blend) {
forEachChildren(additive.animation, (/** @type {Tween} */additiveTween) => {
if (additiveTween.id === tween.id) {
additiveTween._renderTransforms = 1;
}
});
}
}
i++;
});
}
}
if (!targetsLength) {
console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
}
if (iterationDelay) {
forEachChildren(this, (/** @type {Tween} */tween) => {
// If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too
if (!(tween._startTime - tween._delay)) {
tween._delay -= iterationDelay;
}
tween._startTime -= iterationDelay;
});
iterationDuration -= iterationDelay;
} else {
iterationDelay = 0;
}
// Prevents iterationDuration to be NaN if no valid animatable props have been provided
// Prevents _iterationCount to be NaN if no valid animatable props have been provided
if (!iterationDuration) {
iterationDuration = minValue;
this.iterationCount = 0;
}
/** @type {TargetsArray} */
this.targets = parsedTargets;
/** @type {Number} */
this.duration = iterationDuration === minValue ? minValue : clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || minValue;
/** @type {Callback<this>} */
this.onRender = onRender || animDefaults.onRender;
/** @type {EasingFunction} */
this._ease = animEase;
/** @type {Number} */
this._delay = iterationDelay;
// NOTE: I'm keeping delay values separated from offsets in timelines because delays can override previous tweens and it could be confusing to debug a timeline with overridden tweens and no associated visible delays.
// this._delay = parent ? 0 : iterationDelay;
// this._offset += parent ? iterationDelay : 0;
/** @type {Number} */
this.iterationDuration = iterationDuration;
if (!this._autoplay && shouldTriggerRender) this.onRender(this);
}
/**
* @param {Number} newDuration
* @return {this}
*/
stretch(newDuration) {
const currentDuration = this.duration;
if (currentDuration === normalizeTime(newDuration)) return this;
const timeScale = newDuration / currentDuration;
// NOTE: Find a better way to handle the stretch of an animation after stretch = 0
forEachChildren(this, (/** @type {Tween} */tween) => {
// Rounding is necessary here to minimize floating point errors
tween._updateDuration = normalizeTime(tween._updateDuration * timeScale);
tween._changeDuration = normalizeTime(tween._changeDuration * timeScale);
tween._currentTime *= timeScale;
tween._startTime *= timeScale;
tween._absoluteStartTime *= timeScale;
});
return super.stretch(newDuration);
}
/**
* @return {this}
*/
refresh() {
forEachChildren(this, (/** @type {Tween} */tween) => {
const tweenFunc = tween._func;
if (tweenFunc) {
const ogValue = getOriginalAnimatableValue(tween.target, tween.property, tween._tweenType);
decomposeRawValue(ogValue, decomposedOriginalValue);
// TODO: Check for from / to Array based values here,
decomposeRawValue(tweenFunc(), toTargetObject);
tween._fromNumbers = cloneArray(decomposedOriginalValue.d);
tween._fromNumber = decomposedOriginalValue.n;
tween._toNumbers = cloneArray(toTargetObject.d);
tween._strings = cloneArray(toTargetObject.s);
// Make sure to apply relative operators https://github.com/juliangarnier/anime/issues/1025
tween._toNumber = toTargetObject.o ? getRelativeValue(decomposedOriginalValue.n, toTargetObject.n, toTargetObject.o) : toTargetObject.n;
}
});
// This forces setter animations to render once
if (this.duration === minValue) this.restart();
return this;
}
/**
* Cancel the animation and revert all the values affected by this animation to their original state
* @return {this}
*/
revert() {
super.revert();
return cleanInlineStyles(this);
}
/**
* @typedef {this & {then: null}} ResolvedJSAnimation
*/
/**
* @param {Callback<ResolvedJSAnimation>} [callback]
* @return Promise<this>
*/
then(callback) {
return super.then(callback);
}
}
/**
* @param {TargetsParam} targets
* @param {AnimationParams} parameters
* @return {JSAnimation}
*/
export const animate = (targets, parameters) => new JSAnimation(targets, parameters, null, 0, false).init();
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/waapi/composition.js | src/waapi/composition.js | import { addChild, removeChild } from "../core/helpers.js";
/**
* @import {
* DOMTarget,
* } from '../types/index.js'
*/
/**
* @import {
* WAAPIAnimation,
* } from '../waapi/waapi.js'
*/
const WAAPIAnimationsLookups = {
_head: null,
_tail: null,
}
/**
* @param {DOMTarget} $el
* @param {String} [property]
* @param {WAAPIAnimation} [parent]
* @return {globalThis.Animation}
*/
export const removeWAAPIAnimation = ($el, property, parent) => {
let nextLookup = WAAPIAnimationsLookups._head;
let anim;
while (nextLookup) {
const next = nextLookup._next;
const matchTarget = nextLookup.$el === $el;
const matchProperty = !property || nextLookup.property === property;
const matchParent = !parent || nextLookup.parent === parent;
if (matchTarget && matchProperty && matchParent) {
anim = nextLookup.animation;
try { anim.commitStyles(); } catch {};
anim.cancel();
removeChild(WAAPIAnimationsLookups, nextLookup);
const lookupParent = nextLookup.parent;
if (lookupParent) {
lookupParent._completed++;
if (lookupParent.animations.length === lookupParent._completed) {
lookupParent.completed = true;
lookupParent.paused = true;
if (!lookupParent.muteCallbacks) {
lookupParent.onComplete(lookupParent);
lookupParent._resolve(lookupParent);
}
}
}
}
nextLookup = next;
}
return anim;
}
/**
* @param {WAAPIAnimation} parent
* @param {DOMTarget} $el
* @param {String} property
* @param {PropertyIndexedKeyframes} keyframes
* @param {KeyframeAnimationOptions} params
* @retun {globalThis.Animation}
*/
export const addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
const animation = $el.animate(keyframes, params);
const animTotalDuration = params.delay + (+params.duration * params.iterations);
animation.playbackRate = parent._speed;
if (parent.paused) animation.pause();
if (parent.duration < animTotalDuration) {
parent.duration = animTotalDuration;
parent.controlAnimation = animation;
}
parent.animations.push(animation);
removeWAAPIAnimation($el, property);
addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null });
const handleRemove = () => { removeWAAPIAnimation($el, property, parent); };
animation.oncancel = handleRemove;
animation.onremove = handleRemove;
if (!parent.persist) {
animation.onfinish = handleRemove;
}
return animation;
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/waapi/index.js | src/waapi/index.js | export * from './waapi.js'; | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/waapi/waapi.js | src/waapi/waapi.js | import {
isArr,
isKey,
isNum,
isObj,
isStr,
isUnd,
isFnc,
stringStartsWith,
toLowerCase,
isNil,
round,
} from '../core/helpers.js';
import {
scope,
globals,
} from '../core/globals.js';
import {
registerTargets,
} from '../core/targets.js';
import {
getFunctionValue,
setValue,
} from '../core/values.js';
import {
isBrowser,
K,
noop,
emptyString,
shortTransforms,
transformsFragmentStrings,
transformsSymbol,
validTransforms,
cssVarPrefix,
} from '../core/consts.js';
import {
none,
} from '../easings/none.js';
import {
parseEaseString,
} from '../easings/eases/parser.js';
import {
addWAAPIAnimation,
} from './composition.js';
/**
* @import {
* Callback,
* EasingFunction,
* EasingParam,
* DOMTarget,
* DOMTargetsParam,
* DOMTargetsArray,
* WAAPIAnimationParams,
* WAAPITweenOptions,
* WAAPIKeyframeValue,
* WAAPITweenValue
* } from '../types/index.js'
*/
/**
* @import {
* Spring,
* } from '../easings/spring/index.js'
*/
/**
* @import {
* ScrollObserver,
* } from '../events/scroll.js'
*/
/**
* Converts an easing function into a valid CSS linear() timing function string
* @param {EasingFunction} fn
* @param {number} [samples=100]
* @returns {string} CSS linear() timing function
*/
const easingToLinear = (fn, samples = 100) => {
const points = [];
for (let i = 0; i <= samples; i++) points.push(round(fn(i / samples), 4));
return `linear(${points.join(', ')})`;
}
const WAAPIEasesLookups = {}
/**
* @param {EasingParam} ease
* @return {String}
*/
const parseWAAPIEasing = (ease) => {
let parsedEase = WAAPIEasesLookups[ease];
if (parsedEase) return parsedEase;
parsedEase = 'linear';
if (isStr(ease)) {
if (
stringStartsWith(ease, 'linear') ||
stringStartsWith(ease, 'cubic-') ||
stringStartsWith(ease, 'steps') ||
stringStartsWith(ease, 'ease')
) {
parsedEase = ease;
} else if (stringStartsWith(ease, 'cubicB')) {
parsedEase = toLowerCase(ease);
} else {
const parsed = parseEaseString(ease);
if (isFnc(parsed)) parsedEase = parsed === none ? 'linear' : easingToLinear(parsed);
}
// Only cache string based easing name, otherwise function arguments get lost
WAAPIEasesLookups[ease] = parsedEase;
} else if (isFnc(ease)) {
const easing = easingToLinear(ease);
if (easing) parsedEase = easing;
} else if (/** @type {Spring} */(ease).ease) {
parsedEase = easingToLinear(/** @type {Spring} */(ease).ease);
}
return parsedEase;
}
const transformsShorthands = ['x', 'y', 'z'];
const commonDefaultPXProperties = [
'perspective',
'width',
'height',
'margin',
'padding',
'top',
'right',
'bottom',
'left',
'borderWidth',
'fontSize',
'borderRadius',
...transformsShorthands
]
const validIndividualTransforms = /*#__PURE__*/ (() => [...transformsShorthands, ...validTransforms.filter(t => ['X', 'Y', 'Z'].some(axis => t.endsWith(axis)))])();
let transformsPropertiesRegistered = null;
/**
* @param {String} propName
* @param {WAAPIKeyframeValue} value
* @param {DOMTarget} $el
* @param {Number} i
* @param {Number} targetsLength
* @return {String}
*/
const normalizeTweenValue = (propName, value, $el, i, targetsLength) => {
// Do not try to compute strings with getFunctionValue otherwise it will convert CSS variables
let v = isStr(value) ? value : getFunctionValue(/** @type {any} */(value), $el, i, targetsLength);
if (!isNum(v)) return v;
if (commonDefaultPXProperties.includes(propName) || stringStartsWith(propName, 'translate')) return `${v}px`;
if (stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew')) return `${v}deg`;
return `${v}`;
}
/**
* @param {DOMTarget} $el
* @param {String} propName
* @param {WAAPIKeyframeValue} from
* @param {WAAPIKeyframeValue} to
* @param {Number} i
* @param {Number} targetsLength
* @return {WAAPITweenValue}
*/
const parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => {
/** @type {WAAPITweenValue} */
let tweenValue = '0';
const computedTo = !isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName];
if (!isUnd(from)) {
const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength);
tweenValue = [computedFrom, computedTo];
} else {
tweenValue = isArr(to) ? to.map((/** @type {any} */v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo;
}
return tweenValue;
}
export class WAAPIAnimation {
/**
* @param {DOMTargetsParam} targets
* @param {WAAPIAnimationParams} params
*/
constructor(targets, params) {
if (scope.current) scope.current.register(this);
// Skip the registration and fallback to no animation in case CSS.registerProperty is not supported
if (isNil(transformsPropertiesRegistered)) {
if (isBrowser && (isUnd(CSS) || !Object.hasOwnProperty.call(CSS, 'registerProperty'))) {
transformsPropertiesRegistered = false;
} else {
validTransforms.forEach(t => {
const isSkew = stringStartsWith(t, 'skew');
const isScale = stringStartsWith(t, 'scale');
const isRotate = stringStartsWith(t, 'rotate');
const isTranslate = stringStartsWith(t, 'translate');
const isAngle = isRotate || isSkew;
const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*";
try {
CSS.registerProperty({
name: '--' + t,
syntax,
inherits: false,
initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0',
});
} catch {};
});
transformsPropertiesRegistered = true;
}
}
const parsedTargets = registerTargets(targets);
const targetsLength = parsedTargets.length;
if (!targetsLength) {
console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
}
const ease = setValue(params.ease, parseWAAPIEasing(globals.defaults.ease));
const spring = /** @type {Spring} */(ease).ease && ease;
const autoplay = setValue(params.autoplay, globals.defaults.autoplay);
const scroll = autoplay && /** @type {ScrollObserver} */(autoplay).link ? autoplay : false;
const alternate = params.alternate && /** @type {Boolean} */(params.alternate) === true;
const reversed = params.reversed && /** @type {Boolean} */(params.reversed) === true;
const loop = setValue(params.loop, globals.defaults.loop);
const iterations = /** @type {Number} */((loop === true || loop === Infinity) ? Infinity : isNum(loop) ? loop + 1 : 1);
/** @type {PlaybackDirection} */
const direction = alternate ? reversed ? 'alternate-reverse' : 'alternate' : reversed ? 'reverse' : 'normal';
/** @type {FillMode} */
const fill = 'both'; // We use 'both' here because the animation can be reversed during playback
/** @type {String} */
const easing = parseWAAPIEasing(ease);
const timeScale = (globals.timeScale === 1 ? 1 : K);
/** @type {DOMTargetsArray}] */
this.targets = parsedTargets;
/** @type {Array<globalThis.Animation>}] */
this.animations = [];
/** @type {globalThis.Animation}] */
this.controlAnimation = null;
/** @type {Callback<this>} */
this.onComplete = params.onComplete || /** @type {Callback<WAAPIAnimation>} */(/** @type {unknown} */(globals.defaults.onComplete));
/** @type {Number} */
this.duration = 0;
/** @type {Boolean} */
this.muteCallbacks = false;
/** @type {Boolean} */
this.completed = false;
/** @type {Boolean} */
this.paused = !autoplay || scroll !== false;
/** @type {Boolean} */
this.reversed = reversed;
/** @type {Boolean} */
this.persist = setValue(params.persist, globals.defaults.persist);
/** @type {Boolean|ScrollObserver} */
this.autoplay = autoplay;
/** @type {Number} */
this._speed = setValue(params.playbackRate, globals.defaults.playbackRate);
/** @type {Function} */
this._resolve = noop; // Used by .then()
/** @type {Number} */
this._completed = 0;
/** @type {Array.<Object>} */
this._inlineStyles = [];
parsedTargets.forEach(($el, i) => {
const cachedTransforms = $el[transformsSymbol];
const hasIndividualTransforms = validIndividualTransforms.some(t => params.hasOwnProperty(t));
const elStyle = $el.style;
const inlineStyles = this._inlineStyles[i] = {};
/** @type {Number} */
const duration = (spring ? /** @type {Spring} */(spring).settlingDuration : getFunctionValue(setValue(params.duration, globals.defaults.duration), $el, i, targetsLength)) * timeScale;
/** @type {Number} */
const delay = getFunctionValue(setValue(params.delay, globals.defaults.delay), $el, i, targetsLength) * timeScale;
/** @type {CompositeOperation} */
const composite = /** @type {CompositeOperation} */(setValue(params.composition, 'replace'));
for (let name in params) {
if (!isKey(name)) continue;
/** @type {PropertyIndexedKeyframes} */
const keyframes = {};
/** @type {KeyframeAnimationOptions} */
const tweenParams = { iterations, direction, fill, easing, duration, delay, composite };
const propertyValue = params[name];
const individualTransformProperty = hasIndividualTransforms ? validTransforms.includes(name) ? name : shortTransforms.get(name) : false;
const styleName = individualTransformProperty ? 'transform' : name;
if (!inlineStyles[styleName]) {
inlineStyles[styleName] = elStyle[styleName];
}
let parsedPropertyValue;
if (isObj(propertyValue)) {
const tweenOptions = /** @type {WAAPITweenOptions} */(propertyValue);
const tweenOptionsEase = setValue(tweenOptions.ease, ease);
const tweenOptionsSpring = /** @type {Spring} */(tweenOptionsEase).ease && tweenOptionsEase;
const to = /** @type {WAAPITweenOptions} */(tweenOptions).to;
const from = /** @type {WAAPITweenOptions} */(tweenOptions).from;
/** @type {Number} */
tweenParams.duration = (tweenOptionsSpring ? /** @type {Spring} */(tweenOptionsSpring).settlingDuration : getFunctionValue(setValue(tweenOptions.duration, duration), $el, i, targetsLength)) * timeScale;
/** @type {Number} */
tweenParams.delay = getFunctionValue(setValue(tweenOptions.delay, delay), $el, i, targetsLength) * timeScale;
/** @type {CompositeOperation} */
tweenParams.composite = /** @type {CompositeOperation} */(setValue(tweenOptions.composition, composite));
/** @type {String} */
tweenParams.easing = parseWAAPIEasing(tweenOptionsEase);
parsedPropertyValue = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
if (individualTransformProperty) {
keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
cachedTransforms[individualTransformProperty] = parsedPropertyValue;
} else {
keyframes[name] = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
}
addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
if (!isUnd(from)) {
if (!individualTransformProperty) {
elStyle[name] = keyframes[name][0];
} else {
const key = `--${individualTransformProperty}`;
elStyle.setProperty(key, keyframes[key][0]);
}
}
} else {
parsedPropertyValue = isArr(propertyValue) ?
propertyValue.map((/** @type {any} */v) => normalizeTweenValue(name, v, $el, i, targetsLength)) :
normalizeTweenValue(name, /** @type {any} */(propertyValue), $el, i, targetsLength);
if (individualTransformProperty) {
keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
cachedTransforms[individualTransformProperty] = parsedPropertyValue;
} else {
keyframes[name] = parsedPropertyValue;
}
addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
}
}
if (hasIndividualTransforms) {
let transforms = emptyString;
for (let t in cachedTransforms) {
transforms += `${transformsFragmentStrings[t]}var(--${t})) `;
}
elStyle.transform = transforms;
}
});
if (scroll) {
/** @type {ScrollObserver} */(this.autoplay).link(this);
}
}
/**
* @callback forEachCallback
* @param {globalThis.Animation} animation
*/
/**
* @param {forEachCallback|String} callback
* @return {this}
*/
forEach(callback) {
const cb = isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback;
this.animations.forEach(cb);
return this;
}
get speed() {
return this._speed;
}
set speed(speed) {
this._speed = +speed;
this.forEach(anim => anim.playbackRate = speed);
}
get currentTime() {
const controlAnimation = this.controlAnimation;
const timeScale = globals.timeScale;
return this.completed ? this.duration : controlAnimation ? +controlAnimation.currentTime * (timeScale === 1 ? 1 : timeScale) : 0;
}
set currentTime(time) {
const t = time * (globals.timeScale === 1 ? 1 : K);
this.forEach(anim => {
// Make sure the animation playState is not 'paused' in order to properly trigger an onfinish callback.
// The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported.
// https://developer.mozilla.org/en-US/docs/Web/API/Animation/finish_event
// This is not needed for persisting animations since they never finish.
if (!this.persist && t >= this.duration) anim.play();
anim.currentTime = t;
});
}
get progress() {
return this.currentTime / this.duration;
}
set progress(progress) {
this.forEach(anim => anim.currentTime = progress * this.duration || 0);
}
resume() {
if (!this.paused) return this;
this.paused = false;
// TODO: Store the current time, and seek back to the last position
return this.forEach('play');
}
pause() {
if (this.paused) return this;
this.paused = true;
return this.forEach('pause');
}
alternate() {
this.reversed = !this.reversed;
this.forEach('reverse');
if (this.paused) this.forEach('pause');
return this;
}
play() {
if (this.reversed) this.alternate();
return this.resume();
}
reverse() {
if (!this.reversed) this.alternate();
return this.resume();
}
/**
* @param {Number} time
* @param {Boolean} muteCallbacks
*/
seek(time, muteCallbacks = false) {
if (muteCallbacks) this.muteCallbacks = true;
if (time < this.duration) this.completed = false;
this.currentTime = time;
this.muteCallbacks = false;
if (this.paused) this.pause();
return this;
}
restart() {
this.completed = false;
return this.seek(0, true).resume();
}
commitStyles() {
return this.forEach('commitStyles');
}
complete() {
return this.seek(this.duration);
}
cancel() {
this.muteCallbacks = true; // This prevents triggering the onComplete callback and resolving the Promise
return this.commitStyles().forEach('cancel');
}
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,
// and update the CSS variables with the orignal value
this.cancel().targets.forEach(($el, i) => {
const targetStyle = $el.style;
const targetInlineStyles = this._inlineStyles[i];
for (let name in targetInlineStyles) {
const originalInlinedValue = targetInlineStyles[name];
if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) {
targetStyle.removeProperty(toLowerCase(name));
} else {
targetStyle[name] = originalInlinedValue;
}
}
// Remove style attribute if empty
if ($el.getAttribute('style') === emptyString) $el.removeAttribute('style');
});
return this;
}
/**
* @typedef {this & {then: null}} ResolvedWAAPIAnimation
*/
/**
* @param {Callback<ResolvedWAAPIAnimation>} [callback]
* @return Promise<this>
*/
then(callback = noop) {
const then = this.then;
const onResolve = () => {
this.then = null;
callback(/** @type {ResolvedWAAPIAnimation} */(this));
this.then = then;
this._resolve = noop;
}
return new Promise(r => {
this._resolve = () => r(onResolve());
if (this.completed) this._resolve();
return this;
});
}
}
export const waapi = {
/**
* @param {DOMTargetsParam} targets
* @param {WAAPIAnimationParams} params
* @return {WAAPIAnimation}
*/
animate: (targets, params) => new WAAPIAnimation(targets, params),
convertEase: easingToLinear
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/animatable/index.js | src/animatable/index.js | export * from './animatable.js'; | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/animatable/animatable.js | src/animatable/animatable.js | import {
compositionTypes,
noop
} from '../core/consts.js';
import {
scope,
} from '../core/globals.js';
import {
isKey,
isObj,
isStr,
isUnd,
mergeObjects,
forEachChildren,
isArr,
stringStartsWith,
} from '../core/helpers.js';
import {
JSAnimation,
} from '../animation/animation.js';
import {
parseEase,
} from '../easings/eases/parser.js';
/**
* @import {
* TargetsParam,
* AnimatableParams,
* AnimationParams,
* TweenParamsOptions,
* Tween,
* AnimatableProperty,
* AnimatableObject,
* } from '../types/index.js';
*/
export class Animatable {
/**
* @param {TargetsParam} targets
* @param {AnimatableParams} parameters
*/
constructor(targets, parameters) {
if (scope.current) scope.current.register(this);
const beginHandler = () => {
if (this.callbacks.completed) this.callbacks.reset();
this.callbacks.play();
};
const pauseHandler = () => {
if (this.callbacks.completed) return;
let paused = true;
for (let name in this.animations) {
const anim = this.animations[name];
if (!anim.paused && paused) {
paused = false;
break;
}
}
if (paused) {
this.callbacks.complete();
}
};
/** @type {AnimationParams} */
const globalParams = {
onBegin: beginHandler,
onComplete: pauseHandler,
onPause: pauseHandler,
};
/** @type {AnimationParams} */
const callbacksAnimationParams = { v: 1, autoplay: false };
const properties = {};
this.targets = [];
this.animations = {};
/** @type {JSAnimation|null} */
this.callbacks = null;
if (isUnd(targets) || isUnd(parameters)) return;
for (let propName in parameters) {
const paramValue = parameters[propName];
if (isKey(propName)) {
properties[propName] = paramValue;
} else if (stringStartsWith(propName, 'on')) {
callbacksAnimationParams[propName] = paramValue;
} else {
globalParams[propName] = paramValue;
}
}
this.callbacks = new JSAnimation({ v: 0 }, callbacksAnimationParams);
for (let propName in properties) {
const propValue = properties[propName];
const isObjValue = isObj(propValue);
/** @type {TweenParamsOptions} */
let propParams = {};
let to = '+=0';
if (isObjValue) {
const unit = propValue.unit;
if (isStr(unit)) to += unit;
} else {
propParams.duration = propValue;
}
propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to;
const animParams = mergeObjects(globalParams, propParams);
animParams.composition = compositionTypes.replace;
animParams.autoplay = false;
const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init();
if (!this.targets.length) this.targets.push(...animation.targets);
/** @type {AnimatableProperty} */
this[propName] = (to, duration, ease) => {
const tween = /** @type {Tween} */(animation._head);
if (isUnd(to) && tween) {
const numbers = tween._numbers;
if (numbers && numbers.length) {
return numbers;
} else {
return tween._modifier(tween._number);
}
} else {
forEachChildren(animation, (/** @type {Tween} */tween) => {
if (isArr(to)) {
for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) {
if (!isUnd(tween._numbers[i])) {
tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i]));
tween._toNumbers[i] = to[i];
}
}
} else {
tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number));
tween._toNumber = /** @type {Number} */(to);
}
if (!isUnd(ease)) tween._ease = parseEase(ease);
tween._currentTime = 0;
});
if (!isUnd(duration)) animation.stretch(duration);
animation.reset(true).resume();
return this;
}
};
}
}
revert() {
for (let propName in this.animations) {
this[propName] = noop;
this.animations[propName].revert();
}
this.animations = {};
this.targets.length = 0;
if (this.callbacks) this.callbacks.revert();
return this;
}
}
/**
* @param {TargetsParam} targets
* @param {AnimatableParams} parameters
* @return {AnimatableObject}
*/
export const createAnimatable = (targets, parameters) => /** @type {AnimatableObject} */ (new Animatable(targets, parameters));
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/svg/index.js | src/svg/index.js | export { createMotionPath } from "./motionpath.js";
export { createDrawable } from "./drawable.js";
export { morphTo } from "./morphto.js"; | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/svg/morphto.js | src/svg/morphto.js | import {
morphPointsSymbol,
} from '../core/consts.js';
import {
round,
} from '../core/helpers.js';
import {
getPath,
} from './helpers.js';
/**
* @import {
* TargetsParam,
* FunctionValue
* } from '../types/index.js'
*/
/**
* @param {TargetsParam} path2
* @param {Number} [precision]
* @return {FunctionValue}
*/
export const morphTo = (path2, precision = .33) => ($path1) => {
const tagName1 = ($path1.tagName || '').toLowerCase();
if (!tagName1.match(/^(path|polygon|polyline)$/)) {
throw new Error(`Can't morph a <${$path1.tagName}> SVG element. Use <path>, <polygon> or <polyline>.`);
}
const $path2 = /** @type {SVGGeometryElement} */(getPath(path2));
if (!$path2) {
throw new Error("Can't morph to an invalid target. 'path2' must resolve to an existing <path>, <polygon> or <polyline> SVG element.");
}
const tagName2 = ($path2.tagName || '').toLowerCase();
if (!tagName2.match(/^(path|polygon|polyline)$/)) {
throw new Error(`Can't morph a <${$path2.tagName}> SVG element. Use <path>, <polygon> or <polyline>.`);
}
const isPath = $path1.tagName === 'path';
const separator = isPath ? ' ' : ',';
const previousPoints = $path1[morphPointsSymbol];
if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints);
let v1 = '', v2 = '';
if (!precision) {
v1 = $path1.getAttribute(isPath ? 'd' : 'points');
v2 = $path2.getAttribute(isPath ? 'd' : 'points');
} else {
const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength();
const length2 = $path2.getTotalLength();
const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision));
for (let i = 0; i < maxPoints; i++) {
const t = i / (maxPoints - 1);
const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t);
const pointOnPath2 = $path2.getPointAtLength(length2 * t);
const prefix = isPath ? (i === 0 ? 'M' : 'L') : '';
v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' ';
v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' ';
}
}
$path1[morphPointsSymbol] = v2;
return [v1, v2];
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/svg/motionpath.js | src/svg/motionpath.js | import {
isSvgSymbol,
} from '../core/consts.js';
import {
atan2,
PI,
} from '../core/helpers.js';
import {
getPath,
} from './helpers.js';
/**
* @import {
* TargetsParam,
* FunctionValue,
* TweenObjectValue,
* TweenModifier,
* } from '../types/index.js'
*/
// Motion path animation
/**
* @param {SVGGeometryElement} $path
* @param {Number} totalLength
* @param {Number} progress
* @param {Number} lookup
* @param {Boolean} shouldClamp
* @return {DOMPoint}
*/
const getPathPoint = ($path, totalLength, progress, lookup, shouldClamp) => {
const point = progress + lookup;
const pointOnPath = shouldClamp
? Math.max(0, Math.min(point, totalLength)) // Clamp between 0 and totalLength
: (point % totalLength + totalLength) % totalLength; // Wrap around
return $path.getPointAtLength(pointOnPath);
}
/**
* @param {SVGGeometryElement} $path
* @param {String} pathProperty
* @param {Number} [offset=0]
* @return {FunctionValue}
*/
const getPathProgess = ($path, pathProperty, offset = 0) => {
return $el => {
const totalLength = +($path.getTotalLength());
const inSvg = $el[isSvgSymbol];
const ctm = $path.getCTM();
const shouldClamp = offset === 0;
/** @type {TweenObjectValue} */
return {
from: 0,
to: totalLength,
/** @type {TweenModifier} */
modifier: progress => {
const offsetLength = offset * totalLength;
const newProgress = progress + offsetLength;
if (pathProperty === 'a') {
const p0 = getPathPoint($path, totalLength, newProgress, -1, shouldClamp);
const p1 = getPathPoint($path, totalLength, newProgress, +1, shouldClamp);
return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI;
} else {
const p = getPathPoint($path, totalLength, newProgress, 0, shouldClamp);
return pathProperty === 'x' ?
inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e :
inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f
}
}
}
}
}
/**
* @param {TargetsParam} path
* @param {Number} [offset=0]
*/
export const createMotionPath = (path, offset = 0) => {
const $path = getPath(path);
if (!$path) return;
return {
translateX: getPathProgess($path, 'x', offset),
translateY: getPathProgess($path, 'y', offset),
rotate: getPathProgess($path, 'a', offset),
}
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/svg/helpers.js | src/svg/helpers.js | import {
isSvg,
} from '../core/helpers.js';
import {
parseTargets
} from '../core/targets.js';
/**
* @import {
* TargetsParam,
* } from '../types/index.js'
*/
/**
* @param {TargetsParam} path
* @return {SVGGeometryElement|void}
*/
export const getPath = path => {
const parsedTargets = parseTargets(path);
const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]);
if (!$parsedSvg || !isSvg($parsedSvg)) return console.warn(`${path} is not a valid SVGGeometryElement`);
return $parsedSvg;
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/svg/drawable.js | src/svg/drawable.js | import {
K,
proxyTargetSymbol,
} from '../core/consts.js';
import {
sqrt,
isFnc,
} from '../core/helpers.js';
import {
parseTargets,
} from '../core/targets.js';
/**
* @import {
* TargetsParam,
* DrawableSVGGeometry,
* } from '../types/index.js'
*/
/**
* @param {SVGGeometryElement} [$el]
* @return {Number}
*/
const getScaleFactor = $el => {
let scaleFactor = 1;
if ($el && $el.getCTM) {
const ctm = $el.getCTM();
if (ctm) {
const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
scaleFactor = (scaleX + scaleY) / 2;
}
}
return scaleFactor;
}
/**
* Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality.
* @param {SVGGeometryElement} $el - The SVG element to transform into a drawable
* @param {number} start - Starting position (0-1)
* @param {number} end - Ending position (0-1)
* @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
*/
const createDrawableProxy = ($el, start, end) => {
const pathLength = K;
const computedStyles = getComputedStyle($el);
const strokeLineCap = computedStyles.strokeLinecap;
// @ts-ignore
const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null;
let currentCap = strokeLineCap;
const proxy = new Proxy($el, {
get(target, property) {
const value = target[property];
if (property === proxyTargetSymbol) return target;
if (property === 'setAttribute') {
return (...args) => {
if (args[0] === 'draw') {
const value = args[1];
const values = value.split(' ');
const v1 = +values[0];
const v2 = +values[1];
// TOTO: Benchmark if performing two slices is more performant than one split
// const spaceIndex = value.indexOf(' ');
// const v1 = round(+value.slice(0, spaceIndex), precision);
// const v2 = round(+value.slice(spaceIndex + 1), precision);
const scaleFactor = getScaleFactor($scalled);
const os = v1 * -pathLength * scaleFactor;
const d1 = (v2 * pathLength * scaleFactor) + os;
const d2 = (pathLength * scaleFactor +
((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1);
if (strokeLineCap !== 'butt') {
const newCap = v1 === v2 ? 'butt' : strokeLineCap;
if (currentCap !== newCap) {
target.style.strokeLinecap = `${newCap}`;
currentCap = newCap;
}
}
target.setAttribute('stroke-dashoffset', `${os}`);
target.setAttribute('stroke-dasharray', `${d1} ${d2}`);
}
return Reflect.apply(value, target, args);
};
}
if (isFnc(value)) {
return (...args) => Reflect.apply(value, target, args);
} else {
return value;
}
}
});
if ($el.getAttribute('pathLength') !== `${pathLength}`) {
$el.setAttribute('pathLength', `${pathLength}`);
proxy.setAttribute('draw', `${start} ${end}`);
}
return /** @type {DrawableSVGGeometry} */(proxy);
}
/**
* Creates drawable proxies for multiple SVG elements.
* @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors
* @param {number} [start=0] - Starting position (0-1)
* @param {number} [end=0] - Ending position (0-1)
* @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
*/
export const createDrawable = (selector, start = 0, end = 0) => {
const els = parseTargets(selector);
return els.map($el => createDrawableProxy(
/** @type {SVGGeometryElement} */($el),
start,
end
));
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/setup.js | tests/setup.js | import '../node_modules/mocha/mocha.js';
export const testObject = {};
export const anOtherTestObject = {};
const rootEl = document.querySelector(':root');
const testsEl = document.querySelector('#tests');
mocha.setup({
ui: 'tdd',
slow: 100,
timeout: 2000,
globals: ['___browserSync___'],
rootHooks: {
beforeEach(done) {
testObject.plainValue = 10;
testObject.valueWithUnit = '10px';
testObject.multiplePLainValues = '16 32 64 128';
testObject.multipleValuesWithUnits = '16px 32em 64% 128ch';
anOtherTestObject.plainValue = 20;
rootEl.removeAttribute('style');
testsEl.innerHTML = `
<div id="path-tests" class="test">
<div id="square"></div>
<svg id="svg-element" preserveAspectRatio="xMidYMid slice" viewBox="0 0 600 400">
<filter id="displacementFilter">
<feTurbulence type="turbulence" numOctaves="2" baseFrequency="0" result="turbulence"/>
<feDisplacementMap in2="turbulence" in="SourceGraphic" xChannelSelector="R" yChannelSelector="G"/>
</filter>
<g fill="none" fill-rule="evenodd" stroke-width="2">
<line id="line1" x1="51.5" x2="149.5" y1="51.5" y2="149.5" stroke="#F96F82" />
<line id="line2" x1="149.5" x2="51.5" y1="51.5" y2="149.5" stroke="#F96F82" />
<circle id="circle" cx="300" cy="100" r="50" stroke="#FED28B"/>
<polygon id="polygon" stroke="#D1FA9E" points="500 130.381 464.772 149 471.5 109.563 443 81.634 482.386 75.881 500 40 517.614 75.881 557 81.634 528.5 109.563 535.228 149" style="filter: url(#displacementFilter)"/>
<polyline id="polyline" stroke="#7BE6D6" points="63.053 345 43 283.815 95.5 246 148 283.815 127.947 345 63.5 345"/>
<path id="path" stroke="#4E7EFC" d="M250 300c0-27.614 22.386-50 50-50s50 22.386 50 50v50h-50c-27.614 0-50-22.386-50-50z"/>
<path id="path-without-d-attribute-1" stroke="#4E7EFC"/>
<path id="path-without-d-attribute-2" stroke="#F96F82"/>
<rect id="rect" width="100" height="100" x="451" y="251" stroke="#C987FE" rx="25"/>
</g>
</svg>
</div>
<div id="css-tests" class="test test small-test">
<div id="target-id" class="target-class" data-index="0"></div>
<!-- '.target-class' number of elements should be exactly 4 in order to test targets length dependent animations -->
<div class="target-class with-width-attribute" width="200" data-index="1"></div>
<div class="target-class with-inline-styles" data-index="2" style="width: 200px;"></div>
<div class="target-class" data-index="3"></div>
<div class="with-inline-transforms" style="transform: translateX(10px)translateY(-.5rem)scale(.75)"></div>
<div class="css-properties"></div>
</div>
<div id="dom-attributes-tests" class="test test small-test">
<img class="with-width-attribute" src="./assets/icon.png" width=96 height=96 />
<input type="number" id="input-number" name="Input number test" min="0" max="100" value="0">
</div>
<div id="stagger-tests" class="test small-test">
<div id="stagger">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<div id="stagger-grid-tests" class="test small-test">
<div id="grid">
<div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div>
</div>
</div>
<div id="split-text-tests" class="test">
<div id="split-text">
<p>
Split text by characters, words, and lines, do-not-split-hyphens, split <a href="#"><strong>nested elements like</strong></a> <code><strong></code> tags and <span class="nested">any <span class="nested">level <span class="nested">of <span class="nested">nested <span class="nested">tags</span></span></span></span></span> and respect line breaks.<br> Split words in languages without spaces like この日本語の文のように, and properly handles ѕρє¢ιαℓ ¢нαяα¢тєяѕ & 🇪Ⓜ️🅾️🇯ℹ️s
</p>
</div>
</div>
`;
done();
}
},
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/run.js | tests/run.js | import './suites/engine.test.js';
import './suites/seconds.test.js';
import './suites/build.test.js';
import './suites/draggables.test.js';
import './suites/scroll.test.js';
import './suites/waapi.test.js';
import './suites/scope.test.js';
import './suites/targets.test.js';
import './suites/animations.test.js';
import './suites/keyframes.test.js';
import './suites/tweens.test.js';
import './suites/timelines.test.js';
import './suites/timings.test.js';
import './suites/animatables.test.js';
import './suites/callbacks.test.js';
import './suites/controls.test.js';
import './suites/directions.test.js';
import './suites/function-based-values.test.js';
import './suites/parameters.test.js';
import './suites/promises.test.js';
import './suites/stagger.test.js';
import './suites/svg.test.js';
import './suites/text.test.js';
import './suites/units.test.js';
import './suites/utils.test.js';
import './suites/values.test.js';
import './suites/colors.test.js';
import './suites/eases.test.js';
import './suites/leaks.test.js';
mocha.checkLeaks();
mocha.run();
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/utils.js | tests/utils.js | import '../node_modules/chai/chai.js';
import {
addChild,
removeChild,
forEachChildren,
} from '../dist/modules/core/helpers.js';
export const { expect } = chai;
export const getChildAtIndex = (parent, index) => {
let next = parent._head;
let i = 0;
while (next) {
const currentNext = next._next;
if (i === index) break;
next = currentNext;
i++;
}
return next;
}
export const getChildLength = (parent) => {
let next = parent._head;
let i = 0;
while (next) {
next = next._next;
i++;
}
return i;
}
export const browserIs = {
firefox: /firefox|fxios/i.test(navigator.userAgent) && !/seamonkey/i.test(navigator.userAgent),
}
// export const getTweenDelay = t => (t.parent._offset + t._startTime) - t._absoluteStartTime;
// export const getTweenDelay = t => {
// return t._startTime + ((t._startTime - ((t._prev && t._prev.property === t.property) ? t._prev._startTime + t._prev._updateDuration : 0)) - t.parent._delay);
// }
export const getTweenDelay = t => t._delay;
export {
addChild,
removeChild,
forEachChildren,
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/values.test.js | tests/suites/values.test.js | import {
expect,
getChildAtIndex,
forEachChildren,
} from '../utils.js';
import {
animate,
utils,
} from '../../dist/modules/index.js';
import {
unitsExecRgx,
valueTypes,
} from '../../dist/modules/core/consts.js';
suite('Values', () => {
const numberTypeTestTarget = {
number: 1,
decimals: 1.2,
exponent: 1.23456e-5,
func: 1337,
numberString: '1',
decimalsString: '1.2',
exponentString: '1.23456e-5',
funcString: '1337',
}
test('Number type values from numbers', () => {
const animation = animate(numberTypeTestTarget, {
number: 42,
decimals: 42,
exponent: 42,
func: () => 42,
numberString: 42,
decimalsString: 42,
exponentString: 42,
funcString: () => 42,
});
forEachChildren(animation, tween => {
expect(tween._valueType).to.equal(valueTypes.NUMBER);
});
animation.pause();
});
test('Number type values from strings', () => {
const animation = animate(numberTypeTestTarget, {
number: '42',
decimals: '42',
exponent: '42',
func: () => '42',
numberString: '42',
decimalsString: '42',
exponentString: '42',
funcString: () => '42',
});
forEachChildren(animation, tween => {
expect(tween._valueType).to.equal(valueTypes.NUMBER);
});
animation.pause();
});
test('Number type values from relative values operators', resolve => {
const results = {...numberTypeTestTarget};
for (let prop in results) {
results[prop] = +results[prop] + 42;
}
const animation = animate(numberTypeTestTarget, {
number: '+=42',
decimals: '+=42',
exponent: '+=42',
func: () => '+=42',
numberString: '+=42',
decimalsString: '+=42',
exponentString: '+=42',
funcString: () => '+=42',
duration: 10,
onComplete: () => {
for (let prop in results) {
expect(results[prop]).to.equal(numberTypeTestTarget[prop]);
}
resolve();
}
});
forEachChildren(animation, tween => {
expect(tween._valueType).to.equal(valueTypes.NUMBER);
});
});
const shouldNotMatch = [
'range', 'range1', 'range13.134', '10 10', '10px 10px', '10.1px 10.2px', '1.12E0px 1.12E0px',
'1', '1234', '.1234', '0.1234', '1234.1234',
'+1234.1234', '+.1234', '-1234.1234', '-.1234',
'1e+100', '1e-100', '1234e+100', '1234e-100',
'.1234e+100', '.1234e-100', '1234.1234e+100', '1234.1234e-100',
'-1234.1234e+100', '+1234.1234e-100', '0.1234e+100', '0.1234e-100',
'-.1234e+100', '+.1234e-100'
];
const shouldMatch = [
'1px', '1em', '1e', '1E', '1e+100px', '1e-100em', '1e+100e', '1e-100E', '1E+100e', '1E-100E',
'1234px', '1234em', '1234e', '1234E', '1234e+100px', '1234e-100em', '1234e+100e', '1234e-100E', '1234E+100e', '1234E-100E',
'.1234px', '.1234em', '.1234e', '.1234E', '.1234e+100px', '.1234e-100em', '.1234e+100e', '.1234e-100E', '.1234E+100e', '.1234E-100E',
'0.1234px', '0.1234em', '0.1234e', '0.1234E', '0.1234e+100px', '0.1234e-100em', '0.1234e+100e', '0.1234e-100E', '0.1234E+100e', '0.1234E-100E',
'1234.1234px', '1234.1234em', '1234.1234e', '1234.1234E', '1234.1234e+100px', '1234.1234e-100em', '1234.1234e+100e', '1234.1234e-100E', '1234.1234E+100e', '1234.1234E-100E',
'-1234.1234px', '+1234.1234em', '-1234.1234e', '+1234.1234E', '-1234.1234e+100px', '+1234.1234e-100em', '-1234.1234e+100e', '+1234.1234e-100E', '-1234.1234E+100e', '+1234.1234E-100E',
'-.1234px', '+.1234em', '-.1234e', '+.1234E', '-.1234e+100px', '+.1234e-100em', '-.1234e+100e', '+.1234e-100E', '-.1234E+100e', '+.1234E-100E'
];
shouldNotMatch.forEach(value => {
test(`Unit parsing should not match "${value}"`, () => {
const match = unitsExecRgx.test(value);
expect(match).to.be.false;
});
});
shouldMatch.forEach(value => {
test(`Unit parsing should match "${value}"`, () => {
const match = unitsExecRgx.test(value);
expect(match).to.be.true;
});
});
// });
test('Unit type values', () => {
const unitTypeTestTarget = {
number: 1,
decimals: 1.2,
exponent: 1.23456e-5,
func: 1337,
numberUnit: '1px',
decimalsUnit: '1.2px',
exponentUnit: '1.23456e-5px',
funcUnit: '1337px',
}
const animation = animate(unitTypeTestTarget, {
number: '42px',
decimals: '42px',
exponent: '42px',
func: () => '42px',
numberUnit: 42,
decimalsUnit: 42,
exponentUnit: 42,
funcUnit: () => 42,
});
forEachChildren(animation, tween => {
expect(tween._valueType).to.equal(valueTypes.UNIT);
expect(tween._toNumber).to.equal(42);
expect(tween._unit).to.equal('px');
});
animation.pause();
});
test('Tween end value types', resolve => {
const from = {
number: 1,
decimals: 1.2,
exponent: 1.10E+10,
exponent2: 1.5e-10,
numberUnit: '1px',
decimalsUnit: '1.2px',
exponentUnit: '1e-100px',
exponentUnit2: '1.5E-10em',
prefix1: '+1.5e-10em',
prefix2: '-1.5E+100em',
}
const to = {
number: 2,
decimals: 2.2,
exponent: 2.10E+10,
exponent2: 2.5e-10,
numberUnit: '2px',
decimalsUnit: '2.2px',
exponentUnit: '2e-100px',
exponentUnit2: '2.5e-10em',
prefix1: '2.5e-10em',
prefix2: '-2.5e+100em',
}
animate(from, {
number: to.number,
decimals: to.decimals,
exponent: to.exponent,
exponent2: to.exponent2,
numberUnit: to.numberUnit,
decimalsUnit: to.decimalsUnit,
exponentUnit: to.exponentUnit,
exponentUnit2: to.exponentUnit2,
prefix1: to.prefix1,
prefix2: to.prefix2,
duration: 10,
onComplete: () => {
for (let p in from) {
expect(from[p]).to.equal(to[p]);
}
resolve();
}
});
});
const colorTypeTestTarget = {
HEX3: '#f99',
HEX6: '#ff9999',
RGB: 'rgb(255, 153, 153)',
HSL: 'hsl(0, 100%, 80%)',
HEX3A: '#f999',
HEX6A: '#ff999999',
RGBA: 'rgba(255, 153, 153, .6)',
HSLA: 'hsla(0, 100%, 80%, .6)',
func: 'hsla(180, 100%, 50%, .8)',
}
test('Color type values', () => {
const animation = animate(colorTypeTestTarget, {
HEX3: 'hsla(180, 100%, 50%, .8)',
HEX6: 'hsla(180, 100%, 50%, .8)',
RGB: 'hsla(180, 100%, 50%, .8)',
HSL: 'hsla(180, 100%, 50%, .8)',
HEX3A: 'hsla(180, 100%, 50%, .8)',
HEX6A: 'hsla(180, 100%, 50%, .8)',
RGBA: 'hsla(180, 100%, 50%, .8)',
HSLA: 'hsla(180, 100%, 50%, .8)',
func: () => 'hsla(180, 100%, 50%, .8)',
});
forEachChildren(animation, tween => {
expect(tween._valueType).to.equal(valueTypes.COLOR);
expect(tween._toNumbers).to.deep.equal([0, 255, 255, .8]);
});
animation.pause();
});
test('Complex type values', () => {
const complexTypeTestTarget = {
whiteSpace: '0 1 2 1.234',
mixedTypes: 'auto 20px auto 2rem',
cssFilter: 'blur(100px) contrast(200)',
func: 'blur(100px) contrast(200)',
whiteSpaceFromNumber: 10,
mixedTypesFromNumber: 10,
cssFilterFromNumber: 10,
funcFromNumber: 10,
}
const animation = animate(complexTypeTestTarget, {
whiteSpace: '42 42 42 42',
mixedTypes: 'auto 42px auto 42rem',
cssFilter: 'blur(42px) contrast(42)',
func: () => 'blur(42px) contrast(42)',
whiteSpaceFromNumber: '42 42 42 42',
mixedTypesFromNumber: 'auto 42px auto 42rem',
cssFilterFromNumber: 'blur(42px) contrast(42)',
funcFromNumber: () => 'blur(42px) contrast(42)',
});
forEachChildren(animation, tween => {
expect(tween._valueType).to.equal(valueTypes.COMPLEX);
if (tween._toNumbers.length === 4) {
expect(tween._toNumbers).to.deep.equal([42, 42, 42, 42]);
} else {
expect(tween._toNumbers).to.deep.equal([42, 42]);
}
});
animation.pause();
});
test('Get CSS computed values', () => {
/** @type {NodeListOf<HTMLElement>} */
const $targets = document.querySelectorAll('.css-properties');
const animation = animate($targets, {
width: 100,
fontSize: 10,
});
animation.pause().seek(animation.duration);
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 1)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(150);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(32);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(100);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(10);
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
expect(getChildAtIndex(animation, 1)._unit).to.equal('px');
expect($targets[0].style.width).to.equal('100px');
expect($targets[0].style.fontSize).to.equal('10px');
});
test('Get CSS inline values', () => {
/** @type {NodeListOf<HTMLElement>} */
const $targets = document.querySelectorAll('.with-inline-styles');
const animation = animate($targets, {
width: 100,
});
animation.pause().seek(animation.duration);
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(200);
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(100);
expect($targets[0].style.width).to.equal('100px');
});
test('Get default transforms values', () => {
const animation = animate('#target-id', {
translateX: 100,
translateY: 100,
translateZ: 100,
rotate: 360,
rotateX: 360,
rotateY: 360,
rotateZ: 360,
skew: 45,
skewX: 45,
skewY: 45,
scale: 10,
scaleX: 10,
scaleY: 10,
scaleZ: 10,
perspective: 1000,
});
animation.pause().seek(animation.duration);
// Translate
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
expect(getChildAtIndex(animation, 1)._unit).to.equal('px');
expect(getChildAtIndex(animation, 2)._unit).to.equal('px');
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 2)._fromNumber).to.equal(0);
// Rotate
expect(getChildAtIndex(animation, 3)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 4)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 5)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 6)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 3)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 4)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 5)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 6)._fromNumber).to.equal(0);
// Skew
expect(getChildAtIndex(animation, 7)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 8)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 9)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 7)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 8)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 9)._fromNumber).to.equal(0);
// Scale
expect(getChildAtIndex(animation, 10)._unit).to.equal(null);
expect(getChildAtIndex(animation, 11)._unit).to.equal(null);
expect(getChildAtIndex(animation, 12)._unit).to.equal(null);
expect(getChildAtIndex(animation, 13)._unit).to.equal(null);
expect(getChildAtIndex(animation, 10)._fromNumber).to.equal(1);
expect(getChildAtIndex(animation, 11)._fromNumber).to.equal(1);
expect(getChildAtIndex(animation, 12)._fromNumber).to.equal(1);
expect(getChildAtIndex(animation, 13)._fromNumber).to.equal(1);
// Perspective
expect(getChildAtIndex(animation, 14)._unit).to.equal('px');
expect(getChildAtIndex(animation, 14)._fromNumber).to.equal(0);
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
expect($target.style.transform).to.equal('translateX(100px) translateY(100px) translateZ(100px) rotate(360deg) rotateX(360deg) rotateY(360deg) rotateZ(360deg) skew(45deg) skewX(45deg) skewY(45deg) scale(10) scaleX(10) scaleY(10) scaleZ(10) perspective(1000px)');
});
test('Get inline transforms values', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
$target.style.transform = 'translateX(10px) translateY(calc(100px - 10vh)) scale(0.75)';
animate($target, {
translateX: 100,
translateY: 100,
scale: 10,
duration: 10
});
expect(utils.get($target, 'translateX')).to.equal('10px');
expect(utils.get($target, 'translateY')).to.equal('calc(100px - 10vh)');
expect(utils.get($target, 'scale' )).to.equal('0.75');
});
test('Transforms shorthand properties values', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
$target.style.transform = 'translateX(10px) translateY(calc(-100px + 10vh)) translateZ(50px) scale(0.75)';
const animation = animate('#target-id', {
x: 100,
y: 100,
z: 100,
scale: 10,
duration: 10,
});
expect(utils.get('#target-id', 'x')).to.equal('10px');
expect(utils.get('#target-id', 'y')).to.equal('calc(-100px + 10vh)');
expect(utils.get('#target-id', 'z')).to.equal('50px');
expect(utils.get('#target-id', 'scale')).to.equal('0.75');
animation.pause().seek(animation.duration);
expect(utils.get('#target-id', 'x')).to.equal('100px');
expect(utils.get('#target-id', 'y')).to.equal('calc(100px + 100vh)');
expect(utils.get('#target-id', 'z')).to.equal('100px');
expect(utils.get('#target-id', 'scale')).to.equal('10');
});
test('Values with white space', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
const animation = animate($target, {
backgroundSize: ['auto 100%', 'auto 200%'],
duration: 10
});
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.COMPLEX);
expect(getChildAtIndex(animation, 0)._fromNumbers[0]).to.equal(100);
expect(getChildAtIndex(animation, 0)._strings[0]).to.equal('auto ');
expect(getChildAtIndex(animation, 0)._strings[1]).to.equal('%');
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.COMPLEX);
expect(getChildAtIndex(animation, 0)._toNumbers[0]).to.equal(200);
expect($target.style.backgroundSize).to.equal('auto 100%');
animation.pause().seek(animation.duration);
expect($target.style.backgroundSize).to.equal('auto 200%');
});
test('Complex CSS values', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
$target.style.zIndex = 'auto'; // jsdom doesnt set auto to zIndex
const animation = animate($target, {
filter: 'blur(10px) contrast(200)',
translateX: 'calc(calc(15px * 2) - 42rem)',
zIndex: {to: 10, modifier: utils.round(1)},
duration: 10
});
expect($target.style.zIndex).to.equal('0');
expect($target.style.filter).to.equal('blur(0px) contrast(0)');
expect($target.style.transform).to.equal('translateX(calc(0px + 0rem))');
animation.pause().seek(animation.duration);
expect($target.style.zIndex).to.equal('10');
expect(getChildAtIndex(animation, 0)._toNumbers).to.deep.equal([10, 200]);
expect($target.style.filter).to.equal('blur(10px) contrast(200)');
expect(getChildAtIndex(animation, 1)._toNumbers).to.deep.equal([15, 2, 42]);
expect($target.style.transform).to.equal('translateX(calc(30px - 42rem))');
});
test('CSS Variables', () => {
const $target = document.querySelector(':root');
expect(getComputedStyle($target).getPropertyValue('--width')).to.equal('100px');
const animation = animate($target, {
'--width': 200,
duration: 10
});
expect(getComputedStyle($target).getPropertyValue('--width')).to.equal('100px'); // Anime.js removes the first white space to get a simpler (number + unit) animation type instead of commplex type (string + number + string)
animation.pause().seek(animation.duration);
expect(getComputedStyle($target).getPropertyValue('--width')).to.equal('200px'); // Anime.js removes the first white space to get a simpler (number + unit) animation type instead of commplex type (string + number + string)
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(100);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(200);
});
test('CSS Variables in Transforms', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
const x = '12rem';
const rx = '45deg';
const s = '2';
// defined and set the variables in two different set() callS otherwise the values won't be properly computed
utils.set($target, { '--x': x, '--rx': rx, '--s': s });
const setter = utils.set($target, {
translateX: 'var(--x)',
rotateX: 'var(--rx)',
scale: 'var(--s)'
});
expect(getComputedStyle($target).getPropertyValue('--x')).to.equal(x);
expect(getComputedStyle($target).getPropertyValue('--rx')).to.equal(rx);
expect(getComputedStyle($target).getPropertyValue('--s')).to.equal(s);
let transforms = $target.style.transform;
expect(transforms).to.equal(`translateX(${x}) rotateX(${rx}) scale(${s})`);
const x2 = '19rem';
const rx2 = '64deg';
const s2 = '1.25';
const animation = animate($target, {
'--x': x2,
'--rx': rx2,
'--s': s2,
duration: 10
});
animation.pause().seek(animation.duration);
expect(getComputedStyle($target).getPropertyValue('--x')).to.equal(x2);
expect(getComputedStyle($target).getPropertyValue('--rx')).to.equal(rx2);
expect(getComputedStyle($target).getPropertyValue('--s')).to.equal(s2);
// Setting css variables with utils.set() will convert the variable to a static computed value
// So we need to refresh the setter in order to get the updated values from the animation
setter.refresh();
transforms = $target.style.transform;
expect(transforms).to.equal(`translateX(${x2}) rotateX(${rx2}) scale(${s2})`);
});
test('From values', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
$target.style.transform = 'translateX(100px)';
const animation = animate($target, {
translateX: {from: 50},
duration: 10,
});
expect($target.style.transform).to.equal('translateX(50px)');
animation.pause().seek(animation.duration);
expect($target.style.transform).to.equal('translateX(100px)');
});
test('From To values', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
$target.style.transform = 'translateX(100px)';
const animation = animate($target, {
translateX: {from: 50, to: 150},
duration: 10,
});
expect($target.style.transform).to.equal('translateX(50px)');
animation.pause().seek(animation.duration);
expect($target.style.transform).to.equal('translateX(150px)');
});
test('From To values with 0 values', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
$target.style.transform = 'translateX(100px)';
const animation = animate($target, {
translateX: {from: 50, to: 0},
duration: 10,
});
expect($target.style.transform).to.equal('translateX(50px)');
animation.pause().seek(animation.duration);
expect($target.style.transform).to.equal('translateX(0px)');
});
test('From To values shorthand', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
$target.style.transform = 'translateX(100px)';
const animation = animate($target, {
translateX: [50, 150],
duration: 10,
});
expect($target.style.transform).to.equal('translateX(50px)');
animation.pause().seek(animation.duration);
expect($target.style.transform).to.equal('translateX(150px)');
});
test('Relative values with operators +=, -=, *=', () => {
/** @type {HTMLElement} */
const relativeEl = document.querySelector('#target-id');
relativeEl.style.transform = 'translateX(100px)';
relativeEl.style.width = '28px';
const animation = animate(relativeEl, {
translateX: '*=2.5', // 100px * 2.5 = '250px',
width: '-=20px', // 28 - 20 = '8px',
rotate: '+=2turn', // 0 + 2 = '2turn',
duration: 10
});
expect(relativeEl.style.transform).to.equal('translateX(100px) rotate(0turn)');
expect(relativeEl.style.width).to.equal('28px');
animation.pause().seek(animation.duration);
expect(relativeEl.style.transform).to.equal('translateX(250px) rotate(2turn)');
expect(relativeEl.style.width).to.equal('8px');
});
test('Relative from values', () => {
/** @type {HTMLElement} */
const relativeEl = document.querySelector('#target-id');
relativeEl.style.transform = 'translateX(100px) rotate(2turn)';
relativeEl.style.width = '28px';
const animation = animate(relativeEl, {
translateX: { from: '*=2.5' },
width: { from: '-=20px' },
rotate: { from: '+=2turn' },
duration: 10
});
expect(relativeEl.style.transform).to.equal('translateX(250px) rotate(4turn)');
expect(relativeEl.style.width).to.equal('8px');
animation.pause().seek(animation.duration);
expect(relativeEl.style.transform).to.equal('translateX(100px) rotate(2turn)');
expect(relativeEl.style.width).to.equal('28px');
});
test('Relative from to values', () => {
/** @type {HTMLElement} */
const relativeEl = document.querySelector('#target-id');
relativeEl.style.transform = 'translateX(100px) rotate(2turn)';
relativeEl.style.width = '28px';
const animation = animate(relativeEl, {
translateX: ['*=2.5', 10], // Relative from value
width: [100, '-=20px'], // Relative to value
rotate: ['+=2turn', '-=1turn'], // Relative from and to values
duration: 10
});
expect(relativeEl.style.transform).to.equal('translateX(250px) rotate(4turn)');
expect(relativeEl.style.width).to.equal('100px');
animation.pause().seek(animation.duration);
expect(relativeEl.style.transform).to.equal('translateX(10px) rotate(3turn)');
expect(relativeEl.style.width).to.equal('80px');
});
test('Relative values inside keyframes', () => {
/** @type {HTMLElement} */
const relativeEl = document.querySelector('#target-id');
relativeEl.style.transform = 'translateX(100px) rotate(2turn)';
const animation = animate(relativeEl, {
translateX: [{to: '+=10'}, {to: '-=10'}],
rotate: [{from: '+=2turn', to: '-=1turn'}, {from: '+=5turn', to: '-=2turn'}],
duration: 10,
ease: 'linear',
});
expect(relativeEl.style.transform).to.equal('translateX(100px) rotate(4turn)');
animation.seek(animation.duration * .25);
expect(relativeEl.style.transform).to.equal('translateX(105px) rotate(3.5turn)');
animation.seek(animation.duration * .5);
expect(relativeEl.style.transform).to.equal('translateX(110px) rotate(8turn)');
animation.pause().seek(animation.duration);
expect(relativeEl.style.transform).to.equal('translateX(100px) rotate(6turn)');
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/targets.test.js | tests/suites/targets.test.js | import {
expect,
getChildLength,
} from '../utils.js';
import {
testObject,
anOtherTestObject,
} from '../setup.js';
import {
animate,
} from '../../dist/modules/index.js';
suite('Targets', () => {
test('Single element from CSS selector', () => {
const animation = animate('#target-id', {
x: 100,
duration: 100
});
const targetEl = document.querySelector('#target-id');
expect(getChildLength(animation)).to.equal(1);
expect(animation.targets.includes(targetEl)).to.equal(true);
expect(animation.targets.length).to.equal(1);
});
test('Multiple elements from CSS selector', () => {
const animation = animate('.target-class', {
x: 100,
duration: 100
});
const targetEls = document.querySelectorAll('.target-class');
expect(getChildLength(animation)).to.equal(4);
let i = 0;
animation.targets.forEach( el => {
expect(targetEls[i++]).to.equal(el);
});
});
test('Single element from domNode', () => {
const targetEl = document.querySelector('#target-id');
const animation = animate(targetEl, {
x: 100,
duration: 100
});
expect(getChildLength(animation)).to.equal(1);
expect(animation.targets.includes(targetEl)).to.equal(true);
expect(animation.targets.length).to.equal(1);
});
test('Multiple elements from nodeList', () => {
const targetEls = document.querySelectorAll('.target-class');
const animation = animate(targetEls, {
x: 100,
duration: 100
});
expect(getChildLength(animation)).to.equal(4);
let i = 0;
animation.targets.forEach( el => {
expect(targetEls[i++]).to.equal(el);
});
});
test('Single object from JS Object', () => {
const animation = animate(testObject, {
plainValue: 200,
duration: 100
});
expect(getChildLength(animation)).to.equal(1);
expect(animation.targets.includes(testObject)).to.equal(true);
expect(animation.targets.length).to.equal(1);
});
test('Multiple elements from an Array of mixed CSS selectors', () => {
const animation = animate(['#target-id', '.target-class', 'div[data-index="0"]'], {
x: 100,
duration: 100
});
const targetIdEl = document.querySelector('#target-id');
const targetClassEls = document.querySelectorAll('.target-class');
const targetDataEl = document.querySelector('div[data-index="0"]');
expect(getChildLength(animation)).to.equal(4);
expect(animation.targets.includes(targetIdEl)).to.equal(true);
expect(animation.targets.includes(targetDataEl)).to.equal(true);
let i = 0;
animation.targets.forEach( el => {
expect(targetClassEls[i++]).to.equal(el);
});
});
test('Multiple elements and object from an Array of mixed target types', () => {
const targetClassEls = document.querySelectorAll('.target-class');
const animation = animate([testObject, '#target-id', targetClassEls, 'div[data-index="0"]'], {
x: 100,
duration: 100
});
const targetIdEl = document.querySelector('#target-id');
const targetDataEl = document.querySelector('div[data-index="0"]');
expect(getChildLength(animation)).to.equal(5);
expect(animation.targets.includes(testObject)).to.equal(true);
expect(animation.targets.includes(targetIdEl)).to.equal(true);
expect(animation.targets.includes(targetDataEl)).to.equal(true);
expect(animation.targets.length).to.equal(5);
});
test('Multiple elements in nested arrays', () => {
const targetClassEls = document.querySelectorAll('.target-class');
const targetIdEl = document.querySelector('#target-id');
const animation = animate([targetClassEls, targetIdEl, [testObject, anOtherTestObject]], {
x: 100,
duration: 100
});
expect(getChildLength(animation)).to.equal(6);
expect(animation.targets.includes(testObject)).to.equal(true);
expect(animation.targets.includes(anOtherTestObject)).to.equal(true);
expect(animation.targets.includes(targetIdEl)).to.equal(true);
expect(animation.targets.length).to.equal(6);
});
test('Multiple elements in arrays with null or undefined values', () => {
const targetClassEls = document.querySelectorAll('.target-class');
const targetIdEl = document.querySelector('#target-id');
const animation = animate([testObject, anOtherTestObject, null, undefined], {
x: 100,
duration: 100
});
expect(getChildLength(animation)).to.equal(2);
expect(animation.targets.includes(testObject)).to.equal(true);
expect(animation.targets.includes(anOtherTestObject)).to.equal(true);
expect(animation.targets.length).to.equal(2);
});
test('Multiple elements in nested arrays with null or undefined values', () => {
const targetClassEls = document.querySelectorAll('.target-class');
const targetIdEl = document.querySelector('#target-id');
const animation = animate([targetClassEls, targetIdEl, [testObject, anOtherTestObject, null, undefined], null, undefined], {
x: 100,
duration: 100
});
expect(getChildLength(animation)).to.equal(6);
expect(animation.targets.includes(testObject)).to.equal(true);
expect(animation.targets.includes(anOtherTestObject)).to.equal(true);
expect(animation.targets.includes(targetIdEl)).to.equal(true);
expect(animation.targets.length).to.equal(6);
});
test('Properly handle animations without targets', () => {
const animation = animate(undefined, { duration: 10 });
expect(animation.targets).to.deep.equal([]);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/stagger.test.js | tests/suites/stagger.test.js | import {
expect,
getChildAtIndex,
getTweenDelay,
} from '../utils.js';
import { animate, stagger, createTimeline } from '../../dist/modules/index.js';
suite('Stagger', () => {
test('Increase each values by a specific value for each elements', () => {
const animation = animate('.target-class', {
translateX: 100,
duration: 10,
delay: stagger(10),
autoplay: false,
});
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(30);
});
test('Increase each values by a specific value with unit for each elements', () => {
/** @type {NodeListOf<HTMLElement>} */
const staggerEls = document.querySelectorAll('#stagger div');
const animation = animate(staggerEls, {
translateX: stagger('1rem'),
duration: 10,
autoplay: false
});
animation.seek(animation.duration);
expect(staggerEls[0].style.transform).to.equal('translateX(0rem)');
expect(staggerEls[1].style.transform).to.equal('translateX(1rem)');
expect(staggerEls[2].style.transform).to.equal('translateX(2rem)');
expect(staggerEls[3].style.transform).to.equal('translateX(3rem)');
expect(staggerEls[4].style.transform).to.equal('translateX(4rem)');
});
test('Starts the staggering effect from a specific value', () => {
const animation = animate('.target-class', {
translateX: 100,
duration: 10,
delay: stagger(10, { start: 5 }),
autoplay: false,
});
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(30);
});
test('Distributes evenly values between two numbers', () => {
/** @type {NodeListOf<HTMLElement>} */
const staggerEls = document.querySelectorAll('#stagger div');
const animation = animate(staggerEls, {
translateX: stagger([-10, 10]),
duration: 10,
autoplay: false,
});
animation.seek(animation.duration);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(-5);
expect(getChildAtIndex(animation, 2)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 3)._toNumber).to.equal(5);
expect(getChildAtIndex(animation, 4)._toNumber).to.equal(10);
expect(staggerEls[0].style.transform).to.equal('translateX(-10px)');
expect(staggerEls[1].style.transform).to.equal('translateX(-5px)');
expect(staggerEls[2].style.transform).to.equal('translateX(0px)');
expect(staggerEls[3].style.transform).to.equal('translateX(5px)');
expect(staggerEls[4].style.transform).to.equal('translateX(10px)');
});
test('Specific staggered ranged value unit', () => {
/** @type {NodeListOf<HTMLElement>} */
const staggerEls = document.querySelectorAll('#stagger div');
const animation = animate(staggerEls, {
translateX: stagger(['-10rem', '10rem']),
duration: 10,
autoplay: false,
});
animation.seek(animation.duration);
expect(staggerEls[0].style.transform).to.equal('translateX(-10rem)');
expect(staggerEls[1].style.transform).to.equal('translateX(-5rem)');
expect(staggerEls[2].style.transform).to.equal('translateX(0rem)');
expect(staggerEls[3].style.transform).to.equal('translateX(5rem)');
expect(staggerEls[4].style.transform).to.equal('translateX(10rem)');
});
test('Starts the stagger effect from the center', () => {
const animation = animate('#stagger div', {
translateX: 10,
delay: stagger(10, {from: 'center'}),
autoplay: false,
});
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 4))).to.equal(20);
});
test('Starts the stagger effect from the last element', () => {
const animation = animate('#stagger div', {
translateX: 10,
delay: stagger(10, {from: 'last'}),
autoplay: false,
});
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(40);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(30);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 4))).to.equal(0);
});
test('Starts the stagger effect from specific index', () => {
const animation = animate('#stagger div', {
translateX: 10,
delay: stagger(10, {from: 1}),
autoplay: false,
});
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 4))).to.equal(30);
});
test('Changes the order in which the stagger operates', () => {
const animation = animate('#stagger div', {
translateX: 10,
delay: stagger(10, {from: 1, reversed: true}),
autoplay: false
});
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(30);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 4))).to.equal(0);
});
test('Stagger values using an ease function', () => {
const animation = animate('#stagger div', {
translateX: 10,
delay: stagger(10, {ease: 'inOutQuad'}),
autoplay: false,
});
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(5);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(35);
expect(getTweenDelay(getChildAtIndex(animation, 4))).to.equal(40);
});
test('Stagger values on 0 duration animations', () => {
/** @type {NodeListOf<HTMLElement>} */
const staggerEls = document.querySelectorAll('#grid div');
const animation = animate(staggerEls, {
opacity: 0,
duration: 0,
autoplay: false,
delay: stagger(100),
});
animation.seek(animation.duration);
expect(staggerEls[0].style.opacity).to.equal('0');
expect(staggerEls[1].style.opacity).to.equal('0');
expect(staggerEls[2].style.opacity).to.equal('0');
expect(staggerEls[3].style.opacity).to.equal('0');
expect(staggerEls[4].style.opacity).to.equal('0');
expect(staggerEls[5].style.opacity).to.equal('0');
expect(staggerEls[6].style.opacity).to.equal('0');
expect(staggerEls[7].style.opacity).to.equal('0');
expect(staggerEls[8].style.opacity).to.equal('0');
expect(staggerEls[9].style.opacity).to.equal('0');
expect(staggerEls[10].style.opacity).to.equal('0');
expect(staggerEls[11].style.opacity).to.equal('0');
expect(staggerEls[12].style.opacity).to.equal('0');
expect(staggerEls[13].style.opacity).to.equal('0');
expect(staggerEls[14].style.opacity).to.equal('0');
});
test('Grid staggering with a 2D array', () => {
const animation = animate('#grid div', {
scale: [1, 0],
delay: stagger(10, {grid: [5, 3], from: 'center'}),
autoplay: false
});
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.be.closeTo(22.4, .0001);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.be.closeTo(14.1, .01);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.be.closeTo(14.1, .01);
expect(getTweenDelay(getChildAtIndex(animation, 4))).to.be.closeTo(22.4, .0001);
expect(getTweenDelay(getChildAtIndex(animation, 5))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 6))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 7))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 8))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 9))).to.equal(20);
expect(getTweenDelay(getChildAtIndex(animation, 10))).to.be.closeTo(22.4, .0001);
expect(getTweenDelay(getChildAtIndex(animation, 11))).to.be.closeTo(14.1, .01);
expect(getTweenDelay(getChildAtIndex(animation, 12))).to.equal(10);
expect(getTweenDelay(getChildAtIndex(animation, 13))).to.be.closeTo(14.1, .01);
expect(getTweenDelay(getChildAtIndex(animation, 14))).to.be.closeTo(22.4, .0001);
});
test('Grid staggering with a 2D array and axis parameters', () => {
const animation = animate('#grid div', {
translateX: stagger(10, {grid: [5, 3], from: 'center', axis: 'x'}),
translateY: stagger(10, {grid: [5, 3], from: 'center', axis: 'y'}),
autoplay: false
});
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(-20);
expect(getChildAtIndex(animation, 2)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 4)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 6)._toNumber).to.equal(10);
expect(getChildAtIndex(animation, 8)._toNumber).to.equal(20);
expect(getChildAtIndex(animation, 10)._toNumber).to.equal(-20);
expect(getChildAtIndex(animation, 12)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 14)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 16)._toNumber).to.equal(10);
expect(getChildAtIndex(animation, 18)._toNumber).to.equal(20);
expect(getChildAtIndex(animation, 20)._toNumber).to.equal(-20);
expect(getChildAtIndex(animation, 22)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 24)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 26)._toNumber).to.equal(10);
expect(getChildAtIndex(animation, 28)._toNumber).to.equal(20);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 3)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 5)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 7)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 9)._toNumber).to.equal(-10);
expect(getChildAtIndex(animation, 11)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 13)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 15)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 17)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 19)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 21)._toNumber).to.equal(10);
expect(getChildAtIndex(animation, 23)._toNumber).to.equal(10);
expect(getChildAtIndex(animation, 25)._toNumber).to.equal(10);
expect(getChildAtIndex(animation, 27)._toNumber).to.equal(10);
expect(getChildAtIndex(animation, 29)._toNumber).to.equal(10);
});
test('Staggered timeline time positions', () => {
const tl = createTimeline({ defaults: { duration: 10 }, autoplay: false })
.add('.target-class', { id: 'staggered', translateX: 50 }, stagger(100))
expect(getChildAtIndex(tl, 0)._offset).to.equal(0);
expect(getChildAtIndex(tl, 1)._offset).to.equal(100);
expect(getChildAtIndex(tl, 2)._offset).to.equal(200);
expect(getChildAtIndex(tl, 3)._offset).to.equal(300);
expect(getChildAtIndex(tl, 0).id).to.equal('staggered-0');
expect(getChildAtIndex(tl, 1).id).to.equal('staggered-1');
expect(getChildAtIndex(tl, 2).id).to.equal('staggered-2');
expect(getChildAtIndex(tl, 3).id).to.equal('staggered-3');
expect(tl.duration).to.equal(310); // 300 + 10
});
test('Staggered timeline time positions with custom start value', () => {
const tl = createTimeline({ defaults: { duration: 10 }, autoplay: false })
.add('.target-class', { id: 'staggered', translateX: 50 }, stagger(100, { start: 100 }))
expect(getChildAtIndex(tl, 0)._offset).to.equal(100);
expect(getChildAtIndex(tl, 1)._offset).to.equal(200);
expect(getChildAtIndex(tl, 2)._offset).to.equal(300);
expect(getChildAtIndex(tl, 3)._offset).to.equal(400);
expect(getChildAtIndex(tl, 0).id).to.equal('staggered-0');
expect(getChildAtIndex(tl, 1).id).to.equal('staggered-1');
expect(getChildAtIndex(tl, 2).id).to.equal('staggered-2');
expect(getChildAtIndex(tl, 3).id).to.equal('staggered-3');
expect(tl.duration).to.equal(410); // 400 + 10
});
test('Staggered timeline time positions with a label as start value', () => {
const tl = createTimeline({ defaults: { duration: 10 }, autoplay: false })
.label('LABEL', 100)
.add('.target-class', { id: 'staggered', translateX: 50 }, stagger(100, { start: 'LABEL' }))
expect(getChildAtIndex(tl, 0)._offset).to.equal(100);
expect(getChildAtIndex(tl, 1)._offset).to.equal(200);
expect(getChildAtIndex(tl, 2)._offset).to.equal(300);
expect(getChildAtIndex(tl, 3)._offset).to.equal(400);
expect(getChildAtIndex(tl, 0).id).to.equal('staggered-0');
expect(getChildAtIndex(tl, 1).id).to.equal('staggered-1');
expect(getChildAtIndex(tl, 2).id).to.equal('staggered-2');
expect(getChildAtIndex(tl, 3).id).to.equal('staggered-3');
expect(tl.duration).to.equal(410); // 400 + 10
});
test('Staggered timeline values', () => {
const tl = createTimeline({ defaults: { duration: 10 }, autoplay: false })
.add('.target-class', { id: 'staggered', translateX: stagger(100, { from: 'last'}) }, stagger(100))
expect(getChildAtIndex(tl, 0)._head._toNumber).to.equal(300);
expect(getChildAtIndex(tl, 1)._head._toNumber).to.equal(200);
expect(getChildAtIndex(tl, 2)._head._toNumber).to.equal(100);
expect(getChildAtIndex(tl, 3)._head._toNumber).to.equal(0);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/keyframes.test.js | tests/suites/keyframes.test.js | import {
expect,
getChildAtIndex,
getTweenDelay,
} from '../utils.js';
import { animate, utils } from '../../dist/modules/index.js';
import {
valueTypes,
} from '../../dist/modules/core/consts.js';
suite('Keyframes', () => {
test('An array of one raw value should be considered as a simple value', () => {
const animation = animate('#target-id', {
translateX: [50],
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(50);
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
});
test('An array of two raw values should be converted to "From To" values', () => {
const animation = animate('#target-id', {
translateX: [-100, 100],
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(-100);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(100);
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
});
test('The first value of an array of more than two raw values should be used as a from value', () => {
const animation = animate('#target-id', {
translateX: [-100, 100, 50],
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(-100);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(100);
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
expect(getChildAtIndex(animation, 1)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(100);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(50);
expect(getChildAtIndex(animation, 1)._unit).to.equal('px');
});
test('An array of two object values should be converted to keyframes', () => {
const animation = animate('#target-id', {
translateX: [
{ to: -100 },
{ to: 100 }
],
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(-100);
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
expect(getChildAtIndex(animation, 1)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(-100);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(100);
expect(getChildAtIndex(animation, 1)._unit).to.equal('px');
});
test('Unspecified keyframe duration should be inherited from instance duration and devided by the number of keyframes', () => {
const animation = animate('#target-id', {
translateX: [
{ to: -100 },
{ to: 100 },
{ to: 50 },
{ to: 0 }
],
duration: 2000,
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._changeDuration).to.equal(500); // 2000 / 4
expect(getChildAtIndex(animation, 1)._changeDuration).to.equal(500); // 2000 / 4
expect(getChildAtIndex(animation, 2)._changeDuration).to.equal(500); // 2000 / 4
expect(getChildAtIndex(animation, 3)._changeDuration).to.equal(500); // 2000 / 4
});
test('Mixed unspecified keyframe duration should be inherited from instance duration and devided by the number of keyframes', () => {
const animation = animate('#target-id', {
translateX: [
{ to: -100, duration: 800 },
{ to: 100 },
{ to: 50 },
{ to: 0, duration: 1200 }
],
duration: 2000,
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._changeDuration).to.equal(800); // Specified duration
expect(getChildAtIndex(animation, 1)._changeDuration).to.equal(500); // 2000 / 4
expect(getChildAtIndex(animation, 2)._changeDuration).to.equal(500); // 2000 / 4
expect(getChildAtIndex(animation, 3)._changeDuration).to.equal(1200); // Specified duration
});
test('Single keyframe duration should be normaly inherited when only one keyframe is set', () => {
const animation = animate('#target-id', {
translateX: [{ to: -100 }],
duration: 2000,
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._changeDuration).to.equal(2000); // 2000 / 4
});
test('First keyframe should be transfered in the _delay animation', () => {
const animation = animate('#target-id', {
translateX: [
{ to: -100 },
{ to: 100 },
],
delay: 200,
endDelay: 400,
autoplay: false,
});
expect(animation._delay).to.equal(200);
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(0);
});
test('General keyframes instance parameters inheritance', () => {
const roundModifier10 = v => utils.round(v, 10);
const roundModifier05 = v => utils.round(v, 5);
const animation = animate('#target-id', {
translateX: [
{ to: -100 },
{ to: 100, duration: 100, delay: 300, ease: 'linear', modifier: roundModifier10 },
{ to: 50 },
],
translateY: [
{ to: -200 },
{ to: 200 },
{ to: 100 },
],
duration: 1500,
delay: 200,
modifier: roundModifier05,
ease: 'outQuad',
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._changeDuration).to.equal(500); // 1500 / 3
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0);
expect(getChildAtIndex(animation, 0)._ease(.5)).to.equal(.75);
expect(getChildAtIndex(animation, 0)._modifier).to.equal(roundModifier05);
expect(getChildAtIndex(animation, 1)._changeDuration).to.equal(100);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(300);
expect(getChildAtIndex(animation, 1)._ease(.5)).to.equal(.5);
expect(getChildAtIndex(animation, 1)._modifier).to.equal(roundModifier10);
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(-100);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(-100);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(100);
expect(getChildAtIndex(animation, 2)._fromNumber).to.equal(100);
expect(getChildAtIndex(animation, 2)._toNumber).to.equal(50);
expect(getChildAtIndex(animation, 3)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 3)._toNumber).to.equal(-200);
expect(getChildAtIndex(animation, 4)._fromNumber).to.equal(-200);
expect(getChildAtIndex(animation, 4)._toNumber).to.equal(200);
expect(getChildAtIndex(animation, 5)._fromNumber).to.equal(200);
expect(getChildAtIndex(animation, 5)._toNumber).to.equal(100);
});
test('Array keyframes parameters inheritance', () => {
const roundModifier10 = v => utils.round(v, 10);
const roundModifier05 = v => utils.round(v, 5);
const animation = animate('#target-id', {
keyframes: [
{ translateY: -40 },
{ translateX: 250, duration: 100, delay: 300, ease: 'linear', modifier: roundModifier10 },
{ translateY: 40 },
{ translateX: 0 },
{ translateY: 0 }
],
duration: 1500,
delay: 200,
modifier: roundModifier05,
ease: 'outQuad',
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._changeDuration).to.equal(300); // 1500 / 5
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0); // Inherited because its the first keyframe
expect(getChildAtIndex(animation, 0)._ease(.5)).to.equal(.75);
expect(getChildAtIndex(animation, 0)._modifier).to.equal(roundModifier05);
expect(getChildAtIndex(animation, 1)._changeDuration).to.equal(100);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(300);
expect(getChildAtIndex(animation, 1)._ease(.5)).to.equal(.5); // Linear ease
expect(getChildAtIndex(animation, 1)._modifier).to.equal(roundModifier10);
// translateY
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(-40);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(-40);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(-40);
expect(getChildAtIndex(animation, 2)._fromNumber).to.equal(-40);
expect(getChildAtIndex(animation, 2)._toNumber).to.equal(40);
expect(getChildAtIndex(animation, 3)._fromNumber).to.equal(40);
expect(getChildAtIndex(animation, 3)._toNumber).to.equal(40);
expect(getChildAtIndex(animation, 4)._fromNumber).to.equal(40);
expect(getChildAtIndex(animation, 4)._toNumber).to.equal(0);
// translateX
expect(getChildAtIndex(animation, 5)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 5)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 6)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 6)._toNumber).to.equal(250);
expect(getChildAtIndex(animation, 7)._fromNumber).to.equal(250);
expect(getChildAtIndex(animation, 7)._toNumber).to.equal(250);
expect(getChildAtIndex(animation, 8)._fromNumber).to.equal(250);
expect(getChildAtIndex(animation, 8)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 9)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 9)._toNumber).to.equal(0);
});
test('Array keyframes units inheritance', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
const animation = animate($target, {
translateX: [
{ to: [-20, -40] },
{ to: '5rem' },
{ to: '100%' },
{ to: 0 },
{ to: '10%' },
{ to: [50, 200] },
{ to: [25, '100px'] },
],
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
expect(getChildAtIndex(animation, 1)._unit).to.equal('rem'); // switch to rem
expect(getChildAtIndex(animation, 2)._unit).to.equal('%'); // switch to %
expect(getChildAtIndex(animation, 3)._unit).to.equal('%'); // inherit %
expect(getChildAtIndex(animation, 4)._unit).to.equal('%'); // switch back to %
expect(getChildAtIndex(animation, 5)._unit).to.equal('%');
expect(getChildAtIndex(animation, 6)._unit).to.equal('px'); // switch to px
expect($target.style.transform).to.equal('translateX(-20px)');
});
test('Array keyframes with playbackEase', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
const animation = animate($target, {
keyframes: [
{ y: -40 },
{ x: 250 },
{ y: 40 },
{ x: 0, ease: 'outQuad' },
{ y: 0 }
],
duration: 1000,
playbackEase: 'inOutQuad',
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._ease(.5)).to.equal(.5); // All tweens should default to linear ease
expect(getChildAtIndex(animation, 1)._ease(.5)).to.equal(.5);
expect(getChildAtIndex(animation, 2)._ease(.5)).to.equal(.5);
expect(getChildAtIndex(animation, 3)._ease(.5)).to.equal(.75); // Except when they have an ease parameter defined
// Easing should be continuous throughout the sequence
animation.seek(250);
expect($target.style.transform).to.equal('translateY(-25px) translateX(0px)');
animation.seek(500);
expect($target.style.transform).to.equal('translateY(0px) translateX(250px)');
animation.seek(750);
expect($target.style.transform).to.equal('translateY(25px) translateX(0px)');
});
test('Percentage based keyframes values', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
const animation = animate($target, {
keyframes: {
'0%' : { x: 100, y: 100 },
'20%' : { x: -100 },
'50%' : { x: 100 },
'80%' : { x: -100 },
'100%': { x: 100, y: -100 },
},
duration: 1000,
ease: 'linear',
autoplay: false,
});
// Easing should be continuous throughout the sequence
animation.seek(0);
expect($target.style.transform).to.equal('translateX(100px) translateY(100px)');
animation.seek(200);
expect($target.style.transform).to.equal('translateX(-100px) translateY(60px)');
animation.seek(500);
expect($target.style.transform).to.equal('translateX(100px) translateY(0px)');
animation.seek(800);
expect($target.style.transform).to.equal('translateX(-100px) translateY(-60px)');
animation.seek(1000);
expect($target.style.transform).to.equal('translateX(100px) translateY(-100px)');
});
test('Percentage based keyframes with float percentage values', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
const animation = animate($target, {
keyframes: {
'0%' : { x: 0 },
'21.5%' : { x: 50 },
'100%': { x: 100 },
},
duration: 1000,
ease: 'linear',
autoplay: false,
});
// Easing should be continuous throughout the sequence
animation.seek(215);
expect($target.style.transform).to.equal('translateX(50px)');
});
test('Array based keyframes with floating point durations', () => {
/** @type {HTMLElement} */
const $target = document.querySelector('#target-id');
const animation = animate($target, {
x: [100,200,300,400],
ease: 'linear',
duration: 4000, // each keyframes duration: utils.round(4000/3, 12)
autoplay: false
});
const keyDuration = utils.round(4000/3, 12);
expect(animation.duration).to.equal(keyDuration * 3);
// Easing should be continuous throughout the sequence
animation.seek(0);
expect($target.style.transform).to.equal('translateX(100px)');
animation.seek(keyDuration * 1);
expect($target.style.transform).to.equal('translateX(200px)');
animation.seek(keyDuration * 2);
expect($target.style.transform).to.equal('translateX(300px)');
animation.seek(keyDuration * 3);
expect($target.style.transform).to.equal('translateX(400px)');
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/parameters.test.js | tests/suites/parameters.test.js | import {
expect,
getChildAtIndex,
getTweenDelay,
} from '../utils.js';
import {
testObject,
} from '../setup.js';
import { animate, createTimeline, createTimer, utils } from '../../dist/modules/index.js';
import { minValue } from '../../dist/modules/core/consts.js';
suite('Parameters', () => {
const duration = 10;
test('modifier', () => {
const animation1 = animate(testObject, {
plainValue: 3.14159265359,
duration: duration,
autoplay: false,
});
animation1.seek(duration);
expect(testObject.plainValue).to.equal(3.14159265359);
const animation2 = animate(testObject, {
plainValue: 3.14159265359,
duration: duration,
modifier: utils.round(0),
autoplay: false,
});
animation2.seek(duration);
expect(testObject.plainValue).to.equal(3);
const animation3 = animate(testObject, {
valueWithUnit: '3.14159265359px',
duration: duration,
modifier: utils.round(0),
autoplay: false,
});
animation3.seek(duration);
expect(testObject.valueWithUnit).to.equal('3px');
const animation4 = animate(testObject, {
multiplePLainValues: '26.11111111 42.11111111 74.11111111 138.11111111',
duration: duration,
modifier: utils.round(0),
autoplay: false,
});
animation4.seek(duration);
expect(testObject.multiplePLainValues).to.equal('26 42 74 138');
});
test('frameRate', () => {
let resolved = false;
animate(testObject, {
plainValue: [0, 100],
frameRate: 1,
duration: 10000,
ease: 'linear',
onUpdate: (animation) => {
if (animation.progress >= .05 && !resolved) {
resolved = true;
expect(testObject.plainValue).to.be.closeTo(0, 2);
}
}
});
});
test('playbackRate on Animation', resolve => {
animate(testObject, {
plainValue: [0, 100],
playbackRate: .5,
duration: 100,
ease: 'linear',
});
createTimer({
duration: 100,
onComplete: () => {
expect(testObject.plainValue).to.be.closeTo(50, 10);
resolve();
}
})
});
test('playbackRate on Timeline', resolve => {
createTimeline({
playbackRate: .5,
})
.add(testObject, {
plainValue: [0, 100],
playbackRate: .5,
duration: 100,
ease: 'linear',
});
createTimer({
duration: 100,
onComplete: () => {
expect(testObject.plainValue).to.be.closeTo(25, 10);
resolve();
}
})
});
test('playbackEase on Animation', resolve => {
animate(testObject, {
plainValue: [0, 100],
playbackEase: 'outQuad',
duration: 100,
ease: 'linear',
});
createTimer({
duration: 50,
onComplete: () => {
expect(testObject.plainValue).to.be.closeTo(80, 10);
resolve();
}
})
});
test('playbackRate on Timeline', resolve => {
createTimeline({
playbackEase: 'outQuad',
})
.add(testObject, {
plainValue: [0, 100],
playbackEase: 'outQuad',
duration: 100,
ease: 'linear',
});
createTimer({
duration: 50,
onComplete: () => {
expect(testObject.plainValue).to.be.closeTo(95, 10);
resolve();
}
})
});
test('delay', resolve => {
const animation1 = animate(testObject, {
plainValue: [0, 100],
delay: 100,
duration: 100,
});
createTimer({
duration: 50,
onComplete: () => {
expect(animation1.currentTime).to.be.closeTo(-40, 20);
}
});
createTimer({
duration: 150,
onComplete: () => {
expect(animation1.currentTime).to.be.closeTo(50, 20);
}
});
createTimer({
duration: 200,
onComplete: () => {
expect(animation1.currentTime).to.equal(100);
resolve();
}
});
});
test('Specific property parameters', () => {
/** @type {HTMLElement} */
const targetEl = document.querySelector('#target-id');
const roundModifier10 = utils.round(1);
const roundModifier100 = utils.round(2);
const animation = animate(targetEl, {
translateX: {
to: 100,
ease: 'linear',
modifier: roundModifier10,
delay: duration * .25,
duration: duration * .60,
},
rotate: {
to: 360,
duration: duration * .50,
},
translateY: 200,
ease: 'outQuad',
modifier: roundModifier100,
delay: duration * .35,
duration: duration * .70,
});
expect(getChildAtIndex(animation, 0)._ease(.5)).to.equal(0.5);
expect(getChildAtIndex(animation, 0)._modifier).to.equal(roundModifier10);
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0);
expect(getChildAtIndex(animation, 0)._changeDuration).to.equal(duration * .60);
expect(getChildAtIndex(animation, 1)._ease(.5)).to.equal(.75);
expect(getChildAtIndex(animation, 1)._modifier).to.equal(roundModifier100);
// delay = (duration * (.35 - .25))
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(duration * (.1));
expect(getChildAtIndex(animation, 1)._changeDuration).to.equal(duration * .50);
expect(getChildAtIndex(animation, 2)._ease(.5)).to.equal(.75);
expect(getChildAtIndex(animation, 2)._modifier).to.equal(roundModifier100);
// delay = (duration * (.35 - .25))
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(duration * (.1));
expect(getChildAtIndex(animation, 2)._changeDuration).to.equal(duration * .70);
expect(targetEl.style.transform).to.equal('translateX(0px) rotate(0deg) translateY(0px)');
animation.pause();
animation.seek(animation.duration * .5);
expect(targetEl.style.transform).to.equal('translateX(66.7px) rotate(302.4deg) translateY(134.69px)');
});
test('Specific property parameters on transforms values when last transform value update after everything else', resolve => {
/** @type {HTMLElement} */
const targetEl = document.querySelector('#target-id');
const animation = animate(targetEl, {
translateX: {
to: 250,
duration: 400,
ease: 'linear'
},
rotate: {
to: 360,
duration: 900,
ease: 'linear'
},
scale: {
to: 2,
duration: 800,
delay: 400,
ease: 'inOutQuart'
},
delay: 100 // All properties except 'scale' inherit 250ms delay
});
createTimer({
duration: 200,
onComplete: () => {
const transformString = targetEl.style.transform;
const transformValues = transformString.match(/(?:\d*\.)?\d+/g);
expect(parseFloat(transformValues[0])).to.be.closeTo(65, 10);
expect(parseFloat(transformValues[1])).to.be.closeTo(40, 10);
expect(parseFloat(transformValues[2])).to.be.closeTo(1, 1);
animation.pause();
resolve();
}
})
});
test('0 duration animation', () => {
/** @type {HTMLElement} */
const targetEl = document.querySelector('#target-id');
animate(targetEl, {
x: 100,
duration: 0,
});
expect(targetEl.style.transform).to.equal('translateX(100px)');
});
test('0 duration timer with infinite loop', () => {
const timer = createTimer({
duration: 0,
loop: true,
autoplay: false
});
expect(timer.duration).to.equal(minValue);
});
test('0 duration animation with infinite loop', () => {
/** @type {HTMLElement} */
const targetEl = document.querySelector('#target-id');
const animation = animate(targetEl, {
x: [-100, 100],
y: [-100, 100],
duration: 0,
loop: true,
});
expect(animation.duration).to.equal(minValue);
expect(targetEl.style.transform).to.equal('translateX(100px) translateY(100px)');
});
test('0 duration timeline with infinite loop', () => {
/** @type {HTMLElement} */
const targetEl = document.querySelector('#target-id');
const tl = createTimeline({
loop: true,
autoplay: false
})
.add(targetEl, {
x: 100,
duration: 0,
loop: true,
});
expect(tl.duration).to.equal(minValue);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/utils.test.js | tests/suites/utils.test.js | import {
utils,
animate,
createTimeline,
} from '../../dist/modules/index.js';
import {
expect,
addChild,
removeChild,
getChildAtIndex,
getChildLength,
} from '../utils.js';
import {
testObject,
anOtherTestObject,
} from '../setup.js';
suite('Utils', () => {
test('Get a single DOM element', () => {
const [ $target ] = utils.$('#target-id');
expect($target).to.deep.equal(document.querySelector('#target-id'));
});
test('Get a multiple DOM elements', () => {
const targets = utils.$('.target-class');
const $query = document.querySelectorAll('.target-class');
expect(targets).to.deep.equal([$query[0], $query[1], $query[2], $query[3]]);
});
test('Get Object properties', () => {
const plainValue = utils.get(testObject, 'plainValue');
const valueWithUnit = utils.get(testObject, 'valueWithUnit');
const multiplePLainValues = utils.get(testObject, 'multiplePLainValues');
const multipleValuesWithUnits = utils.get(testObject, 'multipleValuesWithUnits');
expect(plainValue).to.equal(10);
expect(valueWithUnit).to.equal('10px');
expect(multiplePLainValues).to.equal('16 32 64 128');
expect(multipleValuesWithUnits).to.equal('16px 32em 64% 128ch');
});
test('Undefined targets should return an empty array', () => {
const targets = utils.$('.targets-doesnt-exist');
expect(targets).to.deep.equal([]);
});
test('Set Object properties', () => {
utils.set(testObject, {
plainValue: 42,
valueWithUnit: '42px',
multiplePLainValues: '40 41 42 43',
multipleValuesWithUnits: '40px 41em 42% 43ch',
});
expect(testObject.plainValue).to.equal(42);
expect(testObject.valueWithUnit).to.equal('42px');
expect(testObject.multiplePLainValues).to.equal('40 41 42 43');
expect(testObject.multipleValuesWithUnits).to.equal('40px 41em 42% 43ch');
});
test('Get DOM attributes', () => {
const withWithAttributeWidth = utils.get('.with-width-attribute', 'width');
const withWithAttributeIndex = utils.get('.with-width-attribute', 'data-index');
const inputNumberMin = utils.get('#input-number', 'min');
const inputNumberMax = utils.get('#input-number', 'max');
expect(withWithAttributeWidth).to.equal('16px'); // 1rem
expect(withWithAttributeIndex).to.equal('1');
expect(inputNumberMin).to.equal('0');
expect(inputNumberMax).to.equal('100');
});
test('Set DOM attributes', () => {
utils.set('.with-width-attribute', {
width: 41,
'data-index': 42
});
utils.set('#input-number', {
min: 41,
max: 42
});
const withWithAttributeWidth = utils.get('.with-width-attribute', 'width');
const withWithAttributeIndex = utils.get('.with-width-attribute', 'data-index');
const inputNumberMin = utils.get('#input-number', 'min');
const inputNumberMax = utils.get('#input-number', 'max');
expect(withWithAttributeWidth).to.equal('41px');
expect(withWithAttributeIndex).to.equal('42');
expect(inputNumberMin).to.equal('41');
expect(inputNumberMax).to.equal('42');
});
test('Get CSS properties', () => {
const targetIdWidth = utils.get('#target-id', 'width');
const cssPrpertiesWidth = utils.get('.css-properties', 'width');
const withInlineStylesWidth = utils.get('.with-inline-styles', 'width');
expect(targetIdWidth).to.equal('16px'); // 1rem
expect(cssPrpertiesWidth).to.equal('150px');
expect(withInlineStylesWidth).to.equal('200px');
});
test('Set CSS properties', () => {
utils.set(['#target-id', '.css-properties', '.with-inline-styles'], {
width: 42
})
expect(utils.get('#target-id', 'width')).to.equal('42px');
expect(utils.get('.css-properties', 'width')).to.equal('42px');
expect(utils.get('.with-inline-styles', 'width')).to.equal('42px');
});
test('Get CSS transforms', () => {
utils.set(['#target-id', '.with-inline-transforms'], {
translateX: 41,
translateY: 1, // has inline rem unit
rotate: 42,
scale: 1,
});
expect(utils.get('.with-inline-transforms', 'translateX')).to.equal('41px');
expect(utils.get('.with-inline-transforms', 'translateY')).to.equal('1rem');
expect(utils.get('.with-inline-transforms', 'rotate')).to.equal('42deg');
expect(utils.get('.with-inline-transforms', 'scale')).to.equal('1');
});
test('Get CSS transforms', () => {
expect(utils.get('.with-inline-transforms', 'translateX')).to.equal('10px');
expect(utils.get('.with-inline-transforms', 'translateY')).to.equal('-0.5rem'); // Has rem
});
test('Get Object properties and convert unit', () => {
expect(utils.get('#target-id', 'width', 'rem')).to.equal('1rem');
expect(utils.get('#target-id', 'width', 'px')).to.equal('16px');
});
test('Set Object properties to specific unit', () => {
utils.set(testObject, {
plainValue: '42px',
valueWithUnit: '42rem',
multiplePLainValues: '40% 41px 42rem 43vh',
multipleValuesWithUnits: '40% 41px 42rem 43vh',
});
expect(testObject.plainValue).to.equal('42px');
expect(testObject.valueWithUnit).to.equal('42rem');
expect(testObject.multiplePLainValues).to.equal('40% 41px 42rem 43vh');
expect(testObject.multipleValuesWithUnits).to.equal('40% 41px 42rem 43vh');
});
test('Add child to linked list', () => {
const parentList = {
_head: null,
_tail: null,
}
const child1 = { id: 1, _prev: null, _next: null, _priority: 1 };
const child2 = { id: 2, _prev: null, _next: null, _priority: 1 };
const child3 = { id: 3, _prev: null, _next: null, _priority: 1 };
addChild(parentList, child1);
expect(parentList._head.id).to.equal(1);
expect(parentList._tail.id).to.equal(1);
addChild(parentList, child2);
expect(parentList._head.id).to.equal(1);
expect(parentList._tail.id).to.equal(2);
expect(child1._prev).to.equal(null);
expect(child1._next.id).to.equal(2);
expect(child2._prev.id).to.equal(1);
expect(child2._next).to.equal(null);
addChild(parentList, child3);
expect(parentList._head.id).to.equal(1);
expect(parentList._tail.id).to.equal(3);
expect(child1._prev).to.equal(null);
expect(child1._next.id).to.equal(2);
expect(child2._prev.id).to.equal(1);
expect(child2._next.id).to.equal(3);
expect(child3._prev.id).to.equal(2);
expect(child3._next).to.equal(null);
});
test('Add child to linked list with sorting', () => {
const parentList = {
_head: null,
_tail: null,
}
const child1 = { id: 1, _prev: null, _next: null, _priority: 999 };
const child2 = { id: 2, _prev: null, _next: null, _priority: 42 };
const child3 = { id: 3, _prev: null, _next: null, _priority: 100 };
const sortMethod = (prev, child) => prev._priority > child._priority;
addChild(parentList, child1, sortMethod);
expect(parentList._head.id).to.equal(1);
expect(parentList._tail.id).to.equal(1);
addChild(parentList, child2, sortMethod);
expect(parentList._head.id).to.equal(2);
expect(parentList._tail.id).to.equal(1);
expect(child2._prev).to.equal(null);
expect(child2._next.id).to.equal(1);
expect(child1._prev.id).to.equal(2);
expect(child1._next).to.equal(null);
addChild(parentList, child3, sortMethod);
expect(parentList._head.id).to.equal(2);
expect(parentList._tail.id).to.equal(1);
expect(child2._prev).to.equal(null);
expect(child2._next.id).to.equal(3);
expect(child3._prev.id).to.equal(2);
expect(child3._next.id).to.equal(1);
expect(child1._prev.id).to.equal(3);
expect(child1._next).to.equal(null);
});
test('Remove child from linked list', () => {
const parentList = {
_head: null,
_tail: null,
}
const child1 = { id: 1, _prev: null, _next: null, _priority: 999 };
const child2 = { id: 2, _prev: null, _next: null, _priority: 42 };
const child3 = { id: 3, _prev: null, _next: null, _priority: 100 };
addChild(parentList, child1);
addChild(parentList, child2);
addChild(parentList, child3);
removeChild(parentList, child1);
expect(child1._prev).to.equal(null);
expect(child1._next).to.equal(null);
expect(parentList._head.id).to.equal(2);
expect(parentList._tail.id).to.equal(3);
expect(child2._prev).to.equal(null);
expect(child2._next.id).to.equal(3);
expect(child3._prev.id).to.equal(2);
expect(child3._next).to.equal(null);
removeChild(parentList, child3);
expect(child3._prev).to.equal(null);
expect(child3._next).to.equal(null);
expect(parentList._head.id).to.equal(2);
expect(parentList._tail.id).to.equal(2);
expect(child2._prev).to.equal(null);
expect(child2._next).to.equal(null);
});
test('utils.shuffle', () => {
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const sum = array.reduce((a, b) => a + b, 0);
const a = [...array];
for (let i = 0; i < 100; i++) {
const s = utils.shuffle(a);
expect(s.reduce((a, b) => a + b, 0)).to.equal(sum);
expect(s.length).to.equal(array.length);
expect(array).to.not.deep.equal(s);
}
});
test('utils.snap', () => {
const array = [25, 100, 400];
const snap = 25;
expect(utils.snap(10, snap)).to.equal(0);
expect(utils.snap(20, snap)).to.equal(25);
expect(utils.snap(50, snap)).to.equal(50);
expect(utils.snap(60, snap)).to.equal(50);
expect(utils.snap(70, snap)).to.equal(75);
expect(utils.snap(10, array)).to.equal(25);
expect(utils.snap(20, array)).to.equal(25);
expect(utils.snap(50, array)).to.equal(25);
expect(utils.snap(63, array)).to.equal(100);
expect(utils.snap(75, array)).to.equal(100);
expect(utils.snap(200, array)).to.equal(100);
expect(utils.snap(300, array)).to.equal(400);
expect(utils.snap(1000, array)).to.equal(400);
});
test('utils.remove(target)', () => {
const [ $target ] = utils.$('#target-id');
const animation1 = animate($target, { x: 100, y: 100 });
const animation2 = animate($target, { rotate: 180 });
const animation3 = animate($target, { scale: 2 });
expect(animation1.targets[0]).to.equal($target);
expect(animation1.paused).to.equal(false);
expect(animation2.targets[0]).to.equal($target);
expect(animation2.paused).to.equal(false);
expect(animation3.targets[0]).to.equal($target);
expect(animation3.paused).to.equal(false);
utils.remove($target);
expect(animation1._head).to.equal(null);
expect(animation1.paused).to.equal(true);
expect(animation2._head).to.equal(null);
expect(animation2.paused).to.equal(true);
expect(animation3._head).to.equal(null);
expect(animation3.paused).to.equal(true);
});
test('Remove targets with Objects ref', () => {
const animation = animate([testObject, anOtherTestObject], {
plainValue: 200,
duration: 100
});
expect(getChildLength(animation)).to.equal(2);
utils.remove(testObject);
expect(getChildLength(animation)).to.equal(1);
utils.remove(anOtherTestObject);
expect(getChildLength(animation)).to.equal(0);
expect(animation._hasChildren).to.equal(false);
});
test('Remove targets from multiple animations at once', () => {
const animation1 = animate([testObject, anOtherTestObject], {
plainValue: 200,
duration: 100
});
const animation2 = animate(anOtherTestObject, {
plainValue: 300,
duration: 100
});
expect(getChildLength(animation1)).to.equal(2);
expect(getChildLength(animation2)).to.equal(1);
utils.remove(testObject);
expect(getChildLength(animation1)).to.equal(1);
expect(getChildLength(animation2)).to.equal(1);
utils.remove(anOtherTestObject);
expect(getChildLength(animation1)).to.equal(0);
expect(getChildLength(animation2)).to.equal(0);
});
test('Remove targets from timeline', () => {
const tl = createTimeline({
defaults: { duration: 100 }
})
.add([testObject, anOtherTestObject], {
plainValue: 200,
})
.add(anOtherTestObject, {
plainValue: 300,
})
expect(tl._hasChildren).to.equal(true);
expect(getChildLength(getChildAtIndex(tl, 0))).to.equal(2);
expect(getChildLength(getChildAtIndex(tl, 1))).to.equal(1);
utils.remove(testObject);
expect(getChildLength(getChildAtIndex(tl, 0))).to.equal(1);
expect(getChildLength(getChildAtIndex(tl, 1))).to.equal(1);
expect(tl._hasChildren).to.equal(true);
utils.remove(anOtherTestObject);
expect(tl._head).to.equal(null);
expect(tl._tail).to.equal(null);
expect(tl._hasChildren).to.equal(false);
});
test('Remove targets on a specific animation', () => {
const animation1 = animate([testObject, anOtherTestObject], {
plainValue: 200,
duration: 100
});
const animation2 = animate([anOtherTestObject, testObject], {
plainValue: 300,
duration: 100
});
expect(getChildLength(animation1)).to.equal(2);
expect(getChildLength(animation2)).to.equal(2);
utils.remove(anOtherTestObject, animation1);
expect(getChildLength(animation1)).to.equal(1);
expect(getChildLength(animation2)).to.equal(2);
utils.remove(testObject, animation2);
expect(getChildLength(animation1)).to.equal(1);
expect(getChildLength(animation2)).to.equal(1);
utils.remove(testObject, animation1);
expect(getChildLength(animation1)).to.equal(0);
expect(getChildLength(animation2)).to.equal(1);
utils.remove(anOtherTestObject, animation2);
expect(getChildLength(animation1)).to.equal(0);
expect(getChildLength(animation2)).to.equal(0);
});
test('Remove targets with CSS selectors', () => {
const animation = animate(['#target-id', '.target-class', 'div[data-index="0"]'], {
x: 100,
duration: 100
});
expect(getChildLength(animation)).to.equal(4);
utils.remove('#target-id');
expect(getChildLength(animation)).to.equal(3);
utils.remove('[data-index="2"]');
expect(getChildLength(animation)).to.equal(2);
utils.remove('.target-class');
expect(getChildLength(animation)).to.equal(0);
});
test('Cancel animations with no tweens left after calling remove', () => {
const animation = animate('#target-id', { x: 100 });
expect(getChildLength(animation)).to.equal(1);
utils.remove('#target-id');
expect(getChildLength(animation)).to.equal(0);
expect(animation._cancelled).to.equal(1);
expect(animation.paused).to.equal(true);
});
test('Do not cancel animations if tweens left after calling remove', () => {
const animation = animate(['#target-id', '.target-class'], { x: 100 });
expect(getChildLength(animation)).to.equal(4);
utils.remove('#target-id');
expect(getChildLength(animation)).to.equal(3);
expect(animation._cancelled).to.equal(0);
animation.pause();
});
test('Remove specific tween property', () => {
const animation = animate('#target-id', { x: 100, y: 100 });
expect(getChildLength(animation)).to.equal(2);
utils.remove('#target-id', animation, 'x');
expect(getChildLength(animation)).to.equal(1);
expect(animation._cancelled).to.equal(0);
animation.pause();
});
test('Remove specific tween property and cancel the animation if no tweens are left', () => {
const animation = animate('#target-id', { x: 100, y: 100 });
expect(getChildLength(animation)).to.equal(2);
utils.remove('#target-id', animation, 'x');
utils.remove('#target-id', animation, 'y');
expect(getChildLength(animation)).to.equal(0);
expect(animation._cancelled).to.equal(1);
expect(animation.paused).to.equal(true);
});
test('Remove the last CSS Transform tween property should not stops the other tweens from updating', resolve => {
const animation = animate('#target-id', { x: 100, y: 100, onComplete: () => {
expect(utils.get('#target-id', 'x', false)).to.equal(100);
expect(utils.get('#target-id', 'y', false)).to.equal(0);
resolve();
}, duration: 30 });
expect(utils.get('#target-id', 'x', false)).to.equal(0);
utils.remove('#target-id', animation, 'y');
});
test('Track instance loop alternate progress with a Timekeeper', () => {
const timekeeper = utils.keepTime((duration) => animate('#target-id', {
x: 100, ease: 'linear', duration, loop: true, alternate: true,
}));
let animation = timekeeper(1000);
expect(animation.currentTime).to.equal(0);
animation.seek(500);
expect(animation.currentTime).to.equal(500);
animation = timekeeper(2000);
expect(animation.currentTime).to.equal(1000);
animation.seek(500);
expect(animation.currentTime).to.equal(500);
animation = timekeeper(500);
expect(animation.currentTime).to.equal(125);
animation.seek(875);
expect(animation.currentTime).to.equal(875);
expect(animation.iterationProgress).to.equal(.25); // It alternates, so we should be at the begining
animation.seek(1375);
expect(animation.currentTime).to.equal(1375);
expect(animation.iterationProgress).to.equal(.75); // It alternates, so we should now be at the end
animation.pause();
});
test('Chained utility functions', () => {
const chain = utils.mapRange(0, 100, 0, 1000).clamp(0, 100);
expect(chain(1)).to.equal(10);
expect(chain(5)).to.equal(50);
expect(chain(50)).to.equal(100);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/promises.test.js | tests/suites/promises.test.js | import {
expect,
} from '../utils.js';
import { animate, createTimeline, createTimer, utils } from '../../dist/modules/index.js';
suite('Promises', () => {
test('then() on timer', resolve => {
createTimer({ duration: 30 }).then(anim => {
expect(anim.currentTime).to.equal(30);
resolve();
});
});
test('then() on animation', resolve => {
animate('#target-id', {
y: 100,
duration: 30,
})
.then(anim => {
expect(anim.currentTime).to.equal(30);
resolve();
});
});
test('then() on timeline', resolve => {
createTimeline()
.add('#target-id', {
x: 100,
duration: 15,
})
.add('#target-id', {
y: 100,
duration: 15,
})
.then(tl => {
expect(tl.currentTime).to.equal(30);
resolve();
});
});
test('Use a timer as a return value in an async function', resolve => {
async function doSomethingAsync() {
async function wait30ms() {
return /** @type {Promise} */(/** @type {unknown} */(createTimer({ duration: 30 })));
}
const asyncTimer = await wait30ms();
expect(asyncTimer.currentTime).to.equal(30);
resolve();
}
doSomethingAsync();
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/scope.test.js | tests/suites/scope.test.js | import {
expect,
} from '../utils.js';
import {
createScope,
} from '../../dist/modules/index.js';
suite('Scope', () => {
test('Default to global root with no params', () => {
const $root = document;
const scope = createScope();
expect(scope.root).to.equal($root);
});
test('Default to global root with non existing selector', () => {
const $root = document;
const scope = createScope({ root: '#i-dont-exit' });
expect(scope.root).to.equal($root);
});
test('Default to global root with undefined selector', () => {
const $root = document;
const scope = createScope({ root: undefined });
expect(scope.root).to.equal($root);
});
test('DOM root', () => {
const $root = document.querySelector('#stagger-tests');
const scope = createScope({ root: '#stagger-tests' });
expect(scope.root).to.equal($root);
});
test('React ref root', () => {
const $root = /** @type {HTMLElement} */(document.querySelector('#stagger-tests'));
const ref = { current: $root };
const scope = createScope({ root: ref });
expect(scope.root).to.equal($root);
});
test('Angular ref root', () => {
const $root = /** @type {HTMLElement} */(document.querySelector('#stagger-tests'));
const ref = { nativeElement: $root };
const scope = createScope({ root: ref });
expect(scope.root).to.equal($root);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/build.test.js | tests/suites/build.test.js | import {
expect,
} from '../utils.js';
import * as esmModules from '../../../dist/modules/index.js';
import * as esmBundle from '../../../dist/bundles/anime.esm.js';
import * as minifiedEsmBundle from '../../../dist/bundles/anime.esm.min.js';
const apiExports = [
'animate',
'createTimer',
'createTimeline',
'createAnimatable',
'createDraggable',
'createScope',
'createSpring',
'onScroll',
'engine',
'easings',
'utils', 'stagger',
'svg', 'createDrawable', 'createMotionPath', 'morphTo',
'text', 'splitText', 'split',
'waapi',
]
suite('Build', () => {
test('ESM modules exports', () => {
apiExports.forEach(exportName => {
expect(esmModules[exportName]).to.exist;
});
});
test('ESM bundle exports', () => {
apiExports.forEach(exportName => {
expect(esmBundle[exportName]).to.exist;
})
});
test('ESM bundle minified exports', () => {
apiExports.forEach(exportName => {
expect(minifiedEsmBundle[exportName]).to.exist;
})
});
test('UMD bundle exports', () => {
apiExports.forEach(exportName => {
expect(window.anime[exportName]).to.exist;
})
});
test('ESM sub modules exports', resolve => {
fetch('../../../package.json')
.then((response) => response.json())
.then((data) => {
const inputs = Object.keys(data.exports)
.filter(k => k !== './package.json')
.map(k => `../../../dist/modules${k.replace('.', '')}/index.js`);
const fetchPromises = inputs.map(path =>
fetch(path)
.then((response) => {
expect(response.ok).to.equal(true, `Failed to fetch ${path}`);
return response.text();
})
.then((content) => {
expect(content).to.exist;
expect(content).to.not.be.empty;
const hasExport = content.includes('export');
expect(hasExport).to.equal(true, `Module at ${path} has no exports`);
return { path, success: true };
})
.catch((error) => {
throw new Error(`Error loading module ${path}: ${error.message}`);
})
);
return Promise.all(fetchPromises);
})
.then((results) => {
expect(results).to.have.length.greaterThan(0);
resolve();
})
.catch((error) => {
resolve(error);
});
});
test('CJS sub modules exports', resolve => {
fetch('../../../package.json')
.then((response) => response.json())
.then((data) => {
const inputs = Object.keys(data.exports)
.filter(k => k !== './package.json')
.map(k => `../../../dist/modules${k.replace('.', '')}/index.cjs`);
const fetchPromises = inputs.map(path =>
fetch(path)
.then((response) => {
expect(response.ok).to.equal(true, `Failed to fetch ${path}`);
return response.text();
})
.then((content) => {
expect(content).to.exist;
expect(content).to.not.be.empty;
const hasExport = content.includes('exports.');
expect(hasExport).to.equal(true, `Module at ${path} has no exports`);
return { path, success: true };
})
.catch((error) => {
throw new Error(`Error loading module ${path}: ${error.message}`);
})
);
return Promise.all(fetchPromises);
})
.then((results) => {
expect(results).to.have.length.greaterThan(0);
resolve();
})
.catch((error) => {
resolve(error);
});
});
test('Package version', () => {
window.AnimeJS.forEach(instance => {
expect(instance.version).to.not.equal('__packageVersion__');
})
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/eases.test.js | tests/suites/eases.test.js | import {
expect,
} from '../utils.js';
import {
animate,
utils,
eases,
cubicBezier,
spring,
linear,
steps,
} from '../../dist/modules/index.js';
function createEasingParam(ease) {
return {
opacity: [0, 1],
ease: ease,
autoplay: false,
duration: 100,
}
}
function getOpacityValue() {
return utils.round(parseFloat(utils.get('#target-id', 'opacity')), 2);
}
suite('Eases', () => {
test("'linear' / eases.linear", () => {
const anim1 = animate('#target-id', createEasingParam('linear'));
anim1.seek(0);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(0);
anim1.seek(50);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(.5);
anim1.seek(100);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(1);
utils.set('#target-id', { opacity: 0 });
const anim2 = animate('#target-id', createEasingParam(eases.linear));
anim2.seek(0);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(0);
anim2.seek(50);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(.5);
anim2.seek(100);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(1);
});
test("'none' / eases.none", () => {
const anim1 = animate('#target-id', createEasingParam('none'));
anim1.seek(0);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(0);
anim1.seek(50);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(.5);
anim1.seek(100);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(1);
utils.set('#target-id', { opacity: 0 });
const anim2 = animate('#target-id', createEasingParam(eases.none));
anim2.seek(0);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(0);
anim2.seek(50);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(.5);
anim2.seek(100);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(1);
});
test("linear(0, 1)", () => {
const anim2 = animate('#target-id', createEasingParam(linear(0, 1)));
anim2.seek(0);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(0);
anim2.seek(50);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(.5);
anim2.seek(100);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(1);
});
test("Custom linear linear(0, 0.25, 1)", () => {
const anim2 = animate('#target-id', createEasingParam(linear(0, 0.25, 1)));
anim2.seek(0);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(0);
anim2.seek(50);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(.25);
anim2.seek(100);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(1);
});
test("Custom uneven linear linear(0, '0.25 75%', 1)", () => {
const anim2 = animate('#target-id', createEasingParam(linear(0, '0.25 75%', 1)));
anim2.seek(0);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(0);
anim2.seek(75);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(.25);
anim2.seek(100);
expect(parseFloat(utils.get('#target-id', 'opacity'))).to.equal(1);
});
const builtInNames = ['', 'Quad', 'Cubic', 'Quart', 'Quint', 'Sine', 'Circ', 'Expo', 'Bounce', 'Back', 'Elastic'];
const fnTypes = ['in', 'out', 'inOut'];
builtInNames.forEach(name => {
fnTypes.forEach(type => {
const easeFunctionName = type + name;
const hasParams = (name === '' || name === 'Back' || name === 'Elastic');
test("'" + easeFunctionName + "' / eases." + easeFunctionName + (hasParams ? '()' : ''), () => {
let fn = eases[easeFunctionName];
if (hasParams) fn = fn();
const anim1 = animate('#target-id', createEasingParam(easeFunctionName));
anim1.seek(50);
if (type === 'in') {
expect(getOpacityValue()).to.be.below(.5);
}
if (type === 'out') {
expect(getOpacityValue()).to.be.above(.5);
}
if (type === 'inOut') {
expect(getOpacityValue()).to.be.equal(.5);
}
utils.set('#target-id', { opacity: 0 });
const anim2 = animate('#target-id', createEasingParam(fn));
anim2.seek(50);
if (type === 'in') {
expect(getOpacityValue()).to.be.below(.5);
}
if (type === 'out') {
expect(getOpacityValue()).to.be.above(.5);
}
if (type === 'inOut') {
expect(getOpacityValue()).to.be.equal(.5);
}
});
});
});
test('Custom power ease: in(x), out(x), inOut(x)', () => {
const anim1 = animate('#target-id', createEasingParam('in(1)'));
anim1.seek(50);
expect(getOpacityValue()).to.equal(.50);
utils.set('#target-id', {opacity: 0});
const anim2 = animate('#target-id', createEasingParam('in(1.5)'));
anim2.seek(50);
expect(getOpacityValue()).to.equal(.35);
utils.set('#target-id', {opacity: 0});
const anim3 = animate('#target-id', createEasingParam('in(2)'));
anim3.seek(50);
expect(getOpacityValue()).to.equal(.25);
});
test('Custom elastic ease: inElastic(x, y), outElastic(x, y), inOutElastic(x, y)', () => {
const anim1 = animate('#target-id', createEasingParam('in(1)'));
anim1.seek(50);
expect(getOpacityValue()).to.equal(.50);
utils.set('#target-id', {opacity: 0});
const anim2 = animate('#target-id', createEasingParam('in(1.5)'));
anim2.seek(50);
expect(getOpacityValue()).to.equal(.35);
utils.set('#target-id', {opacity: 0});
const anim3 = animate('#target-id', createEasingParam('in(2)'));
anim3.seek(50);
expect(getOpacityValue()).to.equal(.25);
});
test('Spring ease overrides animation\'s duration parameter', () => {
const animationParams = createEasingParam(spring());
animationParams.duration = 500;
const animation = animate('#target-id', animationParams);
expect(animation.duration).to.be.above(1000);
});
test('Spring ease overrides tween\'s duration parameter', () => {
const animation = animate('#target-id', {
opacity: [0, 1],
translateX: {
to: 100,
ease: spring(),
duration: 500
},
duration: 400,
autoplay: false
});
expect(animation.duration).to.be.above(1000);
});
test('Spring ease parameters affect animation\'s duration', () => {
const target = '#target-id';
expect(animate(target, createEasingParam(spring())).duration).to.equal(1760);
expect(animate(target, createEasingParam(spring({ mass: 10 }))).duration).to.equal(13700);
expect(animate(target, createEasingParam(spring({ stiffness: 50 }))).duration).to.equal(1760);
expect(animate(target, createEasingParam(spring({ damping: 50 }))).duration).to.equal(3880);
expect(animate(target, createEasingParam(spring({ velocity: 10 }))).duration).to.equal(1700);
});
test('Setting a Spring parameter after creation should update its duration', () => {
const springEasing = spring();
expect(springEasing.settlingDuration).to.equal(1760);
springEasing.mass = 10;
expect(springEasing.settlingDuration).to.equal(13700);
expect(springEasing.mass).to.equal(10);
springEasing.mass = 1;
springEasing.stiffness = 50;
expect(springEasing.mass).to.equal(1);
expect(springEasing.stiffness).to.equal(50);
expect(springEasing.settlingDuration).to.equal(1760);
springEasing.stiffness = 100;
springEasing.damping = 50;
expect(springEasing.stiffness).to.equal(100);
expect(springEasing.damping).to.equal(50);
expect(springEasing.settlingDuration).to.equal(3880);
springEasing.damping = 10;
springEasing.velocity = 10;
expect(springEasing.damping).to.equal(10);
expect(springEasing.velocity).to.equal(10);
expect(springEasing.settlingDuration).to.equal(1700);
});
test('Spring parameters must be clamped at 10000', () => {
const springEasing = spring({
mass: 15000,
stiffness: 15000,
damping: 15000,
velocity: 15000,
});
expect(springEasing.mass).to.equal(10000);
expect(springEasing.stiffness).to.equal(10000);
expect(springEasing.damping).to.equal(10000);
expect(springEasing.velocity).to.equal(10000);
expect(springEasing.settlingDuration).to.be.above(0);
springEasing.mass = 20000;
springEasing.stiffness = 20000;
springEasing.damping = 20000;
springEasing.velocity = 20000;
expect(springEasing.mass).to.equal(10000);
expect(springEasing.stiffness).to.equal(10000);
expect(springEasing.damping).to.equal(10000);
expect(springEasing.velocity).to.equal(10000);
expect(springEasing.settlingDuration).to.be.above(0);
});
test('Spring velocity can be negative', () => {
const springEasing = spring({
velocity: -15000,
});
expect(springEasing.velocity).to.equal(-10000);
expect(springEasing.settlingDuration).to.be.above(0);
springEasing.velocity = -20000;
expect(springEasing.velocity).to.equal(-10000);
expect(springEasing.settlingDuration).to.be.above(0);
});
test('Cubic bézier in: cubicBezier(1,0,1,0)', () => {
const cubicBezierIn = animate('#target-id', createEasingParam(cubicBezier(1,0,1,0)));
cubicBezierIn.seek(50);
expect(getOpacityValue()).to.be.below(.5);
});
test('Cubic bézier out: cubicBezier(0,1,0,1)', () => {
const cubicBezierOut = animate('#target-id', createEasingParam(cubicBezier(0,1,0,1)));
cubicBezierOut.seek(50);
expect(getOpacityValue()).to.be.above(.5);
});
test('Cubic bézier inOut: cubicBezier(1,0,0,1)', () => {
const cubicBezierInOut = animate('#target-id', createEasingParam(cubicBezier(1,0,0,1)));
cubicBezierInOut.seek(50);
expect(getOpacityValue()).to.be.equal(.5);
});
test('Steps from end (default)', () => {
const cubicBezierIn = animate('#target-id', createEasingParam(steps(4)));
cubicBezierIn.seek(0);
expect(getOpacityValue()).to.equal(0);
cubicBezierIn.seek(24);
expect(getOpacityValue()).to.equal(0);
cubicBezierIn.seek(25);
expect(getOpacityValue()).to.equal(.25);
cubicBezierIn.seek(49);
expect(getOpacityValue()).to.equal(.25);
cubicBezierIn.seek(50);
expect(getOpacityValue()).to.equal(.5);
cubicBezierIn.seek(74);
expect(getOpacityValue()).to.equal(.5);
cubicBezierIn.seek(75);
expect(getOpacityValue()).to.equal(.75);
cubicBezierIn.seek(99);
expect(getOpacityValue()).to.equal(.75);
cubicBezierIn.seek(100);
expect(getOpacityValue()).to.equal(1);
});
test('Steps from start', () => {
const cubicBezierIn = animate('#target-id', createEasingParam(steps(4, true)));
cubicBezierIn.seek(0);
expect(getOpacityValue()).to.equal(0);
cubicBezierIn.seek(1);
expect(getOpacityValue()).to.equal(.25);
cubicBezierIn.seek(24);
expect(getOpacityValue()).to.equal(.25);
cubicBezierIn.seek(25);
expect(getOpacityValue()).to.equal(.25);
cubicBezierIn.seek(49);
expect(getOpacityValue()).to.equal(.5);
cubicBezierIn.seek(50);
expect(getOpacityValue()).to.equal(.5);
cubicBezierIn.seek(74);
expect(getOpacityValue()).to.equal(.75);
cubicBezierIn.seek(75);
expect(getOpacityValue()).to.equal(.75);
cubicBezierIn.seek(99);
expect(getOpacityValue()).to.equal(1);
cubicBezierIn.seek(100);
expect(getOpacityValue()).to.equal(1);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/animations.test.js | tests/suites/animations.test.js | import {
expect,
getChildAtIndex,
forEachChildren,
} from '../utils.js';
import {
testObject,
} from '../setup.js';
import {
animate,
createTimer,
utils,
} from '../../dist/modules/index.js';
import {
minValue,
tweenTypes,
} from '../../dist/modules/core/consts.js';
suite('Animations', () => {
// Animation types
test('Get Attribute tween type with SVG attribute values', () => {
const animation = animate('#svg-element path', {
stroke: '#FFFFFF',
d: 'M80 20c-30 0 0 30-30 30',
duration: 100,
});
expect(getChildAtIndex(animation, 0)._tweenType).to.equal(tweenTypes.ATTRIBUTE);
expect(getChildAtIndex(animation, 1)._tweenType).to.equal(tweenTypes.ATTRIBUTE);
});
test('Get CSS tween type with DOM attribute values', () => {
const animation = animate('.with-width-attribute', {
width: 100,
duration: 100,
});
expect(getChildAtIndex(animation, 0)._tweenType).to.equal(tweenTypes.CSS);
expect(getChildAtIndex(animation, 1)._tweenType).to.equal(tweenTypes.CSS);
});
test('Get CSS_VAR tween type with CSS variables properties', () => {
const animation = animate(':root', {
'--width': 200,
duration: 100,
});
expect(getChildAtIndex(animation, 0)._tweenType).to.equal(tweenTypes.CSS_VAR);
});
test('Get Transform tween type with mixed transforms values', () => {
const animation = animate('#target-id', {
translateX: 100,
translateY: 100,
translateZ: 100,
rotate: 100,
rotateX: 100,
rotateY: 100,
rotateZ: 100,
scale: 100,
scaleX: 100,
scaleY: 100,
scaleZ: 100,
skew: 100,
skewX: 100,
skewY: 100,
perspective: 100,
matrix: 100,
matrix3d: 100,
duration: 100,
});
forEachChildren(animation, tween => {
expect(tween._tweenType).to.equal(tweenTypes.TRANSFORM);
});
});
test('Get CSS tween type with mixed values', () => {
const animation = animate('.with-inline-styles', {
width: 50,
height: 50,
fontSize: 50,
backgroundColor: '#FFF',
duration: 100,
});
forEachChildren(animation, tween => {
expect(tween._tweenType).to.equal(tweenTypes.CSS);
});
});
test('Get Object tween type with input values', () => {
const animation = animate('#input-number', {
value: 50,
duration: 100,
});
expect(getChildAtIndex(animation, 0)._tweenType).to.equal(tweenTypes.OBJECT);
});
test('Get Object tween type with plain JS object values', () => {
const animation = animate(testObject, {
plainValue: 20,
valueWithUnit: '20px',
multiplePLainValues: '32 64 128 256',
multipleValuesWithUnits: '32px 64em 128% 25ch',
duration: 100,
});
forEachChildren(animation, tween => {
expect(tween._tweenType).to.equal(tweenTypes.OBJECT);
});
});
test('Get Object tween type with DOM properties that can\'t be accessed with getAttribute()', () => {
const animation = animate('#target-id', {
innerHTML: 9999,
duration: 100,
});
expect(getChildAtIndex(animation, 0)._tweenType).to.equal(tweenTypes.OBJECT);
});
test('Animation\'s tweens timing inheritance', () => {
const animation = animate('#target-id', {
translateX: [
{
to: 50,
delay: 15,
duration: 10,
}, {
to: 200,
delay: 35,
duration: 30,
}, {
to: 350,
delay: 15,
duration: 10,
}
],
});
// The first delay is not counted in the calculation of the total duration
expect(animation.duration).to.equal(10 + 35 + 30 + 15 + 10);
expect(animation.iterationDuration).to.equal(10 + 35 + 30 + 15 + 10);
});
test('Animation\'s values should ends to their correct end position when seeked', resolve => {
/** @type {NodeListOf<HTMLElement>} */
const targetEls = document.querySelectorAll('.target-class');
const animation = animate(targetEls, {
translateX: 270,
delay: function(el, i) { return i * 10; },
ease: 'inOutSine',
autoplay: false
});
const seeker = createTimer({
duration: 35,
onUpdate: self => {
animation.seek(self.progress * animation.duration);
},
onComplete: () => {
expect(targetEls[0].style.transform).to.equal('translateX(270px)');
expect(targetEls[1].style.transform).to.equal('translateX(270px)');
expect(targetEls[2].style.transform).to.equal('translateX(270px)');
expect(targetEls[3].style.transform).to.equal('translateX(270px)');
animation.pause();
resolve();
}
});
expect(targetEls[0].style.transform).to.equal('translateX(0px)');
expect(targetEls[1].style.transform).to.equal('translateX(0px)');
expect(targetEls[2].style.transform).to.equal('translateX(0px)');
expect(targetEls[3].style.transform).to.equal('translateX(0px)');
});
test('Animation\'s values should end to their correct start position when seeked in reverse', resolve => {
/** @type {NodeListOf<HTMLElement>} */
const targetEls = document.querySelectorAll('.target-class');
const animation = animate(targetEls, {
translateX: 270,
// direction: 'reverse',
reversed: true,
ease: 'linear',
duration: 35,
onComplete: () => {
expect(targetEls[0].style.transform).to.equal('translateX(0px)');
expect(targetEls[1].style.transform).to.equal('translateX(0px)');
expect(targetEls[2].style.transform).to.equal('translateX(0px)');
expect(targetEls[3].style.transform).to.equal('translateX(0px)');
resolve();
}
});
animation.seek(0);
expect(targetEls[0].style.transform).to.equal('translateX(270px)');
expect(targetEls[1].style.transform).to.equal('translateX(270px)');
expect(targetEls[2].style.transform).to.equal('translateX(270px)');
expect(targetEls[3].style.transform).to.equal('translateX(270px)');
});
test('Canceled tween should update', resolve => {
/** @type {HTMLElement} */
const targetEl = document.querySelector('#target-id');
const animation1 = animate(targetEl, {
translateX: [
{ to: [0, 200], duration: 20 },
{ to: 300, duration: 20 }
],
});
createTimer({
duration: 20,
onComplete: () => {
const animation2 = animate(targetEl, {
translateX: -100,
duration: 20,
})
}
})
createTimer({
duration: 80,
onComplete: () => {
expect(targetEl.style.transform).to.equal('translateX(-100px)');
resolve();
}
})
});
test('Animate the progress of an animation with 0 duration tweens', resolve => {
const anim1 = animate('.target-class', {
opacity: [0, 1],
duration: 0,
delay: (_, i) => i * 10,
autoplay: false,
})
animate(anim1, {
progress: [0, 1],
ease: 'linear',
duration: 40,
onComplete: self => {
expect(self.progress).to.equal(1);
expect(self.currentTime).to.equal(utils.round(self.duration, 6));
expect(anim1.progress).to.equal(1);
expect(anim1.currentTime).to.equal(utils.round(anim1.duration, 6));
resolve();
}
});
});
test('Animations should have currentTime = 0 if not played', () => {
const anim1 = animate('.target-class', {
opacity: [0, 1],
duration: 300,
autoplay: false,
});
expect(anim1.currentTime).to.equal(0);
});
test('Animations should complete instantly if no animatable props provided', resolve => {
const anim1 = animate('.target-class', {
duration: 15,
loop: true,
});
createTimer({
duration: 30,
onComplete: self => {
expect(anim1.duration).to.equal(minValue);
expect(anim1.paused).to.equal(true);
expect(anim1.completed).to.equal(true);
resolve();
}
});
});
test('Animations should have advanced by one frame imediatly after beeing played', resolve => {
const anim1 = animate('.target-class', {
frameRate: 60,
opacity: [0, 1],
duration: 300,
autoplay: false,
});
anim1.play();
createTimer({
duration: 1,
onComplete: () => {
expect(anim1.currentTime).to.be.at.least(16);
expect(anim1.currentTime).to.be.below(33);
anim1.pause();
resolve();
}
});
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/text.test.js | tests/suites/text.test.js | import {
expect,
browserIs,
} from '../utils.js';
import {
utils,
splitText,
animate,
} from '../../dist/modules/index.js';
// Firefox detect Japanse words differently
const wordsLength = browserIs.firefox ? 44 : 45;
const charsLength = 229;
suite('Text', () => {
test('Defaults text split (words only)', () => {
const split = splitText('#split-text p');
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(0);
split.revert();
});
test('Split chars only', () => {
const split = splitText('#split-text p', { words: false, chars: true });
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(charsLength);
split.revert();
});
test('Split lines only', resolve => {
const split = splitText('#split-text p', {
lines: true,
words: false,
})
.addEffect((split) => {
const firstLevelSpans = split.$target.querySelectorAll('#split-text p > span[data-line]');
expect(split.lines.length).to.be.above(0);
expect(split.lines.length).to.equal(firstLevelSpans.length);
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(0);
resolve();
split.revert();
});
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(0);
});
test('Split words and chars', () => {
const split = splitText('#split-text p', { chars: true });
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(charsLength);
split.revert();
});
test('Split words and lines', resolve => {
const split = splitText('#split-text p', {
lines: true,
});
split.addEffect((split) => {
const firstLevelSpans = split.$target.querySelectorAll('#split-text p > span[data-line]');
expect(split.lines.length).to.be.above(0);
expect(split.lines.length).to.equal(firstLevelSpans.length);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(0);
resolve();
split.revert();
});
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(0);
});
test('Split lines and chars', resolve => {
const split = splitText('#split-text p', {
lines: true,
words: false,
chars: true,
})
.addEffect((split) => {
const firstLevelSpans = split.$target.querySelectorAll('#split-text p > span[data-line]');
expect(split.lines.length).to.be.above(0);
expect(split.lines.length).to.equal(firstLevelSpans.length);
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(charsLength);
resolve();
split.revert();
});
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(0);
});
test('Split lines words and chars', resolve => {
const split = splitText('#split-text p', {
lines: true,
chars: true,
})
.addEffect((split) => {
const firstLevelSpans = split.$target.querySelectorAll('#split-text p > span[data-line]');
expect(split.lines.length).to.be.above(0);
expect(split.lines.length).to.equal(firstLevelSpans.length);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(charsLength);
resolve();
split.revert();
});
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(0);
});
test('Custom css classes', resolve => {
const split = splitText('#split-text p', {
lines: { class: 'split-line' },
words: { class: 'split-word' },
chars: { class: 'split-char' },
})
.addEffect((split) => {
expect(split.lines.length).to.be.above(0);
expect(split.lines.length).to.equal(utils.$('.split-line').length);
expect(split.words.length).to.equal(utils.$('.split-word').length);
expect(split.chars.length).to.equal(utils.$('.split-char').length);
resolve();
split.revert();
});
expect(split.lines.length).to.equal(0);
expect(split.words.length).to.equal(0);
expect(split.chars.length).to.equal(0);
});
test('Wrap text', resolve => {
const split = splitText('#split-text p', {
lines: { wrap: 'clip' },
words: { wrap: 'clip' },
chars: { wrap: 'clip' },
})
.addEffect((split) => {
expect(split.lines.length).to.be.above(0);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(charsLength);
split.lines.forEach($line => expect($line.parentElement.style.overflow).to.equal('clip'));
split.words.forEach($word => expect($word.parentElement.style.overflow).to.equal('clip'));
split.chars.forEach($char => expect($char.parentElement.style.overflow).to.equal('clip'));
resolve();
split.revert();
})
});
test('Clone text', resolve => {
const split = splitText('#split-text p', {
lines: { clone: true },
words: { clone: true },
chars: { clone: true },
});
split.addEffect((split) => {
expect(split.lines.length).to.be.above(0);
expect(split.words.length).to.equal(wordsLength * 2);
expect(split.chars.length).to.equal(charsLength * 4);
resolve();
split.revert();
});
});
test('Custom template', resolve => {
const split = splitText('#split-text p', {
lines: '<span class="split-line split-line-{i}">{value}</span>',
words: '<span class="split-word split-word-{i}">{value}</span>',
chars: '<span class="split-char split-char-{i}">{value}</span>',
});
split.addEffect((split) => {
expect(split.lines.length).to.be.above(0);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(charsLength);
split.lines.forEach(($line, i) => expect($line.classList[1]).to.equal(`split-line-${i}`));
split.words.forEach(($word, i) => expect($word.classList[1]).to.equal(`split-word-${i}`));
split.chars.forEach(($char, i) => expect($char.classList[1]).to.equal(`split-char-${i}`));
resolve();
split.revert();
});
});
test('Init in a document.fonts.ready Promise', resolve => {
document.fonts.ready.then(() => {
splitText('#split-text p', {
lines: true,
words: true,
chars: true,
})
.addEffect((split) => {
const firstLevelSpans = split.$target.querySelectorAll('#split-text p > span[data-line]');
expect(split.lines.length).to.be.above(0);
expect(split.lines.length).to.equal(firstLevelSpans.length);
expect(split.words.length).to.equal(wordsLength);
expect(split.chars.length).to.equal(charsLength);
resolve();
split.revert();
})
});
});
test('addEffect() should only triggers once on load', resolve => {
let calls = 0, timeout;
splitText('#split-text p', {
lines: true,
})
.addEffect((split) => {
calls++;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
expect(calls).to.equal(1);
resolve();
split.revert();
}, 33)
})
});
test('addEffect() should properly track the time of an animation', resolve => {
let animation;
const [ $p ] = utils.$('#split-text p');
const split = splitText('#split-text p', {
lines: true,
})
.addEffect((split) => {
animation = animate(split.lines, {
opacity: 0,
});
return animation;
});
setTimeout(() => {
expect(animation.currentTime).to.be.above(10);
expect(animation.currentTime).to.be.below(100);
$p.style.width = '10px';
}, 50);
setTimeout(() => {
expect(animation.currentTime).to.be.above(150);
resolve();
split.revert();
}, 200);
});
test('addEffect() should properly triggers on resize', resolve => {
document.fonts.ready.then(() => {
let calls = 0;
let cleanups = 0;
let lines = 0;
const [ $p ] = utils.$('#split-text p');
const split = splitText($p, {
lines: true,
})
.addEffect(() => {
calls++;
return () => {
cleanups++;
}
});
expect(calls).to.equal(0);
expect(cleanups).to.equal(0);
setTimeout(() => {
expect(calls).to.equal(1);
expect(cleanups).to.equal(0);
$p.style.width = '10px';
}, 10);
setTimeout(() => {
expect(calls).to.equal(2);
expect(cleanups).to.equal(1);
expect(split.lines.length).to.be.above(lines);
lines = split.lines.length;
$p.style.width = 'auto';
}, 200);
setTimeout(() => {
expect(calls).to.equal(3);
expect(cleanups).to.equal(2);
expect(lines).to.be.above(split.lines.length);
resolve();
split.revert();
}, 400);
});
});
test('addEffect() should only triggers once on load inside a document.fonts.ready Promise', resolve => {
document.fonts.ready.then(() => {
let calls = 0, timeout;
splitText('#split-text p', {
lines: true,
})
.addEffect((split) => {
calls++;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
expect(calls).to.equal(1);
resolve();
split.revert();
}, 33)
})
});
});
test('addEffect() cleanup function should only execute between addEffect', resolve => {
document.fonts.ready.then(() => {
let calls = 0;
let cleanups = 0;
const [ $p ] = utils.$('#split-text p');
const split = splitText($p, {
lines: true,
})
.addEffect(() => {
calls++;
return () => {
cleanups++;
}
});
setTimeout(() => {
expect(calls).to.equal(1);
expect(cleanups).to.equal(0);
$p.style.width = '10px';
}, 10);
setTimeout(() => {
expect(calls).to.equal(2);
expect(cleanups).to.equal(1);
resolve();
split.revert();
}, 200);
});
});
test('addEffect() function should be triggered even when not splitting by lines', resolve => {
let calls = 0;
let cleanups = 0;
const [ $p ] = utils.$('#split-text p');
const split = splitText($p, {
lines: false,
})
.addEffect(() => {
calls++;
return () => {
cleanups++;
}
});
setTimeout(() => {
expect(calls).to.equal(1);
expect(cleanups).to.equal(0);
resolve();
split.revert();
}, 10);
});
test('revert() should properly call cleanups function', resolve => {
document.fonts.ready.then(() => {
let calls = 0;
let cleanups = 0;
const [ $p ] = utils.$('#split-text p');
const split = splitText($p, {
lines: true,
})
.addEffect(self => {
calls++;
self.words.forEach(($word, i) => $word.setAttribute('data-test', i));
return () => {
self.words.forEach(($word, i) => {
expect(+$word.setAttribute('data-test')).to.equal(i);
});
cleanups++;
}
});
setTimeout(() => {
expect(calls).to.equal(1);
expect(cleanups).to.equal(0);
split.revert();
$p.style.width = '10px';
}, 10);
setTimeout(() => {
expect(calls).to.equal(1);
expect(cleanups).to.equal(1);
resolve();
}, 200);
});
});
test('revert() should properly revert animations effects', resolve => {
let animation;
const [ $p ] = utils.$('#split-text p');
const split = splitText('#split-text p', {
lines: true,
})
.addEffect((split) => {
animation = animate(split.lines, {
opacity: 0,
});
return animation;
});
setTimeout(() => {
expect(animation.paused).to.equal(false);
split.revert();
expect(animation.paused).to.equal(true);
resolve();
}, 10);
});
test('refresh() should properly call cleanups function', resolve => {
document.fonts.ready.then(() => {
let calls = 0;
let cleanups = 0;
const [ $p ] = utils.$('#split-text p');
const split = splitText($p, {
lines: true,
})
.addEffect(self => {
calls++;
self.words.forEach(($word, i) => $word.setAttribute('data-test', i));
return () => {
self.words.forEach(($word, i) => {
expect(+$word.getAttribute('data-test')).to.equal(i);
});
cleanups++;
}
});
setTimeout(() => {
expect(calls).to.equal(1);
expect(cleanups).to.equal(0);
split.refresh();
split.revert();
resolve();
}, 10);
});
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/units.test.js | tests/suites/units.test.js | import {
expect,
getChildAtIndex,
} from '../utils.js';
import {
animate,
utils,
} from '../../dist/modules/index.js';
const validUnits = ['cm','mm','in','pc','pt','px','em','ex','ch','rem','vw','vh','vmin','vmax','q','lh','rlh','vb','vi','svw','svh','lvw','lvh','dvw','dvh'];
suite('Units', () => {
test('Default transform units', () => {
const animation = animate('#target-id', {
translateX: 100,
translateY: 100,
translateZ: 100,
rotate: 360,
rotateX: 360,
rotateY: 360,
rotateZ: 360,
skew: 360,
skewX: 360,
skewY: 360,
perspective: 1000,
duration: 10,
});
// Translate
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
expect(getChildAtIndex(animation, 1)._unit).to.equal('px');
expect(getChildAtIndex(animation, 2)._unit).to.equal('px');
// Rotate
expect(getChildAtIndex(animation, 3)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 4)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 5)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 6)._unit).to.equal('deg');
// Skew
expect(getChildAtIndex(animation, 7)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 8)._unit).to.equal('deg');
expect(getChildAtIndex(animation, 9)._unit).to.equal('deg');
// Perspective
expect(getChildAtIndex(animation, 10)._unit).to.equal('px');
});
test('Specified unit on a simple tween', () => {
const animation = animate('#target-id', {
translateX: '100%',
duration: 10,
});
expect(getChildAtIndex(animation, 0)._unit).to.equal('%');
});
test('Units inheritance on From To Values', () => {
const animation = animate('#target-id', {
translateX: [-50, '50%'],
duration: 10,
});
expect(getChildAtIndex(animation, 0)._unit).to.equal('%');
});
test('Should match any units from original values', () => {
validUnits.forEach(unit => {
utils.set('#target-id', { width: 99 + unit });
const animation = animate('#target-id', {
width: 999,
duration: 10,
});
expect(getChildAtIndex(animation, 0)._unit).to.equal(unit);
});
});
test('Should match any units set in the property value', () => {
validUnits.forEach(unit => {
utils.set('#target-id', { width: 99 + 'px' });
const animation = animate('#target-id', {
width: 999 + unit,
duration: 10,
});
expect(getChildAtIndex(animation, 0)._unit).to.equal(unit);
});
});
test('Values set with units should be properly applied', () => {
validUnits.forEach(unit => {
const el = /** @type {HTMLElement} */(document.querySelector('#target-id'));
utils.set(el, {
width: '.9' + unit,
left: '-.099' + unit,
top: '-1E37' + unit,
right: '+1e38' + unit,
bottom: '+0.099' + unit,
});
expect(el.style.width).to.equal('0.9' + unit);
expect(el.style.left).to.equal('-0.099' + unit);
expect(el.style.top).to.equal('-1e+37' + unit);
expect(el.style.right).to.equal('1e+38' + unit);
expect(el.style.bottom).to.equal('0.099' + unit);
});
});
test('Should match any units from complex original values', () => {
validUnits.forEach(unit => {
const el = document.querySelector('#target-id');
utils.set(el, {
width: '.9' + unit,
left: '-.099' + unit,
top: '-1E37' + unit,
right: '+1e38' + unit,
bottom: '+0.099' + unit,
});
const animation = animate(el, {
width: .99,
left: -.0999,
top: -1E3099,
right: +1e3099,
bottom: +0.0999,
duration: 10,
});
expect(getChildAtIndex(animation, 0)._unit).to.equal(unit);
expect(getChildAtIndex(animation, 1)._unit).to.equal(unit);
expect(getChildAtIndex(animation, 2)._unit).to.equal(unit);
expect(getChildAtIndex(animation, 3)._unit).to.equal(unit);
expect(getChildAtIndex(animation, 4)._unit).to.equal(unit);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(.99);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(-.0999);
expect(getChildAtIndex(animation, 2)._toNumber).to.equal(-1E3099);
expect(getChildAtIndex(animation, 3)._toNumber).to.equal(+1e3099);
expect(getChildAtIndex(animation, 4)._toNumber).to.equal(+0.0999);
});
});
test('Basic unit conversion', () => {
const el = /** @type {HTMLElement} */(document.querySelector('#target-id'));
utils.set(el, { fontSize: '20px' });
utils.set(el, { width: '1em' });
expect(el.offsetWidth).to.closeTo(20, 1); // 1em = 20px
utils.set(el, { width: 2 }); // Should inherit the 'em' unit
expect(el.offsetWidth).to.closeTo(40, 1); // 2em = 40px
utils.set(el, { width: '100%' });
expect(el.offsetWidth).to.closeTo(/** @type {HTMLElement} */(el.parentNode).offsetWidth - 2, 1); // -2 = (1px border * 2)
utils.set(el, { width: 50 }); // Should inherit the 'em' unit
expect(el.offsetWidth).to.closeTo(Math.round((/** @type {HTMLElement} */(el.parentNode).offsetWidth - 2) / 2), 1); // 50% of parent 100% -2
utils.set(el, { width: '50px' }); // Should inherit the 'em' unit
expect(el.offsetWidth).to.closeTo(50, 1);
utils.set(el, { width: 'calc(100% - 2px)' }); // Calc should properly overiide from values
expect(el.offsetWidth).to.closeTo(/** @type {HTMLElement} */(el.parentNode).offsetWidth - 4, 1); // -4 = (1px border * 2) - 2
});
const oneRad = (Math.PI * 2) + 'rad';
const halfRad = (Math.PI * 1) + 'rad';
test('Undefined to turn unit conversion', () => {
let animation = animate('#target-id', { rotate: [360, '.5turn'], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(1);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(.5);
});
test('Deg to turn unit conversion', () => {
let animation = animate('#target-id', { rotate: ['360deg', '.5turn'], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(1);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(.5);
});
test('Rad to turn unit conversion', () => {
let animation = animate('#target-id', { rotate: [oneRad, '.5turn'], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(1);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(.5);
});
test('Undefined to rad unit conversion', () => {
let animation = animate('#target-id', { rotate: [360, halfRad], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(Math.PI * 2);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(Math.PI * 1);
});
test('Deg to rad unit conversion', () => {
let animation = animate('#target-id', { rotate: ['360deg', halfRad], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(Math.PI * 2);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(Math.PI * 1);
});
test('Turn to rad unit conversion', () => {
let animation = animate('#target-id', { rotate: ['1turn', halfRad], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(Math.PI * 2);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(Math.PI * 1);
});
test('Undefined to deg unit conversion', () => {
let animation = animate('#target-id', { rotate: [360, '180deg'], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(360);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(180);
});
test('Turn to deg unit conversion', () => {
let animation = animate('#target-id', { rotate: ['1turn', '180deg'], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(360);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(180);
});
test('Rad to turn unit conversion', () => {
let animation = animate('#target-id', { rotate: [oneRad, '180deg'], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(360);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(180);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/colors.test.js | tests/suites/colors.test.js | import {
expect,
getChildAtIndex,
} from '../utils.js';
import {
animate,
utils,
} from '../../dist/modules/index.js';
import {
valueTypes,
} from '../../dist/modules/core/consts.js';
const colors = {
from: {
rgb: {
input: {
HEX3: '#f99',
HEX6: '#ff9999',
RGB: 'rgb(255, 153, 153)',
HSL: 'hsl(0, 100%, 80%)',
},
output: [255, 153, 153, 1]
},
rgba: {
input: {
HEX3A: '#f999',
HEX6A: '#ff999999',
RGBA: 'rgba(255, 153, 153, .6)',
HSLA: 'hsla(0, 100%, 80%, .6)',
},
output: [255, 153, 153, .6]
}
},
to: {
rgb: {
input: {
HEX3: '#0FF',
HEX6: '#00FFFF',
RGB: 'rgb(0, 255, 255)',
HSL: 'hsl(180, 100%, 50%)',
},
output: [0, 255, 255, 1]
},
rgba: {
input: {
HEX3A: '#0FFC',
HEX6A: '#00FFFFCC',
RGBA: 'rgba(0, 255, 255, .8)',
HSLA: 'hsla(180, 100%, 50%, .8)',
},
output: [0, 255, 255, .8]
}
},
}
function createColorTest(testName, inFrom, inTo, outFrom, outTo, fromType, toType) {
return test(testName, () => {
const [ targetEl ] = utils.$('#target-id');
const animation = animate(targetEl, { color: [inFrom, inTo], autoplay: false });
expect(getChildAtIndex(animation, 0)._fromNumbers).to.deep.equal(outFrom);
expect(getChildAtIndex(animation, 0)._valueType).to.deep.equal(valueTypes.COLOR);
expect(getChildAtIndex(animation, 0)._toNumbers).to.deep.equal(outTo);
if (fromType === 'rgba') {
expect(targetEl.style.color).to.equal(`rgba(${outFrom[0]}, ${outFrom[1]}, ${outFrom[2]}, ${outFrom[3]})`);
} else {
expect(targetEl.style.color).to.equal(`rgb(${outFrom[0]}, ${outFrom[1]}, ${outFrom[2]})`);
}
animation.seek(animation.duration);
if (toType === 'rgba') {
expect(targetEl.style.color).to.equal(`rgba(${outTo[0]}, ${outTo[1]}, ${outTo[2]}, ${outTo[3]})`);
} else {
expect(targetEl.style.color).to.equal(`rgb(${outTo[0]}, ${outTo[1]}, ${outTo[2]})`);
}
});
}
function createColorTestsByType(fromType, toType) {
for (let inputFromName in colors.from[fromType].input) {
const inputFromValue = colors.from[fromType].input[inputFromName];
const outputFromValue = colors.from[fromType].output;
for (let inputToName in colors.to[toType].input) {
const inputToValue = colors.to[toType].input[inputToName];
const outputToValue = colors.to[toType].output;
const testName = 'Convert ' + inputFromName + ' to ' + inputToName;
createColorTest(testName, inputFromValue, inputToValue, outputFromValue, outputToValue, fromType, toType);
}
}
}
suite('Colors', () => {
test('Properly apply transparency from computed styles', resolve => {
const [ targetEl ] = utils.$('#target-id');
animate(targetEl, {
backgroundColor: 'rgba(0, 0, 0, 0)',
duration: 10,
onComplete: () => {
expect(targetEl.style.backgroundColor).to.equal('rgba(0, 0, 0, 0)');
resolve();
}
});
});
createColorTestsByType('rgb', 'rgb');
createColorTestsByType('rgb', 'rgba');
createColorTestsByType('rgba', 'rgb');
createColorTestsByType('rgba', 'rgba');
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/svg.test.js | tests/suites/svg.test.js | import {
expect,
getChildAtIndex,
} from '../utils.js';
import {
animate,
utils,
svg,
} from '../../dist/modules/index.js';
suite('SVG', () => {
test('svg.createDrawable', resolve => {
const line1El = document.querySelector('#line1');
const line2El = document.querySelector('#line2');
const circleEl = document.querySelector('#circle');
const polygonEl = document.querySelector('#polygon');
const polylineEl = document.querySelector('#polyline');
const rectEl = document.querySelector('#rect');
animate(svg.createDrawable(['#tests line', '#tests circle', '#tests polygon', '#tests polyline', '#tests rect', '#tests path']), {
draw: '0 1',
ease: 'inOutSine',
translateX: [-100, 0],
opacity: .5,
duration: 10,
onComplete: () => {
expect(line1El.getAttribute('stroke-dasharray')).to.equal('1000 0');
expect(line2El.getAttribute('stroke-dasharray')).to.equal('1000 0');
expect(circleEl.getAttribute('stroke-dasharray')).to.equal('1000 0');
expect(polygonEl.getAttribute('stroke-dasharray')).to.equal('1000 0');
expect(polylineEl.getAttribute('stroke-dasharray')).to.equal('1000 0');
expect(rectEl.getAttribute('stroke-dasharray')).to.equal('1000 0');
resolve();
}
});
});
// It was possible to set unknown properties, like utils.set(svg, {d: '...'})
// I removed this in order to better differenciate svg attributes from css properties
// It's now mendatory for an SVG attribute to be defined on the SVG element in order to be either set using utils.set() or animated
// test('Animating non existant attributes', resolve => {
// const squareEl = document.querySelector('#square');
// const pathTestsEl = document.querySelector('#path-tests');
// /** @type {HTMLElement} */
// const line1El = document.querySelector('#line1');
// const path1El = document.querySelector('#path-without-d-attribute-1');
// const path2El = document.querySelector('#path-without-d-attribute-2');
// animate(svg.createDrawable(['line', 'circle', 'polygon', 'polyline', 'rect', 'path']), {
// draw: '0 1',
// ease: 'inOutSine',
// opacity: .5,
// duration: 10,
// autoplay: false,
// });
// // Opacity animation should default to 1
// expect(line1El.style.opacity).to.equal('1');
// // Setting a non existing attribute
// expect(path1El.getAttribute('d')).to.equal(null);
// utils.set(path1El, { d: 'M250 300c0-27.614 22.386-50 50-50s50 22.386 50 50v50h-50c-27.614 0-50-22.386-50-50z' });
// // Setting a value on a non existing attribute
// expect(path1El.getAttribute('d')).to.equal('M250 300c0-27.614 22.386-50 50-50s50 22.386 50 50v50h-50c-27.614 0-50-22.386-50-50z');
// // Animating a non existing attribute
// expect(path2El.getAttribute('d')).to.equal(null);
// const animateNonExistantAttribute = animate(path2El, {
// d: 'M250 300c0-27.614 22.386-50 50-50s50 22.386 50 50v50h-50c-27.614 0-50-22.386-50-50z',
// duration: 10,
// ease: 'inOutQuad',
// autoplay: false
// });
// animateNonExistantAttribute.seek(animateNonExistantAttribute.duration);
// // Animating a value on a non existing attribute
// expect(path2El.getAttribute('d')).to.equal('M250 300c0-27.614 22.386-50 50-50s50 22.386 50 50v50h-50c-27.614 0-50-22.386-50-50z');
// const pathObj = svg.createMotionPath(path2El);
// const dashOffsetAnimation2 = animate(svg.createDrawable(path2El), {
// draw: '0 1',
// ease: 'inOutSine',
// duration: 10
// });
// dashOffsetAnimation2.seek(dashOffsetAnimation2.duration);
// expect(+path2El.getAttribute('stroke-dasharray').split(' ')[1]).to.equal(0);
// let pathsTestsRect = pathTestsEl.getBoundingClientRect();
// let squareRect = squareEl.getBoundingClientRect();
// // Path animation not started
// expect(squareRect.left - pathsTestsRect.left).to.equal(-7);
// animate(squareEl, {
// translateX: pathObj.x,
// translateY: pathObj.y,
// rotate: pathObj.angle,
// ease: 'inOutSine',
// duration: 10,
// onComplete: () => {
// pathsTestsRect = pathTestsEl.getBoundingClientRect();
// squareRect = squareEl.getBoundingClientRect();
// expect(squareRect.left - pathsTestsRect.left).to.be.above(100);
// resolve();
// }
// });
// });
test('stroke-linecap "round" path should be set to "butt" when hidden', () => {
const [ $path ] = utils.$('#tests path')
const [ $drawablePath ] = svg.createDrawable('#tests path');
expect(getComputedStyle($path).strokeLinecap).to.equal('butt');
$drawablePath.setAttribute('draw', '0 .5');
expect(getComputedStyle($path).strokeLinecap).to.equal('round');
$drawablePath.setAttribute('draw', '0 1');
expect(getComputedStyle($path).strokeLinecap).to.equal('round');
$drawablePath.setAttribute('draw', '.5 1');
expect(getComputedStyle($path).strokeLinecap).to.equal('round');
$drawablePath.setAttribute('draw', '1 1');
expect(getComputedStyle($path).strokeLinecap).to.equal('butt');
$drawablePath.setAttribute('draw', '.25 .25');
expect(getComputedStyle($path).strokeLinecap).to.equal('butt');
});
test('SVG Filters', () => {
// Filters tests
/** @type {HTMLElement} */
const filterPolygonEl = document.querySelector('#polygon');
const feTurbulenceEl = document.querySelector('#displacementFilter feTurbulence');
const feDisplacementMapEl = document.querySelector('#displacementFilter feDisplacementMap');
animate([feTurbulenceEl, feDisplacementMapEl], {
baseFrequency: [.05, 1],
scale: [15, 1],
direction: 'alternate',
ease: 'inOutExpo',
duration: 100
});
// Scale property should be set as an attribute on SVG filter elements
expect(feDisplacementMapEl.getAttribute('scale')).to.equal('15');
animate(filterPolygonEl, {
points: [
'64 68.64 8.574 100 63.446 67.68 64 4 64.554 67.68 119.426 100',
'64 128 8.574 96 8.574 32 64 0 119.426 32 119.426 96'
],
translateX: [430, 430],
translateY: [35, 35],
scale: [.75, 1],
ease: 'inOutExpo',
duration: 100
});
// Scale property should be set as a CSS transform on non SVG filter elements
expect(filterPolygonEl.style.transform).to.equal('translateX(430px) translateY(35px) scale(0.75)');
// Non stylistic SVG attribute should be declared in came case
expect(feTurbulenceEl.hasAttribute('baseFrequency')).to.equal(true);
// Non stylistic SVG attribute should be declared in came case
expect(feTurbulenceEl.hasAttribute('base-frequency')).to.equal(false);
});
test('svg.createMotionPath with offset', resolve => {
const squareEl = document.querySelector('#square');
const [pathEl] = utils.$('#tests path');
const pathSelector = 'motion-path-offset-test';
pathEl.id = pathSelector;
const motionPath = svg.createMotionPath(`#${pathSelector}`);
const anim = animate(squareEl, {
...motionPath,
duration: 10,
autoplay: false,
});
anim.seek(0);
const initialTransform = squareEl.style.transform;
const offset = 0.5;
const motionPathWithOffset = svg.createMotionPath(`#${pathSelector}`, offset);
const animWithOffset = animate(squareEl, {
...motionPathWithOffset,
duration: 10,
autoplay: false,
});
animWithOffset.seek(0);
const offsetTransform = squareEl.style.transform;
expect(initialTransform).to.not.equal(offsetTransform);
animWithOffset.seek(animWithOffset.duration);
const finalOffsetTransform = squareEl.style.transform;
expect(finalOffsetTransform).to.equal(offsetTransform);
resolve();
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/draggables.test.js | tests/suites/draggables.test.js | import {
expect,
} from '../utils.js';
import {
createTimer,
createDraggable,
utils,
} from '../../dist/modules/index.js';
const createMouseEvent = ($target, name, x, y) => $target.dispatchEvent(new MouseEvent('mouse' + name, {
clientX: x,
clientY: y,
bubbles: true,
cancelable: true
}));
const createTouchEvent = ($el, type, x, y) => {
const touch = new Touch({
identifier: 1,
target: $el,
clientX: x,
clientY: y,
pageX: x,
pageY: y,
});
$el.dispatchEvent(new TouchEvent('touch' + type, {
touches: type === 'end' ? [] : [touch],
changedTouches: [touch],
bubbles: true,
composed: true,
cancelable: true
}));
};
suite('Draggables', () => {
test('Triggering a reset in the onSettle callback should correctly set the values', resolve => {
const draggable = createDraggable('#target-id', {
container: '#css-tests',
onSettle: self => {
self.reset();
expect(utils.get('#target-id', 'x', false)).to.equal(0);
expect(utils.get('#target-id', 'y', false)).to.equal(0);
resolve();
}
});
draggable.animate.translateX(100, 10);
draggable.animate.translateY(100, 10);
});
test('Reverting a draggable should properly disconect the ResizeObserver attached to it', resolve => {
const [ $container ] = utils.$('#css-tests');
let resizes = 0;
const draggable = createDraggable('#target-id', {
container: $container,
onResize: () => {
resizes++;
}
});
draggable.revert();
setTimeout(() => {
$container.style.width = '100px';
}, 1)
setTimeout(() => {
expect(resizes).to.equal(0);
resolve();
}, 200)
});
test('Removing the parent should not throw an error', resolve => {
const draggable = createDraggable('#target-id', { container: '#css-tests' });
setTimeout(() => {
document.querySelector('#css-tests').remove();
}, 0);
setTimeout(() => {
resolve();
draggable.revert();
}, 200);
});
test('onUpdate should only trigger when the dragged element actually moves', resolve => {
const [ $target ] = utils.$('#target-id');
const [ $container ] = utils.$('#css-tests');
let updates = 0;
let grabbed = 0;
let dragged = 0;
let released = 0;
const draggable = createDraggable($target, {
container: $container,
onUpdate: () => {
updates++;
},
onGrab: () => grabbed++,
onDrag: () => dragged++,
onRelease: () => released++
});
expect(updates).to.equal(0);
createMouseEvent($target, 'down', 0, 0);
createTimer({
onBegin: () => createMouseEvent(document, 'move', 10, 10),
onUpdate: () => createMouseEvent(document, 'move', 10, 10),
onComplete: () => {
createMouseEvent(document, 'move', 10, 10);
createMouseEvent(document, 'up', 10, 10);
expect(grabbed).to.equal(1);
expect(released).to.equal(1);
expect(updates).to.equal(2);
resolve();
draggable.revert();
},
duration: 50,
});
});
test('onUpdate should properly trigger when the dragged element only moves horizontally', resolve => {
const [ $target ] = utils.$('#target-id');
const [ $container ] = utils.$('#css-tests');
let updates = 0;
let x = 0;
let y = 0;
const draggable = createDraggable($target, {
container: $container,
releaseStiffness: 10000,
releaseDamping: 300,
onUpdate: () => {
updates++;
},
onSettle: () => {
expect(updates).to.be.above(1);
resolve();
draggable.revert();
}
});
expect(updates).to.equal(0);
createMouseEvent($target, 'down', x, y);
createTimer({
onBegin: () => createMouseEvent(document, 'move', ++x, 0),
onUpdate: () => createMouseEvent(document, 'move', ++x, 0),
onComplete: () => {
createMouseEvent(document, 'move', ++x, 0);
createMouseEvent(document, 'up', ++x, 0);
},
duration: 50,
});
});
test('Touch dragging should work in Shadow DOM', resolve => {
const $container = document.querySelector('#css-tests');
const $host = document.createElement('div');
$container.appendChild($host);
const shadowRoot = $host.attachShadow({ mode: 'open' });
const $target = document.createElement('div');
$target.style.cssText = 'width: 100px; height: 100px;';
shadowRoot.appendChild($target);
let updates = 0;
let x = 0;
let y = 0;
const draggable = createDraggable($target, {
releaseStiffness: 10000,
releaseDamping: 300,
onUpdate: () => {
updates++;
},
onSettle: () => {
expect(updates).to.be.above(0);
draggable.revert();
$host.remove();
resolve();
}
});
expect(updates).to.equal(0);
createTouchEvent($target, 'start', x, y);
createTimer({
onUpdate: () => createTouchEvent($target, 'move', ++x, 0),
onComplete: () => {
createTouchEvent($target, 'end', ++x, 0);
},
duration: 100,
});
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/function-based-values.test.js | tests/suites/function-based-values.test.js | import {
expect,
getChildAtIndex,
getTweenDelay,
} from '../utils.js';
import { animate, stagger, utils } from '../../dist/modules/index.js';
import {
valueTypes,
minValue,
} from '../../dist/modules/core/consts.js';
suite('Function based values', () => {
test('Basic function based values', () => {
/** @type {NodeListOf<HTMLElement>} */
const $targets = document.querySelectorAll('.target-class');
const animation = animate($targets, {
autoplay: false,
translateX: (el, i, total) => {
return el.getAttribute('data-index');
},
duration: (el, i, total) => {
const index = parseFloat(el.dataset.index);
return total + ((i + index) * 100);
},
delay: (el, i, total) => {
const index = parseFloat(el.dataset.index);
return total + ((i + index) * 100);
},
});
// Property value
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 2)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 3)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 0)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 1)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 2)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 3)._valueType).to.equal(valueTypes.UNIT);
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(1);
expect(getChildAtIndex(animation, 2)._toNumber).to.equal(2);
expect(getChildAtIndex(animation, 3)._toNumber).to.equal(3);
expect(getChildAtIndex(animation, 0)._unit).to.equal('px');
expect(getChildAtIndex(animation, 1)._unit).to.equal('px');
expect(getChildAtIndex(animation, 2)._unit).to.equal('px');
expect(getChildAtIndex(animation, 3)._unit).to.equal('px');
expect($targets[0].style.transform).to.equal('translateX(0px)');
expect($targets[1].style.transform).to.equal('translateX(0px)');
expect($targets[2].style.transform).to.equal('translateX(0px)');
expect($targets[3].style.transform).to.equal('translateX(0px)');
animation.seek(animation.duration);
expect($targets[0].style.transform).to.equal('translateX(0px)');
expect($targets[1].style.transform).to.equal('translateX(1px)');
expect($targets[2].style.transform).to.equal('translateX(2px)');
expect($targets[3].style.transform).to.equal('translateX(3px)');
// Duration
expect(getChildAtIndex(animation, 0)._changeDuration).to.equal(4);
expect(getChildAtIndex(animation, 1)._changeDuration).to.equal(204);
expect(getChildAtIndex(animation, 2)._changeDuration).to.equal(404);
expect(getChildAtIndex(animation, 3)._changeDuration).to.equal(604);
// Delay
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(200);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(400);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(600);
});
test('Function based keyframes values', () => {
const $targets = document.querySelectorAll('.target-class');
const animation = animate($targets, {
autoplay: false,
translateX: [
{ to: el => el.getAttribute('data-index') * 100, duration: stagger(100), delay: stagger(100) },
{ to: el => el.getAttribute('data-index') * 50, duration: stagger(100), delay: stagger(100) }
],
});
// Values
expect(getChildAtIndex(animation, 0 * 2)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, 1 * 2)._toNumber).to.equal(100);
expect(getChildAtIndex(animation, 2 * 2)._toNumber).to.equal(200);
expect(getChildAtIndex(animation, 3 * 2)._toNumber).to.equal(300);
expect(getChildAtIndex(animation, (0 * 2) + 1)._toNumber).to.equal(0);
expect(getChildAtIndex(animation, (1 * 2) + 1)._toNumber).to.equal(50);
expect(getChildAtIndex(animation, (2 * 2) + 1)._toNumber).to.equal(100);
expect(getChildAtIndex(animation, (3 * 2) + 1)._toNumber).to.equal(150);
// Duration
expect(getChildAtIndex(animation, 0 * 2)._changeDuration).to.equal(minValue);
expect(getChildAtIndex(animation, 1 * 2)._changeDuration).to.equal(100);
expect(getChildAtIndex(animation, 2 * 2)._changeDuration).to.equal(200);
expect(getChildAtIndex(animation, 3 * 2)._changeDuration).to.equal(300);
expect(getChildAtIndex(animation, (0 * 2) + 1)._changeDuration).to.equal(minValue);
expect(getChildAtIndex(animation, (1 * 2) + 1)._changeDuration).to.equal(100);
expect(getChildAtIndex(animation, (2 * 2) + 1)._changeDuration).to.equal(200);
expect(getChildAtIndex(animation, (3 * 2) + 1)._changeDuration).to.equal(300);
// Delay
expect(getTweenDelay(getChildAtIndex(animation, 0 * 2))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 1 * 2))).to.equal(100);
expect(getTweenDelay(getChildAtIndex(animation, 2 * 2))).to.equal(200);
expect(getTweenDelay(getChildAtIndex(animation, 3 * 2))).to.equal(300);
expect(getTweenDelay(getChildAtIndex(animation, (0 * 2) + 1))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, (1 * 2) + 1))).to.equal(100);
expect(getTweenDelay(getChildAtIndex(animation, (2 * 2) + 1))).to.equal(200);
expect(getTweenDelay(getChildAtIndex(animation, (3 * 2) + 1))).to.equal(300);
});
test('Function based string values -> number conversion', () => {
const $targets = document.querySelectorAll('.target-class');
const animation = animate($targets, {
autoplay: false,
translateX: 10,
delay: $el => $el.dataset.index,
});
// Delay
expect(getTweenDelay(getChildAtIndex(animation, 0))).to.equal(0);
expect(getTweenDelay(getChildAtIndex(animation, 1))).to.equal(1);
expect(getTweenDelay(getChildAtIndex(animation, 2))).to.equal(2);
expect(getTweenDelay(getChildAtIndex(animation, 3))).to.equal(3);
});
test('Function based values returns from to Array values', () => {
const $targets = document.querySelectorAll('.target-class');
const animation = animate($targets, {
autoplay: false,
translateX: ($el, i, t) => [$el.dataset.index, (t - 1) - i],
});
// From
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(1);
expect(getChildAtIndex(animation, 2)._fromNumber).to.equal(2);
expect(getChildAtIndex(animation, 3)._fromNumber).to.equal(3);
// To
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(3);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(2);
expect(getChildAtIndex(animation, 2)._toNumber).to.equal(1);
expect(getChildAtIndex(animation, 3)._toNumber).to.equal(0);
});
test('Function based values in from to Array values', () => {
const $targets = document.querySelectorAll('.target-class');
const animation = animate($targets, {
autoplay: false,
translateX: [
($el, i, t) => $el.dataset.index,
($el, i, t) => (t - 1) - i
],
});
// From
expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(1);
expect(getChildAtIndex(animation, 2)._fromNumber).to.equal(2);
expect(getChildAtIndex(animation, 3)._fromNumber).to.equal(3);
// To
expect(getChildAtIndex(animation, 0)._toNumber).to.equal(3);
expect(getChildAtIndex(animation, 1)._toNumber).to.equal(2);
expect(getChildAtIndex(animation, 2)._toNumber).to.equal(1);
expect(getChildAtIndex(animation, 3)._toNumber).to.equal(0);
});
// test('Function based values refresh', () => {
// const $targets = document.querySelectorAll('.target-class');
// const animation = animate($targets, {
// autoplay: false,
// translateX: [
// ($el, i, t) => $el.dataset.index,
// ($el, i, t) => utils.ran
// ],
// });
// console.log(animation._head._func());
// console.log(animation._head._next._func());
// console.log(animation._head._next._next._func());
// // From
// expect(getChildAtIndex(animation, 0)._fromNumber).to.equal(0);
// expect(getChildAtIndex(animation, 1)._fromNumber).to.equal(1);
// expect(getChildAtIndex(animation, 2)._fromNumber).to.equal(2);
// expect(getChildAtIndex(animation, 3)._fromNumber).to.equal(3);
// // To
// expect(getChildAtIndex(animation, 0)._toNumber).to.equal(3);
// expect(getChildAtIndex(animation, 1)._toNumber).to.equal(2);
// expect(getChildAtIndex(animation, 2)._toNumber).to.equal(1);
// expect(getChildAtIndex(animation, 3)._toNumber).to.equal(0);
// });
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/timelines.test.js | tests/suites/timelines.test.js | import {
expect,
getChildAtIndex,
} from '../utils.js';
import {
createTimeline,
eases,
steps,
utils,
createTimer,
animate,
} from '../../dist/modules/index.js';
import {
compositionTypes,
minValue,
} from '../../dist/modules/core/consts.js';
suite('Timelines', () => {
function createTL() {
return createTimeline({
id: 'Test',
defaults: {
duration: 50, // Can be inherited
ease: 'outExpo', // Can be inherited
delay: function(_, i) { return 10 + (i * 20) }, // Can be inherited
},
alternate: true, // Is not inherited
loop: 1 // Is not inherited
})
.add('.target-class', {
translateX: 250,
})
.add('.target-class', {
opacity: .5,
scale: 2
})
.add('#target-id', {
rotate: 180
})
.add('.target-class', {
translateX: 0,
scale: 1
});
}
test('Timeline children position should be added to their delay', () => {
const tl = createTimeline({
autoplay: false,
defaults: {
duration: 50
}
})
.add('#target-id', {
translateX: 100,
delay: 200
})
.add('#target-id', {
translateX: -100,
delay: 300
})
.add('#target-id', {
translateX: 0,
delay: 50
}, '+=150')
.add('#target-id', {
translateX: 100,
}, '+=50')
expect(getChildAtIndex(tl, 0)._offset + getChildAtIndex(tl, 0)._delay).to.equal(200);
expect(getChildAtIndex(tl, 1)._offset + getChildAtIndex(tl, 1)._delay).to.equal(550);
expect(getChildAtIndex(tl, 2)._offset + getChildAtIndex(tl, 2)._delay).to.equal(800);
expect(getChildAtIndex(tl, 3)._offset + getChildAtIndex(tl, 3)._delay).to.equal(900);
});
test('Timeline duration should be equal to the sum of all the animation absoluteEndTime multiply by the iterations count', () => {
const parameterInheritanceTL = createTL();
expect(parameterInheritanceTL.duration).to.equal(420 * 2);
});
test('Timeline default parameters', () => {
const tl = createTimeline({
loop: 1,
reversed: true,
defaults: {
duration: 10,
ease: 'inOut',
alternate: true,
loop: 3,
composition: 'none',
}
})
.add('#target-id', {
translateX: 100,
duration: 15
})
.add('#target-id', {
translateX: 200,
reversed: false,
ease: 'outExpo',
composition: 'blend'
})
expect(getChildAtIndex(tl, 0)._reversed).to.equal(0);
expect(getChildAtIndex(tl, 1)._reversed).to.equal(0);
expect(tl.duration).to.equal(200); // (( 15 * 4 ) + ( 10 * 4 )) * 2 = 200
expect(getChildAtIndex(tl, 0)._head._ease(.75)).to.equal(eases.inOut()(.75));
expect(getChildAtIndex(tl, 1)._head._ease(.75)).to.equal(eases.outExpo(.75));
expect(getChildAtIndex(tl, 0)._head._composition).to.equal(compositionTypes['none']);
expect(getChildAtIndex(tl, 1)._head._composition).to.equal(compositionTypes['blend']);
});
test('Basic timeline time positions', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', { translateX: 100 })
.add('#target-id', { translateX: 200 })
.add('#target-id', { translateX: 300 });
expect(getChildAtIndex(tl, 0)._offset).to.equal(0);
expect(getChildAtIndex(tl, 1)._offset).to.equal(10);
expect(getChildAtIndex(tl, 2)._offset).to.equal(20);
expect(tl.duration).to.equal(30);
});
test('Abslolute timeline time positions', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', { translateX: 100 }, 50)
.add('#target-id', { translateX: 200 }, 25)
.add('#target-id', { translateX: 300 }, 100);
expect(getChildAtIndex(tl, 0)._offset).to.equal(50);
expect(getChildAtIndex(tl, 1)._offset).to.equal(25);
expect(getChildAtIndex(tl, 2)._offset).to.equal(100);
expect(tl.duration).to.equal(110);
});
test('Abslolute timeline time positions with shared child params object', () => {
const childParams = { translateX: 100 };
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', childParams, 50)
.add('#target-id', childParams, 25)
.add('#target-id', childParams, 100);
expect(getChildAtIndex(tl, 0)._offset).to.equal(50);
expect(getChildAtIndex(tl, 1)._offset).to.equal(25);
expect(getChildAtIndex(tl, 2)._offset).to.equal(100);
expect(tl.duration).to.equal(110);
});
test('Relative timeline time positions', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', { translateX: 100 }, '+=20') // 0 + 20 = 20
.add('#target-id', { translateX: 200 }, '*=2') // (20 + 10) * 2 = 60
.add('#target-id', { translateX: 300 }, '-=50'); // (60 + 10) - 50 = 20
expect(getChildAtIndex(tl, 0)._offset).to.equal(20);
expect(getChildAtIndex(tl, 1)._offset).to.equal(60);
expect(getChildAtIndex(tl, 2)._offset).to.equal(20);
expect(tl.duration).to.equal(70); // 60 + 10
});
test('Previous operator with relative values should be properly parsed', () => {
const $target = document.querySelector('#target-id');
const tl = createTimeline({ defaults: { duration: 10 } }).add($target, {
translateX: 100
}).add($target, {
rotate: 100
}, '<<+=100')
expect(getChildAtIndex(tl, 1)._offset).to.equal(100);
});
test('Previous animation end position', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', { translateX: 100 }, '+=40')
.add('#target-id', { translateX: 200 }, '-=30') // 40 + 10 - 30 = 20
.add('#target-id', { translateX: 300 }, '<'); // 20 + 10 = 30
expect(getChildAtIndex(tl, 0)._offset).to.equal(40);
expect(getChildAtIndex(tl, 1)._offset).to.equal(20);
expect(getChildAtIndex(tl, 2)._offset).to.equal(30);
expect(tl.duration).to.equal(50);
});
test('Previous animation end position with relative value', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', { translateX: 100 }, '+=40')
.add('#target-id', { translateX: 200 }, '-=30') // 40 + 10 - 30 = 20
.add('#target-id', { translateX: 300 }, '<+=5'); // 20 + 10 + 5 = 35
expect(getChildAtIndex(tl, 2)._offset).to.equal(35);
});
test('Previous animation start position', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', { translateX: 100 }, '+=40')
.add('#target-id', { translateX: 200 }, '-=30') // 40 + 10 - 30 = 20
.add('#target-id', { translateX: 300 }, '<<'); // 20 = 20
expect(getChildAtIndex(tl, 0)._offset).to.equal(40);
expect(getChildAtIndex(tl, 1)._offset).to.equal(20);
expect(getChildAtIndex(tl, 2)._offset).to.equal(20);
expect(tl.duration).to.equal(50);
});
test('Previous animation start position with relative values', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', { translateX: 100 }, '+=40')
.add('#target-id', { translateX: 200 }, '-=30') // 40 + 10 - 30 = 20
.add('#target-id', { translateX: 300 }, '<<+=5'); // 20 + 5 = 25
expect(getChildAtIndex(tl, 0)._offset).to.equal(40);
expect(getChildAtIndex(tl, 1)._offset).to.equal(20);
expect(getChildAtIndex(tl, 2)._offset).to.equal(25);
expect(tl.duration).to.equal(50);
});
test('Mixed timeline time positions types', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.add('#target-id', { translateX: 100 }, 50)
.add('#target-id', { translateX: 200 }, '-=20') // (50 + 10) - 20 = 40
.add('#target-id', { translateX: 300 }, 0);
expect(getChildAtIndex(tl, 0)._offset).to.equal(50);
expect(getChildAtIndex(tl, 1)._offset).to.equal(40);
expect(getChildAtIndex(tl, 2)._offset).to.equal(0);
expect(tl.duration).to.equal(60); // 50 + 10
});
test('Timeline labels positions', () => {
const tl = createTimeline({ defaults: { duration: 10 } })
.label('A starts', 50)
.label('B starts', 100)
.label('C') // Added without a position before any animations
.add('#target-id', { translateX: 50 }, 'A starts')
.label('A ends', '<')
.label('D') // Added without a position after an animation
.add('#target-id', { translateX: -50 }, 'B starts')
.add('#target-id', { translateX: 0 }, 'A ends')
.add('#target-id', { translateX: 100 }, 'C')
.add('#target-id', { translateX: 150 }, 'D')
expect(tl.labels['A starts']).to.equal(50);
expect(tl.labels['B starts']).to.equal(100);
expect(tl.labels['A ends']).to.equal(50 + 10);
expect(tl.labels['C']).to.equal(0);
expect(tl.labels['D']).to.equal(50 + 10);
expect(getChildAtIndex(tl, 0)._offset).to.equal(tl.labels['A starts']);
expect(getChildAtIndex(tl, 1)._offset).to.equal(tl.labels['B starts']);
expect(getChildAtIndex(tl, 2)._offset).to.equal(tl.labels['A ends']);
expect(getChildAtIndex(tl, 3)._offset).to.equal(tl.labels['C']);
expect(getChildAtIndex(tl, 4)._offset).to.equal(tl.labels['D']);
expect(tl.duration).to.equal(110); // 100 + 10
});
test('Correct tween overiding when adding an animation before multiple keyframe start time on the same property', () => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({
autoplay: false,
defaults: {
duration: 100,
ease: 'linear',
}
})
.add($target, { translateX: 100, top: 100 })
.add($target, {
translateX: [
{ to: 250, duration: 50, delay: 50 },
{ to: 350, duration: 100 },
{ to: 150, duration: 150 }
]
})
.add($target, { translateX: 15, duration: 200 }, '-=275')
.add($target, { top: 25, duration: 50 }, 0)
// expect($target.style.transform).to.equal('translateX(0px)');
// expect($target.style.top).to.equal('0px');
expect($target.style.transform).to.equal('');
expect($target.style.top).to.equal('');
tl.seek(175);
expect($target.style.transform).to.equal('translateX(175px)');
// expect($target.style.top).to.equal('25px');
expect($target.style.top).to.equal('');
tl.seek(275);
expect($target.style.transform).to.equal('translateX(95px)');
tl.seek(375);
expect($target.style.transform).to.equal('translateX(15px)');
tl.seek(tl.duration);
expect($target.style.transform).to.equal('translateX(15px)');
tl.seek(275);
expect($target.style.transform).to.equal('translateX(95px)');
});
test('Correct tween composition with multiple timelines', () => {
const [ $target ] = utils.$('#target-id');
const tl1 = createTimeline({
autoplay: false,
defaults: {
duration: 100,
ease: 'linear',
}
})
.add($target, { x: 100 })
.add($target, { x: 200 })
.init();
tl1.seek(200);
const tl2 = createTimeline({
autoplay: false,
defaults: {
duration: 100,
ease: 'linear',
}
})
.add($target, { x: -100 })
.init();
tl2.seek(0);
// TL 2 should correctly starts at 200px
expect($target.style.transform).to.equal('translateX(200px)');
});
test('Correct initial tween value on loop', () => {
const [ $target1, $target2 ] = utils.$('.target-class');
const tl = createTimeline({
autoplay: false,
loop: 2,
defaults: {
duration: 100,
ease: 'linear',
}
})
.add($target1, { translateX: 100 })
.add($target1, { opacity: 0 })
.add($target2, { translateX: 100 })
.add($target2, { opacity: 0 })
expect($target1.style.transform).to.equal('');
expect($target1.style.top).to.equal('');
expect($target2.style.transform).to.equal('');
expect($target2.style.top).to.equal('');
tl.seek(50);
expect($target1.style.transform).to.equal('translateX(50px)');
expect($target1.style.opacity).to.equal('');
expect($target2.style.transform).to.equal('');
expect($target2.style.opacity).to.equal('');
tl.seek(100);
expect($target1.style.transform).to.equal('translateX(100px)');
expect($target1.style.opacity).to.equal('1');
expect($target2.style.transform).to.equal('');
expect($target2.style.opacity).to.equal('');
tl.seek(150);
expect($target1.style.transform).to.equal('translateX(100px)');
expect($target1.style.opacity).to.equal('0.5');
expect($target2.style.transform).to.equal('');
expect($target2.style.opacity).to.equal('');
tl.seek(200);
expect($target1.style.transform).to.equal('translateX(100px)');
expect($target1.style.opacity).to.equal('0');
expect($target2.style.transform).to.equal('translateX(0px)');
expect($target2.style.opacity).to.equal('');
tl.seek(250);
expect($target1.style.transform).to.equal('translateX(100px)');
expect($target1.style.opacity).to.equal('0');
expect($target2.style.transform).to.equal('translateX(50px)');
expect($target2.style.opacity).to.equal('');
tl.seek(300);
expect($target1.style.transform).to.equal('translateX(100px)');
expect($target1.style.opacity).to.equal('0');
expect($target2.style.transform).to.equal('translateX(100px)');
expect($target2.style.opacity).to.equal('1');
tl.seek(350);
expect($target1.style.transform).to.equal('translateX(100px)');
expect($target1.style.opacity).to.equal('0');
expect($target2.style.transform).to.equal('translateX(100px)');
expect($target2.style.opacity).to.equal('0.5');
tl.seek(400);
expect($target1.style.transform).to.equal('translateX(0px)');
expect($target1.style.opacity).to.equal('1');
expect($target2.style.transform).to.equal('translateX(0px)');
expect($target2.style.opacity).to.equal('1');
tl.seek(550);
expect($target1.style.transform).to.equal('translateX(100px)');
expect($target1.style.opacity).to.equal('0.5');
expect($target2.style.transform).to.equal('translateX(0px)');
expect($target2.style.opacity).to.equal('1');
});
test('Correct tween playback with multiple timelines', resolve => {
const target = {x: 0};
setTimeout(() => {
const tl1 = createTimeline({
defaults: {
duration: 100,
ease: 'linear',
}
})
.add(target, { x: 100 })
.init();
}, 50)
setTimeout(() => {
const tl2 = createTimeline({
defaults: {
duration: 100,
ease: 'linear',
}
})
.add(target, { x: -100 })
.init();
}, 100)
setTimeout(() => {
expect(target.x).to.lessThan(0);
resolve();
}, 150)
});
test('Timeline values', () => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({
autoplay: false,
defaults: {
duration: 100,
ease: 'linear',
}
})
.add($target, { translateX: 100 })
.add($target, { translateX: 200 }, '-=50')
.add($target, { translateX: 300 }, '-=50')
.add($target, {
translateX: [
{ to: 250, duration: 50, delay: 50 },
{ to: 350, duration: 100 },
{ to: 150, duration: 150 }
]
});
expect($target.style.transform).to.equal('');
tl.seek(25);
expect($target.style.transform).to.equal('translateX(25px)');
tl.seek(100);
expect($target.style.transform).to.equal('translateX(125px)');
tl.seek(150);
expect($target.style.transform).to.equal('translateX(212.5px)');
tl.seek(tl.duration);
expect($target.style.transform).to.equal('translateX(150px)');
});
test('Alternate direction timeline children should correctly render on seek after the animation end', resolve => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({
loop: 2,
alternate: true,
onComplete: self => {
self.seek(40);
expect($target.style.transform).to.equal('translateX(175px)');
resolve();
}
})
.add($target, {
translateX: -100,
duration: 10,
loop: 2,
alternate: true,
ease: 'linear',
})
.add($target, {
translateX: 400,
duration: 10,
loop: 2,
alternate: true,
ease: 'linear',
}, '-=5')
});
test('Alternate direction timeline children should correctly render on seek midway', () => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({
loop: 1,
alternate: true,
autoplay: false,
})
.add($target, {
translateX: 100,
duration: 10,
alternate: true,
ease: 'linear',
})
.add($target, {
translateX: 200,
translateY: 100,
duration: 10,
alternate: true,
ease: 'linear',
}, '-=5')
tl.seek(15)
expect($target.style.transform).to.equal('translateX(200px) translateY(100px)');
tl.seek(16)
expect($target.style.transform).to.equal('translateX(185px) translateY(90px)');
tl.seek(15)
expect($target.style.transform).to.equal('translateX(200px) translateY(100px)');
tl.seek(14)
expect($target.style.transform).to.equal('translateX(185px) translateY(90px)');
});
test('Previous tween before last shouln\'t render on loop', resolve => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({
loop: 3,
onLoop: self => {
self.pause();
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.be.above(39);
resolve();
}
})
.add($target, {
translateY: -100,
duration: 100,
})
.add($target, {
translateY: 50,
duration: 100,
})
});
test('Nested timelines', resolve => {
const [ $target ] = utils.$('#target-id');
let timerLog = false;
const timer = createTimer({
duration: 30,
onUpdate: () => { timerLog = true }
});
const animation = animate($target, {
x: 100,
duration: 30,
});
createTimeline({
onComplete: self => {
expect(self.duration).to.equal(50);
expect(timerLog).to.equal(true);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(100);
resolve();
}
})
.sync(timer)
.sync(animation, 20);
expect(timerLog).to.equal(false);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(0);
});
test('Add animation and timers as targets', resolve => {
const [ $target ] = utils.$('#target-id');
let timerLog = false;
const timer = createTimer({
onUpdate: () => { timerLog = true }
});
const animation = animate($target, {
x: 100,
});
createTimeline({
onComplete: self => {
expect(self.duration).to.equal(50);
expect(timerLog).to.equal(true);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(100);
resolve();
}
})
.add(timer, {
currentTime: timer.duration,
duration: 30,
})
.add(animation, {
currentTime: animation.duration,
duration: 30,
}, 20);
expect(timerLog).to.equal(false);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(0);
});
test('Add timers', resolve => {
let timer1Log = false;
let timer2Log = false;
createTimeline({
onComplete: () => {
expect(timer1Log).to.equal(true);
expect(timer2Log).to.equal(true);
resolve();
}
})
.add({
duration: 30,
onUpdate: () => { timer1Log = true }
})
.add({
duration: 30,
onUpdate: () => { timer2Log = true }
}, 20)
});
test('Timeline .add() 0 duration animation', () => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({ autoplay: false })
.add($target, {
y: -100,
duration: 0,
}, 2000)
.seek(2000) // y should be -100
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(-100);
});
test('Timeline .set()', () => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({
autoplay: false
})
.set($target, {
y: -300,
}, 2000)
.seek(2000)
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(-300);
});
test('Timeline mix .set() and .add()', () => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({
autoplay: false,
defaults: {
ease: 'linear',
}
})
.set($target, { translateX: 50 })
.add($target, {
duration: 200,
translateX: 100,
})
.set($target, { translateX: 200 })
.add($target, {
duration: 200,
translateX: 400,
})
.set($target, {
translateX: -100,
}, 800)
tl.seek(0);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(50);
tl.seek(100);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(75);
tl.seek(200);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(200);
tl.seek(300);
expect(Math.round(+$target.style.transform.replace(/[^\d.-]/g, ''))).to.equal(300);
tl.seek(800);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(-100);
});
test('Call callbacks', resolve => {
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
const tl = createTimeline({
onComplete: self => {
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(1);
expect(self.duration).to.equal(40);
resolve();
}
})
.call(() => {
timer1Log += 1;
}, 0)
.call(() => {
timer2Log += 1;
}, 20)
.call(() => {
timer3Log += 1;
}, 40);
});
test('Call callbacks on a 0 duration timeline', resolve => {
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
const tl = createTimeline({
onComplete: self => {
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(1);
expect(self.duration).to.equal(minValue);
resolve();
}
})
.call(() => {
timer1Log += 1;
}, 0)
.call(() => {
timer2Log += 1;
}, 0)
.call(() => {
timer3Log += 1;
}, 0)
});
test('Call callbaks multiple time via seek', () => {
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
const tl = createTimeline({ autoplay: false })
.call(() => { timer1Log += 1; }, 0)
.call(() => { timer2Log += 1; }, 1000)
.call(() => { timer3Log += 1; }, 2000);
expect(timer1Log).to.equal(0);
expect(timer2Log).to.equal(0);
expect(timer3Log).to.equal(0);
tl.seek(500);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(0);
expect(timer3Log).to.equal(0);
tl.seek(1000);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(0);
tl.seek(2000);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(1);
tl.seek(1000);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(2);
expect(timer3Log).to.equal(2);
tl.seek(0);
expect(timer1Log).to.equal(2);
expect(timer2Log).to.equal(2);
expect(timer3Log).to.equal(2);
});
test('Call callbaks with alternate loops', () => {
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
const tl = createTimeline({ autoplay: false, alternate: true, loop: 3 })
.call(() => { timer1Log += 1; }, 0)
.call(() => { timer2Log += 1; }, 1000)
.call(() => { timer3Log += 1; }, 2000);
expect(timer1Log).to.equal(0);
expect(timer2Log).to.equal(0);
expect(timer3Log).to.equal(0);
tl.seek(500);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(0);
expect(timer3Log).to.equal(0);
tl.seek(1500);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(0);
tl.seek(2000);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(1);
tl.seek(3000);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(2);
expect(timer3Log).to.equal(1);
tl.seek(4000);
expect(timer1Log).to.equal(2);
expect(timer2Log).to.equal(2);
expect(timer3Log).to.equal(1);
});
test('Mixed .call and .add', () => {
const $targets = utils.$(['.target-class:nth-child(1)', '.target-class:nth-child(2)', '.target-class:nth-child(3)']);
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
const tl = createTimeline({
loop: 2,
autoplay: false
})
.set($targets, {
opacity: .5,
}, 0)
.add($targets, {
id: 'test',
duration: 500,
opacity: [1, .5],
delay: (el, i) => i * 500,
ease: steps(1),
}, 0)
.call(() => { timer1Log += 1; }, 0)
.call(() => { timer2Log += 1; }, 500)
.call(() => { timer3Log += 1; }, 1000)
.init()
expect(timer1Log).to.equal(0);
expect(timer2Log).to.equal(0);
expect(timer3Log).to.equal(0);
tl.seek(50);
expect($targets[2].style.opacity).to.equal('0.5');
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(0);
expect(timer3Log).to.equal(0);
tl.seek(600);
expect($targets[2].style.opacity).to.equal('0.5');
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(0);
tl.seek(1000);
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(1);
expect($targets[2].style.opacity).to.equal('1');
});
test('.call with odd floating points values A', resolve => {
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
let timer4Log = 0;
const tl = createTimeline({
onComplete: () => {
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(1);
expect(timer4Log).to.equal(1);
resolve();
}
})
.call(() => ++timer1Log, 0)
.call(() => ++timer2Log, 800)
.call(() => ++timer3Log, 8700)
.call(() => ++timer4Log, 8650)
.seek(8650);
});
test('.call with odd floating points values B', resolve => {
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
let timer4Log = 0;
const tl = createTimeline({
onComplete: () => {
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(1);
expect(timer4Log).to.equal(1);
resolve();
}
})
.call(() => ++timer1Log, 0)
.call(() => ++timer2Log, 800)
.call(() => ++timer3Log, 8000)
.call(() => ++timer4Log, 8450)
.seek(8400);
});
test('Set values should properly update on loop', () => {
const $targets = utils.$(['.target-class:nth-child(1)', '.target-class:nth-child(2)', '.target-class:nth-child(3)']);
const tl = createTimeline({
loop: 2,
autoplay: false
})
.set($targets, {
opacity: .5,
}, 0)
.add($targets, {
id: 'test',
duration: 500,
opacity: [1, .5],
delay: (el, i) => i * 500,
ease: steps(1),
}, 0)
.init()
tl.seek(1250);
expect($targets[2].style.opacity).to.equal('1');
tl.seek(1750);
expect($targets[2].style.opacity).to.equal('0.5');
});
test('Remove nested animations', resolve => {
const [ $target ] = utils.$('#target-id');
let timerLog = false;
const timer = createTimer({
duration: 30,
onUpdate: () => { timerLog = true }
});
const animation = animate($target, {
x: 100,
duration: 30,
});
const tl = createTimeline({
onComplete: self => {
expect(self.duration).to.equal(50);
expect(timerLog).to.equal(true);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(0);
resolve();
}
})
.sync(timer)
.sync(animation, 20);
expect(timerLog).to.equal(false);
expect(+$target.style.transform.replace(/[^\d.-]/g, '')).to.equal(0);
tl.remove(animation);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/scroll.test.js | tests/suites/scroll.test.js | import {
expect,
} from '../utils.js';
import {
onScroll,
scrollContainers,
animate,
utils
} from '../../dist/modules/index.js';
suite('Scroll', () => {
test('Reverting an animation with onScroll should also revert the ScrollObserver', () => {
const [ $container ] = utils.$('#css-tests');
const animation = animate('#target-id', {
rotate: 360,
autoplay: onScroll({
container: '#css-tests',
})
});
expect(scrollContainers.get($container)).to.not.equal(undefined);
$container.remove();
$container.width = '100px';
animation.revert();
expect(scrollContainers.get($container)).to.equal(undefined);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/waapi.test.js | tests/suites/waapi.test.js | import {
expect,
} from '../utils.js';
import {
waapi,
utils,
stagger,
eases,
} from '../../dist/modules/index.js';
suite('WAAPI', () => {
CSS.registerProperty({
name: '--translateX',
syntax: '<length-percentage>',
inherits: false,
initialValue: '0px'
});
test('Calling registerProperty on transforms should not conflict with the built-in one', resolve => {
waapi.animate('#target-id', {
scale: 1.5,
duration: 10,
onComplete: self => {
expect(self.completed).to.equal(true);
resolve();
}
})
});
test('Calling .complete() on an animation should trigger the .then() Promise', resolve => {
const instance = waapi.animate('#target-id', {
scale: 1.5,
duration: 500,
autoplay: false,
});
instance.then(self => {
expect(self.completed).to.equal(true);
resolve();
});
setTimeout(() => {
instance.complete();
}, 10);
});
test('Animate multiple elements', resolve => {
const targets = utils.$('.target-class');
const animation = waapi.animate(targets, {
transform: `translateX(100px)`,
duration: 10,
onComplete: anim => {
expect(anim.duration).to.equal(10);
expect(utils.get(targets[0], 'x')).to.equal('100px');
expect(utils.get(targets[1], 'x')).to.equal('100px');
expect(utils.get(targets[2], 'x')).to.equal('100px');
expect(utils.get(targets[3], 'x')).to.equal('100px');
resolve();
},
});
});
test('Animate multiple elements with stagger', resolve => {
const targets = utils.$('.target-class');
const animation = waapi.animate(targets, {
transform: `translateX(100px)`,
duration: 10,
delay: stagger(1),
onComplete: anim => {
expect(anim.duration).to.equal(13);
expect(utils.get(targets[0], 'x')).to.equal('100px');
expect(utils.get(targets[1], 'x')).to.equal('100px');
expect(utils.get(targets[2], 'x')).to.equal('100px');
expect(utils.get(targets[3], 'x')).to.equal('100px');
resolve();
},
});
});
test('Animate with function based values', resolve => {
const targets = utils.$('.target-class');
const animation = waapi.animate(targets, {
transform: (_, i) => `translateX(${i * 100}px)`,
duration: 10,
delay: stagger(1),
onComplete: anim => {
expect(utils.get(targets[0], 'x')).to.equal('0px');
expect(utils.get(targets[1], 'x')).to.equal('100px');
expect(utils.get(targets[2], 'x')).to.equal('200px');
expect(utils.get(targets[3], 'x')).to.equal('300px');
resolve();
},
});
});
test('Animate with function based keyframes value', resolve => {
const targets = utils.$('.target-class');
const animation = waapi.animate(targets, {
transform: ['translateX(200px)', (_, i) => `translateX(${i * 100}px)`],
duration: 10,
delay: stagger(1),
onComplete: anim => {
expect(utils.get(targets[0], 'x')).to.equal('0px');
expect(utils.get(targets[1], 'x')).to.equal('100px');
expect(utils.get(targets[2], 'x')).to.equal('200px');
expect(utils.get(targets[3], 'x')).to.equal('300px');
resolve();
},
});
});
test('Seek an animation', () => {
const targets = utils.$('.target-class');
const animation = waapi.animate(targets, {
translate: `100px`,
duration: 10,
autoplay: false,
ease: 'linear',
});
expect(animation.currentTime).to.equal(0);
animation.seek(5).commitStyles();
expect(utils.get(targets[0], 'translate')).to.equal('50px');
expect(animation.currentTime).to.equal(5);
animation.seek(animation.duration).commitStyles();
expect(animation.currentTime).to.equal(animation.duration);
expect(utils.get(targets[0], 'translate')).to.equal('100px');
});
test('Set and get progress on an animation', () => {
const targets = utils.$('.target-class');
const animation = waapi.animate(targets, {
translate: `100px`,
duration: 10,
autoplay: false,
ease: 'linear',
});
expect(animation.progress).to.equal(0);
animation.progress = .5;
animation.commitStyles();
expect(utils.get(targets[0], 'translate')).to.equal('50px');
expect(animation.progress).to.equal(.5);
animation.progress = 1;
animation.commitStyles();
expect(utils.get(targets[0], 'translate')).to.equal('100px');
});
test('Individual transforms', resolve => {
const target = utils.$('#target-id');
const animation = waapi.animate(target, {
x: 100,
y: 200,
rotate: 45,
scale: 2,
duration: 10,
ease: 'linear',
onComplete: anim => {
expect(anim.duration).to.equal(10);
expect(utils.get(target, '--translateX')).to.equal('100px');
expect(utils.get(target, '--translateY')).to.equal('200px');
expect(utils.get(target, '--rotate')).to.equal('45deg');
expect(utils.get(target, '--scale')).to.equal('2');
resolve();
},
});
});
test('revert() an animation', resolve => {
const targets = utils.$('.target-class');
utils.set(targets, {
backgroundColor: '#FF0000',
opacity: .5,
});
const animation = waapi.animate(targets, {
opacity: 1,
backgroundColor: '#0000FF',
x: 100,
y: 200,
rotate: 45,
scale: 2,
duration: 10,
ease: 'linear',
onComplete: () => {
targets.forEach($el => {
expect(utils.get($el, 'opacity')).to.equal('1');
expect(utils.get($el, 'backgroundColor')).to.equal('rgb(0, 0, 255)');
});
animation.revert();
targets.forEach($el => {
expect(utils.get($el, 'opacity')).to.equal('0.5');
expect(utils.get($el, 'backgroundColor')).to.equal('rgb(255, 0, 0)');
expect(utils.get($el, 'transform')).to.equal('none');
// expect(utils.get($el, '--translateX')).to.equal('0px');
// expect(utils.get($el, '--translateY')).to.equal('0px');
// expect(utils.get($el, '--rotate')).to.equal('0deg');
// expect(utils.get($el, '--scale')).to.equal('1');
});
resolve();
},
});
});
test('utils.remove() a single target', resolve => {
const targets = utils.$('.target-class');
waapi.animate(targets, {
opacity: .5,
duration: 10,
onComplete: () => {
targets.forEach(($el, i) => {
expect(utils.get($el, 'opacity')).to.equal(!i ? '1' : '0.5');
});
resolve();
},
});
utils.remove(targets[0]);
});
test('utils.remove() on a specific animation', resolve => {
const targets = utils.$('.target-class');
const anim1 = waapi.animate(targets, {
opacity: .5,
duration: 10,
});
waapi.animate(targets, {
width: ['0px', '100px'],
duration: 10,
onComplete: () => {
targets.forEach(($el, i) => {
expect(utils.get($el, 'opacity')).to.equal('1');
expect(utils.get($el, 'width')).to.equal('100px');
});
resolve();
},
});
utils.remove(targets, anim1);
});
test('utils.remove() on a specific property', resolve => {
const targets = utils.$('.target-class');
const anim1 = waapi.animate(targets, {
opacity: .5,
duration: 10,
});
waapi.animate(targets, {
width: ['0px', '100px'],
duration: 10,
onComplete: () => {
targets.forEach(($el, i) => {
expect(utils.get($el, 'opacity')).to.equal('1');
expect(utils.get($el, 'width')).to.equal('100px');
});
resolve();
},
});
utils.remove(targets, null, 'opacity');
});
test('utils.remove() on a specific animation and property', resolve => {
const targets = utils.$('.target-class');
const anim1 = waapi.animate(targets, {
opacity: .5,
height: ['0px', '200px'],
duration: 10,
});
waapi.animate(targets, {
width: ['0px', '100px'],
duration: 10,
onComplete: () => {
targets.forEach(($el, i) => {
expect(utils.get($el, 'opacity')).to.equal('1');
expect(utils.get($el, 'height')).to.equal('200px');
expect(utils.get($el, 'width')).to.equal('100px');
});
resolve();
},
});
utils.remove(targets, null, 'opacity');
});
test('WAAPI ease cache should not cache functions', () => {
const [ $target1, $target2 ] = utils.$('.target-class');
const animation1 = waapi.animate($target1, {
opacity: 0,
autoplay: false,
duration: 10,
ease: eases.out(1),
});
const animation2 = waapi.animate($target2, {
opacity: 0,
autoplay: false,
duration: 10,
ease: eases.out(4),
});
animation1.seek(5);
animation2.seek(5);
expect(utils.get($target1, 'opacity')).to.not.equal(utils.get($target2, 'opacity'));
});
test('WAAPI ease cache should cache strings', () => {
const [ $target1, $target2 ] = utils.$('.target-class');
const animation1 = waapi.animate($target1, {
opacity: 0,
autoplay: false,
duration: 10,
ease: 'out(1)',
});
const animation2 = waapi.animate($target2, {
opacity: 0,
autoplay: false,
duration: 10,
ease: 'out(4)',
});
animation1.seek(5);
animation2.seek(5);
expect(utils.get($target1, 'opacity')).to.not.equal(utils.get($target2, 'opacity'));
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/callbacks.test.js | tests/suites/callbacks.test.js | import {
expect,
} from '../utils.js';
import {
animate,
createTimeline,
utils,
} from '../../dist/modules/index.js';
function setupAnimationCallBack(callbackName, callbackFunc) {
const parameters = {
translateX: 100,
autoplay: false,
delay: 10,
duration: 80,
}
parameters[callbackName] = callbackFunc;
return parameters;
}
suite('Callbacks', () => {
test('onBegin on animation', () => {
let callbackCheck = 0;
const animation = animate('#target-id', setupAnimationCallBack('onBegin', () => { callbackCheck += 1; }));
expect(callbackCheck).to.equal(0);
expect(animation.began).to.equal(false);
// delay is not taken into account with seek(), so seek(10) actually move the playhead to 10ms + 10ms of delay
animation.seek(5);
expect(callbackCheck).to.equal(1);
expect(animation.began).to.equal(true);
animation.seek(80);
expect(callbackCheck).to.equal(1);
expect(animation.began).to.equal(true);
animation.seek(0);
expect(callbackCheck).to.equal(1);
expect(animation.began).to.equal(false);
animation.seek(5);
expect(callbackCheck).to.equal(2);
expect(animation.began).to.equal(true);
});
test('onBegin on looped animation', () => {
let callbackCheck = 0;
const animation = animate('#target-id', { loop: 2, ...setupAnimationCallBack('onBegin', () => { callbackCheck += 1; }) });
expect(callbackCheck).to.equal(0);
expect(animation.began).to.equal(false);
animation.seek(5);
expect(callbackCheck).to.equal(1);
expect(animation.began).to.equal(true);
animation.seek(80);
expect(callbackCheck).to.equal(1);
expect(animation.began).to.equal(true);
animation.seek(85);
expect(callbackCheck).to.equal(1);
expect(animation.began).to.equal(true);
animation.seek(240);
expect(animation.began).to.equal(true);
expect(callbackCheck).to.equal(1);
animation.seek(100);
expect(animation.began).to.equal(true);
expect(callbackCheck).to.equal(1);
animation.seek(0);
expect(animation.began).to.equal(false);
expect(callbackCheck).to.equal(1);
animation.seek(5);
expect(animation.began).to.equal(true);
expect(callbackCheck).to.equal(2);
});
test('onBegin on timeline', () => {
let tlCallbackCheck = 0;
let tlAnim1CallbackCheck = 0;
let tlAnim2CallbackCheck = 0;
const tl = createTimeline(setupAnimationCallBack('onBegin', () => { tlCallbackCheck += 1; }));
tl.add('#target-id', setupAnimationCallBack('onBegin', () => { tlAnim1CallbackCheck += 1; }))
tl.add('#target-id', setupAnimationCallBack('onBegin', () => { tlAnim2CallbackCheck += 1; }))
expect(tlCallbackCheck).to.equal(0);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(5);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(10);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(11);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(100);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(101);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(95);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(0);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(5);
expect(tlCallbackCheck).to.equal(2);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(11);
expect(tlCallbackCheck).to.equal(2);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(101);
expect(tlCallbackCheck).to.equal(2);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(2);
});
test('onBegin on looped timeline', () => {
let tlCallbackCheck = 0;
let tlAnim1CallbackCheck = 0;
let tlAnim2CallbackCheck = 0;
const tl = createTimeline({loop: 2, ...setupAnimationCallBack('onBegin', () => { tlCallbackCheck += 1; })})
.add('#target-id', setupAnimationCallBack('onBegin', () => { tlAnim1CallbackCheck += 1; }))
.add('#target-id', setupAnimationCallBack('onBegin', () => { tlAnim2CallbackCheck += 1; }))
.init();
expect(tlCallbackCheck).to.equal(0);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(5);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(10);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(11);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(101);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1)
tl.seek(191);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(160);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(10);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(11);
expect(tlAnim1CallbackCheck).to.equal(3);
expect(tlAnim2CallbackCheck).to.equal(1);
});
test('onBegin and onComplete on delayed timeline', resolve => {
let tlBeginCheck = 0;
let tlCompleteCheck = 0;
let tlAnim1BeginCheck = 0;
let tlAnim1CompleteCheck = 0;
const startTime = new Date().getTime();
const tl = createTimeline({
delay: 1000,
loop: 1,
autoplay: false,
onBegin: () => { tlBeginCheck += 1; },
onComplete: () => {
const endTime = new Date().getTime();
tlCompleteCheck += 1;
// Using a range between 50 and 100 instead of 75 because of time calculation inconsistencies
expect(endTime - startTime).to.be.above(50);
expect(endTime - startTime).to.be.below(100);
expect(tlBeginCheck).to.equal(1);
expect(tlCompleteCheck).to.equal(1);
expect(tlAnim1BeginCheck).to.equal(1);
expect(tlAnim1CompleteCheck).to.equal(1);
resolve();
},
})
.add('#target-id', {
x: 100,
duration: 0,
onBegin: () => { tlAnim1BeginCheck += 1; },
onComplete: () => { tlAnim1CompleteCheck += 1; },
})
.init();
tl.seek(-75);
expect(tlBeginCheck).to.equal(0);
expect(tlCompleteCheck).to.equal(0);
expect(tlAnim1BeginCheck).to.equal(0);
expect(tlAnim1CompleteCheck).to.equal(0);
tl.play();
});
test('onComplete on animation', () => {
let callbackCheck = 0;
const animation = animate('#target-id', setupAnimationCallBack('onComplete', () => { callbackCheck += 1; }));
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(50);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(0);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(100);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(true);
animation.seek(50);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(false);
animation.seek(100);
expect(callbackCheck).to.equal(2);
expect(animation.completed).to.equal(true);
});
test('onComplete on looped animation', () => {
let callbackCheck = 0;
const animation = animate('#target-id', { loop: 2, ...setupAnimationCallBack('onComplete', () => { callbackCheck += 1; }) });
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(10);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(80);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(240);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(true);
animation.seek(0);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(false);
animation.seek(80);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(false);
animation.seek(240);
expect(callbackCheck).to.equal(2);
expect(animation.completed).to.equal(true);
});
test('onComplete on looped alternate animation', () => {
let callbackCheck = 0;
const animation = animate('#target-id', { loop: 1, alternate: true, ...setupAnimationCallBack('onComplete', () => { callbackCheck += 1; }) });
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(10);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(80);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(140);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(160);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(true);
});
test('onComplete on reversed animation', () => {
let callbackCheck = 0;
const animation = animate('#target-id', { reversed: true, ...setupAnimationCallBack('onComplete', () => { callbackCheck += 1; }) });
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(10);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(80);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(true);
});
test('onComplete after caling animation.reverse()', () => {
let callbackCheck = 0;
const animation = animate('#target-id', { reversed: true, ...setupAnimationCallBack('onComplete', () => { callbackCheck += 1; }) });
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(20);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.reverse();
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(80);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(true);
});
test('onComplete on looped reversed alternate animation', () => {
let callbackCheck = 0;
const animation = animate('#target-id', { loop: 1, alternate: true, reversed: true, ...setupAnimationCallBack('onComplete', () => { callbackCheck += 1; }) });
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(10);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(80);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(140);
expect(callbackCheck).to.equal(0);
expect(animation.completed).to.equal(false);
animation.seek(160);
expect(callbackCheck).to.equal(1);
expect(animation.completed).to.equal(true);
});
test('onComplete on timeline', () => {
let tlCallbackCheck = 0;
let tlAnim1CallbackCheck = 0;
let tlAnim2CallbackCheck = 0;
const tl = createTimeline(setupAnimationCallBack('onComplete', () => { tlCallbackCheck += 1; }))
.add('#target-id', setupAnimationCallBack('onComplete', () => { tlAnim1CallbackCheck += 1; }))
.add('#target-id', setupAnimationCallBack('onComplete', () => { tlAnim2CallbackCheck += 1; }))
.init();
expect(tlCallbackCheck).to.equal(0);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(50);
expect(tlCallbackCheck).to.equal(0);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(150);
expect(tlCallbackCheck).to.equal(0);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(200);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(0);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(150);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(200);
expect(tlCallbackCheck).to.equal(2);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(2);
});
test('onComplete on looped timeline', () => {
let tlCallbackCheck = 0;
let tlAnim1CallbackCheck = 0;
let tlAnim2CallbackCheck = 0;
const tl = createTimeline({loop: 2, ...setupAnimationCallBack('onComplete', () => { tlCallbackCheck += 1; })})
.add('#target-id', setupAnimationCallBack('onComplete', () => { tlAnim1CallbackCheck += 1; }))
.add('#target-id', setupAnimationCallBack('onComplete', () => { tlAnim2CallbackCheck += 1; }))
.init();
expect(tlCallbackCheck).to.equal(0);
expect(tlAnim1CallbackCheck).to.equal(0);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(90);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(0);
tl.seek(180);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(200);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(160);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1)
tl.seek(90);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(0);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(90);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(1);
tl.seek(180);
expect(tlAnim1CallbackCheck).to.equal(2);
expect(tlAnim2CallbackCheck).to.equal(2);
tl.seek(540);
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(4);
expect(tlAnim2CallbackCheck).to.equal(4);
});
test('onBegin and onComplete on looped timeline', () => {
let tlOnBeginCheck = 0;
let tlOnCompleteCheck = 0;
let childOnBeginCheck = 0;
let childOnCompleteCheck = 0;
const tl = createTimeline({
loop: 2,
onBegin: () => { tlOnBeginCheck += 1; },
onComplete: () => { tlOnCompleteCheck += 1; },
loopDelay: 10
})
.add({
delay: 10,
duration: 80,
onBegin: () => { childOnBeginCheck += 1; },
onComplete: () => { childOnCompleteCheck += 1; }
});
expect(tlOnBeginCheck).to.equal(0);
expect(tlOnCompleteCheck).to.equal(0);
expect(childOnBeginCheck).to.equal(0);
expect(childOnCompleteCheck).to.equal(0);
tl.seek(5);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(childOnBeginCheck).to.equal(0);
expect(childOnCompleteCheck).to.equal(0);
tl.seek(11); // Delay 10
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(childOnBeginCheck).to.equal(1);
expect(childOnCompleteCheck).to.equal(0);
tl.seek(100);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(childOnBeginCheck).to.equal(1);
expect(childOnCompleteCheck).to.equal(1);
tl.seek(200);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(childOnBeginCheck).to.equal(2);
expect(childOnCompleteCheck).to.equal(2);
tl.seek(300);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(1);
expect(childOnBeginCheck).to.equal(3);
expect(childOnCompleteCheck).to.equal(3);
});
test('onBegin and onComplete on alternate timeline', () => {
let tlOnBeginCheck = 0;
let tlOnCompleteCheck = 0;
let child1OnBeginCheck = 0;
let child1OnCompleteCheck = 0;
let child2OnBeginCheck = 0;
let child2OnCompleteCheck = 0;
const tl = createTimeline({
loop: 2,
alternate: true,
onBegin: () => { tlOnBeginCheck += 1; },
onComplete: () => { tlOnCompleteCheck += 1; },
})
.add({
duration: 100,
onBegin: () => { child1OnBeginCheck += 1; },
onComplete: () => { child1OnCompleteCheck += 1; }
})
.add({
duration: 100,
onBegin: () => { child2OnBeginCheck += 1; },
onComplete: () => { child2OnCompleteCheck += 1; }
})
expect(tlOnBeginCheck).to.equal(0);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(5);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(10);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(100);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(110);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(1);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(200);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(1);
console.warn('Edge case where the onComplete won\'t fire before an alternate loop');
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(210); // Loop once and alternate to reversed playback, so no callback triggers should happen
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(1);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(400); // Loop twice and alternate back to forward playback
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(1);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(410);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(2);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(1);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(600);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(1);
expect(child1OnBeginCheck).to.equal(2);
expect(child1OnCompleteCheck).to.equal(2);
expect(child2OnBeginCheck).to.equal(2);
expect(child2OnCompleteCheck).to.equal(1);
});
test('onComplete on reversed timeline should complete and ignore children', () => {
let tlOnBeginCheck = 0;
let tlOnCompleteCheck = 0;
let child1OnBeginCheck = 0;
let child1OnCompleteCheck = 0;
let child2OnBeginCheck = 0;
let child2OnCompleteCheck = 0;
const tl = createTimeline({
reversed: true,
defaults: {
ease: 'linear',
duration: 100
},
onBegin: () => { tlOnBeginCheck += 1; },
onComplete: () => { tlOnCompleteCheck += 1; },
})
.add('.target-class:nth-child(1)', {
y: 100,
onBegin: () => { child1OnBeginCheck += 1; },
onComplete: () => { child1OnCompleteCheck += 1; }
})
.add('.target-class:nth-child(2)', {
y: 100,
onBegin: () => { child2OnBeginCheck += 1; },
onComplete: () => { child2OnCompleteCheck += 1; }
})
// .init();
expect(tlOnBeginCheck).to.equal(0);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(5);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(10);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(100);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(110);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(200);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(1);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
});
test('onComplete on timeline after caling reverse()', () => {
let tlOnBeginCheck = 0;
let tlOnCompleteCheck = 0;
let child1OnBeginCheck = 0;
let child1OnCompleteCheck = 0;
let child2OnBeginCheck = 0;
let child2OnCompleteCheck = 0;
const tl = createTimeline({
defaults: {
ease: 'linear',
duration: 100
},
// autoplay: false,
onBegin: () => { tlOnBeginCheck += 1; },
onComplete: () => { tlOnCompleteCheck += 1; },
})
.add('.target-class:nth-child(1)', {
y: 100,
onBegin: () => { child1OnBeginCheck += 1; },
onComplete: () => { child1OnCompleteCheck += 1; }
})
.add('.target-class:nth-child(2)', {
y: 100,
onBegin: () => { child2OnBeginCheck += 1; },
onComplete: () => { child2OnCompleteCheck += 1; }
})
// .init();
expect(tlOnBeginCheck).to.equal(0);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(5);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(10);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(100);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(110);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(1);
expect(child2OnCompleteCheck).to.equal(0);
tl.reverse();
tl.seek(200);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(1);
expect(child1OnBeginCheck).to.equal(1);
expect(child1OnCompleteCheck).to.equal(1);
expect(child2OnBeginCheck).to.equal(1);
expect(child2OnCompleteCheck).to.equal(0);
});
test('onBegin and onComplete on alternate timeline with reversed children', () => {
let tlOnBeginCheck = 0;
let tlOnCompleteCheck = 0;
let child1OnBeginCheck = 0;
let child1OnCompleteCheck = 0;
let child2OnBeginCheck = 0;
let child2OnCompleteCheck = 0;
const tl = createTimeline({
loop: 2,
alternate: true,
defaults: {
ease: 'linear',
reversed: true,
duration: 100
},
// autoplay: false,
onBegin: () => { tlOnBeginCheck += 1; },
onComplete: () => { tlOnCompleteCheck += 1; },
})
.add('.target-class:nth-child(1)', {
y: 100,
onBegin: () => { child1OnBeginCheck += 1; },
onComplete: () => { child1OnCompleteCheck += 1; }
})
.add('.target-class:nth-child(2)', {
y: 100,
onBegin: () => { child2OnBeginCheck += 1; },
onComplete: () => { child2OnCompleteCheck += 1; }
})
// .init();
expect(tlOnBeginCheck).to.equal(0);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(5);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(10);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(100);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(110);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(210); // Loop once and alternate to reversed playback, so no callback triggers should happen
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(380);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(0);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
tl.seek(600);
expect(tlOnBeginCheck).to.equal(1);
expect(tlOnCompleteCheck).to.equal(1);
expect(child1OnBeginCheck).to.equal(0);
expect(child1OnCompleteCheck).to.equal(0);
expect(child2OnBeginCheck).to.equal(0);
expect(child2OnCompleteCheck).to.equal(0);
});
test('onComplete on timeline with animations of the same duration as the timeline', resolve => {
let tlCallbackCheck = 0;
let tlAnim1CallbackCheck = 0;
let tlAnim2CallbackCheck = 0;
let tlAnim3CallbackCheck = 0;
let tlAnim4CallbackCheck = 0;
const target = { value: 1 };
const tl = createTimeline({
onComplete: () => { tlCallbackCheck += 1 },
})
.add(target, {
value: 0,
duration: 1.8,
onComplete: () => { tlAnim1CallbackCheck += 1; },
}, 0)
.add(target,{
value: 1,
duration: 1.4,
onComplete: () => { tlAnim2CallbackCheck += 1; },
}, .4)
.add(target, {
value: 2,
duration: 1,
onComplete: () => { tlAnim3CallbackCheck += 1; },
}, .8)
.add(target, {
value: 3,
duration: 1,
onComplete: () => { tlAnim4CallbackCheck += 1; },
}, .8);
tl.then(() => {
expect(tlCallbackCheck).to.equal(1);
expect(tlAnim1CallbackCheck).to.equal(1);
expect(tlAnim2CallbackCheck).to.equal(1);
expect(tlAnim3CallbackCheck).to.equal(1);
expect(tlAnim4CallbackCheck).to.equal(1);
expect(tl.completed).to.equal(true);
resolve();
});
});
test('onBeforeUpdate on animation', () => {
let callbackCheck = false;
let ticks = 0;
const animation = animate('#target-id', setupAnimationCallBack('onBeforeUpdate', () => { ticks++; callbackCheck = true; }));
expect(callbackCheck).to.equal(false);
animation.seek(5);
expect(ticks).to.equal(1);
expect(callbackCheck).to.equal(true);
animation.seek(9); // delay: 10
expect(ticks).to.equal(2);
expect(callbackCheck).to.equal(true);
animation.seek(10); // delay: 10
expect(callbackCheck).to.equal(true);
expect(ticks).to.equal(3);
animation.seek(15);
expect(ticks).to.equal(4);
});
test('onBeforeUpdate on timeline', () => {
let tlCallbackCheck = false;
let tlAnim1CallbackCheck = false;
let tlAnim2CallbackCheck = false;
let ticks = 0;
const tl = createTimeline(setupAnimationCallBack('onBeforeUpdate', () => { ticks++; tlCallbackCheck = true; }))
.add('#target-id', setupAnimationCallBack('onBeforeUpdate', () => { ticks++; tlAnim1CallbackCheck = true; }))
.add('#target-id', setupAnimationCallBack('onBeforeUpdate', () => { ticks++; tlAnim2CallbackCheck = true; }))
.init();
expect(tlCallbackCheck).to.equal(false);
expect(tlAnim1CallbackCheck).to.equal(false);
expect(tlAnim2CallbackCheck).to.equal(false);
tl.seek(5);
expect(ticks).to.equal(1);
expect(tlCallbackCheck).to.equal(true);
expect(tlAnim1CallbackCheck).to.equal(false);
expect(tlAnim2CallbackCheck).to.equal(false);
tl.seek(9); // delay: 10
expect(ticks).to.equal(2);
expect(tlCallbackCheck).to.equal(true);
expect(tlAnim1CallbackCheck).to.equal(false);
expect(tlAnim2CallbackCheck).to.equal(false);
tl.seek(10); // delay: 10
expect(ticks).to.equal(3);
expect(tlCallbackCheck).to.equal(true);
expect(tlAnim1CallbackCheck).to.equal(false);
expect(tlAnim2CallbackCheck).to.equal(false);
tl.seek(11); // delay: 10
expect(ticks).to.equal(5);
expect(tlCallbackCheck).to.equal(true);
expect(tlAnim1CallbackCheck).to.equal(true);
expect(tlAnim2CallbackCheck).to.equal(false);
tl.seek(150);
expect(ticks).to.equal(8);
expect(tlCallbackCheck).to.equal(true);
expect(tlAnim1CallbackCheck).to.equal(true);
expect(tlAnim2CallbackCheck).to.equal(true);
tl.seek(250);
expect(ticks).to.equal(10);
expect(tlCallbackCheck).to.equal(true);
expect(tlAnim1CallbackCheck).to.equal(true);
expect(tlAnim2CallbackCheck).to.equal(true);
});
test('onUpdate on animation', () => {
let callbackCheck = false;
let ticks = 0;
const animation = animate('#target-id', setupAnimationCallBack('onUpdate', () => { ticks++; callbackCheck = true; }));
expect(callbackCheck).to.equal(false);
animation.seek(5);
expect(ticks).to.equal(1);
expect(callbackCheck).to.equal(true);
animation.seek(9); // delay: 10
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | true |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/types.test.js | tests/suites/types.test.js | import { animate, createTimer, createTimeline, utils } from '../../dist/modules/index.js';
animate('.anime-css', {
keyframes: {
'0%' : {
a: 100,
b: 'string',
c0: (el) => el.dataset.index,
c1: (el, i) => el.dataset.index + i,
c2: (el, i, t) => t - (el.dataset.index + i),
},
'20%' : { x: '0rem', y: '-2.5rem', rotate: 45, ease: 'out' },
'40%' : { x: '17rem', y: '-2.5rem' },
'50%' : { x: '17rem', y: '2.5rem', rotate: 90 },
'75%' : { x: '0rem', y: '2.5rem' },
'100%': { x: '0rem', y: '0rem', rotate: 180 }
},
duration: 4000,
ease: 'linear',
loop: true,
});
animate('.anime-css', {
keyframes: [
{x: 100, duration: 1000},
{y: 100, duration: 1000},
],
duration: 4000,
ease: 'linear',
loop: true,
});
const animation = animate('#target-id', {
a: 100,
b: 'string',
c0: (el) => el.dataset.index, // el should be of type target
c1: (el, i) => el.dataset.index + i,
c2: (el, i, t) => { t - (el.dataset.index + i) }, // Should throw because not returing a valid value
d: {
to: 100,
duration: 10,
},
e: {
from: (el, i, t) => t - (el.dataset.index + i),
delay: 10,
},
f: [0, 100],
g: [0, [0, 100], 0, '10px', () => utils.random(100, 200, 3), 0],
scale: [
{ to: [0, 1], duration: 200, ease: 'outBack' },
{ to: 1, duration: 100, delay: 500, ease: 'inQuart' },
],
delay: (_, i, t) => i * t,
duration: (_, i, t) => i * t,
modifier: v => v * 100,
loopDelay: 100,
loop: true,
alternate: true,
autoplay: false,
ease: 'inOut',
frameRate: 30,
playbackRate: 1.5,
playbackEase: 'cubicBezier(0.1, 0.2, 0.3, 0.4)',
composition: 'none',
onBegin: self => console.log(self.currentTime),
onUpdate: self => console.log(self.currentTime),
onRender: self => console.log(self.currentTime),
onLoop: self => console.log(self.currentTime),
onComplete: self => console.log(self.currentTime),
})
const timer = createTimer({
delay: () => 100,
duration: () => 100,
loopDelay: 100,
loop: true,
alternate: true,
autoplay: false,
frameRate: 30,
playbackRate: 1.5,
onBegin: self => console.log(self.currentTime),
onUpdate: self => console.log(self.currentTime),
onLoop: self => console.log(self.currentTime),
onComplete: self => console.log(self.currentTime),
})
const tl = createTimeline({
defaults: {
duration: 100
}
})
.add('label', 10000)
.add('#target-id', {
a: 100,
b: 'string',
c: (el, i, t) => { t - (el.dataset.index + i) }, // Should throw
d: {
to: 100,
duration: 10,
},
e: {
from: (el, i, t) => t - (el.dataset.index + i),
delay: 10,
},
f: [0, 100],
g: (el) => el.dataset.index, // el should be of type target
delay: (_, i, t) => i * t,
duration: (_, i, t) => i * t,
modifier: v => v * 100,
loopDelay: 100,
loop: true,
alternate: true,
autoplay: false,
ease: 'inOut',
frameRate: 30,
playbackRate: 1.5,
composition: 'none',
onBegin: self => console.log(self.currentTime),
onUpdate: self => console.log(self.currentTime),
onRender: self => console.log(self.currentTime),
onLoop: self => console.log(self.currentTime),
onComplete: self => console.log(self.currentTime),
}, 'label')
.add({
delay: () => 100,
duration: () => 100,
loopDelay: 100,
loop: true,
alternate: true,
autoplay: false,
frameRate: 30,
playbackRate: 1.5,
onBegin: self => console.log(self.currentTime),
onUpdate: self => console.log(self.currentTime),
onLoop: self => console.log(self.currentTime),
onComplete: self => console.log(self.currentTime),
}, 10000)
.add(self => {
console.log(self.currentTime)
}, 10000)
/** @param {String} v */
animation.onComplete = (v) => v;
/** @param {Animation} v */
timer.onComplete = (v) => v;
/** @param {Timeline} v */
tl.onComplete = (v) => v;
/** @param {Timeline} v */
tl.onComplete = (v) => v;
/** @param {Timer} v */
timer.onComplete = (v) => v;
animation.then
timer.then
tl.then
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/animatables.test.js | tests/suites/animatables.test.js | import {
expect,
} from '../utils.js';
import {
createAnimatable,
createTimer,
utils,
} from '../../dist/modules/index.js';
suite('Animatables', () => {
test('Get and animate animatable values', resolve => {
const animatable = createAnimatable('#target-id', {
x: 20,
y: 30,
rotate: 40,
});
expect(animatable.x()).to.equal(0);
expect(animatable.y()).to.equal(0);
expect(animatable.rotate()).to.equal(0);
const x = animatable.x(100);
const y = animatable.y(150);
const rotate = animatable.rotate(45);
expect(animatable.animations.x.duration).to.equal(20);
expect(animatable.animations.y.duration).to.equal(30);
expect(animatable.animations.rotate.duration).to.equal(40);
createTimer({
duration: 50,
onComplete: () => {
expect(animatable.x()).to.equal(100);
expect(animatable.y()).to.equal(150);
expect(animatable.rotate()).to.equal(45);
resolve();
}
});
});
test('Get and animate animatable complex values', resolve => {
const animatable = createAnimatable('#target-id', {
backgroundColor: 20,
});
expect(animatable.backgroundColor()).deep.equal([0, 214, 114, 1]);
const bg = animatable.backgroundColor([100, 200, 0, 1]);
expect(animatable.animations.backgroundColor.duration).to.equal(20);
createTimer({
duration: 50,
onComplete: () => {
expect(animatable.backgroundColor()).deep.equal([100, 200, 0, 1]);
resolve();
}
});
});
test('Get and set animatable values', () => {
const animatable = createAnimatable('#target-id', {
x: 0,
y: 0,
rotate: 0,
});
expect(animatable.x()).to.equal(0);
expect(animatable.y()).to.equal(0);
expect(animatable.rotate()).to.equal(0);
animatable.x(100);
animatable.y(150);
animatable.rotate(45);
expect(animatable.x()).to.equal(100);
expect(animatable.y()).to.equal(150);
expect(animatable.rotate()).to.equal(45);
});
test('Defines custom units for animatable values', resolve => {
const animatable = createAnimatable('#target-id', {
x: { unit: 'em' },
y: { unit: 'rem' },
rotate: { unit: 'rad', duration: 50 },
duration: 40
});
expect(animatable.x()).to.equal(0);
expect(animatable.y()).to.equal(0);
expect(animatable.rotate()).to.equal(0);
animatable.x(10);
animatable.y(15);
animatable.rotate(1);
createTimer({
duration: 50,
onComplete: () => {
expect(animatable.x()).to.equal(10);
expect(animatable.y()).to.equal(15);
expect(animatable.rotate()).to.equal(1);
expect(utils.get('#target-id', 'x')).to.equal('10em');
expect(utils.get('#target-id', 'y')).to.equal('15rem');
expect(utils.get('#target-id', 'rotate')).to.equal('1rad');
resolve();
}
});
});
test('Animatable onBegin callbacks', resolve => {
let began = 0;
const animatable = createAnimatable('#target-id', {
x: 10,
y: 10,
rotate: 5,
onBegin: () => {
began++;
},
});
animatable.x(100).y(100).rotate(100);
createTimer({
duration: 20,
onComplete: () => {
animatable.x(-100).y(-100).rotate(-100);
createTimer({
duration: 20,
onComplete: () => {
expect(began).to.equal(2);
animatable.revert();
resolve();
}
});
}
});
});
test('Animatable onComplete callbacks', resolve => {
let completes = 0;
const animatable = createAnimatable('#target-id', {
x: 40,
y: 40,
rotate: 5,
onComplete: () => {
completes++;
},
});
animatable.x(100).y(100).rotate(100);
createTimer({
duration: 20,
onComplete: () => {
animatable.x(-100).y(-100).rotate(-100);
createTimer({
duration: 60,
onComplete: () => {
animatable.x(-50).y(-50).rotate(-50);
createTimer({
duration: 60,
onComplete: () => {
expect(completes).to.equal(2);
animatable.revert();
resolve();
}
});
}
});
}
});
});
test('Animatable onUpdate callbacks', resolve => {
let updates = 0;
const animatable = createAnimatable('#target-id', {
x: 20,
y: 20,
rotate: 5,
onUpdate: () => {
updates++;
},
});
animatable.x(100).y(100).rotate(100);
createTimer({
duration: 20,
onComplete: () => {
animatable.x(-100).y(-100).rotate(-100);
}
});
createTimer({
duration: 40,
onComplete: () => {
expect(updates).to.be.above(1);
expect(updates).to.be.below(6);
animatable.revert();
resolve();
}
});
});
test('Revert an animatable', () => {
const animatable = createAnimatable('#target-id', {
x: { unit: 'em' },
y: { unit: 'rem' },
rotate: { unit: 'rad', duration: 50 },
duration: 40
});
expect(animatable.targets.length).to.equal(1);
animatable.revert();
expect(animatable.targets.length).to.equal(0);
expect(animatable.animations.x).to.equal(undefined);
expect(animatable.animations.y).to.equal(undefined);
expect(animatable.animations.rotate).to.equal(undefined);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/controls.test.js | tests/suites/controls.test.js | import {
expect,
getChildAtIndex,
forEachChildren,
} from '../utils.js';
import {
animate,
createTimeline,
createTimer,
utils,
} from '../../dist/modules/index.js';
import {
minValue,
} from '../../dist/modules/core/consts.js';
suite('Controls', () => {
test('Alternate the direction of an animation', resolve => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
let hasReversed = false;
animate($target, {
translateX: 100,
duration: 100,
delay: 50,
onUpdate: self => {
if (self.currentTime >= 100 * .75 && !hasReversed) {
hasReversed = true;
const timeStamp = self.currentTime;
self.alternate();
setTimeout(() => {
expect(self.currentTime).to.be.below(timeStamp);
resolve();
}, 33);
}
},
});
});
test('Alternate the direction of a reversed animation', resolve => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
let hasReversed = false;
animate($target, {
translateX: 100,
duration: 100,
delay: 50,
reversed: true,
onUpdate: self => {
if (!hasReversed) {
hasReversed = true;
const timeStamp = self.currentTime;
self.alternate();
setTimeout(() => {
expect(self.currentTime).to.be.above(timeStamp);
resolve();
}, 33);
}
},
});
});
test('Alternate the direction of a looped animation', resolve => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
let hasReversed = false;
animate($target, {
translateX: 100,
duration: 100,
delay: 50,
loop: 3,
onUpdate: self => {
if (self.currentTime >= (100 * 2.5) && !hasReversed) {
hasReversed = true;
const timeStamp = self.currentTime;
self.alternate();
setTimeout(() => {
expect(self.currentTime).to.be.below(timeStamp);
expect(self.currentIteration).to.equal(1);
resolve();
}, 33);
}
},
});
});
test('Alternate the direction of a looped alternate animation', resolve => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
let hasReversed = false;
animate($target, {
translateX: 100,
duration: 100,
delay: 50,
loop: 3,
alternate: true,
onUpdate: self => {
if (self.currentTime >= (100 * 2.5) && !hasReversed) {
hasReversed = true;
const timeStamp = self.currentTime;
self.alternate();
setTimeout(() => {
expect(self.currentTime).to.be.below(timeStamp);
expect(self.currentIteration).to.equal(1);
resolve();
}, 33);
}
},
});
});
test('Alternate the direction of a looped alternate reversed animation with odd iteration count', resolve => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
let hasReversed = false;
animate($target, {
translateX: 100,
duration: 100,
delay: 50,
loop: 3,
alternate: true,
reversed: true,
onUpdate: self => {
if (self.currentTime >= (100 * 2.5) && !hasReversed) {
hasReversed = true;
const timeStamp = self.currentTime;
self.alternate();
setTimeout(() => {
expect(self.currentTime).to.be.below(timeStamp);
expect(self.currentIteration).to.equal(1);
resolve();
}, 33);
}
},
});
});
test('Alternate the direction of a looped alternate reversed animation with even iteration count', resolve => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
let hasReversed = false;
animate($target, {
translateX: 100,
duration: 100,
delay: 100,
loop: 2,
alternate: true,
reversed: true,
onUpdate: self => {
if (self.currentTime >= (100 * 1.5) && !hasReversed) {
hasReversed = true;
const timeStamp = self.currentTime;
self.alternate();
setTimeout(() => {
expect(self.currentTime).to.be.above(timeStamp);
expect(self.currentIteration).to.equal(1);
resolve();
}, 40);
}
},
});
});
test('Complete a timer', () => {
const timer1 = createTimer({ duration: 1000 });
timer1.complete();
expect(timer1._cancelled).to.equal(1);
expect(timer1.paused).to.equal(true);
expect(timer1.currentTime).to.equal(1000);
});
test('Complete an animation', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
$target.style.height = '100px';
const animation1 = animate($target, {
width: 32,
height: 200,
ease: 'linear',
});
animation1.complete();
expect(animation1._cancelled).to.equal(1);
expect(animation1.paused).to.equal(true);
expect(animation1.currentTime).to.equal(1000);
expect($target.getAttribute('style')).to.equal('height: 200px; width: 32px;');
});
test('Complete a timeline', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
$target.style.height = '100px';
$target.style.transform = 'translateY(100px)';
const tl = createTimeline({defaults: {ease: 'linear'}})
.add($target, {
width: 32,
height: 200,
})
.add($target, {
width: 64,
height: 400,
translateX: 200,
translateY: 200,
});
tl.complete();
expect(tl._cancelled).to.equal(1);
expect(getChildAtIndex(tl, 0)._cancelled).to.equal(1);
expect(getChildAtIndex(tl, 1)._cancelled).to.equal(1);
expect(tl.paused).to.equal(true);
expect(getChildAtIndex(tl, 0).paused).to.equal(true);
expect(getChildAtIndex(tl, 1).paused).to.equal(true);
expect(tl.currentTime).to.equal(tl.duration);
expect(getChildAtIndex(tl, 0).currentTime).to.equal(getChildAtIndex(tl, 0).duration);
expect(getChildAtIndex(tl, 1).currentTime).to.equal(getChildAtIndex(tl, 1).duration);
expect($target.getAttribute('style')).to.equal('height: 400px; transform: translateY(200px) translateX(200px); width: 64px;');
});
test('Cancel a timer', () => {
const timer1 = createTimer({ duration: 1000 });
timer1.seek(500).cancel();
expect(timer1._cancelled).to.equal(1);
expect(timer1.paused).to.equal(true);
});
test('Cancel an animation', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
$target.style.height = '100px';
const animation1 = animate($target, {
width: 32,
height: 200,
ease: 'linear',
});
animation1.seek(500).cancel();
expect(animation1._cancelled).to.equal(1);
expect(animation1.paused).to.equal(true);
expect($target.getAttribute('style')).to.equal('height: 150px; width: 24px;');
});
test('Cancel a timeline', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
$target.style.height = '100px';
$target.style.transform = 'translateY(100px)';
const tl = createTimeline({defaults: {ease: 'linear'}})
.add($target, {
width: 32,
height: 200,
})
.add($target, {
width: 64,
height: 400,
translateX: 200,
translateY: 200,
});
tl.seek(1000);
tl.cancel();
expect(tl._cancelled).to.equal(1);
expect(getChildAtIndex(tl, 0)._cancelled).to.equal(1);
expect(getChildAtIndex(tl, 1)._cancelled).to.equal(1);
expect(tl.paused).to.equal(true);
expect(getChildAtIndex(tl, 0).paused).to.equal(true);
expect(getChildAtIndex(tl, 1).paused).to.equal(true);
expect($target.getAttribute('style')).to.equal('height: 200px; transform: translateY(100px) translateX(0px); width: 32px;');
});
test('Revert a timeline', () => {
const timer1 = createTimer({ duration: 1000 });
timer1.seek(500);
timer1.revert();
expect(timer1._cancelled).to.equal(1);
expect(timer1.paused).to.equal(true);
});
test('Revert an animation with CSS properties', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const animation1 = animate($target, {
width: 200,
height: 200,
});
animation1.seek(500);
animation1.revert();
expect(animation1._cancelled).to.equal(1);
expect(animation1.paused).to.equal(true);
expect($target.getAttribute('style')).to.equal(null);
});
test('Revert an animation with Transforms properties', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const animation1 = animate($target, {
translateX: 200,
translateY: 200,
});
animation1.seek(500);
animation1.revert();
expect(animation1._cancelled).to.equal(1);
expect(animation1.paused).to.equal(true);
expect($target.getAttribute('style')).to.equal(null);
});
test('Revert an animation with CSS properties with existing inline styles and clean newly added inline styles', () => {
const targets = document.querySelectorAll('.target-class');
const cssText = [];
targets.forEach(($target, i) => {
const targetStyle = /** @type {HTMLElement} */($target).style;
targetStyle.borderRadius = `${i * 10}%`;
cssText[i] = targetStyle.cssText;
});
const animation1 = animate(targets, {
borderRadius: '50%',
width: 200,
height: 200,
});
animation1.seek(500);
animation1.revert();
expect(animation1._cancelled).to.equal(1);
expect(animation1.paused).to.equal(true);
targets.forEach(($target, i) => {
const targetStyle = /** @type {HTMLElement} */($target).style;
expect(targetStyle.cssText).to.equal(cssText[i]);
});
});
test('Revert an animation with transform properties with existing inline styles and clean newly added inline styles', () => {
const targets = document.querySelectorAll('.target-class');
const cssText = [];
targets.forEach(($target, i) => {
const targetStyle = /** @type {HTMLElement} */($target).style;
targetStyle.borderRadius = `${i * 10}%`;
cssText[i] = targetStyle.cssText;
});
const animation1 = animate(targets, {
translateX: 200,
translateY: 200,
});
animation1.seek(500);
animation1.revert();
expect(animation1._cancelled).to.equal(1);
expect(animation1.paused).to.equal(true);
targets.forEach(($target, i) => {
const targetStyle = /** @type {HTMLElement} */($target).style;
expect(targetStyle.cssText).to.equal(cssText[i]);
});
});
test('Revert a timeline and and clean inline styles', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const tl = createTimeline({defaults: {ease: 'linear'}})
.add($target, {
width: 32,
height: 200,
})
.add($target, {
width: 64,
height: 400,
translateX: 200,
translateY: 200,
});
tl.seek(1500);
tl.revert();
expect(tl._cancelled).to.equal(1);
expect(getChildAtIndex(tl, 0)._cancelled).to.equal(1);
expect(getChildAtIndex(tl, 1)._cancelled).to.equal(1);
expect(tl.paused).to.equal(true);
expect(getChildAtIndex(tl, 0).paused).to.equal(true);
expect(getChildAtIndex(tl, 1).paused).to.equal(true);
expect($target.getAttribute('style')).to.equal(null);
});
test('Revert a timeline with existing inline styles and clean newly added inline styles', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
$target.style.height = '100px';
$target.style.transform = 'translateY(100px)';
const tl = createTimeline({defaults: {ease: 'linear'}})
.add($target, {
width: 32,
height: 200,
})
.add($target, {
width: 64,
height: 400,
translateX: 200,
translateY: 200,
});
tl.seek(1500);
tl.revert();
expect(tl._cancelled).to.equal(1);
expect(getChildAtIndex(tl, 0)._cancelled).to.equal(1);
expect(getChildAtIndex(tl, 1)._cancelled).to.equal(1);
expect(tl.paused).to.equal(true);
expect(getChildAtIndex(tl, 0).paused).to.equal(true);
expect(getChildAtIndex(tl, 1).paused).to.equal(true);
expect($target.getAttribute('style')).to.equal('transform: translateY(100px); height: 100px;');
});
test('Reset a playing animation', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const animation1 = animate($target, {
translateX: 200,
translateY: 200,
autoplay: false,
duration: 1000,
loop: 1
});
expect(animation1.currentTime).to.equal(0);
// expect(animation1.progress).to.equal(0);
expect(animation1.paused).to.equal(true);
expect(animation1.began).to.equal(false);
expect(animation1.completed).to.equal(false);
expect(animation1.currentIteration).to.equal(0);
animation1.seek(1500);
animation1.resume();
expect(animation1.currentTime).to.equal(1500);
// expect(animation1.progress).to.equal(.75);
expect(animation1.paused).to.equal(false);
expect(animation1.began).to.equal(true);
expect(animation1.completed).to.equal(false);
expect(animation1.currentIteration).to.equal(1);
animation1.pause();
animation1.seek(2000);
expect(animation1.currentTime).to.equal(2000);
// expect(animation1.progress).to.equal(1);
expect(animation1.paused).to.equal(true);
expect(animation1.began).to.equal(true);
expect(animation1.completed).to.equal(true);
expect(animation1.currentIteration).to.equal(1);
animation1.seek(500);
animation1.resume();
animation1.reset();
expect(animation1.currentTime).to.equal(0);
// expect(animation1.progress).to.equal(0);
expect(animation1.paused).to.equal(true);
expect(animation1.began).to.equal(false);
expect(animation1.completed).to.equal(false);
expect(animation1.currentIteration).to.equal(0);
animation1.pause();
});
test('Reset a playing timeline', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const tl = createTimeline({
autoplay: false,
duration: 1000,
loop: 1
})
.add($target, {
width: 32,
height: 200,
})
.add($target, {
width: 64,
height: 400,
translateX: 200,
translateY: 200,
});
expect(tl.currentTime).to.equal(0);
expect(tl.progress).to.equal(0);
expect(tl.paused).to.equal(true);
expect(tl.began).to.equal(false);
expect(tl.completed).to.equal(false);
expect(tl.currentIteration).to.equal(0);
forEachChildren(tl, child => {
expect(child.currentTime).to.equal(0);
expect(child.progress).to.equal(0);
expect(child.paused).to.equal(true);
expect(child.began).to.equal(false);
expect(child.completed).to.equal(false);
expect(child.currentIteration).to.equal(0);
});
tl.seek(3000);
tl.resume();
expect(tl.currentTime).to.equal(3000);
expect(tl.progress).to.equal(.75);
expect(tl.paused).to.equal(false);
expect(tl.began).to.equal(true);
expect(tl.completed).to.equal(false);
expect(tl.currentIteration).to.equal(1);
tl.pause();
tl.seek(4000);
expect(tl.currentTime).to.equal(4000);
expect(tl.progress).to.equal(1);
expect(tl.paused).to.equal(true);
expect(tl.began).to.equal(true);
expect(tl.completed).to.equal(true);
expect(tl.currentIteration).to.equal(1);
forEachChildren(tl, child => {
expect(child.paused).to.equal(true);
expect(child.began).to.equal(true);
expect(child.completed).to.equal(true);
});
tl.seek(500);
tl.resume();
tl.reset();
expect(tl.currentTime).to.equal(0);
expect(tl.progress).to.equal(0);
expect(tl.paused).to.equal(true);
expect(tl.began).to.equal(false);
expect(tl.completed).to.equal(false);
expect(tl.currentIteration).to.equal(0);
forEachChildren(tl, child => {
expect(child.currentTime).to.equal(0);
expect(child.progress).to.equal(0);
expect(child.paused).to.equal(true);
expect(child.began).to.equal(false);
expect(child.completed).to.equal(false);
expect(child.currentIteration).to.equal(0);
});
tl.pause();
});
test('Reseting an animation should set its values back to their initial states', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const ogY = utils.get($target, 'y');
animate($target, {
y: -100,
autoplay: false,
duration: 1000,
loop: 1,
})
.reset();
const newY = utils.get($target, 'y');
expect(newY).to.equal(ogY);
});
test('Reseting a timeline should set its values back to their initial states', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const ogY = utils.get($target, 'y');
const tl = createTimeline({ autoplay: false })
.add($target, { y: -100, duration: 500 }, 1000)
.add($target, { y: 100, duration: 500 }, 2000)
.reset();
const newY = utils.get($target, 'y');
expect(newY).to.equal(ogY);
});
test('Reset a cancelled animation', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const animation1 = animate($target, {
translateX: 200,
translateY: 200,
duration: 1000,
loop: 1
});
expect(animation1._cancelled).to.equal(0);
expect(animation1.currentTime).to.equal(0);
// expect(animation1.progress).to.equal(0);
expect(animation1.paused).to.equal(false);
expect(animation1.began).to.equal(false);
expect(animation1.completed).to.equal(false);
expect(animation1.currentIteration).to.equal(0);
animation1.seek(1500);
animation1.cancel();
expect(animation1._cancelled).to.equal(1);
expect(animation1.currentTime).to.equal(1500);
// expect(animation1.progress).to.equal(.75);
expect(animation1.paused).to.equal(true);
expect(animation1.began).to.equal(true);
expect(animation1.completed).to.equal(false);
expect(animation1.currentIteration).to.equal(1);
animation1.reset();
expect(animation1._cancelled).to.equal(0);
expect(animation1.currentTime).to.equal(0);
// expect(animation1.progress).to.equal(0);
expect(animation1.paused).to.equal(true);
expect(animation1.began).to.equal(false);
expect(animation1.completed).to.equal(false);
expect(animation1.currentIteration).to.equal(0);
animation1.pause();
});
test('Reset a cancelled timeline', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const tl = createTimeline({
duration: 1000,
loop: 1
})
.add($target, {
width: 32,
height: 200,
})
.add($target, {
width: 64,
height: 400,
translateX: 200,
translateY: 200,
});
expect(tl._cancelled).to.equal(0);
expect(tl.currentTime).to.equal(0);
expect(tl.progress).to.equal(0);
expect(tl.paused).to.equal(false);
expect(tl.began).to.equal(false);
expect(tl.completed).to.equal(false);
expect(tl.currentIteration).to.equal(0);
forEachChildren(tl, child => {
expect(child._cancelled).to.equal(0);
expect(child.currentTime).to.equal(0);
expect(child.progress).to.equal(0);
expect(child.paused).to.equal(true);
expect(child.began).to.equal(false);
expect(child.completed).to.equal(false);
});
tl.seek(3000);
tl.cancel();
expect(tl._cancelled).to.equal(1);
expect(tl.currentTime).to.equal(3000);
expect(tl.progress).to.equal(.75);
expect(tl.paused).to.equal(true);
expect(tl.began).to.equal(true);
expect(tl.completed).to.equal(false);
expect(tl.currentIteration).to.equal(1);
forEachChildren(tl, child => {
expect(child._cancelled).to.equal(1);
expect(child.paused).to.equal(true);
});
tl.reset();
expect(tl._cancelled).to.equal(0);
expect(tl.currentTime).to.equal(0);
expect(tl.progress).to.equal(0);
expect(tl.paused).to.equal(true);
expect(tl.began).to.equal(false);
expect(tl.completed).to.equal(false);
expect(tl.currentIteration).to.equal(0);
forEachChildren(tl, child => {
expect(child._cancelled).to.equal(0);
expect(child.currentTime).to.equal(0);
expect(child.progress).to.equal(0);
expect(child.paused).to.equal(true);
expect(child.began).to.equal(false);
expect(child.completed).to.equal(false);
});
tl.pause();
});
test('Refresh an animation', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
$target.setAttribute('data-width', '128px');
const animation1 = animate($target, {
width: $el => $el.dataset.width,
duration: 100,
autoplay: false
});
animation1.seek(100);
expect($target.style.width).to.equal('128px');
$target.setAttribute('data-width', '256px');
animation1.refresh().restart().seek(100);
expect($target.style.width).to.equal('256px');
});
test('Refresh an animation with relative values', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const animation1 = animate($target, {
x: '+=50',
rotate: () => '+=10',
duration: 100,
autoplay: false
});
animation1.seek(100);
expect(utils.get($target, 'x')).to.equal('50px');
expect(utils.get($target, 'rotate')).to.equal('10deg');
animation1.refresh().restart().seek(100);
// Only function based value should refresh
expect(utils.get($target, 'x')).to.equal('50px');
expect(utils.get($target, 'rotate')).to.equal('20deg');
});
test('Refresh a timeline', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
$target.setAttribute('data-width', '128px');
const tl = createTimeline();
tl.add($target, {
width: $el => $el.dataset.width,
duration: 100,
autoplay: false
}).add({
duration: 100
});
tl.seek(200);
expect($target.style.width).to.equal('128px');
$target.setAttribute('data-width', '256px');
tl.refresh().restart().seek(200);
expect($target.style.width).to.equal('256px');
});
test('Stretch a timer', () => {
const timer1 = createTimer({
duration: 1273,
autoplay: false,
});
expect(timer1.duration).to.equal(1273);
for (let i = 0, l = 9999; i < l; i++) {
const newTime = 1 + i;
timer1.stretch(newTime);
expect(timer1.duration).to.equal(newTime);
expect(timer1.iterationDuration).to.equal(newTime);
}
timer1.stretch(0);
expect(timer1.duration).to.equal(minValue);
expect(timer1.iterationDuration).to.equal(minValue);
});
test('Stretch a looped timer', () => {
const timer1 = createTimer({
duration: 1273,
autoplay: false,
loop: 3,
});
expect(timer1.duration).to.equal(1273 * 4);
for (let i = 0, l = 9999; i < l; i++) {
const newTime = 1 + i;
timer1.stretch(newTime);
expect(timer1.duration).to.equal(newTime);
expect(timer1.iterationDuration).to.equal(newTime / timer1.iterationCount);
}
timer1.stretch(0);
expect(timer1.duration).to.equal(minValue);
expect(timer1.iterationDuration).to.equal(minValue);
});
test('Stretch an animation', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const animation1 = animate($target, {
width: [{to: 100, duration: 100}, {to: 100, duration: 200}],
duration: 100,
autoplay: false
});
expect(animation1.duration).to.equal(300);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(100);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(200);
animation1.stretch(600);
expect(animation1.duration).to.equal(600);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(200);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(400);
animation1.stretch(30);
expect(animation1.duration).to.equal(30);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(10);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(20);
animation1.stretch(0);
expect(animation1.duration).to.equal(minValue);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(minValue);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(minValue);
// NOTE: Once an animation duration has been stretched to 0, all tweens are set to 0
animation1.stretch(30);
expect(animation1.duration).to.equal(30);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(30);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(30);
});
test('Stretch an timeline', () => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const tl = createTimeline()
.add($target, {
width: [{to: 100, duration: 100}, {to: 100, duration: 200}],
})
.add($target, {
width: [{to: 100, duration: 100}, {to: 100, duration: 200}],
})
expect(tl.duration).to.equal(600);
expect(getChildAtIndex(tl, 0).duration).to.equal(300);
expect(getChildAtIndex(tl, 1).duration).to.equal(300);
tl.stretch(1200);
expect(tl.duration).to.equal(1200);
expect(getChildAtIndex(tl, 0).duration).to.equal(600);
expect(getChildAtIndex(tl, 1).duration).to.equal(600);
tl.stretch(300);
expect(tl.duration).to.equal(300);
expect(getChildAtIndex(tl, 0).duration).to.equal(150);
expect(getChildAtIndex(tl, 1).duration).to.equal(150);
});
test('Seek an animation', resolve => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const animation1 = animate($target, {
width: 200,
duration: 200,
autoplay: false
});
expect(animation1.currentTime).to.equal(0);
expect(animation1.progress).to.equal(0);
expect(animation1.began).to.equal(false);
expect(animation1.completed).to.equal(false);
animation1.seek(100);
expect(animation1.currentTime).to.equal(100);
expect(animation1.progress).to.equal(.5);
expect(animation1.began).to.equal(true);
expect(animation1.completed).to.equal(false);
animation1.seek(200);
expect(animation1.currentTime).to.equal(200);
expect(animation1.progress).to.equal(1);
expect(animation1.began).to.equal(true);
expect(animation1.completed).to.equal(true);
animation1.seek(150);
expect(animation1.currentTime).to.equal(150);
expect(animation1.progress).to.equal(.75);
expect(animation1.began).to.equal(true);
expect(animation1.completed).to.equal(false);
animation1.resume();
createTimer({
duration: 65,
onComplete: () => {
animation1.pause();
expect(animation1.currentTime).to.equal(200);
expect(animation1.progress).to.equal(1);
expect(animation1.completed).to.equal(true);
resolve();
}
});
});
test('Seek a timeline', resolve => {
const $target = /** @type {HTMLElement} */(document.querySelector('#target-id'));
const tl = createTimeline({ autoplay: false })
.add($target, { width: 200, duration: 100 })
.add($target, { width: 400, duration: 100 });
expect(tl.currentTime).to.equal(0);
expect(tl.progress).to.equal(0);
expect(tl.began).to.equal(false);
expect(tl.completed).to.equal(false);
tl.seek(100);
expect(tl.currentTime).to.equal(100);
expect(tl.progress).to.equal(.5);
expect(tl.began).to.equal(true);
expect(tl.completed).to.equal(false);
tl.seek(200);
expect(tl.currentTime).to.equal(200);
expect(tl.progress).to.equal(1);
expect(tl.began).to.equal(true);
expect(tl.completed).to.equal(true);
tl.seek(150);
expect(tl.currentTime).to.equal(150);
expect(tl.progress).to.equal(.75);
expect(tl.began).to.equal(true);
expect(tl.completed).to.equal(false);
tl.resume();
createTimer({
duration: 65,
onComplete: () => {
tl.pause();
expect(tl.currentTime).to.equal(200);
expect(tl.progress).to.equal(1);
expect(tl.completed).to.equal(true);
resolve();
}
});
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/tweens.test.js | tests/suites/tweens.test.js | import {
removeChild,
expect,
getChildAtIndex,
} from '../utils.js';
import {
utils,
stagger,
animate,
createTimer,
createTimeline,
engine,
} from '../../dist/modules/index.js';
import {
compositionTypes,
valueTypes,
} from '../../dist/modules/core/consts.js';
suite('Tweens', () => {
test('Single tween timings', () => {
const delay = 200;
const duration = 300;
const animation = animate('#target-id', {
translateX: '100%',
delay: delay,
duration: duration,
autoplay: false,
});
const firstTween = getChildAtIndex(animation, 0);
const firstTweenChangeEndTime = firstTween._updateDuration + firstTween._startTime;
expect(firstTween._startTime).to.equal(0);
expect(firstTweenChangeEndTime).to.equal(duration);
expect(animation.duration).to.equal(duration);
});
test('Keyframes tween timings', () => {
const delay1 = 200;
const duration1 = 300;
const delay2 = 300;
const duration2 = 400;
const animation = animate('#target-id', {
translateX: [
{to: '100%', delay: delay1, duration: duration1},
{to: '200%', delay: delay2, duration: duration2}
],
autoplay: false,
});
const firstTween = getChildAtIndex(animation, 0);
const firstTweenChangeEndTime = firstTween._updateDuration + firstTween._startTime;
expect(firstTween._startTime).to.equal(0);
expect(firstTweenChangeEndTime).to.equal(duration1);
const secondTween = getChildAtIndex(animation, 1);
const secondTweenChangeEndTime = secondTween._updateDuration + secondTween._startTime;
expect(secondTween._startTime).to.equal(duration1 + delay2);
expect(secondTweenChangeEndTime).to.equal(duration1 + (delay2 + duration2));
expect(animation.duration).to.equal(duration1 + delay2 + duration2);
});
test('Simple tween ease', () => {
const animation = animate('#target-id', {
translateX: '100%',
ease: 'linear',
autoplay: false,
});
expect(getChildAtIndex(animation, 0)._ease(.5)).to.equal(.5);
});
test('Color tween', () => {
const animation = animate('#target-id', {
translateX: '100%',
backgroundColor: '#000',
autoplay: false,
});
expect(getChildAtIndex(animation, 1)._valueType).to.equal(valueTypes.COLOR);
});
test('Canceled tween should not update after the next sibling has been cancelled', () => {
const [ $target ] = utils.$('#target-id');
const tl = createTimeline({
autoplay: false,
defaults: { ease: 'linear' },
})
.add($target, {
translateX: [0, 100],
duration: 20
})
.add($target, {
translateX: -100,
duration: 5,
onComplete: self => {
removeChild(self, self._tail);
}
}, 10);
tl.seek(5);
expect($target.style.transform).to.equal('translateX(25px)');
tl.seek(10);
expect($target.style.transform).to.equal('translateX(50px)');
tl.seek(15);
expect($target.style.transform).to.equal('translateX(-100px)');
tl.seek(20);
expect($target.style.transform).to.equal('translateX(-100px)');
});
test('Do not remove tween siblings on animation pause', resolve => {
const animation1 = animate('#target-id', {
translateX: [{to: -50}, {to: 200}],
duration: 100,
});
const animation2 = animate('#target-id', {
translateX: [{to: 100}, {to: -100}],
duration: 100,
delay: 50,
});
createTimer({
duration: 50,
onComplete: () => {
animation1.pause();
animation2.pause();
expect(animation1.paused).to.equal(true);
// This one should be null since the first should have been cancel
expect(animation1._head._nextRep).to.be.null;
expect(animation2.paused).to.equal(true);
expect(animation2._head._nextRep).to.not.be.null;
resolve();
}
});
});
test('Remove tween siblings on animation complete', resolve => {
const animation1 = animate('#target-id', { translateX: 200, duration: 50 });
const animation2 = animate('#target-id', { translateX: 200, duration: 50, delay: 10 });
createTimer({
duration: 100,
onComplete: () => {
expect(animation1.paused).to.equal(true);
expect(animation1._cancelled).to.equal(1);
expect(animation1._head._prevRep).to.be.null;
expect(animation2.paused).to.equal(true);
expect(animation2._cancelled).to.equal(1);
expect(animation2._head._nextRep).to.be.null;
resolve();
}
});
});
test('Re-add tween siblings on restart after animation completes', resolve => {
const animation1 = animate('#target-id', { translateX: 200, duration: 50 });
const animation2 = animate('#target-id', { translateX: 200, duration: 50, delay: 10 });
createTimer({
duration: 100,
onComplete: () => {
expect(animation1._cancelled).to.equal(1);
expect(animation2._cancelled).to.equal(1);
animation1.restart();
animation2.restart();
createTimer({
duration: 20,
onComplete: () => {
animation1.pause();
animation2.pause();
expect(animation1.paused).to.equal(true);
expect(animation1._cancelled).to.equal(0);
expect(animation1._head._prevRep).to.not.be.null;
expect(animation2.paused).to.equal(true);
expect(animation2._cancelled).to.equal(0);
expect(animation2._head._nextRep).to.not.be.null;
resolve();
}
});
}
});
});
test('Re-add tween siblings on restart after animation completes in seconds', resolve => {
engine.timeUnit = 's';
const animation1 = animate('#target-id', { translateX: 200, duration: .05 });
const animation2 = animate('#target-id', { translateX: 200, duration: .05, delay: .01 });
createTimer({
duration: .1,
onComplete: () => {
expect(animation1._cancelled).to.equal(1);
expect(animation2._cancelled).to.equal(1);
animation1.restart();
animation2.restart();
createTimer({
duration: .02,
onComplete: () => {
animation1.pause();
animation2.pause();
expect(animation1.paused).to.equal(true);
expect(animation1._cancelled).to.equal(0);
expect(animation1._head._prevRep).to.not.be.null;
expect(animation2.paused).to.equal(true);
expect(animation2._cancelled).to.equal(0);
expect(animation2._head._nextRep).to.not.be.null;
resolve();
engine.timeUnit = 'ms';
}
});
}
});
});
test('Properly override looped tween', resolve => {
const anim1 = animate('#target-id', {
scale: 2,
alternate: true,
loop: true,
duration: 100,
composition: 'replace',
});
const anim2 = animate('#target-id', {
scale: 4,
duration: 40,
composition: 'replace',
onComplete: () => {
expect(anim1.completed).to.equal(false);
expect(anim1._cancelled).to.equal(1);
resolve();
}
});
});
test('Properly override timeline tweens', resolve => {
const tl1 = createTimeline()
.add('#target-id', {
x: 200,
duration: 60,
}, 0)
.add('#target-id', {
y: 200,
duration: 60,
}, 0)
createTimeline({
delay: 10,
})
.add('#target-id', {
x: 100,
duration: 30,
}, 0)
.add('#target-id', {
y: 100,
duration: 30,
}, 0)
.then(() => {
expect(tl1._cancelled).to.equal(1);
resolve();
});
});
test('Do not pause animation with partially overriden tweens', resolve => {
const anim1 = animate('#target-id', {
x: 100,
scale: 2,
alternate: true,
loop: true,
duration: 80,
composition: 'replace',
});
animate('#target-id', {
scale: 4,
duration: 40,
composition: 'replace',
onComplete: () => {
expect(anim1.completed).to.equal(false);
expect(anim1._cancelled).to.equal(0);
anim1.pause();
resolve();
}
});
});
test('Do not pause timeline with partially overriden tweens', resolve => {
const tl1 = createTimeline()
.add('#target-id', {
x: 200,
duration: 60,
}, 0)
.add('#target-id', {
y: 200,
duration: 60,
}, 0)
createTimeline({
delay: 10,
})
.add('#target-id', {
x: 100,
duration: 30,
}, 0)
.then(() => {
expect(tl1._cancelled).to.equal(0);
tl1.pause();
resolve();
});
});
test('Do not override tweens with composition none', resolve => {
const anim1 = animate('#target-id', {
x: 100,
scale: 2,
duration: 80,
composition: 'none',
onComplete: () => {
expect(utils.get('#target-id', 'x', false)).to.equal(100);
expect(utils.get('#target-id', 'scale', false)).to.equal(2);
resolve();
}
});
animate('#target-id', {
scale: 4,
duration: 40,
composition: 'none',
onComplete: () => {
expect(anim1.completed).to.equal(false);
expect(anim1._cancelled).to.equal(0);
expect(utils.get('#target-id', 'scale', false)).to.equal(4);
}
});
});
test('Properly blend tweens with composition blend', resolve => {
const anim1 = animate('#target-id', {
x: 100,
scale: 2,
duration: 200,
composition: 'blend',
ease: 'linear',
onComplete: () => {
expect(utils.get('#target-id', 'x', false)).to.be.above(180);
expect(utils.get('#target-id', 'scale', false)).to.be.above(3.9);
resolve();
}
});
animate('#target-id', {
x: 200,
scale: 4,
duration: 100,
composition: 'blend',
ease: 'linear',
onComplete: () => {
expect(anim1.completed).to.equal(false);
expect(anim1._cancelled).to.equal(0);
expect(utils.get('#target-id', 'x', false)).to.be.above(120);
expect(utils.get('#target-id', 'x', false)).to.be.below(150);
expect(utils.get('#target-id', 'scale', false)).to.be.above(3);
expect(utils.get('#target-id', 'scale', false)).to.be.below(3.5);
}
});
});
test('Properly assign specific tween properties', () => {
const easeA = t => t;
const easeB = t => t * 2;
const modifierA = v => v;
const modifierB = v => v * 2;
const anim1 = animate('#target-id', {
x: {
to: 100,
modifier: modifierA,
composition: 'blend',
ease: easeA,
},
y: 100,
composition: 'none',
ease: easeB,
modifier: modifierB,
autoplay: false,
});
const tweenX = /** @type {Tween} */(anim1._head);
const tweenY = /** @type {Tween} */(tweenX._next);
expect(tweenX._modifier).to.equal(modifierA);
expect(tweenX._ease).to.equal(easeA);
expect(tweenX._composition).to.equal(compositionTypes.blend);
expect(tweenY._modifier).to.equal(modifierB);
expect(tweenY._ease).to.equal(easeB);
expect(tweenY._composition).to.equal(compositionTypes.none);
});
test('Seeking inside the delay of a tween should correctly render the previous tween to value', () => {
const anim = createTimeline({
autoplay: false
})
.add('#target-id', {
scale: [
{ to: [0, 1], duration: 200, ease: 'outBack' },
{ to: [0, 0], duration: 100, delay: 500, ease: 'inQuart' },
],
delay: 200
})
.init()
anim.seek(404); // Seek after [0, 1] inside the delay of [0, 0]
expect(utils.get('#target-id', 'scale', false)).to.equal(1);
});
test('Correct tweens override and from value definition', () => {
const duration = 1000;
const $els = utils.$('.target-class');
const tl = createTimeline({
loop: 3,
alternate: true,
autoplay: false,
})
.add($els[0], {
translateX: [{to: -50}, {to: 200}],
duration: 1000,
}, 0)
.add($els[0], {
translateX: [{to: 100}, {to: -100}],
duration: 1000,
delay: 500,
}, 0)
.add([$els[0], $els[1], $els[2]], {
translateY: el => el.id == 'square-1' ? -50 : el.id == 'square-2' ? -100 : -150,
duration: 1600,
delay: 1250,
}, stagger(500, {start: '-=250'}))
.add([$els[0], $els[1], $els[2]], {
translateY: [
{ to: 50, duration: 500, delay: stagger(250, {start: 0}) },
{ to: 75, duration: 500, delay: 1000 },
{ to: 100, duration: 500, delay: 1000 }
],
}, '-=1250')
.add($els[0], {
id: 'TEST A',
translateY: 50,
}, '-=' + (duration))
.add($els[1], {
translateY: 50,
}, '-=' + duration)
.add($els[2], {
translateY: 50,
}, '-=' + duration)
.add([$els[0], $els[1], $els[2]], {
rotate: '-=180',
duration: duration * 2,
delay: stagger(100),
}, '-=' + duration * .75)
.add([$els[0], $els[1], $els[2]], {
id: 'TEST B',
translateY: 0,
delay: stagger(100),
}, '-=' + duration)
const animA = /** @type {$Animation} */(tl._head._next._next._next._next._next._next);
const animB = /** @type {$Animation} */(animA._next._next._next._next);
expect(animA._head._fromNumber).to.equal(75);
expect(animB._head._fromNumber).to.equal(50);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/directions.test.js | tests/suites/directions.test.js | import {
expect,
} from '../utils.js';
import {
animate,
utils,
} from '../../dist/modules/index.js';
suite('Directions', () => {
test('Direction normal should update from 0 to 1', resolve => {
const [ target ] = utils.$('#target-id');
const animation = animate(target, {
translateX: 100,
duration: 10,
onComplete: () => {
expect(target.style.transform).to.equal('translateX(100px)');
resolve();
},
});
animation.seek(0);
expect(target.style.transform).to.equal('translateX(0px)');
});
test('Direction reverse should update from 1 to 0', resolve => {
const [ target ] = utils.$('#target-id');
const animation = animate(target, {
translateX: 100,
reversed: true,
duration: 10,
onComplete: () => {
expect(target.style.transform).to.equal('translateX(0px)');
resolve();
},
});
animation.seek(0);
expect(target.style.transform).to.equal('translateX(100px)');
});
test('Manually reversed infinite animation should update', resolve => {
const [ target ] = utils.$('#target-id');
let loopCounts = 0;
const animation = animate(target, {
translateX: 100,
reversed: false,
loop: true,
duration: 20,
onLoop: self => {
loopCounts++;
if (loopCounts === 2) {
self.pause();
expect(loopCounts).to.equal(2);
expect(self.currentTime).to.be.at.least(40);
expect(self.paused).to.equal(true);
resolve();
}
},
});
animation.reverse();
});
test('Direction alternate should update from 0 to 1 when no loop parameter is specified', resolve => {
const [ target ] = utils.$('#target-id');
const animation = animate(target, {
translateX: 100,
alternate: true,
duration: 10,
onComplete: () => {
expect(target.style.transform).to.equal('translateX(100px)');
resolve();
},
});
animation.seek(0);
expect(target.style.transform).to.equal('translateX(0px)');
});
test('Direction alternate should update from 0 to 1 then 1 to 0 when a loop parameter is specified', resolve => {
const [ target ] = utils.$('#target-id');
const animation = animate(target, {
translateX: 100,
alternate: true,
duration: 10,
loop: 3,
onComplete: () => {
expect(target.style.transform).to.equal('translateX(0px)');
resolve();
},
});
animation.seek(0);
expect(target.style.transform).to.equal('translateX(0px)');
});
test('Infinite loop with direction alternate should update from 0 to 1 then 1 to 0...', resolve => {
const [ target ] = utils.$('#target-id');
let loopCounts = 0;
const animation = animate(target, {
translateX: 100,
alternate: true,
duration: 50,
ease: 'linear',
loop: Infinity,
onLoop: self => {
loopCounts++;
if (loopCounts === 4) {
// Infinite loop onLoop events don't garanty rounded number since they're still in the middle of the animation
expect(parseFloat(utils.get(target, 'translateX'))).to.be.below(50);
self.pause();
resolve();
}
},
});
animation.seek(0);
expect(target.style.transform).to.equal('translateX(0px)');
});
test('Direction alternate reverse should update from 1 to 0 when no loop parameter is specified', resolve => {
const [ target ] = utils.$('#target-id');
const animation = animate(target, {
translateX: 100,
alternate: true,
reversed: true,
duration: 10,
onComplete: () => {
expect(target.style.transform).to.equal('translateX(0px)');
resolve();
},
});
animation.seek(0);
expect(target.style.transform).to.equal('translateX(100px)');
});
test('Direction alternate reverse should update from 1 to 0 then 0 to 1 when a loop parameter is specified', resolve => {
const [ target ] = utils.$('#target-id');
const animation = animate(target, {
translateX: 100,
// direction: 'alternate-reverse',
alternate: true,
reversed: true,
duration: 10,
loop: 3,
onComplete: () => {
expect(target.style.transform).to.equal('translateX(100px)');
resolve();
},
});
animation.seek(0);
expect(target.style.transform).to.equal('translateX(100px)');
});
test('Infinite loop with direction alternate reverse should update from 1 to 0 then 0 to 1...', resolve => {
const [ target ] = utils.$('#target-id');
let loopCounts = 0;
const animation = animate(target, {
translateX: 100,
// direction: 'alternate-reverse',
alternate: true,
reversed: true,
duration: 50,
loop: Infinity,
onLoop: self => {
loopCounts++;
if (loopCounts === 4) {
// Infinite loop onLoop events don't garanty rounded number since they're still in the middle of the animation
expect(parseFloat(utils.get(target, 'translateX'))).to.be.above(50);
self.pause();
resolve();
}
},
});
animation.seek(0);
expect(target.style.transform).to.equal('translateX(100px)');
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/timings.test.js | tests/suites/timings.test.js | import {
expect,
getChildAtIndex,
} from '../utils.js';
import {
animate,
utils
} from '../../dist/modules/index.js';
suite('Timings', () => {
test('Specified timings parameters', resolve => {
animate('#target-id', {
translateX: 100,
delay: 10,
duration: 20,
loop: 1,
loopDelay: 10,
onComplete: a => {
expect(a.currentTime).to.equal(20 + 10 + 20);
resolve();
},
});
});
const complexTimingsParams = {
translateX: {
to: 50,
delay: () => 15,
duration: () => 10,
},
translateY: {
to: 35,
delay: 10,
duration: 10,
},
translateZ: {
to: 20,
delay: 35,
duration: 30,
},
delay: () => 10,
duration: () => 10,
loopDelay: 10,
loop: 1,
autoplay: false
};
test('Iteration currentTime should be negative when a delay is defined', () => {
const animation = animate('#target-id', complexTimingsParams);
expect(animation.currentTime).to.equal(-10);
animation.seek(5)
expect(animation.currentTime).to.equal(5);
animation.seek(animation.duration)
expect(animation.currentTime).to.equal(animation.duration);
});
test('Duration must be equal to the highest tween end value minus the delay', () => {
const animation = animate('#target-id', complexTimingsParams);
expect(animation.duration).to.equal(55 + 10 + 55);
});
test('IterationChangeEndTime must be equal to the highest iterationChangeEndTime of the the longest tween minus the delay', () => {
const animation = animate('#target-id', complexTimingsParams);
expect(animation.iterationDuration).to.equal(65 - 10);
});
test('Delay should delay the start of the animation', resolve => {
const start = Date.now();
const animation = animate('#target-id', {
x: 100,
delay: 100,
duration: 100,
ease: 'linear',
onBegin: self => {
self.pause();
const current = Date.now() - start;
expect(current).to.be.closeTo(100, 17);
expect(utils.get('#target-id', 'x', false)).to.equal(0);
animation.seek(50);
expect(utils.get('#target-id', 'x', false)).to.equal(50);
animation.seek(100);
expect(utils.get('#target-id', 'x', false)).to.equal(100);
resolve();
}
});
});
test('Delayed alternate looped animations should start correctly', () => {
animate('#target-id', {
y: -100,
loop: 2,
delay: 1000,
alternate: true,
autoplay: false,
});
expect(utils.get('#target-id', 'y', false)).to.equal(0);
});
test('Negative delay on alternate looped animations should render the value in advance', () => {
const animation = animate('#target-id', {
scale: [0, 1],
ease: 'linear',
loop: true,
duration: 1000,
delay: -5250,
alternate: true,
autoplay: false,
});
animation.seek(0);
expect(utils.get('#target-id', 'scale', false)).to.equal(.75)
});
test('Get and set iterationProgress on non looped animation', () => {
const animation = animate('#target-id', {
scale: [0, 1],
ease: 'linear',
duration: 1000,
autoplay: false
});
animation.iterationProgress = 0;
expect(utils.get('#target-id', 'scale', false)).to.equal(0);
animation.iterationProgress = .5;
expect(utils.get('#target-id', 'scale', false)).to.equal(.5);
animation.iterationProgress = 1;
expect(utils.get('#target-id', 'scale', false)).to.equal(1);
expect(animation.currentTime).to.equal(1000);
});
test('Get and set iterationProgress on a looped animation with pre-defined iterations', () => {
const animation = animate('#target-id', {
scale: [0, 1],
ease: 'linear',
duration: 1000,
autoplay: false,
loop: 3,
});
animation.seek(2200);
expect(utils.get('#target-id', 'scale', false)).to.equal(.2);
animation.iterationProgress = 0;
expect(animation.currentTime).to.equal(2000);
expect(utils.get('#target-id', 'scale', false)).to.equal(0);
animation.iterationProgress = .5;
expect(utils.get('#target-id', 'scale', false)).to.equal(.5);
animation.iterationProgress = 1;
expect(utils.get('#target-id', 'scale', false)).to.equal(0);
expect(animation.currentTime).to.equal(3000);
});
test('Get and set currentIteration on a looped animation with pre-defined iterations', () => {
const animation = animate('#target-id', {
scale: [0, 1],
ease: 'linear',
duration: 1000,
autoplay: false,
loop: 4,
});
animation.currentIteration = 0;
expect(animation.currentIteration).to.equal(0);
animation.seek(1500);
expect(animation.currentIteration).to.equal(1);
animation.currentIteration = 2;
expect(animation.currentIteration).to.equal(2);
expect(animation.currentTime).to.equal(2000);
animation.currentIteration = 99;
expect(animation.currentIteration).to.equal(4);
expect(animation.currentTime).to.equal(4000);
});
test('Get and set currentTime on a looped animation with pre-defined iterations', () => {
const animation = animate('#target-id', {
scale: [0, 1],
ease: 'linear',
duration: 1000,
autoplay: false,
loop: 4,
});
animation.currentTime = 1500;
expect(animation.currentTime).to.equal(1500);
expect(utils.get('#target-id', 'scale', false)).to.equal(.5);
animation.currentTime = 4250;
expect(animation.currentTime).to.equal(4250);
expect(utils.get('#target-id', 'scale', false)).to.equal(.25);
animation.currentTime = 5500;
expect(animation.currentTime).to.equal(5000);
expect(utils.get('#target-id', 'scale', false)).to.equal(1);
});
test('Get and set iterationCurrentTime on a looped animation with pre-defined iterations', () => {
const animation = animate('#target-id', {
scale: [0, 1],
ease: 'linear',
duration: 1000,
autoplay: false,
loop: 4,
});
animation.iterationCurrentTime = 500;
expect(animation.currentTime).to.equal(500);
expect(animation.currentIteration).to.equal(0);
expect(animation.iterationCurrentTime).to.equal(500);
expect(utils.get('#target-id', 'scale', false)).to.equal(.5);
animation.iterationCurrentTime = 1500;
expect(animation.currentTime).to.equal(1500);
expect(animation.currentIteration).to.equal(1);
expect(animation.iterationCurrentTime).to.equal(500);
expect(utils.get('#target-id', 'scale', false)).to.equal(.5);
animation.iterationCurrentTime = 250;
expect(animation.currentTime).to.equal(1250);
expect(animation.currentIteration).to.equal(1);
expect(animation.iterationCurrentTime).to.equal(250);
expect(utils.get('#target-id', 'scale', false)).to.equal(.25);
});
test('Get and set cancelled on an animation', () => {
const animation = animate('#target-id', complexTimingsParams);
expect(animation.cancelled).to.equal(false);
animation.cancelled = true;
expect(animation.cancelled).to.equal(true);
expect(animation.paused).to.equal(true);
animation.cancelled = false;
expect(animation.cancelled).to.equal(false);
expect(animation.paused).to.equal(false);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/leaks.test.js | tests/suites/leaks.test.js | import {
expect, forEachChildren,
} from '../utils.js';
import {
engine,
} from '../../dist/modules/index.js';
suite('Leaks', () => {
test('Engine should not contain any active tickable', resolve => {
setTimeout(() => {
forEachChildren(engine, child => {
console.warn('Active child id:', child.id);
});
expect(engine._tail).to.equal(null);
resolve();
}, 10)
});
}); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/node.test.js | tests/suites/node.test.js | import { expect } from 'chai';
import { animate, createTimer, createTimeline, engine } from '../../dist/modules/index.js';
import { render } from '../../dist/modules/core/render.js';
// import { animate } from '../visual/assets/anime.4.0.0.beta-29.js';
const totalInstances = 10000;
const targets = [];
for (let i = 0; i < totalInstances; i++) {
targets.push({ prop: Math.random() });
}
suite('Node tests', () => {
test('Barebone test to see if an animation runs', resolve => {
const obj = {test: 1}
const startTime = Date.now();
animate(obj, {
test: 2,
duration: 1000,
onComplete: () => {
const endTime = Date.now() - startTime;
expect(endTime).to.be.closeTo(1000, 15);
console.log('endTime:', endTime);
expect(obj.test).to.equal(2);
resolve();
}
});
});
function getOptimizationStatus(fn) {
// @ts-ignore
const status = %GetOptimizationStatus(fn);
// console.log(status, status.toString(2).padStart(12, '0'));
if (status & (1 << 0)) console.log(fn, ' is function');
if (status & (1 << 1)) console.log(fn, ' is never optimized');
if (status & (1 << 2)) console.log(fn, ' is always optimized');
if (status & (1 << 3)) console.log(fn, ' is maybe deoptimized');
if (status & (1 << 4)) console.log(fn, ' is optimized');
if (status & (1 << 5)) console.log(fn, ' is optimized by TurboFan');
if (status & (1 << 6)) console.log(fn, ' is interpreted');
if (status & (1 << 7)) console.log(fn, ' is marked for optimization');
if (status & (1 << 8)) console.log(fn, ' is marked for concurrent optimization');
if (status & (1 << 9)) console.log(fn, ' is optimizing concurrently');
if (status & (1 << 10)) console.log(fn, ' is executing');
if (status & (1 << 11)) console.log(fn, ' topmost frame is turbo fanned');
console.log(fn, ' optimization status is ', status);
return status;
}
test('test if the animate() function can be optimized', () => {
for (let i = 0; i < totalInstances; i++) {
animate(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
})
}
const animation = animate(targets[0], {
prop: Math.random(),
duration: Math.random() * 2,
ease: 'linear',
});
const tween = animation._head;
const animateIsOptimized = getOptimizationStatus(animate);
// @ts-ignore
const animationHasFastProperties = %HasFastProperties(animation);
// @ts-ignore
const tweenHasFastProperties = %HasFastProperties(tween);
if (animationHasFastProperties) console.log('animation has fast properties');
if (tweenHasFastProperties) console.log('tween has fast properties');
expect(animateIsOptimized).to.equal(49);
expect(animationHasFastProperties).to.equal(true);
expect(tweenHasFastProperties).to.equal(true);
});
test('test if the createTimeline() function can be optimized', () => {
for (let i = 0; i < totalInstances; i++) {
createTimeline({
defaults: {
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
},
})
.add(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
})
.add(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
})
}
const tl1 = createTimeline({
defaults: {
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
},
})
.add(targets[0], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
})
.add(targets[1], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
})
expect(getOptimizationStatus(createTimeline)).to.equal(49);
const tl2 = createTimeline({
defaults: {
duration: Math.random() * 10,
autoplay: false
}
});
for (let i = 0; i < 3500; i++) {
tl2.add(targets[i], {
prop: Math.random()
});
}
tl2.restart();
tl2.play();
tl2.pause();
expect(getOptimizationStatus(createTimeline)).to.equal(49);
const tlHasFastProperties = %HasFastProperties(tl2);
if (tlHasFastProperties) console.log('timeline has fast properties');
expect(tlHasFastProperties).to.equal(true);
});
test('test if the createTimer() function can be optimized', () => {
for (let i = 0; i < totalInstances * 2; i++) {
createTimer({
duration: Math.random() * 2
})
}
const timer = createTimer({
duration: Math.random() * 2,
});
const animateIsOptimized = getOptimizationStatus(createTimer);
const animationHasFastProperties = %HasFastProperties(timer);
if (animationHasFastProperties) console.log('timer has fast properties');
expect(animateIsOptimized).to.equal(49);
expect(animationHasFastProperties).to.equal(true);
});
const generateInstances = () => {
let anim, tl, timer;
for (let i = 0; i < totalInstances; i++) {
anim = animate(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
});
tl = createTimeline()
.add(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
})
.add(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3,
})
timer = createTimer({
delay: Math.random() * 1.5,
duration: Math.random() * 2,
loopDelay: Math.random() * 3
});
}
return { anim, tl, timer }
}
test('test if the render() function can be optimized', resolve => {
// First test a normal run
for (let i = 0; i < totalInstances; i++) {
animate(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 100,
loopDelay: Math.random() * 3
})
}
setTimeout(() => {
expect(getOptimizationStatus(render)).to.equal(49);
// Then mix animation types an manually render them
const animations = [];
// animations.push(globalClock._additiveAnimation);
for (let i = 0; i < totalInstances / 3; i++) {
animations.push(animate(targets[i], {prop: Math.random(), duration: Math.random() * 100, autoplay: false}));
animations.push(createTimer({duration: Math.random() * 100, autoplay: false}));
}
// animations.push(globalClock._additiveAnimation);
const start = Date.now();
for (let i = 0; i < animations.length; i++) {
const time = Date.now() - start;
const tickMode = Math.random() < .5 ? 0 : -1;
render(animations[i], time, 0, 0, tickMode);
}
setTimeout(() => {
expect(getOptimizationStatus(render)).to.equal(49);
resolve();
}, 200)
}, 200)
});
test('test if the engine.update() function can be optimized', resolve => {
// First test a normal run
for (let i = 0; i < totalInstances; i++) {
animate(targets[i], {
prop: Math.random(),
delay: Math.random() * 1.5,
duration: Math.random() * 100,
loopDelay: Math.random() * 3,
frameRate: Math.random() * 10,
});
createTimer({
duration: Math.random() * 100,
frameRate: Math.random() * 10,
});
}
setTimeout(() => {
expect(getOptimizationStatus(engine.update)).to.equal(49);
resolve();
}, 200)
});
test('test if engine has fast properties', () => {
const { anim, tl, timer } = generateInstances();
expect(%HasFastProperties(engine)).to.equal(true);
});
test('test if engine\'s defaults has fast properties', () => {
const { anim, tl, timer } = generateInstances();
expect(%HasFastProperties(engine.defaults)).to.equal(true);
});
test('test if timer has fast properties', () => {
const { anim, tl, timer } = generateInstances();
expect(%HasFastProperties(timer)).to.equal(true);
});
test('test if animation has fast properties', () => {
const { anim, tl, timer } = generateInstances();
expect(%HasFastProperties(anim)).to.equal(true);
});
test('test if tween has fast properties', () => {
const { anim, tl, timer } = generateInstances();
const tween = anim._head;
expect(%HasFastProperties(tween)).to.equal(true);
});
test('test if tl has fast properties', () => {
const { anim, tl, timer } = generateInstances();
expect(%HasFastProperties(tl)).to.equal(true);
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/engine.test.js | tests/suites/engine.test.js | import {
expect,
} from '../utils.js';
import {
animate,
engine,
utils,
} from '../../dist/modules/index.js';
const defaultEnginePauseState = engine.paused;
const defaultEngineReqId = engine.reqId;
suite('Engine', () => {
test('Initial offset position should be properly calculated on cold start', resolve => {
setTimeout(() => {
const animation1 = animate('#target-id', {
x: 100,
duration: 20,
onComplete: () => {
const animation2 = animate('#target-id', {
x: 100,
duration: 20,
});
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);
resolve();
}
});
}, 50);
});
test('Set useDefaultMainLoop to false should prevent animations from running', resolve => {
// Needed to kill the engine
engine.pause();
// Needed to reset engine to its original state
engine.paused = defaultEnginePauseState;
engine.reqId = defaultEngineReqId;
engine.useDefaultMainLoop = false;
let renderCheck = 0;
const animation = animate('#target-id', {
x: 100,
duration: 20,
onUpdate: () => {
renderCheck++;
},
});
setTimeout(() => {
expect(animation.began).to.equal(false);
expect(animation.currentTime).to.equal(0);
expect(renderCheck).to.equal(0);
engine.useDefaultMainLoop = true; // Reset
resolve();
}, 70);
});
test('Manually tick the engine with an external loop', resolve => {
engine.useDefaultMainLoop = false;
let raf = 0;
function customLoop() {
raf = requestAnimationFrame(customLoop);
engine.update();
}
customLoop();
let renderCheck = 0;
const animation = animate('#target-id', {
translateX: 100,
onRender: () => {
renderCheck++;
},
duration: 50,
});
setTimeout(() => {
expect(animation.began).to.equal(true);
expect(animation.completed).to.equal(true);
expect(animation.currentTime).to.equal(50);
expect(renderCheck).to.be.above(2);
cancelAnimationFrame(raf);
engine.useDefaultMainLoop = true; // Reset
resolve();
}, 70);
});
test('Pause and resume the engine', resolve => {
let renderCheck = 0;
const animation = animate('#target-id', {
translateX: 100,
onRender: () => {
renderCheck++;
},
duration: 50,
});
engine.pause();
setTimeout(() => {
expect(animation.began).to.equal(false);
expect(animation.completed).to.equal(false);
expect(animation.currentTime).to.equal(0);
expect(renderCheck).to.equal(0);
engine.resume();
setTimeout(() => {
expect(animation.began).to.equal(true);
expect(animation.completed).to.equal(true);
expect(animation.currentTime).to.equal(50);
expect(renderCheck).to.be.above(2);
resolve();
}, 100);
}, 50);
});
test('Default precision should be 4', () => {
const [ $target ] = utils.$('#target-id');
const initialTransformString = 'translateX(0.12345px) scale(0.12345)';
$target.style.transform = initialTransformString;
const animation = animate($target, {
x: 2.12345,
scale: 2.12345,
ease: 'linear',
autoplay: false,
duration: 500,
});
expect($target.style.transform).to.equal(initialTransformString);
animation.seek(250);
expect($target.style.transform).to.equal('translateX(1.1235px) scale(1.1235)');
animation.seek(500);
expect($target.style.transform).to.equal('translateX(2.12345px) scale(2.12345)');
});
test('Changing precision should affect only animated values', () => {
const defaultPrecision = engine.precision;
engine.precision = 1;
const [ $target ] = utils.$('#target-id');
const initialTransformString = 'translateX(0.12345px) scale(0.12345)';
$target.style.transform = initialTransformString;
const animation = animate($target, {
x: 2.12345,
scale: 2.12345,
ease: 'linear',
autoplay: false,
duration: 500,
});
expect($target.style.transform).to.equal(initialTransformString);
animation.seek(250);
expect($target.style.transform).to.equal('translateX(1.1px) scale(1.1)');
animation.seek(500);
expect($target.style.transform).to.equal('translateX(2.12345px) scale(2.12345)');
engine.precision = defaultPrecision;
});
test('Changing the time unit should affect duration values', resolve => {
const defaultUnit = engine.timeUnit;
const defaultDuration = /** @type {Number} */(engine.defaults.duration);
engine.timeUnit = 's';
expect(engine.defaults.duration).to.equal(defaultDuration * .001);
const animation = animate('#target-id', {
x: 100,
ease: 'linear',
duration: .75,
});
setTimeout(() => {
expect(animation.currentTime).to.be.above(.1);
expect(animation.currentTime).to.be.below(.75);
resolve();
engine.timeUnit = defaultUnit;
}, 150)
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/suites/seconds.test.js | tests/suites/seconds.test.js | import {
expect,
getChildAtIndex,
} from '../utils.js';
import {
minValue,
} from '../../dist/modules/core/consts.js';
import {
animate,
createTimeline,
createTimer,
engine,
} from '../../dist/modules/index.js';
suite('Seconds', () => {
test('Calls added to a 0 duration timeline with a delay should not fire before the end of the delay duration', resolve => {
engine.timeUnit = 's';
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
const tl = createTimeline({
delay: 1,
loop: 1,
autoplay: false,
// onUpdate: self => console.log(self.id, self._currentTime),
onComplete: self => {
expect(timer1Log).to.equal(1);
expect(timer2Log).to.equal(1);
expect(timer3Log).to.equal(1);
engine.timeUnit = 'ms';
resolve();
}
})
.call(() => { timer1Log += 1; }, 0)
.call(() => { timer2Log += 1; }, 0)
.call(() => { timer3Log += 1; }, 0)
.init();
tl.seek(-.1);
expect(timer1Log).to.equal(0);
expect(timer2Log).to.equal(0);
expect(timer3Log).to.equal(0);
tl.play();
});
test('Timers offset time should be properly scaled when not controlled by a Timeline', () => {
engine.timeUnit = 's';
const timer1 = createTimer({ duration: .05, autoplay: false, });
const timer2 = createTimer({ duration: .05, delay: .01, autoplay: false, });
expect(timer1._offset).to.be.below(1);
expect(timer2._offset).to.be.below(1);
});
test('Stretch a looped timer', () => {
engine.timeUnit = 's';
const timer1 = createTimer({
duration: .1,
autoplay: false,
loop: 0,
});
expect(timer1.duration).to.equal(.1);
for (let i = 1, l = 9999; i < l; i++) {
const newTime = +(i * .1).toFixed(1);
timer1.stretch(newTime);
expect(timer1.duration).to.equal(newTime);
expect(timer1.iterationDuration).to.equal(newTime);
}
timer1.stretch(0);
expect(timer1.duration).to.equal(minValue);
expect(timer1.iterationDuration).to.equal(minValue);
engine.timeUnit = 'ms';
});
test('Stretch a looped timer', () => {
engine.timeUnit = 's';
const timer1 = createTimer({
duration: .1,
autoplay: false,
loop: 3,
});
expect(timer1.duration).to.equal(.1 * 4);
for (let i = 1, l = 9999; i < l; i++) {
const newTime = +(i * .1).toFixed(1);
timer1.stretch(newTime);
expect(timer1.duration).to.equal(newTime);
expect(timer1.iterationDuration).to.equal(newTime / timer1.iterationCount);
}
timer1.stretch(0);
expect(timer1.duration).to.equal(minValue);
expect(timer1.iterationDuration).to.equal(minValue);
engine.timeUnit = 'ms';
});
test('Stretch an animation', () => {
engine.timeUnit = 's';
const animation1 = animate('#target-id', {
width: [{to: 100, duration: .1}, {to: 100, duration: .2}],
duration: .1,
autoplay: false
});
expect(animation1.duration).to.equal(.3);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(.1);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(.2);
animation1.stretch(.6);
expect(animation1.duration).to.equal(.6);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(.2);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(.4);
animation1.stretch(.03);
expect(animation1.duration).to.equal(.03);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(.01);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(.02);
animation1.stretch(0);
expect(animation1.duration).to.equal(minValue);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(minValue);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(minValue);
animation1.stretch(.03);
expect(animation1.duration).to.equal(.03);
expect(getChildAtIndex(animation1, 0)._updateDuration).to.equal(.03);
expect(getChildAtIndex(animation1, 1)._updateDuration).to.equal(.03);
engine.timeUnit = 'ms';
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/scope/index.js | tests/playground/scope/index.js | import {
animate,
utils,
createScope,
} from '../../../dist/modules/index.js';
const scope = createScope({
mediaQueries: { isSmall: '(max-width: 800px)' },
defaults: { ease: 'linear' },
root: '.scoped',
})
.add(self => {
const squares = utils.$('.square');
self.addOnce((scope) => {
console.log('ADDED ONCE');
// Everything declared here will be only called once and won't be reverted on mediaquery changes
animate('.square', {
y: [0, -50, 0, 50, 0],
loop: true,
ease: 'inOut(2)',
duration: 2500
});
})
self.addOnce(() => {
console.log('ADDED ONCE');
// Everything declared here will be only called once and won't be reverted on mediaquery changes
animate('.square', {
x: [0, -100, 0, 100, 0],
loop: true,
ease: 'inOut(2)',
duration: 2500
});
})
const rotationAnimation = self.keepTime(() => animate('.square', {
rotate: 360,
duration: 2000,
loop: true,
alternate: true
}));
// Recreate the animation while keeping track of its current time between mediaquery changes
// self.keepTime(() => animate('.square', {
// scale: self.matches.isSmall ? .5 : 1.5,
// rotate: 360,
// duration: 2000,
// loop: true,
// alternate: true
// }));
function handlePointerEnter() {
animate(this, {
scale: 1.5,
ease: 'out(3)',
duration: 500
});
}
function handlePointerLeave() {
animate(this, {
scale: 1,
ease: 'out(3)',
duration: 500
});
}
self.keepTime(() => animate('.square', {
background: ($el) => utils.get($el, utils.randomPick(['--skyblue', '--lavender', '--pink'])),
loop: true,
ease: 'inOut(2)',
alternate: true,
duration: 2000,
}));
squares.forEach($square => $square.addEventListener('pointerenter', handlePointerEnter));
squares.forEach($square => $square.addEventListener('pointerleave', handlePointerLeave));
return () => {
squares.forEach($square => $square.removeEventListener('pointerenter', handlePointerEnter));
squares.forEach($square => $square.removeEventListener('pointerleave', handlePointerLeave));
}
});
document.body.addEventListener('click', () => {
console.log('REVERT');
scope.revert();
}) | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/draggables/callbacks/index.js | tests/playground/draggables/callbacks/index.js | import {
animate,
createDraggable,
utils,
Draggable
} from '../../../../dist/modules/index.js';
const [ $log1, $log2 ] = utils.$('.log');
const [ $container ] = /** @type {Array<HTMLElement>} */(utils.$('#container '));
const log = ($log, text) => {
const $spans = $log.querySelectorAll('span');
const date = new Date;
const ms = utils.padEnd(date.getMilliseconds(), 3, '0');
const s = utils.padEnd(date.getSeconds(), 2, '0');
const m = utils.padEnd(date.getMinutes(), 2, '0');
const h = utils.padEnd(date.getHours(), 2, '0');
if ($spans.length > 300) {
for (let i = 0; i < 200; i++) {
$log.removeChild($spans[i]);
}
}
const $el = document.createElement('span');
$el.innerHTML = `${h}:${m}:${s}:${ms} ${text}<br>`;
$log.appendChild($el);
$log.scrollTop = $log.scrollHeight;
}
const manualDraggable = createDraggable('#manual', {
velocityMultiplier: 0,
container: '#container',
snap: self => self.$target.offsetWidth,
onSnap: () => log($log1, 'A onSnap'),
onGrab: () => log($log1, 'A onGrab'),
onDrag: () => log($log1, 'A onDrag'),
onUpdate: () => log($log1, 'A onUpdate'),
onRelease: () => log($log1, 'A onRelease'),
onSettle: () => log($log1, 'A onSettle'),
onResize: () => log($log1, 'A onResize'),
onAfterResize: () => log($log1, 'A onAfterResize'),
});
const animatedDraggable = createDraggable('#animated', {
container: '#container',
onGrab: () => log($log2, 'B onGrab'),
onDrag: () => log($log2, 'B onDrag'),
onUpdate: () => log($log2, 'B onUpdate'),
onRelease: () => log($log2, 'B onRelease'),
onSettle: () => log($log2, 'B onSettle'),
onResize: () => log($log2, 'B onResize'),
onAfterResize: () => log($log2, 'B onAfterResize'),
});
animate(animatedDraggable, {
x: (draggable) => {
return $container.offsetWidth - /** @type {Draggable} */(draggable).$target.offsetWidth;
},
y: (draggable) => {
return $container.offsetHeight - /** @type {Draggable} */(draggable).$target.offsetHeight * 2;
},
}); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/standalone.js | tests/playground/onscroll/assets/standalone.js | import {
utils,
onScroll,
animate,
} from '../../../../dist/modules/index.js';
const $logs = utils.$('.log');
const log = ($log, text) => {
const $spans = $log.querySelectorAll('span');
if ($spans.length > 300) {
for (let i = 0; i < 200; i++) {
$log.removeChild($spans[i]);
}
}
const $el = document.createElement('span');
$el.innerHTML = `${text}<br>`;
$log.appendChild($el);
$log.scrollTop = $log.scrollHeight;
}
const scollers = [];
$logs.forEach(($log, i) => {
scollers.push(onScroll({
id: 'section ' + i,
target: `#section-0${i+1}`,
enter: 'max top',
leave: 'min bottom',
sync: 1,
debug: true,
onUpdate: self => {
log($log, self.progress);
},
onEnter: self => {
log($log, `enter #section-0${i+1}`);
},
onLeave: self => {
log($log, `leave #section-0${i+1}`);
}
}));
});
// Link a timer / animation / timeline later
const animation = animate('#section-04 h2', {
scale: 20,
});
scollers[3].link(animation);
// Lazy load example
utils.$('.lazy-load').forEach(($lazy, i) => {
onScroll({
target: $lazy,
repeat: false,
enter: { target: i * 6 + 'rem', container: 'bottom-=' + 2 + ((i) * 2) + 'rem'},
onEnter: self => {
/** @type {HTMLMediaElement} */(self.target).src = self.target.dataset.src;
},
debug: true
})
})
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/sync-methods.js | tests/playground/onscroll/assets/sync-methods.js | import {
utils,
animate,
onScroll,
stagger,
} from '../../../../dist/modules/index.js';
// Sync
const sections = utils.$('section');
const methods = ['play', 'play pause', 'resume alternate resume reset', 'play reverse'];
sections.forEach(($section, i) => {
animate($section.querySelectorAll('.card'), {
z: [i * 10, i * 10],
rotate: [stagger(utils.random(-1, 1, 2)), stagger(15)],
transformOrigin: ['75% 75%', '75% 75%'],
ease: 'inOut(1)',
autoplay: onScroll({
sync: methods[i],
debug: true,
enter: 'max center',
leave: 'min center',
}),
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/horizontal-container.js | tests/playground/onscroll/assets/horizontal-container.js | import {
utils,
onScroll,
createTimeline,
animate,
} from '../../../../dist/modules/index.js';
const tl = createTimeline({
autoplay: onScroll({
target: 'body',
enter: 'top min+=100',
leave: 'bottom max-=100',
sync: 1,
debug: true,
})
});
utils.$('.card').forEach(($card, i) => {
tl.add($card, {
z: [300, i * 2],
y: [300, 0],
rotateX: [-180, 0],
rotateY: [utils.random(-30, 30), 0],
rotateZ: [utils.random(-30, 30), 0],
ease: 'inOut(1)',
});
});
tl.init();
animate('.stack', {
rotateY: -360,
autoplay: onScroll({
container: '.sticky-container',
target: '.sticky-scroller',
axis: 'x',
sync: 1,
enter: 'left left+=100',
leave: 'right right-=100',
debug: true,
}),
})
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/function-based-values.js | tests/playground/onscroll/assets/function-based-values.js | import {
utils,
animate,
onScroll,
stagger,
} from '../../../../dist/modules/index.js';
const isLandscapeMedia = matchMedia('(orientation: landscape)');
utils.$('.section').forEach($section => {
animate($section.querySelectorAll('.card'), {
rotate: [stagger(utils.random(-1, 1, 2)), stagger(15)],
transformOrigin: ['75% 75%', '75% 75%'],
ease: 'inOut(2)',
autoplay: onScroll({
axis: () => isLandscapeMedia.matches ? 'x' : 'y',
enter: () => isLandscapeMedia.matches ? 'max-=25vw start+=25vw' : 'max start',
leave: () => isLandscapeMedia.matches ? 'min+=25vw end-=25vw' : 'min end',
sync: .5,
debug: true,
}),
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/sticky-snap.js | tests/playground/onscroll/assets/sticky-snap.js | import {
utils,
onScroll,
createTimeline,
} from '../../../../dist/modules/index.js';
const tl = createTimeline({
defaults: {
ease: 'inOut(1)',
},
autoplay: onScroll({
target: '.sticky-container',
sync: 1,
enter: 'top',
leave: 'bottom',
debug: true,
}),
});
utils.$('.card').forEach(($card, i) => {
tl.add($card, {
z: [40, i],
y: [i % 2 ? '-100vh' : '50vh', `${-i * 3}px`],
opacity: { to: [0, 1], duration: 50 },
rotateX: [-180, 0],
rotateY: [utils.random(-30, 30), 0],
rotateZ: [utils.random(-30, 30), 0],
});
});
tl.init();
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/svg-target.js | tests/playground/onscroll/assets/svg-target.js | import {
animate,
onScroll,
utils,
} from '../../../../dist/modules/index.js';
utils.set('.section', {
rotate: () => utils.random(-45, 45),
});
utils.set('svg.logo', {
scale: .5,
});
animate('svg.logo', {
scale: 2,
ease: 'inOut(2)',
autoplay: onScroll({
axis: 'y',
enter: 'max-=25% start',
leave: 'min+=25% end',
sync: .5,
debug: true,
}),
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/debug.js | tests/playground/onscroll/assets/debug.js | import {
utils,
onScroll,
createTimeline,
animate,
} from '../../../../dist/modules/index.js';
animate('#edges .target', {
rotate: 360,
autoplay: onScroll({
container: '#edges .container',
enter: 'bottom top',
leave: 'top bottom',
sync: 1,
debug: true
})
})
animate('#edges-inverted .target', {
rotate: 360,
autoplay: onScroll({
container: '#edges-inverted .container',
enter: 'top bottom',
leave: 'bottom top ',
sync: 1,
debug: true
})
})
animate('#offsets .target', {
rotate: 360,
autoplay: onScroll({
container: '#offsets .container',
enter: 'bottom-=100 top+=20',
leave: 'top+=100 bottom-=20',
sync: 1,
debug: true
})
})
animate('#hori-edges .target', {
rotate: 360,
autoplay: onScroll({
container: '#hori-edges .container',
axis: 'x',
enter: 'bottom top',
leave: 'top bottom',
sync: 1,
debug: true
})
})
animate('#hori-edges-inverted .target', {
rotate: 360,
autoplay: onScroll({
container: '#hori-edges-inverted .container',
axis: 'x',
enter: 'top bottom',
leave: 'bottom top',
sync: 1,
debug: true
})
})
animate('#hori-offsets .target', {
rotate: 360,
autoplay: onScroll({
container: '#hori-offsets .container',
axis: 'x',
enter: 'right-=120 left+=20',
leave: 'left+=120 right-=20',
sync: 1,
debug: true
})
})
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/min-max.js | tests/playground/onscroll/assets/min-max.js | import {
utils,
animate,
onScroll,
stagger,
} from '../../../../dist/modules/index.js';
// Sync
const sections = utils.$('section');
const colors = ['#FF4B4B', '#A4FF4F', '#33B3F1', '#FF4FCF'];
sections.forEach(($section, i) => {
animate($section.querySelectorAll('.card'), {
z: [i * 10, i * 10],
rotate: [stagger(utils.random(-1, 1, 2)), stagger(15)],
transformOrigin: ['75% 75%', '75% 75%'],
ease: 'inOut(1)',
autoplay: onScroll({
sync: true,
debug: true,
enter: 'max start',
leave: 'min end',
}),
});
onScroll({
target: $section,
debug: true,
enter: 'max center',
leave: 'min center',
onEnter: self => {
animate(document.body, {
backgroundColor: colors[i],
});
}
});
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/onscroll/assets/sync-modes.js | tests/playground/onscroll/assets/sync-modes.js | import {
utils,
animate,
onScroll,
stagger,
} from '../../../../dist/modules/index.js';
const $logs = utils.$('.log');
const log = ($log, text) => {
const $spans = $log.querySelectorAll('span');
if ($spans.length > 300) {
for (let i = 0; i < 200; i++) {
$log.removeChild($spans[i]);
}
}
const $el = document.createElement('span');
$el.innerHTML = `${text}<br>`;
$log.appendChild($el);
$log.scrollTop = $log.scrollHeight;
}
animate('#section-01 .card', {
rotate: [stagger(utils.random(-1, 1, 2)), stagger(15)],
transformOrigin: ['75% 75%', '75% 75%'],
ease: 'inOut(2)',
autoplay: onScroll({
enter: 'max-=100 top',
leave: 'min+=100 bottom',
sync: .5,
debug: true,
onEnter: () => log($logs[0], 'onEnter'),
onLeave: () => log($logs[0], 'onLeave'),
onUpdate: self => log($logs[0], 'onUpdate ' + self.linked.progress.toFixed(3)),
onEnterForward: () => { log($logs[0], 'onEnterForward'); },
onLeaveForward: () => { log($logs[0], 'onLeaveForward'); },
onEnterBackward: () => { log($logs[0], 'onEnterBackward'); },
onLeaveBackward: () => { log($logs[0], 'onLeaveBackward'); },
onSyncComplete: () => log($logs[0], 'onSyncComplete'),
}),
});
animate('#section-02 .card', {
rotate: [stagger(utils.random(-1, 1, 2)), stagger(15)],
transformOrigin: ['75% 75%', '75% 75%'],
ease: 'inOut(2)',
loop: true,
alternate: true,
autoplay: onScroll({
enter: 'max-=100 top',
leave: 'min+=100 bottom',
sync: 'play pause',
debug: true,
onEnter: () => log($logs[1], 'onEnter'),
onLeave: () => log($logs[1], 'onLeave'),
onUpdate: self => log($logs[1], 'onUpdate ' + self.progress.toFixed(3)),
onEnterForward: () => { log($logs[1], 'onEnterForward'); },
onLeaveForward: () => { log($logs[1], 'onLeaveForward'); },
onEnterBackward: () => { log($logs[1], 'onEnterBackward'); },
onLeaveBackward: () => { log($logs[1], 'onLeaveBackward'); },
onSyncComplete: () => log($logs[1], 'onSyncComplete'),
}),
});
animate('#section-03 .card', {
rotate: [stagger(utils.random(-1, 1, 2)), stagger(15)],
transformOrigin: ['75% 75%', '75% 75%'],
ease: 'inOut(2)',
autoplay: onScroll({
enter: 'max-=100 top',
leave: 'min+=100 bottom',
sync: 'play alternate reverse reset',
debug: true,
onEnter: () => log($logs[2], 'onEnter'),
onLeave: () => log($logs[2], 'onLeave'),
onUpdate: self => log($logs[2], 'onUpdate ' + self.progress.toFixed(3)),
onEnterForward: () => { log($logs[2], 'onEnterForward'); },
onLeaveForward: () => { log($logs[2], 'onLeaveForward'); },
onEnterBackward: () => { log($logs[2], 'onEnterBackward'); },
onLeaveBackward: () => { log($logs[2], 'onLeaveBackward'); },
onSyncComplete: () => log($logs[2], 'onSyncComplete'),
}),
});
animate('#section-04 .card', {
rotate: [stagger(utils.random(-1, 1, 2)), stagger(15)],
transformOrigin: ['75% 75%', '75% 75%'],
ease: 'linear',
autoplay: onScroll({
enter: 'max-=100 top',
leave: 'min+=100 bottom',
sync: 'inOutExpo',
debug: true,
onEnter: () => log($logs[3], 'onEnter'),
onLeave: () => log($logs[3], 'onLeave'),
onUpdate: self => log($logs[3], 'onUpdate ' + self.linked.progress.toFixed(3)),
onEnterForward: () => { log($logs[3], 'onEnterForward'); },
onLeaveForward: () => { log($logs[3], 'onLeaveForward'); },
onEnterBackward: () => { log($logs[3], 'onEnterBackward'); },
onLeaveBackward: () => { log($logs[3], 'onLeaveBackward'); },
onSyncComplete: () => log($logs[3], 'onSyncComplete'),
}),
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/svg-motion-path/index.js | tests/playground/svg-motion-path/index.js | import { animate, svg } from '../../../dist/modules/index.js';
animate(['.no-specified-width .dom-el', '.no-specified-width .rect-el'], {
duration: 3000,
loop: true,
ease: 'linear',
...svg.createMotionPath('#noSpecifiedWidth')
});
animate(['.specified-width .dom-el', '.specified-width .rect-el'], {
duration: 3000,
loop: true,
ease: 'linear',
...svg.createMotionPath('#specifiedWidth')
});
animate(['.preserveAspectRatio .dom-el', '.preserveAspectRatio .rect-el'], {
duration: 3000,
loop: true,
ease: 'linear',
...svg.createMotionPath('#preserveAspectRatio')
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/benchmark/index.js | tests/playground/benchmark/index.js | import { waapi, animate, createTimer, utils, engine } from '../../../dist/modules/index.js';
import {
Object3D,
Vector3,
Color,
PerspectiveCamera,
BoxGeometry,
MeshBasicMaterial,
InstancedMesh,
Scene,
WebGLRenderer,
} from '../../../node_modules/three/build/three.module.min.js';
// engine.frameRate = 30;
// engine.suspendWhenHidden = false;
const noop = () => {};
const url = new URL(window.location.href);
const urlParams = url.searchParams;
const $particlesContainer = document.querySelector('#particles-container');
const $countRange = document.querySelector('#count-range');
const $restartButton = document.querySelector('#restart-button');
const $activeTweens = document.querySelector('#active-tweens');
const $configItems = document.querySelectorAll('.config-item');
const startedSymbol = Symbol();
const reversedSymbol = Symbol();
const duration = 4000;
const ease = 'linear';
const particleDiameter = 10;
const AnimeTransformMode = {
minCount: 500,
maxCount: 10000,
defaultCount: 1500,
step: 500,
};
const AnimeWAAPITransformMode = {
minCount: 500,
maxCount: 10000,
defaultCount: 1500,
step: 500,
};
const WAAPITransformMode = {
minCount: 500,
maxCount: 10000,
defaultCount: 1500,
step: 500,
};
const webglThreejsMode = {
minCount: 5000,
maxCount: 100000,
defaultCount: 10000,
step: 5000,
};
const renderModes = {
'css-transform': AnimeTransformMode,
'anime-waapi-css-transform': AnimeWAAPITransformMode,
'wappi-css-transform': WAAPITransformMode,
'webgl-threejs': webglThreejsMode,
};
const config = {
mode: urlParams.get('mode') || 'css-transform',
count: urlParams.get('count') !== null ? +urlParams.get('count') : 1500,
x: urlParams.get('x') !== null ? urlParams.get('x') === 'true' : true,
y: urlParams.get('y') !== null ? urlParams.get('y') === 'true' : true,
rotation: urlParams.get('rotation') !== null ? urlParams.get('rotation') === 'true' : false,
scale: urlParams.get('scale') !== null ? urlParams.get('scale') === 'true' : false,
}
let containerRect = $particlesContainer.getBoundingClientRect();
let containerW = containerRect.width;
let containerH = containerRect.height;
let W = containerW;
let H = containerH;
let halfW = W * .5;
let halfH = H * .5;
let maxScale = 1;
// Tweens values factories
function getRandomX(el) {
return el[reversedSymbol] || el.reversed ? Math.random() > .5 ? -halfW : halfW : -halfW + Math.random() * W;
}
function getRandomY(el) {
return el[reversedSymbol] || el.reversed ? -halfH + Math.random() * H : Math.random() > .5 ? -halfH : halfH;
}
function getRandomScale() {
return (.25 + (Math.random() * .75)) * maxScale;
}
function getRandomRad() {
return -Math.PI + (Math.random() * (2 * Math.PI));
}
function getRandomDeg() {
return -180 + (Math.random() * 360);
}
function getBeginOffset(i) {
return i * ((duration) / config.count);
}
// Anime.js CSS Transform mode
AnimeTransformMode.init = () => {
if (AnimeTransformMode.isInitialized) return;
AnimeTransformMode.isInitialized = true;
function createParticule() {
const $el = document.createElement('div');
$el.classList.add('particle');
$el.classList.add(`color${(1 + (Math.random() * 2)).toFixed()}`);
$el[reversedSymbol] = !!utils.random(0, 1);
return $el;
}
function animateParticle($el, i) {
let delay = 0;
$el[reversedSymbol] = !$el[reversedSymbol];
if (!$el[startedSymbol]) {
$el[startedSymbol] = true;
delay = getBeginOffset(i);
}
const params = {
delay,
duration,
ease,
composition: 'none',
onComplete: () => animateParticle($el, i),
};
if (config.x) params.x = getRandomX($el);
if (config.y) params.y = getRandomY($el);
if (config.rotation) params.rotate = getRandomDeg();
if (config.scale) params.scale = getRandomScale();
animate($el, params);
}
AnimeTransformMode.cancel = () => {
const $particles = document.querySelectorAll('.particle');
utils.remove($particles);
$particlesContainer.innerHTML = '';
}
AnimeTransformMode.refresh = () => {
maxScale = utils.clamp(AnimeTransformMode.maxCount / config.count, .125, 5);
for (let i = 0; i < config.count; i++) {
const $el = createParticule();
$particlesContainer.appendChild($el);
animateParticle($el, i);
}
}
AnimeTransformMode.resize = () => {
W = containerW;
H = containerH;
halfW = W * .5;
halfH = H * .5;
}
}
// Anime.js + WAAPI CSS Transform mode
AnimeWAAPITransformMode.init = () => {
if (AnimeWAAPITransformMode.isInitialized) return;
AnimeWAAPITransformMode.isInitialized = true;
function createParticule() {
const $el = document.createElement('div');
$el.classList.add('particle');
$el.classList.add(`color${(1 + (Math.random() * 2)).toFixed()}`);
$el[reversedSymbol] = !!utils.random(0, 1);
return $el;
}
function animateParticle($el, i) {
let delay = 0;
$el[reversedSymbol] = !$el[reversedSymbol];
if (!$el[startedSymbol]) {
$el[startedSymbol] = true;
delay = getBeginOffset(i);
}
const params = {
delay,
duration,
ease,
onComplete: () => animateParticle($el, i),
};
let transform = ``;
if (config.x) transform += `translateX(${getRandomX($el)}px) `;
if (config.y) transform += `translateY(${getRandomY($el)}px) `;
if (config.rotation) transform += `rotate(${getRandomDeg()}deg) `;
if (config.scale) transform += `scale(${getRandomScale()}) `;
params.transform = transform;
waapi.animate($el, params);
}
AnimeWAAPITransformMode.cancel = () => {
const animations = document.getAnimations();
animations.forEach(animation => { animation.cancel() });
$particlesContainer.innerHTML = '';
}
AnimeWAAPITransformMode.refresh = () => {
maxScale = utils.clamp(AnimeWAAPITransformMode.maxCount / config.count, .125, 5);
for (let i = 0; i < config.count; i++) {
const $el = createParticule();
$particlesContainer.appendChild($el);
animateParticle($el, i);
}
}
AnimeWAAPITransformMode.resize = () => {
W = containerW;
H = containerH;
halfW = W * .5;
halfH = H * .5;
}
}
// WAAPI CSS Transform mode
WAAPITransformMode.init = () => {
if (WAAPITransformMode.isInitialized) return;
WAAPITransformMode.isInitialized = true;
function createParticule() {
const $el = document.createElement('div');
$el.classList.add('particle');
$el.classList.add(`color${(1 + (Math.random() * 2)).toFixed()}`);
$el[reversedSymbol] = !!utils.random(0, 1);
return $el;
}
function animateParticle($el, i) {
let delay = 0;
$el[reversedSymbol] = !$el[reversedSymbol];
if (!$el[startedSymbol]) {
$el[startedSymbol] = true;
delay = getBeginOffset(i);
}
let transform = ``;
if (config.x) transform += `translateX(${getRandomX($el)}px) `;
if (config.y) transform += `translateY(${getRandomY($el)}px) `;
if (config.rotation) transform += `rotate(${getRandomDeg()}deg) `;
if (config.scale) transform += `scale(${getRandomScale()}) `;
const anim = $el.animate({ transform }, {
delay,
duration,
easing: ease,
fill: 'forwards',
});
anim.onfinish = () => {
// $el.style.transform = transform;
// commitStyles() and cancel() have a huge impact on performance, but it simulates a real world usecase where you want to make sure the animations are properly removed
anim.commitStyles();
anim.cancel();
animateParticle($el, i);
}
}
WAAPITransformMode.cancel = () => {
const animations = document.getAnimations();
animations.forEach(animation => { animation.cancel() });
$particlesContainer.innerHTML = '';
}
WAAPITransformMode.refresh = () => {
maxScale = utils.clamp(WAAPITransformMode.maxCount / config.count, .125, 5);
for (let i = 0; i < config.count; i++) {
const $el = createParticule();
$particlesContainer.appendChild($el);
animateParticle($el, i);
}
}
WAAPITransformMode.resize = () => {
W = containerW;
H = containerH;
halfW = W * .5;
halfH = H * .5;
}
}
// WebGL Three.js mode
webglThreejsMode.init = () => {
if (webglThreejsMode.isInitialized) return;
webglThreejsMode.isInitialized = true;
class InstancedMeshProxy {
constructor(count) {
this.index = 0;
this._x = new Float32Array(count);
this._y = new Float32Array(count);
this._rotation = new Float32Array(count);
this._scale = new Float32Array(count);
this._started = new Int8Array(count);
this._reversed = new Int8Array(count);
}
set x(v) { this._x[this.index] = v; }
get x() { return this._x[this.index]; }
set y(v) { this._y[this.index] = v; }
get y() { return this._y[this.index]; }
set rotation(v) { this._rotation[this.index] = v; }
get rotation() { return this._rotation[this.index]; }
set scale(v) { this._scale[this.index] = v; }
get scale() { return this._scale[this.index]; }
set started(v) { this._started[this.index] = v; }
get started() { return this._started[this.index]; }
set reversed(v) { this._reversed[this.index] = v; }
get reversed() { return this._reversed[this.index]; }
}
const dummy = new Object3D();
const camera = new PerspectiveCamera(60, containerW / containerH, 1, 150);
camera.position.set(0, 0, -150);
camera.lookAt(0, 0, 0);
const geometry = new BoxGeometry(1, 1, 1);
// const geometry = new SphereGeometry(1, 6, 3);
const material = new MeshBasicMaterial();
const mesh = new InstancedMesh(geometry, material, webglThreejsMode.maxCount);
const meshProxy = new InstancedMeshProxy(webglThreejsMode.maxCount);
const scene = new Scene();
scene.add(mesh);
const renderer = new WebGLRenderer({
antialias: false,
powerPreference: 'high-performance',
});
renderer.setPixelRatio(1);
renderer.setSize(containerW, containerH);
const renderLoop = createTimer({
onUpdate: () => renderer.render(scene, camera),
autoplay: false,
});
const screenCoords = new Vector3();
const worldCoords = new Vector3();
const colors = [new Color('#FF4B4B'), new Color('#9F3A39'), new Color('#CF4242')];
function renderMesh(i) {
meshProxy.index = i;
dummy.position.set(meshProxy.x, meshProxy.y, 0);
const r = meshProxy.rotation;
dummy.rotation.set(r, r, r);
const s = meshProxy.scale;
dummy.scale.set(s, s, s);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
mesh.instanceMatrix.needsUpdate = true;
}
function animateParticle(i, l) {
meshProxy.index = i;
meshProxy.reversed = ~~!meshProxy.reversed;
let delay = 0;
const started = meshProxy.started;
if (!started) {
meshProxy.started = 1;
delay = getBeginOffset(i);
}
const params = {
composition: 'none', // Needed to avoid overiding proxy tweens
delay,
duration,
ease,
onRender: () => renderMesh(i),
onUpdate: () => meshProxy.index = i,
onComplete: self => {
animateParticle(i, l);
},
};
if (config.x) params.x = getRandomX(meshProxy);
if (config.y) params.y = getRandomY(meshProxy);
if (config.rotation) params.rotation = getRandomRad();
if (config.scale) params.scale = getRandomScale();
animate(meshProxy, params);
}
webglThreejsMode.cancel = () => {
for (let i = 0; i < webglThreejsMode.maxCount; i++) {
meshProxy.index = i;
meshProxy.x = 0;
meshProxy.y = 0;
meshProxy.rotation = 0;
meshProxy.scale = 0;
meshProxy.started = 0;
meshProxy.reversed = 0;
renderMesh(i);
}
utils.remove(meshProxy);
renderLoop.pause();
}
webglThreejsMode.refresh = () => {
if (!$particlesContainer.querySelector('canvas')) {
$particlesContainer.appendChild(renderer.domElement);
}
maxScale = utils.clamp(webglThreejsMode.maxCount / config.count, .25, 2);
for (let i = 0; i < config.count; i++) {
meshProxy.index = i;
meshProxy.scale = maxScale;
meshProxy.rotation = Math.PI * .2;
meshProxy.reversed = utils.random(0, 1);
mesh.setColorAt(i, utils.randomPick(colors));
animateParticle(i, config.count);
}
mesh.instanceColor.needsUpdate = true;
renderLoop.play();
}
webglThreejsMode.resize = () => {
camera.aspect = containerW / containerH;
camera.updateProjectionMatrix();
renderer.setSize(containerW, containerH);
screenCoords.set(2, 2, .5);
screenCoords.unproject(camera);
screenCoords.sub(camera.position).normalize();
worldCoords.copy(camera.position).add(screenCoords.multiplyScalar(-camera.position.z / screenCoords.z));
W = worldCoords.x;
H = worldCoords.y;
halfW = W * .5;
halfH = H * .5;
}
}
// Init and controls
function updateTweensCount() {
$activeTweens.textContent = `
${config.count * (~~config.x + ~~config.y + ~~config.rotation + ~~config.scale)}
`;
}
function updateUI() {
$configItems.forEach($item => {
if ($item.name === 'mode') {
$item.checked = $item.value === config[$item.name];
}
if ($item.name === 'count') {
$item.value = config.count;
}
if ($item.name === 'tween') {
$item.checked = config[$item.value];
}
});
updateTweensCount();
}
function restartActiveDemo() {
const activeMode = renderModes[config.mode];
activeMode.init();
activeMode.cancel();
activeMode.resize();
activeMode.refresh();
}
function activateMode(modeName) {
const selectedMode = renderModes[config.mode];
if (selectedMode && selectedMode.isInitialized) {
selectedMode.cancel();
}
config.mode = modeName;
const activeMode = renderModes[modeName];
if (config.count > activeMode.maxCount || config.count < activeMode.minCount) {
config.count = activeMode.defaultCount;
}
$countRange.setAttribute('min', activeMode.minCount);
$countRange.setAttribute('max', activeMode.maxCount);
$countRange.setAttribute('step', activeMode.step);
restartActiveDemo();
updateUI();
}
function updateUrl() {
for (let name in config) {
url.searchParams.set(name, config[name]);
}
window.history.replaceState(null, null, url);
}
function onLoad() {
activateMode(config.mode);
updateUI();
updateUrl();
}
function onConfigItemChange() {
if (this.name === 'mode') {
activateMode(this.value);
}
if (this.name === 'count') {
config.count = this.value;
renderModes[config.mode].cancel();
renderModes[config.mode].refresh();
updateUI();
}
if (this.name === 'tween') {
config[this.value] = this.checked;
updateTweensCount();
}
updateUrl();
resetAverageFps();
}
function onRangeInput() {
config.count = $countRange.value;
updateUrl();
updateUI();
}
function onResize() {
containerRect = $particlesContainer.getBoundingClientRect();
containerW = containerRect.width;
containerH = containerRect.height;
renderModes[config.mode].resize();
}
$configItems.forEach($item => $item.onchange = onConfigItemChange);
$countRange.oninput = onRangeInput;
$restartButton.onclick = restartActiveDemo;
window.onload = onLoad;
window.onresize = onResize;
// MONITOR
// Calculating FPS past requestAnimationFrame limit with requestIdleCallback
// https://www.clicktorelease.com/blog/calculating-fps-with-requestIdleCallback/
const $fps = document.getElementById('fps');
const $avg = document.getElementById('avg');
let t = Date.now();
let hasrICBeenCalledForThisFrame = null;
let frames = 0;
let rICFPS = 0;
let fps = 0;
let activateAverage = false;
let averageFPS = null;
let mixedFPS = 0;
let previousMixedFPS = 0;
let maxScreenRefreshRate = 60;
function fpsCallback(d) {
const goal = 1000 / maxScreenRefreshRate;
const elapsed = goal - d.timeRemaining();
rICFPS = goal * maxScreenRefreshRate / elapsed;
hasrICBeenCalledForThisFrame = true;
}
function updateFpsMeter(fps) {
$fps.value = fps.toFixed(2);
if (!activateAverage) return;
if (averageFPS === null) {
averageFPS = mixedFPS;
} else {
averageFPS += (previousMixedFPS - averageFPS) * .1;
}
previousMixedFPS = mixedFPS;
}
function updateAverageFpsMeter(fps) {
if (!activateAverage) return;
$avg.value = averageFPS.toFixed(2);
}
const reqIdleCallback = window.requestIdleCallback ? requestIdleCallback : () => {};
function updateFps() {
const dt = Date.now() - t;
if (dt > 1000) {
fps = frames * 1000 / dt;
frames = 0;
t = Date.now();
}
mixedFPS = hasrICBeenCalledForThisFrame ? rICFPS : fps;
hasrICBeenCalledForThisFrame = false;
requestAnimationFrame(updateFps);
reqIdleCallback(fpsCallback);
frames++;
}
updateFps();
setInterval(() => { updateFpsMeter(mixedFPS) }, 500);
setInterval(() => { updateAverageFpsMeter(mixedFPS) }, 2000);
function resetAverageFps() {
averageFPS = null;
activateAverage = false;
$avg.value = '00.00';
setTimeout(() => { activateAverage = true; }, 2000);
}
resetAverageFps();
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/threejs/instanced-mesh/index.js | tests/playground/threejs/instanced-mesh/index.js | import { animate, createTimer, createTimeline, utils, engine, stagger } from '../../../../dist/modules/index.js';
import {
Object3D,
Vector3,
Color,
PerspectiveCamera,
BoxGeometry,
SphereGeometry,
MeshPhongMaterial, // Changed from MeshBasicMaterial for light interaction
InstancedMesh,
AmbientLight,
DirectionalLight,
Scene,
WebGLRenderer,
Mesh,
PCFSoftShadowMap,
Matrix4,
Euler,
Quaternion,
MathUtils,
} from '../../../node_modules/three/build/three.module.min.js';
const { random, cos, sin, sqrt, PI } = Math;
const $particlesContainer = document.querySelector('#particles-container');
const count = 2500;
const duration = 3000;
const colors = [new Color('#FF4B4B'), new Color('#9F3A39'), new Color('#CF4242')];
let containerRect = $particlesContainer.getBoundingClientRect();
let containerW = containerRect.width;
let containerH = containerRect.height;
let W = 20;
let H = 10;
const target = { x: 0, y: 0, r: W * .25 };
class InstancedMeshProxy {
constructor(instancedMesh, initialIndex = 0) {
this._mesh = instancedMesh;
this._currentIndex = initialIndex;
this._matrix = new Matrix4();
this._position = new Vector3();
this._rotation = new Euler();
this._quaternion = new Quaternion();
this._scale = new Vector3(1, 1, 1);
this._dummyMatrix = new Matrix4();
this.theta = utils.random(0, 1, 5) * PI * 2;
this.radius = (W * .1) * sqrt(utils.random(0, 1, 5));
}
set index(value) {
if (value < 0 || value >= this._mesh.count) {
throw new Error(`Index ${value} is out of bounds for InstancedMesh with count ${this._mesh.count}`);
}
this._currentIndex = value;
this._mesh.getMatrixAt(this._currentIndex, this._dummyMatrix);
this._dummyMatrix.decompose(this._position, this._quaternion, this._scale);
this._rotation.setFromQuaternion(this._quaternion);
}
get index() {
return this._currentIndex;
}
set x(value) {
this._position.x = value;
this._updateMatrix();
}
set y(value) {
this._position.y = value;
this._updateMatrix();
}
set z(value) {
this._position.z = value;
this._updateMatrix();
}
get x() { return this._position.x; }
get y() { return this._position.y; }
get z() { return this._position.z; }
set rotateX(value) {
this._rotation.x = MathUtils.degToRad(value);
this._updateMatrix();
}
set rotateY(value) {
this._rotation.y = MathUtils.degToRad(value);
this._updateMatrix();
}
set rotateZ(value) {
this._rotation.z = MathUtils.degToRad(value);
this._updateMatrix();
}
get rotateX() { return MathUtils.radToDeg(this._rotation.x); }
get rotateY() { return MathUtils.radToDeg(this._rotation.y); }
get rotateZ() { return MathUtils.radToDeg(this._rotation.z); }
set scale(value) {
this._scale.set(value, value, value);
this._updateMatrix();
}
get scale() { return this._scale.x; }
_updateMatrix() {
this._quaternion.setFromEuler(this._rotation);
this._matrix.compose(this._position, this._quaternion, this._scale);
this._mesh.setMatrixAt(this._currentIndex, this._matrix);
this._mesh.instanceMatrix.needsUpdate = true;
}
}
const dummy = new Object3D();
const camera = new PerspectiveCamera(60, containerW / containerH, 1, 400);
camera.position.set(0, 0, -100);
camera.lookAt(0, 0, 0);
const geometry = new BoxGeometry(1, 1, 1);
const material = new MeshPhongMaterial({
color: 0xffffff,
shininess: 60,
specular: 0x004488,
});
const mesh = new InstancedMesh(geometry, material, count);
mesh.castShadow = true;
mesh.receiveShadow = true;
const meshProxy = new InstancedMeshProxy(mesh);
const meshes = [];
for (let i = 0; i < count; i++) {
meshes.push(new InstancedMeshProxy(mesh, i));
}
// Create ground plane to receive shadows
const groundGeometry = new BoxGeometry(200, 200, 1);
const groundMaterial = new MeshPhongMaterial({ color: 0x808080 });
const ground = new Mesh(groundGeometry, groundMaterial);
ground.rotation.x = Math.PI / 2;
ground.position.y = -50;
ground.receiveShadow = true;
const scene = new Scene();
scene.add(mesh);
scene.add(ground);
// Add lighting
const ambientLight = new AmbientLight(0x404040, 0.5);
scene.add(ambientLight);
// Add main directional light with shadow
const mainLight = new DirectionalLight(0xffffff, 1);
mainLight.position.set(50, 50, 50);
mainLight.castShadow = true;
mainLight.shadow.camera.near = 1;
mainLight.shadow.camera.far = 200;
mainLight.shadow.camera.left = -50;
mainLight.shadow.camera.right = 50;
mainLight.shadow.camera.top = 50;
mainLight.shadow.camera.bottom = -50;
mainLight.shadow.mapSize.width = 2048;
mainLight.shadow.mapSize.height = 2048;
mainLight.shadow.bias = -0.001;
scene.add(mainLight);
// Add fill light
const fillLight = new DirectionalLight(0x8080ff, 0.5);
fillLight.position.set(-50, 20, -50);
scene.add(fillLight);
const renderer = new WebGLRenderer({
antialias: false, // Enabled antialiasing for better quality
powerPreference: 'high-performance',
});
// renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(containerW, containerH);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = PCFSoftShadowMap;
$particlesContainer.appendChild(renderer.domElement);
const renderLoop = createTimer({
onUpdate: () => {
renderer.render(scene, camera);
},
autoplay: false
});
const screenCoords = new Vector3();
const worldCoords = new Vector3();
// animate(meshes, {
// x: () => utils.random(-100, 100),
// y: () => utils.random(-100, 100),
// z: () => utils.random(-100, 100),
// rotateX: () => utils.random(-180, 180),
// rotateY: () => utils.random(-180, 180),
// rotateZ: () => utils.random(-180, 180),
// scale: () => utils.random(1, 3, 2),
// loop: true,
// duration: 5000,
// delay: stagger([0, count]),
// onLoop: self => self.refresh().restart()
// })
const tl = createTimeline({
defaults: {
loop: true,
ease: 'inOut(1.3)',
onLoop: self => self.refresh(),
},
});
tl.add(meshes, {
x: m => target.x + (m.radius * cos(m.theta)),
y: m => target.y + (m.radius * sin(m.theta)),
duration: () => duration + utils.random(-100, 100),
ease: 'inOut(1.5)',
onLoop: self => {
const t = self.targets[0];
// t.theta = random() * PI * 2;
// t.radius = target.r * sqrt(random());
self.refresh();
},
}, stagger((duration / count) * 1.125))
.add(target, {
r: () => W * utils.random(.05, .5, 2),
duration: 1250,
}, 0)
.add(target, {
x: () => utils.random(-W * .1, W * .1),
modifier: x => x + sin(tl.currentTime * .0007) * (W * .1),
duration: 2800,
}, 0)
.add(target, {
y: () => utils.random(-H * .1, H * .1),
modifier: y => y + cos(tl.currentTime * .00012) * (H * .1),
duration: 1800,
}, 0)
.add(target, {
z: () => utils.random(-W * .1, W * .1),
modifier: x => x + sin(tl.currentTime * .0007) * (W * .1),
duration: 2800,
}, 0)
renderLoop.play();
function onResize() {
containerRect = $particlesContainer.getBoundingClientRect();
containerW = containerRect.width;
containerH = containerRect.height;
camera.aspect = containerW / containerH;
camera.updateProjectionMatrix();
renderer.setSize(containerW, containerH);
screenCoords.set(2, 2, .5);
screenCoords.unproject(camera);
screenCoords.sub(camera.position).normalize();
worldCoords.copy(camera.position).add(screenCoords.multiplyScalar(-camera.position.z / screenCoords.z));
W = worldCoords.x;
H = worldCoords.y;
}
onResize();
window.onresize = onResize; | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/threejs/instanced-mesh/InstancedMeshProxy.js | tests/playground/threejs/instanced-mesh/InstancedMeshProxy.js | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false | |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/tl-seek-test/index.js | tests/playground/tl-seek-test/index.js | import {
createTimeline,
stagger,
utils,
} from '../../../dist/modules/index.js';
const count = 2000;
const tl = createTimeline({
autoplay: false,
});
for (let i = 0; i < count; i++) {
const $el = document.createElement('div');
const hue = Math.round(360 / count * i);
$el.style.opacity = '.5';
$el.style.backgroundColor = `hsl(${hue}, 60%, 60%)`;
document.body.appendChild($el);
tl.add($el, {
opacity: 0,
scale: 2,
duration: 100,
})
}
/**
* @param {MouseEvent} e [description]
*/
window.onmousemove = (e) => {
tl.progress = e.clientX / window.innerWidth;
} | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/keyframes/index.js | tests/playground/keyframes/index.js | import {
animate,
} from '../../../dist/modules/index.js';
const easeOut = 'cubicBezier(0, 0, 0.58, 1)';
const easeIn = 'cubicBezier(0.42, 0, 1, 1)';
// const easeOut = 'out(1.64)';
// const easeIn = 'in(1.64)';
// const easeOut = 'out';
// const easeIn = 'in';
const $css = document.querySelector('.css').classList.add('is-animated');
document.querySelector('.waapi').animate([
{ offset: 0, left: '0rem', top: '0rem' },
{ offset: .3, left: '0rem', top: '-2.5rem', rotate: '45deg', easing: 'ease-out' },
{ offset: .4, left: '17rem', top: '-2.5rem' },
{ offset: .5, left: '17rem', top: '2.5rem', rotate: '90deg' },
{ offset: .7, left: '0rem', top: '2.5rem' },
{ offset: 1, left: '0rem', top: '0rem', rotate: '180deg', easing: 'ease-out' },
], {
duration: 4000,
easing: 'linear',
fill: 'forwards',
iterations: Infinity,
});
animate('.anime', {
keyframes: {
'0%' : { x: '0rem', y: '0rem' },
'30%' : { x: '0rem', y: '-2.5rem', rotate: 45, ease: easeOut },
'40%' : { x: '17rem', y: '-2.5rem' },
'50%' : { x: '17rem', y: '2.5rem', rotate: 90 },
'70%' : { x: '0rem', y: '2.5rem' },
'100%': { x: '0rem', y: '0rem', rotate: 180, ease: easeOut }
},
duration: 4000, // the duration is devided by the total number of keyframes (4000 / 5 = 800)
// ease: 'inOut', // this ease is applied to all keyframes without an ease parameter defined
ease: 'linear',
loop: true,
}); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/timekeeper/index.js | tests/playground/timekeeper/index.js | import {
utils,
createScope,
createTimeline,
stagger
} from '../../../dist/modules/index.js';
createScope({
mediaQueries: { minM: '(min-width: 800px)' }
}).add(self => {
self.keepTime(scope => {
const isMinM = scope.matches.minM;
document.body.classList.toggle('is-min-m', isMinM);
return createTimeline().add('.square', {
x: isMinM ? 0 : [-50, 50],
y: isMinM ? [-50, 50] : 0,
rotate: -90,
scale: .75,
alternate: true,
loop: true,
ease: 'inOutQuad',
mediaQueries: { minM: '(min-width: 800px)' }
}).add(self => {
self.preserve(timekeeper);
}); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/assets/js/anime.esm.js | tests/playground/assets/js/anime.esm.js | /**
* anime.js - ESM
* @version v4.0.0-beta.102.1
* @author Julian Garnier
* @license MIT
* @copyright (c) 2024 Julian Garnier
* @see https://animejs.com
*/
/** @typedef {Animation} $Animation */
/** @typedef {Animatable} $Animatable */
/** @typedef {$Animation|Timeline} Renderable */
/** @typedef {Timer|Renderable} Tickable */
/** @typedef {Tickable|$Animatable|Draggable|ScrollObserver|Scope} Revertible */
/**
* @callback EasingFunction
* @param {Number} time
* @return {Number}
*/
/**
* @typedef {('linear'|'linear(x1, x2 25%, x3)'|'in'|'out'|'inOut'|'outIn'|'inQuad'|'outQuad'|'inOutQuad'|'outInQuad'|'inCubic'|'outCubic'|'inOutCubic'|'outInCubic'|'inQuart'|'outQuart'|'inOutQuart'|'outInQuart'|'inQuint'|'outQuint'|'inOutQuint'|'outInQuint'|'inSine'|'outSine'|'inOutSine'|'outInSine'|'inCirc'|'outCirc'|'inOutCirc'|'outInCirc'|'inExpo'|'outExpo'|'inOutExpo'|'outInExpo'|'inBounce'|'outBounce'|'inOutBounce'|'outInBounce'|'inBack'|'outBack'|'inOutBack'|'outInBack'|'inElastic'|'outElastic'|'inOutElastic'|'outInElastic'|'irregular'|'cubicBezier'|'steps'|'in(p = 1.675)'|'out(p = 1.675)'|'inOut(p = 1.675)'|'outIn(p = 1.675)'|'inBack(overshoot = 1.70158)'|'outBack(overshoot = 1.70158)'|'inOutBack(overshoot = 1.70158)'|'outInBack(overshoot = 1.70158)'|'inElastic(amplitude = 1, period = .3)'|'outElastic(amplitude = 1, period = .3)'|'inOutElastic(amplitude = 1, period = .3)'|'outInElastic(amplitude = 1, period = .3)'|'irregular(length = 10, randomness = 1)'|'cubicBezier(x1, y1, x2, y2)'|'steps(steps = 10)')} EaseStringParamNames
*/
// A hack to get both ease names suggestions AND allow any strings
// https://github.com/microsoft/TypeScript/issues/29729#issuecomment-460346421
/** @typedef {(String & {})|EaseStringParamNames|EasingFunction|Spring} EasingParam */
/** @typedef {HTMLElement|SVGElement} DOMTarget */
/** @typedef {Record<String, any>} JSTarget */
/** @typedef {DOMTarget|JSTarget} Target */
/** @typedef {Target|NodeList|String} TargetSelector */
/** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */
/** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */
/** @typedef {Array.<DOMTarget>} DOMTargetsArray */
/** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */
/** @typedef {Array.<JSTarget>} JSTargetsArray */
/** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */
/** @typedef {Array.<Target>} TargetsArray */
/**
* @callback FunctionValue
* @param {Target} target - The animated target
* @param {Number} index - The target index
* @param {Number} length - The total number of animated targets
* @return {Number|String|TweenObjectValue|Array.<Number|String|TweenObjectValue>}
*/
/**
* @callback TweenModifier
* @param {Number} value - The animated value
* @return {Number|String}
*/
/** @typedef {[Number, Number, Number, Number]} ColorArray */
/**
* @typedef {Object} Tween
* @property {Number} id
* @property {Animation} parent
* @property {String} property
* @property {Target} target
* @property {String|Number} _value
* @property {Function|null} _func
* @property {EasingFunction} _ease
* @property {Array.<Number>} _fromNumbers
* @property {Array.<Number>} _toNumbers
* @property {Array.<String>} _strings
* @property {Number} _fromNumber
* @property {Number} _toNumber
* @property {Array.<Number>} _numbers
* @property {Number} _number
* @property {String} _unit
* @property {TweenModifier} _modifier
* @property {Number} _currentTime
* @property {Number} _delay
* @property {Number} _updateDuration
* @property {Number} _startTime
* @property {Number} _changeDuration
* @property {Number} _absoluteStartTime
* @property {tweenTypes} _tweenType
* @property {valueTypes} _valueType
* @property {Number} _composition
* @property {Number} _isOverlapped
* @property {Number} _isOverridden
* @property {Number} _renderTransforms
* @property {Tween} _prevRep
* @property {Tween} _nextRep
* @property {Tween} _prevAdd
* @property {Tween} _nextAdd
* @property {Tween} _prev
* @property {Tween} _next
*/
/**
* @typedef TweenDecomposedValue
* @property {Number} t - Type
* @property {Number} n - Single number value
* @property {String} u - Value unit
* @property {String} o - Value operator
* @property {Array.<Number>} d - Array of Numbers (in case of complex value type)
* @property {Array.<String>} s - Strings (in case of complex value type)
*/
/** @typedef {{_head: null|Tween, _tail: null|Tween}} TweenPropertySiblings */
/** @typedef {Record<String, TweenPropertySiblings>} TweenLookups */
/** @typedef {WeakMap.<Target, TweenLookups>} TweenReplaceLookups */
/** @typedef {Map.<Target, TweenLookups>} TweenAdditiveLookups */
/**
* @typedef {Object} TimerOptions
* @property {Number|String} [id]
* @property {TweenParamValue} [duration]
* @property {TweenParamValue} [delay]
* @property {Number} [loopDelay]
* @property {Boolean} [reversed]
* @property {Boolean} [alternate]
* @property {Boolean|Number} [loop]
* @property {Boolean|ScrollObserver} [autoplay]
* @property {Number} [frameRate]
* @property {Number} [playbackRate]
*/
/**
* @callback TimerCallback
* @param {Timer} self - Returns itself
* @return *
*/
/**
* @typedef {Object} TimerCallbacks
* @property {TimerCallback} [onComplete]
* @property {TimerCallback} [onLoop]
* @property {TimerCallback} [onBegin]
* @property {TimerCallback} [onUpdate]
*/
/**
* @typedef {TimerOptions & TimerCallbacks} TimerParams
*/
/**
* @typedef {Number|String|FunctionValue} TweenParamValue
*/
/**
* @typedef {TweenParamValue|[TweenParamValue, TweenParamValue]} TweenPropValue
*/
/**
* @typedef {'none'|'replace'|'blend'|compositionTypes} TweenComposition
*/
/**
* @typedef {Object} TweenParamsOptions
* @property {TweenParamValue} [duration]
* @property {TweenParamValue} [delay]
* @property {EasingParam} [ease]
* @property {TweenModifier} [modifier]
* @property {TweenComposition} [composition]
*/
/**
* @typedef {Object} TweenValues
* @property {TweenParamValue} [from]
* @property {TweenPropValue} [to]
* @property {TweenPropValue} [fromTo]
*/
/**
* @typedef {TweenParamsOptions & TweenValues} TweenKeyValue
*/
/**
* @typedef {Array.<TweenKeyValue|TweenPropValue>} ArraySyntaxValue
*/
/**
* @typedef {TweenParamValue|ArraySyntaxValue|TweenKeyValue} TweenOptions
*/
/**
* @typedef {Partial<{to: TweenParamValue|Array.<TweenParamValue>; from: TweenParamValue|Array.<TweenParamValue>; fromTo: TweenParamValue|Array.<TweenParamValue>;}>} TweenObjectValue
*/
/**
* @typedef {Object} PercentageKeyframeOptions
* @property {EasingParam} [ease]
*/
/**
* @typedef {Record<String, TweenParamValue>} PercentageKeyframeParams
*/
/**
* @typedef {Record<String, PercentageKeyframeParams & PercentageKeyframeOptions>} PercentageKeyframes
*/
/**
* @typedef {Array<Record<String, TweenOptions | TweenModifier | boolean> & TweenParamsOptions>} DurationKeyframes
*/
/**
* @typedef {Object} AnimationOptions
* @property {PercentageKeyframes|DurationKeyframes} [keyframes]
* @property {EasingParam} [playbackEase]
*/
/**
* @callback AnimationCallback
* @param {Animation} self - Returns itself
* @return *
*/
/**
* @typedef {Object} AnimationCallbacks
* @property {AnimationCallback} [onComplete]
* @property {AnimationCallback} [onLoop]
* @property {AnimationCallback} [onRender]
* @property {AnimationCallback} [onBegin]
* @property {AnimationCallback} [onUpdate]
*/
// TODO: Currently setting TweenModifier to the intersected Record<> makes the FunctionValue type target param any if only one parameter is set
/**
* @typedef {Record<String, TweenOptions | AnimationCallback | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & AnimationCallbacks} AnimationParams
*/
/**
* @typedef {TimerOptions & AnimationOptions & TweenParamsOptions & TimerCallbacks & AnimationCallbacks & TimelineCallbacks} DefaultsParams
*/
/**
* @typedef {Object} TimelineOptions
* @property {DefaultsParams} [defaults]
* @property {EasingParam} [playbackEase]
*/
/**
* @callback TimelineCallback
* @param {Timeline} self - Returns itself
* @return {*}
*/
/**
* @typedef {Object} TimelineCallbacks
* @property {TimelineCallback} [onComplete]
* @property {TimelineCallback} [onLoop]
* @property {TimelineCallback} [onRender]
* @property {TimelineCallback} [onBegin]
* @property {TimelineCallback} [onUpdate]
*/
/**
* @typedef {TimerOptions & TimelineOptions & TimelineCallbacks} TimelineParams
*/
/**
* @typedef {Object} ScopeParams
* @property {DOMTargetSelector} [root]
* @property {DefaultsParams} [defaults]
* @property {Record<String, String>} [mediaQueries]
*/
/**
* @callback AnimatablePropertySetter
* @param {Number|Array.<Number>} to
* @param {Number} [duration]
* @param {EasingParam} [ease]
* @return {AnimatableObject}
*/
/**
* @callback AnimatablePropertyGetter
* @return {Number|Array.<Number>}
*/
/**
* @typedef {AnimatablePropertySetter & AnimatablePropertyGetter} AnimatableProperty
*/
/**
* @typedef {Animatable & Record<String, AnimatableProperty>} AnimatableObject
*/
/**
* @typedef {Object} AnimatablePropertyParamsOptions
* @property {String} [unit]
* @property {TweenParamValue} [duration]
* @property {EasingParam} [ease]
* @property {TweenModifier} [modifier]
* @property {TweenComposition} [composition]
*/
/**
* @typedef {Record<String, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions} AnimatableParams
*/
// Environments
// TODO: Do we need to check if we're running inside a worker ?
const isBrowser = typeof window !== 'undefined';
/** @type {Object|Null} */
const win = isBrowser ? window : null;
/** @type {Document} */
const doc = isBrowser ? document : null;
// Enums
/** @enum {Number} */
const tweenTypes = {
INVALID: 0,
OBJECT: 1,
ATTRIBUTE: 2,
CSS: 3,
TRANSFORM: 4,
CSS_VAR: 5,
};
/** @enum {Number} */
const valueTypes = {
NUMBER: 0,
UNIT: 1,
COLOR: 2,
COMPLEX: 3,
};
/** @enum {Number} */
const tickModes = {
NONE: 0,
AUTO: 1,
FORCE: 2,
};
/** @enum {Number} */
const compositionTypes = {
replace: 0,
none: 1,
blend: 2,
};
// Cache symbols
const isRegisteredTargetSymbol = Symbol();
const isDomSymbol = Symbol();
const isSvgSymbol = Symbol();
const transformsSymbol = Symbol();
const morphPointsSymbol = Symbol();
const draggableSymbol = Symbol();
const proxyTargetSymbol = Symbol();
// Numbers
const minValue = 1e-11;
const maxValue = 1e12;
const K = 1e3;
const maxFps = 120;
// Strings
const emptyString = '';
const shortTransforms = new Map();
shortTransforms.set('x', 'translateX');
shortTransforms.set('y', 'translateY');
shortTransforms.set('z', 'translateZ');
const validTransforms = [
'translateX',
'translateY',
'translateZ',
'rotate',
'rotateX',
'rotateY',
'rotateZ',
'scale',
'scaleX',
'scaleY',
'scaleZ',
'skew',
'skewX',
'skewY',
'perspective',
'matrix',
'matrix3d',
];
const transformsFragmentStrings = validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {});
// Functions
/** @return {void} */
const noop = () => {};
// Regex
const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;
const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;
const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;
const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
// export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g;
const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;
// export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i;
const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;
const lowerCaseRgx = /([a-z])([A-Z])/g;
const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in ()
const relativeValuesExecRgx = /(\*=|\+=|-=)/;
/** @type {DefaultsParams} */
const defaults = {
/** @type {Number|String} */
id: null,
/** @type {PercentageKeyframes|DurationKeyframes} */
keyframes: null,
playbackEase: null,
playbackRate: 1,
frameRate: maxFps,
/** @type {Number|Boolean} */
loop: 0,
reversed: false,
alternate: false,
autoplay: true,
duration: K,
delay: 0,
loopDelay: 0,
/** @type {EasingParam} */
ease: 'outQuad',
/** @type {'none'|'replace'|'blend'|compositionTypes} */
composition: compositionTypes.replace,
/** @type {TweenModifier} */
modifier: v => v,
onBegin: noop,
onUpdate: noop,
onRender: noop,
onLoop: noop,
onComplete: noop,
};
const globals = {
/** @type {DefaultsParams} */
defaults,
/** @type {Document|DOMTarget} */
root: doc,
/** @type {Scope} */
scope: null,
precision: 4,
timeScale: 1,
tickThreshold: 200,
};
// Strings
/**
* @param {String} str
* @return {String}
*/
const toLowerCase = str => str.replace(lowerCaseRgx, '$1-$2').toLowerCase();
/**
* Prioritize this method instead of regex when possible
* @param {String} str
* @param {String} sub
* @return {Boolean}
*/
const stringStartsWith = (str, sub) => str.indexOf(sub) === 0;
// Time
// Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement.
const now = Date.now;
// Types checkers
const isArr = Array.isArray;
/**@param {any} a @return {a is Record<String, any>} */
const isObj = a => a && a.constructor === Object;
/**@param {any} a @return {a is Number} */
const isNum = a => typeof a === 'number' && !isNaN(a);
/**@param {any} a @return {a is String} */
const isStr = a => typeof a === 'string';
/**@param {any} a @return {a is Function} */
const isFnc = a => typeof a === 'function';
/**@param {any} a @return {a is undefined} */
const isUnd = a => typeof a === 'undefined';
/**@param {any} a @return {a is null | undefined} */
const isNil = a => isUnd(a) || a === null;
/**@param {any} a @return {a is SVGElement} */
const isSvg = a => isBrowser && a instanceof SVGElement;
/**@param {any} a @return {Boolean} */
const isHex = a => hexTestRgx.test(a);
/**@param {any} a @return {Boolean} */
const isRgb = a => stringStartsWith(a, 'rgb');
/**@param {any} a @return {Boolean} */
const isHsl = a => stringStartsWith(a, 'hsl');
/**@param {any} a @return {Boolean} */
const isCol = a => isHex(a) || isRgb(a) || isHsl(a);
/**@param {any} a @return {Boolean} */
const isKey = a => !globals.defaults.hasOwnProperty(a);
// Number
/**
* @param {Number|String} str
* @return {Number}
*/
const parseNumber = str => isStr(str) ?
parseFloat(/** @type {String} */(str)) :
/** @type {Number} */(str);
// Math
const pow = Math.pow;
const sqrt = Math.sqrt;
const sin = Math.sin;
const cos = Math.cos;
const abs = Math.abs;
const exp = Math.exp;
const ceil = Math.ceil;
const floor = Math.floor;
const asin = Math.asin;
const max = Math.max;
const atan2 = Math.atan2;
const PI = Math.PI;
const _round = Math.round;
/**
* @param {Number} v
* @param {Number} min
* @param {Number} max
* @return {Number}
*/
const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
/**
* @param {Number} v
* @param {Number} decimalLength
* @return {Number}
*/
const round = (v, decimalLength) => {
if (decimalLength < 0) return v;
const m = 10 ** decimalLength;
return _round(v * m) / m;
};
/**
* @param {Number} v
* @param {Number|Array<Number>} increment
* @return {Number}
*/
const snap = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
/**
* @param {Number} start
* @param {Number} end
* @param {Number} progress
* @return {Number}
*/
const interpolate = (start, end, progress) => start + (end - start) * progress;
/**
* @param {Number} v
* @return {Number}
*/
const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v;
/**
* @param {Number} v
* @return {Number}
*/
const clampZero = v => v < minValue ? minValue : v;
// Arrays
/**
* @template T
* @param {T[]} a
* @return {T[]}
*/
const cloneArray = a => isArr(a) ? [ ...a ] : a;
// Objects
/**
* @template T
* @template U
* @param {T} o1
* @param {U} o2
* @return {T & U}
*/
const mergeObjects = (o1, o2) => {
const merged = /** @type {T & U} */({ ...o1 });
for (let p in o2) {
const o1p = /** @type {T & U} */(o1)[p];
merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p;
} return merged;
};
// Linked lists
/**
* @param {Object} parent
* @param {Function} callback
* @param {Boolean} [reverse]
* @param {String} [prevProp]
* @param {String} [nextProp]
* @return {void}
*/
const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => {
let next = parent._head;
let adjustedNextProp = nextProp;
if (reverse) {
next = parent._tail;
adjustedNextProp = prevProp;
}
while (next) {
const currentNext = next[adjustedNextProp];
callback(next);
next = currentNext;
}
};
/**
* @param {Object} parent
* @param {Object} child
* @param {String} [prevProp]
* @param {String} [nextProp]
* @return {void}
*/
const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => {
const prev = child[prevProp];
const next = child[nextProp];
prev ? prev[nextProp] = next : parent._head = next;
next ? next[prevProp] = prev : parent._tail = prev;
child[prevProp] = null;
child[nextProp] = null;
};
/**
* @param {Object} parent
* @param {Object} child
* @param {Function} [sortMethod]
* @param {String} prevProp
* @param {String} nextProp
* @return {void}
*/
const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => {
let prev = parent._tail;
while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp];
const next = prev ? prev[nextProp] : parent._head;
prev ? prev[nextProp] = child : parent._head = child;
next ? next[prevProp] = child : parent._tail = child;
child[prevProp] = prev;
child[nextProp] = next;
};
/*
* Base class to control framerate and playback rate.
* Inherited by Engine, Timer, Animation and Timeline.
*/
class Clock {
constructor() {
/** @type {Number} */
this.currentTime = 0;
/** @type {Number} */
this.deltaTime = 0;
/** @type {Number} */
this._elapsedTime = 0;
/** @type {Number} */
this._startTime = 0;
/** @type {Number} */
this._lastTime = 0;
/** @type {Number} */
this._scheduledTime = 0;
/** @type {Number} */
this._frameDuration = K / maxFps;
/** @type {Number} */
this._fps = maxFps;
/** @type {Number} */
this._speed = 1;
/** @type {Boolean} */
this._hasChildren = false;
}
get frameRate() {
return this._fps;
}
set frameRate(frameRate) {
const previousFrameDuration = this._frameDuration;
const fr = +frameRate;
const fps = fr < minValue ? minValue : fr;
const frameDuration = K / fps;
this._fps = fps;
this._frameDuration = frameDuration;
this._scheduledTime += frameDuration - previousFrameDuration;
}
get playbackRate() {
return this._speed;
}
set playbackRate(playbackRate) {
const pbr = +playbackRate;
this._speed = pbr < minValue ? minValue : pbr;
}
/**
* @param {Number} time
* @return {tickModes}
*/
requestTick(time) {
const scheduledTime = this._scheduledTime;
const elapsedTime = this._elapsedTime;
this._elapsedTime += (time - elapsedTime);
// If the elapsed time is lower than the scheduled time
// this means not enough time has passed to hit one frameDuration
// so skip that frame
if (elapsedTime < scheduledTime) return tickModes.NONE;
const frameDuration = this._frameDuration;
const frameDelta = elapsedTime - scheduledTime;
// Ensures that _scheduledTime progresses in steps of at least 1 frameDuration.
// Skips ahead if the actual elapsed time is higher.
this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta;
return tickModes.AUTO;
}
/**
* @param {Number} time
* @return {Number}
*/
computeDeltaTime(time) {
const delta = time - this._lastTime;
this.deltaTime = delta;
this._lastTime = time;
return delta;
}
}
/**
* @param {Tickable} tickable
* @param {Number} time
* @param {Number} muteCallbacks
* @param {Number} internalRender
* @param {tickModes} tickMode
* @return {Number}
*/
const render = (tickable, time, muteCallbacks, internalRender, tickMode) => {
const duration = tickable.duration;
const currentTime = tickable.currentTime;
const _currentIteration = tickable._currentIteration;
const _iterationDuration = tickable._iterationDuration;
const _iterationCount = tickable._iterationCount;
const _loopDelay = tickable._loopDelay;
const _reversed = tickable.reversed;
const _alternate = tickable._alternate;
const _hasChildren = tickable._hasChildren;
const updateStartTime = tickable._delay;
const updateEndTime = updateStartTime + _iterationDuration;
const tickableTime = clamp(time - updateStartTime, -updateStartTime, duration);
const deltaTime = tickableTime - currentTime;
const isOverTime = tickableTime >= duration;
const forceTick = tickMode === tickModes.FORCE;
const autoTick = tickMode === tickModes.AUTO;
// Time has jumped more than 200ms so consider this tick manual
// NOTE: the manual abs is faster than Math.abs()
const isManual = forceTick || (deltaTime < 0 ? deltaTime * -1 : deltaTime) >= globals.tickThreshold;
let hasBegun = tickable.began;
let isOdd = 0;
let iterationElapsedTime = tickableTime;
// Execute the "expensive" iterations calculations only when necessary
if (_iterationCount > 1) {
// bitwise NOT operator seems to be generally faster than Math.floor() across browsers
const currentIteration = ~~(tickableTime / (_iterationDuration + (isOverTime ? 0 : _loopDelay)));
tickable._currentIteration = clamp(currentIteration, 0, _iterationCount);
// Prevent the iteration count to go above the max iterations when reaching the end of the animation
if (isOverTime) {
tickable._currentIteration--;
}
isOdd = tickable._currentIteration % 2;
iterationElapsedTime = tickableTime % (_iterationDuration + _loopDelay);
}
// Checks if exactly one of _reversed and (_alternate && isOdd) is true
const isReversed = _reversed ^ (_alternate && isOdd);
const _ease = /** @type {Renderable} */(tickable)._ease;
let iterationTime = isOverTime ? isReversed ? 0 : duration : isReversed ? _iterationDuration - iterationElapsedTime : iterationElapsedTime;
if (_ease) {
iterationTime =_iterationDuration * _ease(iterationTime / _iterationDuration) || 0;
}
const isRunningBackwards = iterationTime < tickable._iterationTime;
const seekMode = isManual ? isRunningBackwards ? 2 : 1 : 0; // 0 = automatic, 1 = manual forward, 2 = manual backward
const precision = globals.precision;
tickable._iterationTime = iterationTime;
tickable._backwards = isRunningBackwards && !isReversed;
if (!muteCallbacks && !hasBegun && tickableTime > 0) {
hasBegun = tickable.began = true;
tickable.onBegin(tickable);
}
// Update animation.currentTime only after the children have been updated to prevent wrong seek direction calculatiaon
tickable.currentTime = tickableTime;
// Render checks
// Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer
let hasRendered = 0;
if (hasBegun && tickable._currentIteration !== _currentIteration) {
if (!muteCallbacks) tickable.onLoop(tickable);
// Reset all children on loop to get the callbacks working and initial proeprties properly set on each iteration
if (_hasChildren) {
forEachChildren(tickable, (/** @type {$Animation} */child) => child.reset(), true);
}
}
if (
forceTick ||
autoTick && (
time >= updateStartTime && time <= updateEndTime || // Normal render
time <= updateStartTime && currentTime > 0 || // Playhead is before the animation start time so make sure the animation is at its initial state
time >= updateEndTime && currentTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state
) ||
iterationTime >= updateEndTime && currentTime !== duration ||
iterationTime <= updateStartTime && currentTime > 0 ||
time <= currentTime && currentTime === duration && tickable.completed // Force a render if a seek occurs on an completed animation
) {
if (hasBegun) {
// Trigger onUpdate callback before rendering
tickable.computeDeltaTime(currentTime);
if (!muteCallbacks) tickable.onUpdate(tickable);
}
// Start tweens rendering
if (!_hasChildren) {
// Only Animtion can have tweens, Timer returns undefined
let tween = /** @type {Tween} */(/** @type {$Animation} */(tickable)._head);
let tweenTarget;
let tweenStyle;
let tweenTargetTransforms;
let tweenTargetTransformsProperties;
let tweenTransformsNeedUpdate = 0;
// const absoluteTime = tickable._offset + updateStartTime + iterationTime;
// TODO: Check if tickable._offset can be replaced by the absoluteTime value to avoid avinf to compute it in the render loop
const parent = tickable.parent;
const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + updateStartTime + iterationTime;
while (tween) {
const tweenComposition = tween._composition;
const tweenCurrentTime = tween._currentTime;
const tweenChangeDuration = tween._changeDuration;
const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration;
const tweenNextRep = tween._nextRep;
const tweenPrevRep = tween._prevRep;
const tweenHasComposition = tweenComposition !== compositionTypes.none;
if ((seekMode || (
(tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) &&
(tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime)
)) && (!tweenHasComposition || (
!tween._isOverridden &&
(!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) &&
(!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) &&
(!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay)))
))
) {
const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration);
const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration);
const tweenModifier = tween._modifier;
const tweenValueType = tween._valueType;
const tweenType = tween._tweenType;
const tweenIsObject = tweenType === tweenTypes.OBJECT;
const tweenIsNumber = tweenValueType === valueTypes.NUMBER;
// Skip rounding for number values on property object
// Otherwise if the final value is a string, round the in-between frames values
const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : precision;
// Recompose tween value
/** @type {String|Number} */
let value;
/** @type {Number} */
let number;
if (tweenIsNumber) {
value = number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
} else if (tweenValueType === valueTypes.UNIT) {
// Rounding the values speed up string composition
number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
value = `${number}${tween._unit}`;
} else if (tweenValueType === valueTypes.COLOR) {
const fn = tween._fromNumbers;
const tn = tween._toNumbers;
const r = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[0], tn[0], tweenProgress))), 0, 255), 0);
const g = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[1], tn[1], tweenProgress))), 0, 255), 0);
const b = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[2], tn[2], tweenProgress))), 0, 255), 0);
const a = clamp(/** @type {Number} */(tweenModifier(round(interpolate(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1);
value = `rgba(${r},${g},${b},${a})`;
if (tweenHasComposition) {
const ns = tween._numbers;
ns[0] = r;
ns[1] = g;
ns[2] = b;
ns[3] = a;
}
} else if (tweenValueType === valueTypes.COMPLEX) {
value = tween._strings[0];
for (let j = 0, l = tween._toNumbers.length; j < l; j++) {
const n = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision)));
const s = tween._strings[j + 1];
value += `${s ? n + s : n}`;
if (tweenHasComposition) {
tween._numbers[j] = n;
}
}
}
// For additive tweens and Animatables
if (tweenHasComposition) {
tween._number = number;
}
if (!internalRender && tweenComposition !== compositionTypes.blend) {
const tweenProperty = tween.property;
tweenTarget = tween.target;
if (tweenIsObject) {
tweenTarget[tweenProperty] = value;
} else if (tweenType === tweenTypes.ATTRIBUTE) {
/** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value));
} else {
tweenStyle = /** @type {DOMTarget} */(tweenTarget).style;
if (tweenType === tweenTypes.TRANSFORM) {
if (tweenTarget !== tweenTargetTransforms) {
tweenTargetTransforms = tweenTarget;
// NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage.
tweenTargetTransformsProperties = tweenTarget[transformsSymbol];
}
tweenTargetTransformsProperties[tweenProperty] = value;
tweenTransformsNeedUpdate = 1;
} else if (tweenType === tweenTypes.CSS) {
tweenStyle[tweenProperty] = value;
} else if (tweenType === tweenTypes.CSS_VAR) {
tweenStyle.setProperty(tweenProperty,/** @type {String} */(value));
}
}
if (hasBegun) hasRendered = 1;
} else {
// Used for composing timeline tweens without having to do a real render
tween._value = value;
}
}
// NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax
// to reduce memory usage on string composition
if (tweenTransformsNeedUpdate && tween._renderTransforms) {
let str = emptyString;
for (let key in tweenTargetTransformsProperties) {
str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `;
}
tweenStyle.transform = str;
tweenTransformsNeedUpdate = 0;
}
tween = tween._next;
}
if (hasRendered && !muteCallbacks) {
/** @type {$Animation} */(tickable).onRender(/** @type {$Animation} */(tickable));
}
}
}
// End tweens rendering
// Start onComplete callback and resolve Promise
if (hasBegun && isOverTime) {
if (_iterationCount === Infinity) {
// Offset the tickable _startTime with its duration to reset currentTime to 0 and continue the infinite timer
tickable._startTime += tickable.duration;
} else if (tickable._currentIteration >= _iterationCount - 1) {
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | true |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/playback/index.js | tests/playground/playback/index.js | import {
createTimeline,
stagger,
utils,
engine,
} from '../../../dist/modules/index.js';
const [$animPlay] = utils.$('#animation-play');
const [$animPause] = utils.$('#animation-pause');
const [$animReverse] = utils.$('#animation-reverse');
const [$animResume] = utils.$('#animation-resume');
const [$animToggle] = utils.$('#animation-alternate');
const [$animReversed] = utils.$('#animation-reversed');
const [$animProgress] = utils.$('#animation-progress');
const [$animationCurrentTime] = utils.$('#animation-currentTime');
const [$engineFramerate] = utils.$('#engine-frameRate');
const [$engineFPS] = utils.$('#engine-fps');
const [$enginePlaybackrate] = utils.$('#engine-playbackRate');
const [engineSpeedEl] = utils.$('#engine-speed');
const [$animFramerate] = utils.$('#animation-frameRate');
const [$animationFPS] = utils.$('#animation-fps');
const [$animPlaybackrate] = utils.$('#animation-playbackRate');
const [$animSpeed] = utils.$('#animation-speed');
const [$animTimeDrift] = utils.$('#animation-time-drift');
const animation = createTimeline({
loop: true,
onLoop: self => {
console.log(self.currentIteration);
},
onUpdate: (self) => {
/** @type {HTMLInputElement} */
($animProgress).value = `${self.iterationProgress}`;
/** @type {HTMLInputElement} */
($animationCurrentTime).value = `${self.currentTime}`;
/** @type {HTMLInputElement} */
($animReversed).value = `${self.reversed}`;
},
})
.add('.square', {
translateY: [{ to: '-10rem', duration: 300 }, { to: '0rem', ease: 'inOut', duration: 700 }],
scaleX: [{ to: .8 }, { to: 1, ease: 'inOut' }],
scaleY: [{ to: 2, duration: 500}, { to: 1, ease: 'inOut', duration: 350 }],
delay: stagger(100),
onBegin: () => {
console.log('BEGAN')
},
onComplete: () => {
console.log('COMPLETE')
}
});
const startTime = Date.now();
$animPlay.onclick = () => {
// animation.play();
animation.reversed = false;
}
$animPause.onclick = () => {
animation.pause();
}
$animResume.onclick = () => {
animation.resume();
}
$animReverse.onclick = () => {
// animation.reverse();
animation.reversed = true;
}
$animToggle.onclick = () => {
animation.alternate();
}
$engineFramerate.oninput = () => {
engine.fps = +/** @type {HTMLInputElement} */($engineFramerate).value;
/** @type {HTMLInputElement} */
($engineFPS).value = `${engine.fps}`;
}
$enginePlaybackrate.oninput = () => {
engine.speed = +/** @type {HTMLInputElement} */($enginePlaybackrate).value;
/** @type {HTMLInputElement} */
(engineSpeedEl).value = `${engine.speed}`;
}
$animFramerate.oninput = () => {
animation.fps = +/** @type {HTMLInputElement} */($animFramerate).value;
/** @type {HTMLInputElement} */
($animationFPS).value = `${animation.fps}`;
}
$animPlaybackrate.oninput = () => {
animation.speed = +/** @type {HTMLInputElement} */($animPlaybackrate).value;
/** @type {HTMLInputElement} */
($animSpeed).value = `${animation.speed}`;
}
$animProgress.oninput = v => {
animation.iterationProgress = v.target.value;
}
setInterval(() => {
const elapsed = Date.now() - startTime;
/** @type {HTMLInputElement} */
($animTimeDrift).value = (animation.currentTime - elapsed) + 'ms';
}, 1000);
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/sandbox/index.js | tests/playground/sandbox/index.js | import { waapi, animate, onScroll, $, set, stagger, spring, random, utils } from '../../../dist/modules/index.js';
async function animation() {
await animate('test', { x: 100 });
} | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/timeline/test/index.js | tests/playground/timeline/test/index.js | import { createTimeline, stagger } from '../../../../dist/modules/index.js';
// import { inspect } from '../../../lib/gui/index.js';
const duration = 1000;
const red = '#F64E4D';
const blue = '#61C3FF';
const green = '#18FF74';
const yellow = '#F6FF56';
const tl = createTimeline({
// beginDelay: 2000,
loop: 3,
alternate: true,
})
.add('.square', {
translateY: el => el.id == 'square-1' ? -50 : el.id == 'square-2' ? -100 : -150,
backgroundColor: green,
duration: 1600,
delay: 1250,
beginDelay: 500,
}, stagger(500, {start: '-=250'}))
// .add(// '#square-1', {
// translateY: -50,
// backgroundColor: green,
// duration: 1600,
// delay: 500,
// })
// .add(// '#square-2', {
// translateY: -100,
// backgroundColor: green,
// duration: 1600,
// })
// .add(// '#square-3', {
// translateY: -150,
// backgroundColor: green,
// duration: 1600,
// })
.add('.square', {
translateX: [
{ to: stagger([-100, 100]), duration: 1000, delay: 500 },
{ to: 0, duration: 1000, delay: 500 }
],
translateY: [
{ to: 50, duration: 500, delay: stagger(250, {start: 0}) },
{ to: 75, duration: 500, delay: 1000 },
{ to: 100, duration: 500, delay: 1000 }
],
scaleX: [
{ to: .25, duration: 500, delay: stagger(250, {start: 0}), ease: 'easeInOutExpo' },
{ to: 1, duration: 1000 },
{ to: .5, duration: 500, ease: 'easeInOutExpo' },
{ to: 1, duration: 500 }
],
scaleY: [
{ to: 1, duration: 500, delay: stagger(250, {start: 0}) },
{ to: 1.5, duration: 500, delay: 500, ease: 'easeInOutExpo' },
{ to: 1, duration: 500 },
{ to: 2, duration: 500, delay: 500, ease: 'easeInOutExpo' },
{ to: 1, duration: 500 }
],
rotate: [
{ to: 90, duration: 500, delay: stagger(250, {start: 0}), ease: 'easeInOutExpo' },
{ to: 180, duration: 1000, delay: 500, ease: 'easeInOutExpo' },
{ to: 45, duration: 500, delay: 250, ease: 'easeInOutExpo' },
{ to: 180, duration: 500 }
],
}, '-=1250')
.add('.square', {
rotate: -180,
scale: .5,
backgroundColor: red,
duration: 3000,
delay: stagger(250),
}, '-=3250')
.add('#square-1', {
translateY: 50,
backgroundColor: blue,
left: -200,
}, '-=' + duration)
.add('#square-2', {
translateY: 50,
backgroundColor: blue,
left: -150,
}, '-=' + duration)
.add('#square-3', {
translateY: 50,
backgroundColor: blue,
left: -100,
}, '-=' + duration)
.add('.square', {
rotate: '-=180',
scale: 1,
backgroundColor: yellow,
left: 100,
opacity: .5,
duration: duration * 2,
delay: stagger(100),
}, '-=' + duration * .75)
.add('.square', {
translateY: 0,
backgroundColor: red,
delay: stagger(100),
}, '-=' + duration)
.add('.square', {
translateX: '-=100',
duration: 1000,
// }, stagger(1000, {start: '-=10000'}))
}, 0)
.add('.square', {
translateX: '+=100',
duration: 1000,
}, stagger(250, {start: 500}))
// if (tl.children) {
// tl.children.forEach(child => {
// child.tweens.forEach(tween => {
// if (tween.property === 'rotate') {
// console.log(tween._nx);
// }
// });
// });
// } else {
// forEachChildren(tl, child => {
// forEachChildren(child, tween => {
// if (tween.property === 'rotate') {
// console.log(tween._nextSibling);
// }
// })
// })
// }
inspect(tl);
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/timeline/nested/index.js | tests/playground/timeline/nested/index.js | import { animate, createTimer, createTimeline, eases, stagger, utils } from '../../../../dist/modules/index.js';
// import { inspect } from '../../../lib/gui/index.js';
const A = animate('.square:nth-child(1)', { x: 200, onBegin: () => console.log('A BEGAN'), onComplete: () => console.log('A COMPLETE') })
const B = animate('.square:nth-child(2)', { x: 200, onBegin: () => console.log('B BEGAN'), onComplete: () => console.log('B COMPLETE') })
const C = animate('.square:nth-child(3)', { x: 200, onBegin: () => console.log('C BEGAN'), onComplete: () => console.log('C COMPLETE') })
const rotateAll = animate('.square', { rotate: 360 })
const TL = createTimeline({
loop: true,
alternate: true
})
.sync(A)
.sync(B, '-=500')
.sync(C, '-=500')
.sync(rotateAll, 0)
const timer = createTimer({
onUpdate: self => console.log(self.currentTime)
})
createTimeline({
loop: true,
})
.sync(TL)
.sync(timer, 0)
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/timeline/test-sets/index.js | tests/playground/timeline/test-sets/index.js | import { createTimeline, stagger, utils, engine, animate } from '../../../../dist/modules/index.js';
// import { createTimeline, stagger, utils, engine, animate } from '../../assets/js/anime.esm.js';
// import { inspect } from '../../../lib/gui/index.js';
const [ $square ] = utils.$('.square');
// let call1Log = 0;
// let call2Log = 0;
// let call3Log = 0;
// let call4Log = 0;
// const tl = createTimeline({
// // loop: 2,
// // autoplay: false,
// // onUpdate: e => console.log(e.progress),
// alternate: true,
// loop: 2,
// // loopDelay: 1000,
// defaults: {
// ease: 'linear',
// // duration: 250
// }
// })
// .call(() => console.log(`BEGIN: ${++call1Log}`), 0)
// .call(() => console.log(`MID: ${++call2Log}`), 250)
// .call(() => console.log(`UP: ${++call3Log}`), 1000)
// .call(() => console.log(`END: ${++call4Log}`), 2000)
// .set('.square', { backgroundColor: '#FF0000' }, 0)
// .set('.square', { backgroundColor: '#00FF00' }, 1000)
// .set('.square', { backgroundColor: '#0000FF' }, 2000)
// .add('.square', {
// rotate: 180,
// duration: 1000,
// // onBegin: () => {
// // console.log('begin');
// // },
// // onComplete: () => {
// // console.log('complete');
// // },
// }, 0)
// .init();
const [ $el ] = utils.$('#timeline-test');
utils.set($el, { '--x': '-2px' });
const delay = 0;
const speed = 1;
const triggerCB = (e) => {
console.log(`${e.id}`)
}
// let time = 0;
let timer1Log = 0;
let timer2Log = 0;
let timer3Log = 0;
const tl = createTimeline({ autoplay: true, loop: 3, alternate: true })
.call(() => { timer1Log += 1; console.log('1') }, 0)
.call(() => { timer2Log += 1; console.log('2') }, 100)
.call(() => { timer3Log += 1; console.log('3') }, 200);
// tl.seek(100);
// tl.seek(0);
// tl.seek(50);
// tl.seek(2000);
// tl.seek(200);
// tl.seek(0);
// console.log(timer1Log);
// inspect(tl);
// let tlOnBeginCheck = 0;
// let tlOnCompleteCheck = 0;
// let child1OnBeginCheck = 0;
// let child1OnCompleteCheck = 0;
// let child2OnBeginCheck = 0;
// let child2OnCompleteCheck = 0;
// const tl = createTimeline({
// loop: Infinity,
// alternate: true,
// defaults: {
// ease: 'linear',
// reversed: true,
// duration: 250
// },
// // autoplay: false,
// onBegin: () => { tlOnBeginCheck += 1; },
// onComplete: () => { tlOnCompleteCheck += 1; },
// })
// .add('.square:nth-child(1)', {
// y: 100,
// onBegin: () => { console.log('child 1 BEGIN'); child1OnBeginCheck += 1; },
// onComplete: () => { console.log('child 1 COMPLETE'); child1OnCompleteCheck += 1; }
// })
// .add('.square:nth-child(2)', {
// id: 'id-2',
// y: 100,
// onBegin: () => { console.log('child 2 BEGIN'); child2OnBeginCheck += 1; },
// onComplete: () => { console.log('child 2 COMPLETE'); child2OnCompleteCheck += 1; }
// })
// .init();
// console.log(tl);
// tl.seek(2000);
// tl.seek(5);
// tl.seek(10);
// tl.seek(100);
// tl.seek(110);
// tl.seek(201)
// inspect(tl);
// tl.seek(5);
// tl.seek(10);
// tl.seek(100);
// tl.seek(110);
// tl.seek(200);
// tl.seek(380);
// tl.seek(410);
// tl.seek(450);
// console.log(tl.duration, tlOnCompleteCheck);
// const tl2 = createTimeline({
// autoplay: false,
// loop: 2,
// defaults: {
// duration: 100,
// ease: 'linear',
// }
// })
// .add('.square:nth-child(1)', { translateY: 100 })
// .add('.square:nth-child(1)', { opacity: 0 })
// .add('.square:nth-child(2)', { translateY: 100 })
// .add('.square:nth-child(2)', { opacity: 0 })
// inspect(tl2); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/lerp/index.js | tests/playground/lerp/index.js | import {
animate,
createTimer,
utils,
} from '../../../dist/modules/index.js';
const [ $input ] = utils.$('.input');
const [ $damped ] = utils.$('.damped');
const [ $lerped ] = utils.$('.lerped');
animate($input, {
x: [-200, 200],
modifier: utils.snap(100),
duration: 2000,
loop: true,
alternate: true,
ease: 'linear',
});
createTimer({
frameRate: 10,
onUpdate: clock => {
const sourceX = utils.get($input, 'x', false);
const lerpedX = utils.get($lerped, 'x', false);
utils.set($lerped, {
x: utils.lerp(lerpedX, sourceX, .075)
});
}
});
createTimer({
frameRate: 10,
onUpdate: clock => {
const sourceX = utils.get($input, 'x', false);
const lerpedX = utils.get($damped, 'x', false);
utils.set($damped, {
x: utils.damp(lerpedX, sourceX, clock.deltaTime, .075)
});
}
});
let seededRandom = utils.createSeededRandom(0);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(utils.random() * -1);
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
seededRandom = utils.createSeededRandom(0);
console.log('RESET');
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10));
console.log(seededRandom(0, 10)); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/waapi/playback/index.js | tests/playground/waapi/playback/index.js | import {
waapi,
stagger,
utils,
createTimer,
createScope,
onScroll
} from '../../../../dist/modules/index.js';
const [$animResume] = utils.$('#animation-resume');
const [$animPlay] = utils.$('#animation-play');
const [$animPause] = utils.$('#animation-pause');
const [$animReverse] = utils.$('#animation-reverse');
const [$animAlternate] = utils.$('#animation-alternate');
const [$animCancel] = utils.$('#animation-cancel');
const [$animRestart] = utils.$('#animation-restart');
const [$animRevert] = utils.$('#animation-revert');
const [$animProgress] = utils.$('#animation-progress');
const [$animCurrentTime] = utils.$('#animation-currentTime');
const [$animPlaybackrate] = utils.$('#animation-playbackRate');
const [$animSpeed] = utils.$('#animation-speed');
const [$animTimeDrift] = utils.$('#animation-time-drift');
const scope = createScope({
mediaQueries: { 'm': '(min-width: 800px)' }
})
.add(self => {
const y = self.matches.m ? -10 : 10;
const animation = waapi.animate('.square', {
scale: 2,
backgroundColor: 'var(--bg)',
delay: stagger(70),
loop: 1,
alternate: true,
ease: 'inOut(4)',
duration: 750,
})
const scrollAnim = waapi.animate('.square', {
translate: ($el, i, t) => `0px ${stagger([-20, 20])($el, i, t)}rem`,
rotate: `90deg`,
delay: stagger(100),
reversed: true,
autoplay: onScroll({
target: document.body,
sync: 1,
enter: 'max',
leave: 'min',
debug: true,
})
})
const startTime = Date.now();
$animPlay.onclick = () => animation.play();
$animPause.onclick = () => animation.pause();
$animReverse.onclick = () => animation.reverse();
$animAlternate.onclick = () => animation.alternate();
$animResume.onclick = () => animation.resume();
$animCancel.onclick = () => animation.cancel();
$animRestart.onclick = () => animation.restart();
$animCancel.onclick = () => animation.cancel();
$animRevert.onclick = () => animation.revert();
($animProgress).oninput = v => {
animation.seek(+/** @type {HTMLInputElement} */(v.target).value * animation.duration);
}
($animPlaybackrate).oninput = v => {
const speed = /** @type {HTMLInputElement} */(v.target).value;
animation.speed = +speed;
/** @type {HTMLInputElement} */
($animSpeed).value = speed;
}
createTimer({
onUpdate: () => {
const elapsed = Date.now() - startTime;
/** @type {HTMLInputElement} */
($animTimeDrift).value = (animation.currentTime - elapsed) + 'ms';
/** @type {HTMLInputElement} */
($animCurrentTime).value = `${animation.currentTime}`;
/** @type {HTMLInputElement} */
($animProgress).value = `${animation.progress}`;
}
})
})
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/waapi/composition/index.js | tests/playground/waapi/composition/index.js | import { waapi, animate, stagger, createSpring, utils, eases, engine } from '../../../../dist/modules/index.js';
let currentY = 0;
let alternate = false;
/**
* @param {MouseEvent} e
*/
const animateSquares = (e) => {
const X = e.offsetX;
const Y = e.offsetY;
const duration = alternate ? 500 : 3000;
waapi.animate('.container-A .square', {
translate: `${X}px ${Y}px`,
opacity: { to: () => utils.random(.1, 1, 3), duration: () => utils.random(500, 4000, 0) },
scale: { to: () => utils.random(.1, 2, 3), duration: () => utils.random(500, 4000, 0) },
// rotate: { to: () => utils.random(-180, 180, 2) + 'deg', duration: () => utils.random(500, 4000, 0) },
// ease: createSpring({ stiffness: utils.clamp(Math.abs(currentY - Y) * .5, 100, 200) }),
duration,
ease: 'out',
delay: stagger(24, { grid: [10, 10], from: 'center' }),
});
waapi.animate('.container-B .square', {
x: X,
y: Y,
opacity: { to: () => utils.random(.1, 1, 3), duration: () => utils.random(500, 4000, 0) },
scale: { to: () => utils.random(.1, 2, 3), duration: () => utils.random(500, 4000, 0) },
// rotate: { to: () => utils.random(-180, 180, 2) + 'deg', duration: () => utils.random(500, 4000, 0) },
// ease: createSpring({ stiffness: utils.clamp(Math.abs(currentY - Y) * .5, 100, 200) }),
duration,
ease: 'out',
delay: stagger(24, { grid: [10, 10], from: 'center' }),
});
const jsAnimation = animate('.container-C .square', {
x: X,
y: Y,
opacity: { to: () => utils.random(.1, 1, 3), duration: () => utils.random(500, 4000, 0) },
scale: { to: () => utils.random(.1, 2, 3), duration: () => utils.random(500, 4000, 0) },
// rotate: { to: () => utils.random(-180, 180, 2) + 'deg', duration: () => utils.random(500, 4000, 0) },
// ease: createSpring({ stiffness: utils.clamp(Math.abs(currentY - Y) * .5, 100, 200) }),
duration,
ease: 'out',
delay: stagger(24, { grid: [10, 10], from: 'center' }),
// composition: 'blend',
});
currentY = Y;
alternate = !alternate;
}
document.onclick = animateSquares;
// const wait = () => new Promise((res) => setTimeout(() => res(), 0));
// async function timeWaster() {
// let x = 0n;
// while (true) {
// x++;
// if (x % 10000000n === 0n) {
// await wait();
// }
// }
// }
// timeWaster() | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/waapi/eases/index.js | tests/playground/waapi/eases/index.js | import { waapi, animate, stagger, createSpring, utils } from '../../../../dist/modules/index.js';
const $animation = document.querySelector('.animation');
const total = 36;
for (let i = 0; i < total; i++) {
const $square = document.createElement('div');
$square.classList.add('square', 'red');
utils.set($square, { rotate: (i / total) * 360, translateY: 250 })
$animation.appendChild($square);
}
// WAAPI
// const targets = document.querySelectorAll('.square');
// const animations = [];
// targets.forEach(($el, i) => {
// animations[i] = $el.animate({
// transform: `rotate(${(i / total) * 360}deg) translateY(200px) scaleX(.25)`,
// backgroundColor: [`var(--orange)`, `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,
// direction: 'alternate',
// fill: 'forwards',
// delay: i * 95,
// duration: 1680,
// })
// });
// animations.forEach(anim => {
// anim.currentTime += 10000;
// });
// Anime.js WAAPI wrapper
waapi.animate('.square', {
transform: (_, i) => `rotate(${(i / total) * 360}deg) translateY(200px) scaleX(.25)`,
backgroundColor: {
to: [`var(--orange)`, `var(--red)`],
ease: 'linear',
duration: 3000,
},
ease: createSpring({ stiffness: 150 }),
loop: true,
alternate: true,
delay: stagger(95),
}).seek(10000)
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/tests/playground/waapi/values/index.js | tests/playground/waapi/values/index.js | import { waapi, animate, stagger, utils, createTimer } from '../../../../dist/modules/index.js';
let alternate = false;
let x = utils.random(0, window.innerWidth - 800);
let y = utils.random(0, window.innerHeight - 260);
let bg = `rgb(255, 0, ${utils.random(0, 255)})`;
let rotate = stagger(alternate ? [-180, 180] : [0, 360], { grid: [10, 10], from: 'center' });
let opacityScale = stagger(alternate ? [1, 0] : [0, 1], { grid: [10, 10], from: 'center' });
const animateWAAPI = () => {
waapi.animate('.container-A .square', {
opacity: opacityScale,
translate: { to: `${x}px ${y}px`, duration: 750 },
scale: [1, opacityScale, stagger([4, 1], { grid: [10, 10], from: 'center' }), .5, 1],
rotate: rotate,
background: { from: bg, ease: 'inOut(2)', duration: 500 },
ease: 'ease-out',
duration: 1000,
delay: stagger(100, { grid: [10, 10], from: 'center' }),
});
}
const animateWAAPIIndividualTransforms = () => {
waapi.animate('.container-B .square', {
opacity: opacityScale,
x: { to: x, duration: 750 },
y: { to: y, duration: 750 },
scale: [1, opacityScale, stagger([4, 1], { grid: [10, 10], from: 'center' }), .5, 1],
rotate: rotate,
background: { from: bg, ease: 'inOut(2)', duration: 500 },
ease: 'ease-out',
duration: 1000,
delay: stagger(100, { grid: [10, 10], from: 'center' }),
});
}
const animateJS = () => {
animate('.container-C .square', {
opacity: opacityScale,
x: { to: x, duration: 750 },
y: { to: y, duration: 750 },
scale: [1, opacityScale, stagger([4, 1], { grid: [10, 10], from: 'center' }), .5, 1],
rotate: rotate,
background: { from: bg, ease: 'inOut(2)', duration: 500 },
ease: 'out',
// composition: 'blend',
duration: 1000,
delay: stagger(100, { grid: [10, 10], from: 'center' }),
});
}
const animateAll = () => {
x = utils.random(0, window.innerWidth - 800);
y = utils.random(0, window.innerHeight - 260);
bg = `rgb(255, 0, ${utils.random(0, 255)})`;
rotate = stagger(alternate ? [-180, 180] : [0, 360], { grid: [10, 10], from: 'center' });
opacityScale = stagger(alternate ? [1, 0] : [0, 1], { grid: [10, 10], from: 'center' });
animateWAAPI();
animateWAAPIIndividualTransforms();
animateJS();
alternate = !alternate;
}
setTimeout(() => {
animateAll();
createTimer({
duration: 1500,
loop: true,
onLoop: () => animateAll()
})
}, 500); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/animejs-v4-logo-animation/index.js | examples/animejs-v4-logo-animation/index.js | import { createTimeline, stagger, svg, utils, cubicBezier, eases } from '../../dist/modules/index.js';
const [ $dot1 ] = utils.$('#dot-1');
const onions = [];
for (let i = 0; i < 4; i++) {
const $clone = $dot1.cloneNode();
$clone.id = 'dot-1-' + i;
utils.set($clone, { opacity: 0 });
$dot1.parentNode.appendChild($clone);
onions.push($clone);
}
utils.set(onions, {
transformOrigin: '100% 50% 0px'
});
utils.set(['#a-1', '#n-1', '#i-1', '#m-1', '#e-1', '#dot-1', '#line', '#line-0'], {
transformOrigin: '50% 100% 0px',
});
utils.set('#four', {
transformOrigin: '50% 50% 0px',
});
utils.set('#dot-1', {
translateY: 70,
scaleY: 3.5,
});
utils.set(['#dot-1', '#line path', '#four', ...onions], {
opacity: 0,
});
utils.set(['#line', '#line-0'], {
opacity: 1,
});
const splashCurve = cubicBezier(0.225, 1, 0.915, 0.980);
const sweechCurve = eases.outElastic(1.1, 0.9);
const tl = createTimeline({
// autoplay: false
// loop: 3,
// loopDelay: 2000,
});
tl.label('FALL')
tl.add('#line-0', {
translateY: {to: [-280, 19], ease: 'inQuart', duration: 320 },
scaleY: { to: [3, 1.75], ease: 'outElastic(1, 1.4)', duration: 300, delay: 320 },
scaleX: { to: [.8, 1], ease: 'outElastic(1, 1.4)', duration: 650, delay: 320 },
d: [
{ to: svg.morphTo('#line-0-1', 0), delay: 320, duration: 60, ease: 'inQuad' },
{ to: svg.morphTo('#line-0-2', 0), duration: 80 },
{ to: svg.morphTo('#line-0-3', 0), duration: 90 },
{ to: svg.morphTo('#line-0-4', 0), duration: 90 },
{ to: svg.morphTo('#line-0-6', 0), duration: 140 },
],
ease: 'inOutQuad',
})
.label('WIGGLE')
.add('#line-0', {
d: [
{ to: svg.morphTo('#line-1', 0), duration: 340, ease: 'inOutQuad' },
{ to: svg.morphTo('#line-2', 0), duration: 260 },
{ to: svg.morphTo('#line-3', 0), duration: 180 },
{ to: svg.morphTo('#line-4', 0), duration: 180 },
{ to: svg.morphTo('#line-5', 0), duration: 340, ease: 'outSine' }
],
translateY: { to: 0, duration: 500 },
scaleX: { to: .9, delay: 750, duration: 550, ease: 'outQuad' },
scaleY: 1,
duration: 900,
})
.label('POP')
.set('#line', { opacity: 0 }, 'POP')
.set('#dot-1', { opacity: 1, transformOrigin: '50% 50% 0px' }, 'POP')
.add(['#a-1', '#n-1', '#i-1', '#m-1', '#e-1'], {
translateY: [
{ to: [35, -80], duration: 190, ease: splashCurve },
{ to: 4, duration: 120, delay: 20, ease: 'inQuad' },
{ to: 0, duration: 120, ease: 'outQuad' }
],
scaleX: [
{ to: [.25, .85], duration: 190, ease: 'outQuad' },
{ to: 1.08, duration: 120, delay: 85, ease: 'inOutSine' },
{ to: 1, duration: 260, delay: 25, ease: 'outQuad' }
],
scaleY: [
{ to: [.4, 1.5], duration: 120, ease: 'outSine' },
{ to: .6, duration: 120, delay: 180, ease: 'inOutSine' },
{ to: 1.2, duration: 180, delay: 25, ease: 'outQuad' },
{ to: 1, duration: 190, delay: 15, ease: 'outQuad' }
],
duration: 400,
ease: 'outSine',
}, stagger(80, { from: 'center' }))
.add('#dot-1', {
translateY: [
{ to: [30, -170], duration: 240, ease: splashCurve },
{ to: 35, duration: 180, delay: 120, ease: 'inQuad' },
{ to: -50, duration: 250, ease: splashCurve },
{ to: 5, duration: 170, delay: 20, ease: 'inQuad' },
{ to: 0, duration: 120, ease: 'outQuad' }
],
scaleX: { to: [1.1, 1], duration: 260, ease: 'outQuad' },
scaleY: { to: [4, 1], duration: 190, ease: 'outQuad' },
rotate: [
{ to: '+=.75turn', duration: 480, ease: 'outSine' },
{ to: '+=.25turn', duration: 420, delay: 160, ease: 'outSine' },
],
ease: 'outSine',
}, 'POP')
.add('#logo', {
scale: [1.3, 1],
translateY: [-23, 0],
duration: 1000,
ease: 'outExpo',
}, 'POP')
.add('#i-1', {
scaleY: [
{ to: .25, duration: 150, ease: 'outExpo' },
{ to: 1, duration: 700, delay: 0, ease: 'outElastic(2.11, 0.61)' },
],
scaleX: [
{ to: 1.5, duration: 50, ease: 'outSine' },
{ to: 1, duration: 900, delay: 0, ease: 'outElastic(2.11, 0.61)' },
],
}, '<<+=380')
.label('SWEECH', '-=290')
.add('#dot-1', {
ease: sweechCurve,
duration: 900,
points: svg.morphTo('#dot-2', 0),
}, 'SWEECH')
.add(onions, {
opacity: stagger([1, .4]),
ease: sweechCurve,
scaleX: [4, 1],
duration: 900,
points: svg.morphTo('#dot-2', 0),
delay: stagger(18)
}, 'SWEECH');
const sweechParams = {
ease: sweechCurve,
duration: 900,
}
tl
.add('#a-1', { d: svg.morphTo('#a-2', 0), ...sweechParams }, 'SWEECH+=00')
.add('#n-1', { d: svg.morphTo('#n-2', 0), ...sweechParams }, 'SWEECH+=10')
.add('#i-1', { points: svg.morphTo('#i-2', 0), ...sweechParams }, 'SWEECH+=20')
.add('#m-1', { d: svg.morphTo('#m-2', 0), ...sweechParams }, 'SWEECH+=30')
.add('#e-1', { d: svg.morphTo('#e-2', 0), ...sweechParams }, 'SWEECH+=40')
.add(svg.createDrawable(['#j-line', '#s-line']), {
opacity: [.25, 1],
draw: '0 1',
duration: 620,
ease: 'outQuint',
delay: stagger(40)
}, 'SWEECH+=250')
.label('FOUR', '<+=80')
.add('#four', {
fill: { from: '#FFF', delay: 600, ease: 'out(2)', duration: 900 },
opacity: { to: [0, 1], duration: 350, ease: 'out(1)' },
scale: { to: [1.75, 1], duration: 1400, ease: 'inOutExpo' },
}, 'FOUR')
.add('#blur feGaussianBlur', {
stdDeviation: ['15,15', '0,0'],
ease: 'out(2)',
duration: 1000,
}, '<<')
.set(['#j', '#s'], { opacity: 1 }, '<<')
.set(['#j-line', '#s-line', ...onions], { opacity: 0 }, '<<')
.add(['#a-1', '#n-1', '#i-1', '#m-1', '#e-1', '#j', '#s', '#dot-1'], {
translateX: '-=68',
ease: 'inOutQuint',
duration: 1250,
delay: stagger(14),
}, '<<')
const chars = ' !#%&"()*+×,.:;-_=><?@[]^/{|}.-~—0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const charsLength = chars.length;
function wrapInSpan(targetDiv) {
let target = document.querySelector(targetDiv);
let text = target.textContent;
let wrappedText = '';
for (let char of text) {
wrappedText += `<span>${char === ' ' ? ' ' : char}</span>`;
}
target.innerHTML = wrappedText;
}
wrapInSpan('#sub-text');
tl.label('TEXT', '<-=600')
.add('#sub-text span', {
opacity: [
{ to: .9, duration: 200 },
// { to: .9, duration: 1000 }
],
textContent: {
to: $el => [0, chars.indexOf($el.textContent)],
modifier: v => { const c = chars[utils.round(v, 0)]; return c ? c : ' ' },
},
duration: 800,
ease: 'inOutExpo',
delay: stagger(30, { from: 'center', ease: 'inOut(2)' }),
}, 'TEXT')
// .add('#sub-text span', {
// opacity: [
// { to: 1, duration: 100 },
// { to: .7, duration: 1000 }
// ],
// ease: 'out(3)',
// delay: stagger(20, { ease: 'inQuad' }),
// }, '<-=800')
.label('OUTRO', '+=1000')
.add('#four', {
translateX: '-=250',
ease: 'inOutExpo',
duration: 750,
}, 'OUTRO')
.add(['#j', '#s', '#dot-1'], {
opacity: 0,
duration: 620,
ease: 'outQuint',
}, 'OUTRO')
.add(['#a-1', '#n-1', '#i-1', '#m-1', '#e-1'], {
translateY: 80,
duration: 300,
ease: 'outQuint',
delay: stagger(30, { start: 300, from: 'last' }),
}, 'OUTRO')
.add('#sub-text span', {
textContent: {
to: $el => [chars.indexOf($el.textContent), 0],
modifier: v => { const c = chars[utils.round(v, 0)]; return c ? c : ' ' },
},
duration: 800,
ease: 'inOutExpo',
delay: stagger(30, { from: 'center', reversed: true, ease: 'inOut(2)' }),
}, '<<+=200')
.add('#four', {
opacity: { to: 0, duration: 650, ease: 'out(1)' },
}, '<<+=750')
.add('#blur feGaussianBlur', {
stdDeviation: '15,15',
ease: 'out(2)',
duration: 750,
}, '<<')
.init();
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/onscroll-responsive-scope/index.js | examples/onscroll-responsive-scope/index.js | import {
animate,
onScroll,
stagger,
createScope,
} from '../../dist/modules/index.js';
createScope({
mediaQueries: { landscape: '(orientation: landscape)' },
defaults: { ease: 'out(3)', duration: 500 },
}).add((scope) => {
let cardsAnimation;
if (scope.matches.landscape) {
cardsAnimation = animate('.card', {
transformOrigin: '50% 150%',
y: {
from: stagger(['-40vh','40vh'], {from: 'center'}),
},
rotate: {
to: stagger([-30, 30]),
delay: stagger([0, 950], { from: 'last', start: 200 }),
ease: 'inOut(3)',
},
x: ['-60vw', stagger(['-20%', '20%'])],
delay: stagger(60, { from: 'last' }),
duration: 750,
});
} else {
cardsAnimation = animate('.card', {
y: ['150vh', stagger(['20%', '-20%'])],
rotate: {
from: (_, i) => i % 2 ? '-20deg' : '20deg',
ease: 'inOut(3)',
},
delay: stagger(50, { from: 'last' })
});
}
onScroll({
target: '.sticky-container',
enter: 'top',
leave: 'bottom',
// debug: true,
sync: .1
}).link(cardsAnimation)
}); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/timeline-50K-stars/index.js | examples/timeline-50K-stars/index.js | import { animate, createTimeline, utils, steps, cubicBezier } from '../../dist/modules/index.js';
const [$animation] = utils.$('#animation');
const [$button] = utils.$('.star-button');
const [$cursor] = utils.$('.cursor');
const [$count] = utils.$('.count');
const [$label] = utils.$('.label');
const [$star] = utils.$('.star-icon');
const [$starPoly] = utils.$('.star-icon polygon');
const data = {
count: 1,
add: 1,
mult: 0,
}
const increaseCount = (cursor) => {
$label.innerHTML = `Starred`;
$starPoly.setAttribute('fill', 'currentColor');
const $starClone = /** @type {HTMLElement} */($star.cloneNode(true));
$starClone.classList.add('star-particle');
$animation.appendChild($starClone);
const left = /** @type {HTMLElement} */($button).offsetLeft + 4;
animate($starClone, {
translateY: { to: utils.random(-175, -225), ease: 'out'},
translateX: [
{ from: left, to: left + utils.random(-40, 40), ease: 'out'},
{ to: left + utils.random(-40, 40), ease: 'inOut(2)'}
],
color: { from: '#FFDD8E' },
scale: [1, 1.2, 1, .8],
ease: 'inOut(2)',
opacity: 0,
})
if (cursor) {
const $cursorClone = /** @type {HTMLElement} */($cursor.cloneNode(true));
$animation.appendChild($cursorClone);
createTimeline()
.add($cursorClone, {
x: { to: [utils.random(-250, 250), utils.random(-70, 70)], ease: 'out(3)' },
y: { to: [utils.random(0, 1) ? -300 : 300, utils.random(0, 10)], ease: 'out(6)' },
backgroundPosition: { to: '-40px 0px', ease: steps(1), duration: 150 },
opacity: [0, 1],
duration: 400,
})
.add($cursorClone, {
x: { to: utils.random(-250, 250), ease: 'inOut(3)' },
y: { to: utils.random(0, 1) ? -300 : 300, ease: 'inOut(6)' },
backgroundPosition: { to: '0px 0px', ease: steps(1), duration: 50 },
opacity: 0,
duration: 750,
})
.init()
}
}
utils.set($cursor, {
x: 300,
y: -250,
});
const clickAnimation = createTimeline({
loop: 500,
autoplay: false,
onLoop: self => self.refresh()
})
.add('.star-button', {
scale: [1, .97, 1],
rotate: () => utils.random(-data.mult, data.mult),
ease: 'out(4)',
}, 0)
.call(() => increaseCount(true), 0)
createTimeline()
.add($cursor, {
x: { to: 0, ease: 'out(3)' },
y: { to: 10, ease: 'out(6)' },
backgroundPosition: { to: '-40px 0px', ease: steps(1), duration: 250 },
duration: 750,
})
.add('.star-button', {
scale: [1, .97, 1],
ease: 'out(4)',
duration: 750,
}, '<+=500')
.set($count, { innerHTML: '1' }, '<<+=500')
.call(() => increaseCount(true), '<<')
.label('CLICK START', '+=250')
.set($count, { innerHTML: '2' }, 'CLICK START')
.set($count, { innerHTML: '3' }, 'CLICK START+=400')
.set($count, { innerHTML: '4' }, 'CLICK START+=500')
.set($count, { innerHTML: '5' }, 'CLICK START+=600')
.set($count, { innerHTML: '6' }, 'CLICK START+=700')
.add($cursor, {
x: { to: -150, ease: 'inOut(3)' },
y: { to: 250, ease: 'inOut(6)' },
backgroundPosition: { to: '0px 0px', ease: steps(1), duration: 50 },
duration: 750,
}, 'CLICK START-=500')
.add(data, {
mult: [0, 0, 1.5, .25, 0, 0],
duration: 10000,
ease: cubicBezier(1,0,0,1),
}, 'CLICK START')
.add(clickAnimation, {
progress: 1,
duration: 10000,
ease: cubicBezier(.65,0,0,1),
}, 'CLICK START')
.add($count, {
innerHTML: ['5', '40000'],
modifier: utils.round(0),
ease: cubicBezier(1,0,1,1),
duration: 5000
}, 'CLICK START+=800')
.add($count, {
innerHTML: '49999',
modifier: utils.round(0),
ease: cubicBezier(0,1,0,1),
duration: 4250
}, '<')
.add($cursor, {
x: { to: 0, ease: 'out(3)' },
y: { to: 10, ease: 'out(6)' },
backgroundPosition: { to: '-40px 0px', ease: steps(1), duration: 250 },
duration: 750,
}, '<+=250')
.add('.star-button', {
scale: [1, .97, 1],
ease: 'out(4)',
duration: 750,
}, '<+=500')
.set($count, { innerHTML: '50000' }, '<<+=500')
.call(() => increaseCount(false), '<<')
.add($cursor, {
x: { to: -150, ease: 'inOut(3)' },
y: { to: 250, ease: 'inOut(6)' },
backgroundPosition: { to: '0px 0px', ease: steps(1), duration: 250 },
duration: 750,
}, '<<+=1000')
.add($animation, {
scale: 1.25,
translateZ: 0,
duration: 13000,
ease: 'inOutQuad',
}, 'CLICK START')
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/svg-line-drawing/index.js | examples/svg-line-drawing/index.js | import {
svg,
createTimeline,
stagger,
utils,
} from '../../dist/modules/index.js';
function generateLines(numberOfLines) {
const svgWidth = 1100;
const svgHeight = 1100;
const margin = 50; // Margin from the edges of the SVG
const spacing = (svgWidth - margin * 2) / (numberOfLines - 1);
let svgContent = `<svg width="${svgWidth}px" height="${svgHeight}px" viewBox="0 0 ${svgWidth} ${svgHeight}">
<g id="lines" fill="none" fill-rule="evenodd">`;
for (let i = 0; i < numberOfLines; i++) {
const x = margin + i * spacing;
svgContent += `<line x1="${x}" y1="${margin}" x2="${x}" y2="${svgHeight - margin}" class="line-v" stroke="#A4FF4F"></line>`;
}
svgContent += `</g></svg>`;
return svgContent;
}
function generateCircles(numberOfCircles) {
const svgWidth = 1100;
const svgHeight = 1100;
const centerX = svgWidth / 2;
const centerY = svgHeight / 2;
const maxRadius = 500;
const step = maxRadius / numberOfCircles;
let svgContent = `<svg width="${svgWidth}px" height="${svgHeight}px" viewBox="0 0 ${svgWidth} ${svgHeight}">
<g id="circles" fill="none" fill-rule="evenodd">`;
for (let i = 0; i < numberOfCircles; i++) {
const radius = (i + 1) * step;
svgContent += `<circle class="circle" stroke="#A4FF4F" stroke-linecap="round" stroke-linejoin="round" stroke-width="10" cx="${centerX}" cy="${centerY}" r="${radius}"></circle>`;
}
svgContent += `</g></svg>`;
return svgContent;
}
const svgLines = generateLines(100);
const svgCircles = generateCircles(50);
document.body.innerHTML += svgLines;
document.body.innerHTML += svgCircles;
createTimeline({
playbackEase: 'out(4)',
loop: 0,
defaults: {
ease: 'inOut(4)',
duration: 10000,
loop: true,
}
})
.add(svg.createDrawable('.line-v'), {
// strokeWidth: [0, 20, 20, 20, 0],
draw: [
'.5 .5',
() => { const l = utils.random(.05, .45, 2); return `${.5 - l} ${.5 + l}` },
'0.5 0.5',
],
stroke: '#FF4B4B',
}, stagger([0, 8000], { start: 0, from: 'first' }))
.add(svg.createDrawable('.circle'), {
draw: [
() => { const v = utils.random(-1, -.5, 2); return `${v} ${v}`},
() => `${utils.random(0, .25, 2)} ${utils.random(.5, .75, 2)}`,
() => { const v = utils.random(1, 1.5, 2); return `${v} ${v}`},
],
stroke: '#FF4B4B',
}, stagger([0, 8000], { start: 0 }))
.init()
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/advanced-grid-staggering/index.js | examples/advanced-grid-staggering/index.js | import { createTimeline, utils, stagger } from '../../dist/modules/index.js';
const staggerVisualizerEl = document.querySelector('.stagger-visualizer');
const fragment = document.createDocumentFragment();
const rows = +utils.get(document.body, '--rows');
const grid = [rows, rows];
const numberOfElements = rows * rows;
var animation;
for (let i = 0; i < numberOfElements; i++) {
const dotEl = document.createElement('div');
dotEl.classList.add('dot');
fragment.appendChild(dotEl);
}
staggerVisualizerEl.appendChild(fragment);
let index = utils.random(0, numberOfElements);
let nextIndex = 0;
utils.set('.cursor', {
x: stagger('-1rem', {grid, from: index, axis: 'x'}),
y: stagger('-1rem', {grid, from: index, axis: 'y'})
});
function animateGrid() {
if (animation) animation.pause();
nextIndex = utils.random(0, numberOfElements);
animation = createTimeline({
defaults: {
ease: 'inOutQuad',
},
onComplete: animateGrid
})
.add('.cursor', {
keyframes: [
{ scale: .625 },
{ scale: 1.125 },
{ scale: 1 }
],
duration: 600
})
.add('.dot', {
keyframes: [
{
x: stagger('-.175rem', {grid, from: index, axis: 'x'}),
y: stagger('-.175rem', {grid, from: index, axis: 'y'}),
duration: 200
}, {
x: stagger('.125rem', {grid, from: index, axis: 'x'}),
y: stagger('.125rem', {grid, from: index, axis: 'y'}),
scale: 2,
duration: 500
}, {
x: 0,
y: 0,
scale: 1,
duration: 600,
}
],
delay: stagger(50, {grid, from: index}),
}, 0)
.add('.cursor', {
x: { from: stagger('-1rem', {grid, from: index, axis: 'x'}), to: stagger('-1rem', {grid, from: nextIndex, axis: 'x'}), duration: utils.random(800, 1200) },
y: { from: stagger('-1rem', {grid, from: index, axis: 'y'}), to: stagger('-1rem', {grid, from: nextIndex, axis: 'y'}), duration: utils.random(800, 1200) },
ease: 'outCirc'
}, '-=1500')
index = nextIndex;
}
animateGrid();
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/animatable-follow-cursor/index.js | examples/animatable-follow-cursor/index.js | import {
createAnimatable,
utils,
stagger,
} from '../../dist/modules/index.js';
// Setup
const [ $particles ] = utils.$('.particles');
const rows = /** @type {Number} */(utils.get($particles, '--size', false));
let w = window.innerWidth;
let h = window.innerHeight;
let hw = w / 2;
let hh = h / 2;
for (let i = 0; i < (rows * rows); i++) {
$particles.appendChild(document.createElement('div'));
}
// Animations
const duration = stagger(50, { ease: 'in(1)', from: 'center', grid: [rows, rows] });
const particles = createAnimatable('.particles div', {
x: { duration }, // Register the prop as animatable
y: { duration }, // Register the prop as animatable
rotate: { unit: 'rad', duration: 0 }, // Register the prop to be set without animation
ease: 'outElastic(.3, 1.4)',
});
/** @param {PointerEvent} e */
window.onpointermove = e => {
const { clientX, clientY } = e;
particles.x(utils.mapRange(clientX, 0, w, -hw, hw));
particles.y(utils.mapRange(clientY, 0, h, -hh, hh));
particles.rotate(-Math.atan2(hw - clientX, hh - clientY));
}
// Responsive
window.onresize = () => {
w = window.innerWidth;
h = window.innerHeight;
hw = w / 2;
hh = h / 2;
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/timeline-stress-test/index.js | examples/timeline-stress-test/index.js | import {
createTimeline,
stagger,
utils,
} from '../../dist/modules/index.js';
const count = 2024;
const duration = 10000;
const distance = 20;
const angle = utils.mapRange(0, count, 0, Math.PI * 100);
for (let i = 0; i < count; i++) {
const $el = document.createElement('div');
const hue = utils.round(360 / count * i, 0);
utils.set($el, { background: `hsl(${hue}, 60%, 60%)` });
document.body.appendChild($el);
}
createTimeline()
.add('div', {
x: (_, i) => `${Math.sin(angle(i)) * distance}rem`,
y: (_, i) => `${Math.cos(angle(i)) * distance}rem`,
scale: [0, .4, .2, .9, 0],
playbackEase: 'inOutSine',
loop: true,
duration,
}, stagger([0, duration]))
.init()
.seek(10000);
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/draggable-playground/index.js | examples/draggable-playground/index.js | import {
animate,
createTimer,
createDraggable,
createAnimatable,
utils,
stagger,
eases,
createSpring,
createTimeline,
engine,
} from '../../dist/modules/index.js';
engine.timeUnit = 'ms';
// engine.timeUnit = 's';
const [ $log ] = utils.$('#log');
createDraggable('#fixed', {
container: document.body,
onDrag: self => {
$log.innerHTML = `${utils.round(self.velocity, 3)}`;
}
});
let scrollTop, scrollStyles;
function blockScrolling() {
if (scrollStyles) return;
const $scroll = document.scrollingElement;
scrollTop = $scroll.scrollTop;
scrollStyles = utils.set([document.documentElement, $scroll], {
overflow: 'hidden', position: 'sticky', height: window.innerHeight - 1 + 'px'
});
}
function enableScrolling() {
if (!scrollStyles) return;
scrollStyles.revert();
scrollStyles = null;
window.scrollTo({ top: scrollTop, behavior: 'instant' });
}
const [ $drawer ] = /** @type {Array<HTMLElement>} */(utils.$('.drawer'));
const drawerOpenAnim = createTimeline({
autoplay: false,
defaults: { ease: 'linear' }
})
.add('#draggables', {
y: [10, 0],
scale: $el => [1 - (20 / $el.offsetWidth), 1],
borderRadius: ['.5rem', 0],
opacity: [.5, 1],
}, 0)
.add(document.body, {
backgroundColor: { from: '#000' },
}, 0)
.add($drawer, {
opacity: [1, 0],
duration: 10,
delay: 990,
ease: 'out(4)',
}, 0);
const drawer = createDraggable($drawer, {
container: () => [0, $drawer.offsetWidth, $drawer.offsetHeight, 0],
y: { snap: ({ $target }) => $target.offsetHeight },
x: false,
velocityMultiplier: 4,
containerFriction: 1,
onUpdate: (self) => {
drawerOpenAnim.progress = self.progressY;
self.progressY < .95 ? blockScrolling() : enableScrolling();
},
onResize: (self) => {
self.progressY = self.progressY > .5 ? 1 : 0
}
});
utils.$('#toggle-drawer')[0].onclick = () => {
drawer.stop();
animate(drawer, {
progressY: drawer.y < 100 ? 1 : 0,
duration: 375,
ease: 'out(4)',
});
}
drawer.progressY = 1;
createDraggable('#nested-draggable', {
container: '.drawer',
});
createDraggable('#body-snap', {
container: document.body,
x: { snap: 200 },
y: { snap: 100 },
});
const [ $rangeX ] = utils.$('.range-x .draggable');
const rangeX = createDraggable($rangeX, {
container: '.range-x',
containerPadding: 10,
snap: 200,
y: false,
onGrab: () => animateRangeX.pause(), // Here we manually pause the animation animating the draggable
onSettle: () => {
animateRangeX.refresh().restart();
}
});
const animateRangeX = animate(rangeX, {
progressX: el => el.progressX > .5 ? 0 : 1,
// loop: true,
duration: 1500,
ease: 'inOut(3)',
onLoop: self => self.refresh()
});
const rangeY = createDraggable('.range-y .draggable', {
container: '.range-y',
containerPadding: 10,
snap: 200,
x: false,
// containerFriction: 0,
// minVelocity: 2,
// minVelocity: 2,
cursor: { onHover: 'ns-resize', onGrab: 'move' },
// cursor: false,
releaseEase: createSpring({
mass: 1,
stiffness: 400,
damping: 30
}),
});
createDraggable('#container-no-scroll .draggable', {
container: '#container-no-scroll',
containerPadding: 10,
});
createDraggable('#container-scroll .draggable', {
container: '#container-scroll',
containerPadding: 10,
scrollThreshold: 10,
});
createDraggable('#transformed-container .draggable', {
container: '#transformed-container',
containerPadding: 10,
});
createDraggable('#array-container .draggable', {
container: [0, 200, 200, 0],
containerPadding: 50,
});
// Bounded flick carousel
const boundedFlickLength = utils.$('#bounded-flick .carousel-item').length;
const boundedFlickWidth = 290;
const boundedFlicker = createDraggable('#bounded-flick .carousel', {
container: [0, 0, 0, -boundedFlickWidth * (boundedFlickLength - 1)],
y: false,
snap: boundedFlickWidth,
});
utils.set('#bounded-flick .carousel', {
width: `${boundedFlickLength * boundedFlickWidth - 10}`
});
// Snap carousel
const [ $snapCarousel ] = utils.$('#snap-carousel .carousel');
const snapCarouselItems = /** @type {Array<HTMLElement>} */(utils.$('#snap-carousel .carousel-item'));
const snapTo = snapCarouselItems.map($el => -$el.offsetLeft);
createDraggable($snapCarousel, {
trigger: '#snap-carousel',
x: { modifier: utils.wrap(snapTo[snapTo.length / 2], 0) },
y: false,
snap: snapTo,
// containerFriction: 1,
});
// Object target
const [ $flickCarousel ] = utils.$('#infinite-flick .carousel');
const flickLength = utils.$('#infinite-flick .carousel-item').length;
const flickData = { width: 290, speedX: 2, wheelY: 0 };
utils.set($flickCarousel, { width: `${flickLength * flickData.width - 10}` });
const flickAnimatable = createAnimatable($flickCarousel, {
x: 0,
modifier: utils.wrap(-flickData.width * (flickLength / 2), 0),
});
const flickDraggable = createDraggable(flickData, {
trigger: '#infinite-flick',
y: false,
onGrab: () => animate(flickData, { speedX: 0, duration: 500 }),
onRelease: () => animate(flickData, { speedX: 2, duration: 500 }),
releaseDamping: 10,
});
createTimer({
onUpdate: () => {
const { x } = flickAnimatable;
x(/** @type {Number} */(x()) - flickData.speedX + flickDraggable.deltaX - flickData.wheelY);
}
});
// Support mousewheel
const wheelDeltaAnim = animate(flickData, {
wheelY: () => 0,
duration: 500,
autoplay: false,
});
/**
* @type {EventListener}
* @param {WheelEvent} e
*/
function onWheel(e) {
e.preventDefault();
flickData.wheelY = utils.lerp(flickData.wheelY, e.deltaY, .2);
wheelDeltaAnim.refresh().restart()
}
$flickCarousel.addEventListener('wheel', onWheel, { passive: false });
// Draggable list
const list = [];
const snap = 60;
let bodySticky;
utils.$('#onsnap-callback .draggable').forEach(($listItem, itemIndex) => {
const draggable = createDraggable($listItem, {
container: '#onsnap-callback',
x: false,
containerPadding: 10,
snap,
onGrab: self => {
animate(self.$target, { scale: 1.05, duration: 350 });
bodySticky = utils.set(document.scrollingElement, { position: 'sticky' }) // Hack for Safari mobile
},
onRelease: self => {
animate(self.$target, { scale: 1.00, duration: 450 });
bodySticky.revert();
},
onSnap: self => {
const fromIndex = list.indexOf(self);
const toIndex = utils.round(0).clamp(0, list.length - 1)(self.destY / snap);
if (toIndex !== fromIndex) {
list.splice(fromIndex, 1);
list.splice(toIndex, 0, self);
list.forEach((item, i) => {
if (i !== toIndex) {
animate(item, {
y: i * snap,
duration: 750,
ease: eases.outElastic(.8, 1)
});
}
});
}
}
});
draggable.y = itemIndex * snap;
utils.set($listItem, { willChange: 'transform', z: 10 });
list.push(draggable);
});
utils.set('#onsnap-callback .list', { height: `${list.length * snap - 10}` });
// Map value carousel
const carouselItems = utils.$('#map-props .carousel-item');
const itemAngle = 360 / carouselItems.length;
utils.set('#map-props .carousel-item', {
top: '50%',
left: '50%',
x: '-50%',
y: '-50%',
rotateY: stagger(itemAngle),
z: 'min(40vw, 200px)',
});
const carousel = createDraggable('#map-props .carousel', {
trigger: '#map-props',
x: { mapTo: 'rotateY' },
y: false,
snap: itemAngle,
dragSpeed: .4,
releaseStiffness: 10,
containerPadding: 10,
});
const [ $prev, $next ] = utils.$('.carousel-buttons .button');
const prev = e => {
e.preventDefault();
animate(carousel, { x: utils.snap(carousel.x + 40, itemAngle), duration: 500, ease: 'out(4)' });
}
const next = e => {
e.preventDefault();
animate(carousel, { x: utils.snap(carousel.x - 40, itemAngle), duration: 500, ease: 'out(4)' });
}
$prev.addEventListener('click', prev);
$next.addEventListener('click', next);
// Dynamic values
const dynamicDraggables = utils.$('.dynamic .draggable').map($el => {
return createDraggable($el, {
container: '.dynamic',
containerPadding: 10,
snap: 1,
containerFriction: 1,
});
});
const [ left, right, center ] = dynamicDraggables;
// Set the initial padding values
left.containerPadding[1] = 100;
right.containerPadding[3] = 100;
center.parameters.containerPadding = () => [10, Math.abs(right.x - 10), 10, left.x + 10];
center.refresh();
// Update center and right padding on left drag
left.onUpdate = ({ x }) => {
right.containerPadding[3] = x + 90;
center.refresh();
}
// Update center and left padding on right drag
right.onUpdate = ({ x }) => {
left.containerPadding[1] = Math.abs(x - 90);
center.refresh();
}
// left.animateInView();
// center.animateInView();
// right.animateInView();
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/svg-graph/index.js | examples/svg-graph/index.js | import {
svg,
animate,
createTimeline,
stagger,
utils,
} from '../../dist/modules/index.js';
const line = svg.createDrawable('line');
createTimeline({
loop: true,
defaults: {
ease: 'inOut(3)',
duration: 2000,
}
})
.add('#views', {
opacity: [0, 1],
duration: 500,
}, 0)
.add('#b', {
x: [0, 0],
width: [0, 900],
}, 0)
.add('#count', {
innerHTML: { from: 0 },
modifier: v => utils.round(v, 0).toLocaleString(),
}, '<<')
.add('#b', {
x: 900,
width: 0,
duration: 1500,
}, '+=500')
.add('#views', {
opacity: 0,
duration: 1500,
}, '<<')
.init()
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/easings-visualizer/index.js | examples/easings-visualizer/index.js | import { animate, createTimeline, eases, createSpring, utils, stagger } from '../../dist/modules/index.js';
function bindInputsToObject(name, obj, onChange = () => {}) {
const $bindedInputs = document.querySelectorAll(`[data-${ name }]`);
$bindedInputs.forEach($input => $input.addEventListener('input', event => {
const prop = event.currentTarget.dataset[name];
const value = event.currentTarget.value;
const $sibling = document.querySelectorAll(`[data-${ name }="${ prop }"]`);
$sibling.forEach($bind => $bind.value = value);
obj[prop] = value;
onChange(obj, prop, value);
}));
return $bindedInputs;
}
// SVG curve stuff
function createSvgCurve(strokeWidth = 1) {
const $svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const $curve = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
$svg.setAttribute('viewBox', '0 0 100 100');
$curve.setAttribute('stroke-width', strokeWidth);
$curve.setAttribute('points', '0 100 50 50 100 0');
$curve.setAttribute('stroke-linecap', 'round');
$curve.setAttribute('stroke-linejoin', 'round');
$curve.setAttribute('fill', 'none');
$curve.setAttribute('fill-rule', 'evenodd');
$svg.appendChild($curve);
return $svg;
}
function createCurvePoints(maxPoints = 100) {
const points = [];
for (let i = 0; i < maxPoints + 1; i++) {
points.push({
x: utils.round((i / maxPoints) * 100, 10),
y: utils.round(100 - ((i / maxPoints) * 100), 10),
});
}
return points;
}
const $easesEditor = document.querySelector('#eases-editor');
const $mainCurve = document.querySelector('#ease-curve');
const $easeName = document.querySelector('#ease-name');
const $easeList = document.querySelector('#eases-list');
const mainCurvePoints = createCurvePoints(400);
const buttonCurvePoints = createCurvePoints(100);
const buttons = [];
utils.set($mainCurve, { points: coordsToPoints(mainCurvePoints) });
const easesLookup = { createSpring, ...eases };
const easesList = {
in: [{ name: 'power', value: 1.675, min: 1, max: 10, step: .1 }],
out: [{ name: 'power', value: 1.675, min: 1, max: 10, step: .1 }],
inOut: [{ name: 'power', value: 1.675, min: 1, max: 10, step: .1 }],
inSine: null,
outSine: null,
inOutSine: null,
inQuad: null,
outQuad: null,
inOutQuad: null,
inCubic: null,
outCubic: null,
inOutCubic: null,
inQuart: null,
outQuart: null,
inOutQuart: null,
inQuint: null,
outQuint: null,
inOutQuint: null,
inExpo: null,
outExpo: null,
inOutExpo: null,
inCirc: null,
outCirc: null,
inOutCirc: null,
inBack: [{ name: 'overshoot', value: 1.70158, min: 0, max: 5, step: .01 }],
outBack: [{ name: 'overshoot', value: 1.70158, min: 0, max: 5, step: .01 }],
inOutBack: [{ name: 'overshoot', value: 1.70158, min: 0, max: 5, step: .01 }],
inBounce: null,
outBounce: null,
inOutBounce: null,
inElastic: [
{ name: 'amplitude', value: 1, min: 1, max: 3, step: .01 },
{ name: 'period', value: .3, min: 0, max: 2, step: .01 }
],
outElastic: [
{ name: 'amplitude', value: 1, min: 1, max: 3, step: .01 },
{ name: 'period', value: .3, min: 0, max: 2, step: .01 }
],
inOutElastic: [
{ name: 'amplitude', value: 1, min: 1, max: 3, step: .01 },
{ name: 'period', value: .3, min: 0, max: 2, step: .01 }
],
createSpring: [
{ name: 'mass', value: 1, min: 0, max: 10, step: .01 },
{ name: 'stiffness', value: 100, min: 1, max: 1000, step: 1 },
{ name: 'damping', value: 10, min: .1, max: 50, step: .1 },
{ name: 'velocity', value: 0, min: 0, max: 100, step: .1 },
],
steps: [
{ name: 'steps', value: 10, min: 0, max: 50, step: 1 },
{ name: 'jumpterm', value: 0, min: 0, max: 1, step: 1 }
],
irregular: [
{ name: 'steps', value: 10, min: 0, max: 50, step: 1 },
{ name: 'randomness', value: 1, min: 0, max: 4, step: .001 },
],
cubicBezier: [
{ name: 'x1', value: 0.2, min: 0, max: 1, step: .01 },
{ name: 'y1', value: 2.0, min: -2, max: 3, step: .01 },
{ name: 'x2', value: 0.6, min: 0, max: 1, step: .01 },
{ name: 'y2', value: 0.4, min: -2, max: 3, step: .01 },
],
linear: [
{ name: 'p1', value: 0.00, min: -.5, max: 1.5, step: .01 },
{ name: 'p2', value: 0.50, min: -.5, max: 1.5, step: .01 },
{ name: 'p3', value: 1.00, min: -.5, max: 1.5, step: .01 },
],
}
function createElement(tag, className = null, innerHTML = null) {
const el = document.createElement(tag);
if (className) el.className = className;
if (innerHTML) el.innerHTML = innerHTML;
return el;
}
function coordsToPoints(mainCurvePoints) {
let points = '';
mainCurvePoints.forEach(p => points += `${p.x} ${p.y} `);
return points;
}
const parameters = {
ease: eases.out,
name: 'out',
computedEasing: null,
easeDuration: 450,
transitionEasing: 'inOut(3)',
p1: null,
p2: null,
p3: null,
p4: null,
}
function animateEasing() {
const totalDuration = 1250;
utils.set('.axis-x:not(:first-child)', { opacity: 0 });
createTimeline({
defaults: {
duration: totalDuration,
ease: 'linear',
},
})
.add('.axis-y', {
translateX: ['calc(var,(--unit) * 0)', 'calc(var(--unit) * 40)'],
onUpdate: self => self.targets[0].dataset.value = utils.round(self.progress, 1),
}, 0)
.add('.axis-x:first-child', {
translateY: ['calc(var(--unit) * 0)', 'calc(var(--unit) * -40)'],
ease: parameters.computedEasing,
}, 0)
.set('.axis-x:not(:first-child)', {
opacity: [0, .2],
}, stagger([0, totalDuration], { start: 0 }))
}
function updateCurve($curve, points, ease, params, duration = parameters.easeDuration) {
const parsedEasing = params ? ease(...params) : ease;
parameters.computedEasing = parsedEasing;
utils.set(points, { y: stagger([100, 0], { ease: parsedEasing }) });
animate($curve, {
points: coordsToPoints(points),
duration,
ease: parameters.transitionEasing,
composition: duration ? 'add' : 'none',
modifier: v => utils.round(v, 2)
});
}
function updateName(name, ease, params) {
let easeName = name;
if (params) {
easeName += '(';
params.forEach((p, i) => {
easeName += p + (i === params.length - 1 ? ')' : ', ');
});
}
$easeName.value = easeName;
}
function updateParameters(state) {
let params;
for (let p in state) {
if (p === 'p1' || p === 'p2' || p === 'p3' || p === 'p4') {
const pVal = state[p];
if (pVal !== null) {
if (!params) params = [];
params.push(+pVal);
}
}
}
const ease = state.name === 'spring' ? params ? state.ease(...params).ease : state.ease().ease : state.ease
updateCurve($mainCurve, mainCurvePoints, ease, state.name === 'spring' ? undefined : params);
updateName(state.name, ease, params);
animate('.axis-x:not(:first-child)', {
translateY: stagger([0, -40], {
ease: parameters.computedEasing,
modifier: v => `calc(var(--unit) * ${v}`,
}),
duration: parameters.easeDuration,
ease: parameters.transitionEasing,
composition: 'add',
});
}
const $parameters = bindInputsToObject('parameters', parameters, updateParameters);
function selectEase(name) {
const easeFunction = easesLookup[name];
const easeParams = easesList[name];
parameters.ease = easeFunction;
parameters.name = name;
parameters.p1 = null;
parameters.p2 = null;
parameters.p3 = null;
parameters.p4 = null;
const $legends = document.querySelectorAll('.parameter-legend');
$parameters.forEach($el => $el.disabled = true);
$legends.forEach(($el, i) => {$el.disabled = true; $el.textContent = '--'});
if (easeParams) {
easeParams.forEach((p, i) => {
const propName = 'p' + (i + 1);
const $ps = document.querySelectorAll(`[data-parameters=${ propName }]`);
$ps.forEach($p => {
$p.disabled = false;
$p.min = p.min;
$p.max = p.max;
$p.step = p.step;
$p.value = p.value;
});
$legends[i].innerHTML = '⚙︎ ' + p.name;
parameters[propName] = p.value;
});
}
const $button = document.querySelector('.ease-' + name);
buttons.forEach($el => $el.classList.remove('is-active'));
$button.classList.add('is-active');
utils.set('.axis-x:not(:first-child)', { opacity: 0 });
updateParameters(parameters);
}
function createEaseButton(name, ease, hasParams) {
const $button = createElement('button', 'ease-button');
const $name = createElement('span', 'ease-name', name);
const $svgCurve = createSvgCurve(2);
updateCurve($svgCurve.querySelector('polyline'), buttonCurvePoints, ease, null, 0);
$button.classList.add('ease-' + name);
$button.appendChild($svgCurve);
$button.appendChild($name);
if (hasParams) {
$button.appendChild(createElement('span', 'ease-config', '⚙︎'));
}
$button.onclick = () => {
if (name !== parameters.name) {
selectEase(name);
}
if (window.innerWidth < 639) {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
}
animateEasing();
}
return $button;
}
for (let easeName in easesList) {
const params = easesList[easeName];
let ease = easesLookup[easeName];
if (easeName === 'spring') {
ease = ease().solver;
} else if (easeName === 'cubicBezier') {
ease = ease(0.2, 2.0, 0.6, 0.4);
} else if (params) {
ease = ease();
}
const $button = createEaseButton(easeName, ease, params);
$easeList.appendChild($button);
buttons.push($button);
}
selectEase('out');
animateEasing();
$easesEditor.onclick = animateEasing;
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/additive-fireflies/index.js | examples/additive-fireflies/index.js | import { animate, createTimer, utils } from '../../dist/modules/index.js';
const $animationWrapper = document.querySelector('#animation-wrapper');
const $circle = document.querySelector('#circle');
const viewport = {w: window.innerWidth * .5, h: window.innerHeight * .5};
const rows = 15;
const baseRadius = $circle.offsetWidth / 1.85;
const activeRadius = $circle.offsetWidth / .75;
const pointer = {x: 0, y: 0, isDown: false, radius: baseRadius};
const radiusTimeOut = createTimer({
duration: 150,
onComplete: () => pointer.radius = baseRadius
});
function animateParticule($el) {
createTimer({
frameRate: 4,
onUpdate: () => {
const angle = Math.random() * Math.PI * 2;
const radius = pointer.isDown ? activeRadius : baseRadius;
animate($el, {
x: { to: (Math.cos(angle) * radius) + pointer.x, duration: () => utils.random(1000, 2000) },
y: { to: (Math.sin(angle) * radius) + pointer.y, duration: () => utils.random(1000, 2000) },
backgroundColor: '#FF0000',
scale: .5 + utils.random(.1, 1, 2),
duration: () => utils.random(1000, 1500),
ease: `inOut(${utils.random(1, 5)})`,
composition: 'blend'
});
}
})
}
document.addEventListener('mousemove', e => {
pointer.x = e.pageX - viewport.w;
pointer.y = e.pageY - viewport.h;
pointer.radius = (pointer.isDown ? activeRadius : baseRadius * 1.25);
radiusTimeOut.restart();
utils.set($circle, { translateX: pointer.x, translateY: pointer.y });
});
document.addEventListener('mousedown', e => {
pointer.isDown = true;
animate($circle, { scale: .5, opacity: 1, filter: 'saturate(1.25)' });
});
document.addEventListener('mouseup', e => {
pointer.isDown = false;
animate($circle, { scale: 1, opacity: .3, filter: 'saturate(1)' });
});
const colors = ['red', 'orange', 'lightorange'];
for (let i = 0; i < (rows * rows); i++) {
const $particle = document.createElement('div');
$particle.classList.add('particle');
utils.set($particle, { color: `var(--${colors[utils.random(0, colors.length - 1)]})` });
$animationWrapper.appendChild($particle);
animateParticule($particle);
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/timeline-seamless-loop/index.js | examples/timeline-seamless-loop/index.js | import { createTimeline, utils, stagger } from '../../dist/modules/index.js';
const wrapperEl = document.querySelector('#test-wrapper');
const numberOfEls = 500;
const loopDuration = 6000;
const animDuration = loopDuration * .2;
const delay = loopDuration / numberOfEls;
let tl = createTimeline({
defaults: {
ease: 'inOutSine',
loopDelay: (loopDuration * .2) - animDuration,
duration: animDuration
},
})
.add(wrapperEl, {
rotate: -360,
loop: true,
duration: 24000,
ease: 'linear',
})
function createEl(i) {
let el = document.createElement('div');
const strength = utils.round(+stagger([0, 1], {
ease: 'inOutSine',
reversed: true,
from: 'center',
})(el, i, numberOfEls), 100);
const hue = utils.round(360 / numberOfEls * i, 2);
const bgColor = 'hsl('+hue+',40%,60%)';
const rotate = (360 / numberOfEls) * i;
const translateY = '-100%';
const scale = 1;
el.classList.add('el');
utils.set(el, { backgroundColor: bgColor, rotate, translateY, scale });
tl.add(el, {
backgroundColor: [
{to: 'hsl('+hue+','+(40+(20*strength))+'%,'+(60+(20*strength))+'%)'},
{to: bgColor}
],
rotate: [
{to: rotate+(10*strength)},
{to: rotate}
],
translateY: [
{to: '-100' - (10 * strength) + '%'},
{to: translateY}
],
scale: [
{to: [scale, scale+(.25*strength)]},
{to: scale}
],
loop: -1,
}, delay * i);
wrapperEl.appendChild(el);
};
for (let i = 0; i < numberOfEls; i++) createEl(i);
tl.seek(10000); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/timeline-refresh-starlings/index.js | examples/timeline-refresh-starlings/index.js | import {
createTimeline,
stagger,
utils,
} from '../../dist/modules/index.js';
const { random, cos, sin, sqrt, PI } = Math;
const count = 2500;
const duration = 3000;
const win = { w: window.innerWidth * .26, h: window.innerHeight * .26 };
const target = { x: 0, y: 0, r: win.w * .25 };
const radius = Symbol();
const theta = Symbol();
for (let i = 0; i < count; i++) {
const $el = document.createElement('div');
const h = utils.random(15, 25);
const l = utils.random(10, 18);
utils.set($el, { background: `hsl(${h}, 60%, ${l}%)` });
$el[theta] = random() * PI * 2;
$el[radius] = target.r * sqrt(random());
document.body.appendChild($el);
}
const tl = createTimeline({
defaults: {
loop: true,
ease: 'inOut(1.3)',
onLoop: self => self.refresh(),
},
});
tl.add('div', {
x: $el => target.x + ($el[radius] * cos($el[theta])),
y: $el => target.y + ($el[radius] * sin($el[theta])),
duration: () => duration + utils.random(-100, 100),
ease: 'inOut(1.5)',
onLoop: self => {
const t = self.targets[0];
t[theta] = random() * PI * 2;
t[radius] = target.r * sqrt(random());
self.refresh();
},
}, stagger((duration / count) * 1.125))
.add(target, {
r: () => win.w * utils.random(.05, .5, 2),
duration: 1250,
}, 0)
.add(target, {
x: () => utils.random(-win.w, win.w),
modifier: x => x + sin(tl.currentTime * .0007) * (win.w * .65),
duration: 2800,
}, 0)
.add(target, {
y: () => utils.random(-win.h, win.h),
modifier: y => y + cos(tl.currentTime * .00012) * (win.h * .65),
duration: 1800,
}, 0);
tl.seek(20000) | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/draggable-infinite-auto-carousel/index.js | examples/draggable-infinite-auto-carousel/index.js | import {
animate,
createTimer,
createDraggable,
createAnimatable,
utils,
} from '../../dist/modules/index.js';
const [ $carousel ] = /** @type {Array<HTMLElement>} */(utils.$('.carousel'));
$carousel.innerHTML += $carousel.innerHTML; // Clone the children for creating the illusion of infinity
const carouselItems = /** @type {Array<HTMLElement>} */(utils.$('.carousel-item'));
/**
* @param {Number} total
* @param {HTMLElement} $el
* @return {Number}
*/
const getTotalWidth = (total, $el) => {
const style= getComputedStyle($el);
const marginsWidth = parseInt(style.marginLeft) + parseInt(style.marginRight);
return total + $el.offsetWidth + marginsWidth;
}
const carousel = { width: carouselItems.reduce(getTotalWidth, 0), speedX: 2, wheelX: 0, wheelY: 0 };
const animatable = createAnimatable($carousel, {
x: 0, modifier: v => utils.wrap(v, -carousel.width / 2, 0)
});
const { x } = animatable;
const draggable = createDraggable(carousel, {
trigger: '#infinite-carousel',
y: false,
onGrab: () => animate(carousel, { speedX: 0, duration: 500 }),
onRelease: () => animate(carousel, { speedX: 2, duration: 500 }),
onResize: () => carousel.width = carouselItems.reduce(getTotalWidth, 0),
releaseStiffness: 20,
velocityMultiplier: 1.5
});
createTimer({
onUpdate: () => {
x(/** @type {Number} */(x()) - carousel.speedX + draggable.deltaX - carousel.wheelX - carousel.wheelY);
}
});
// Support mousewheel
const wheelDeltaAnim = animate(carousel, {
wheelY: 0, // We make sure the wheel delta always goes back to 0
wheelX: 0, // We make sure the wheel delta always goes back to 0
duration: 500,
autoplay: false,
ease: 'out(4)'
});
/**
* @type {EventListener}
* @param {WheelEvent} e
*/
function onWheel(e) {
e.preventDefault();
carousel.wheelY = utils.lerp(carousel.wheelY, e.deltaY, .2);
carousel.wheelX = utils.lerp(carousel.wheelX, e.deltaX, .2);
wheelDeltaAnim.refresh().restart()
}
$carousel.addEventListener('wheel', onWheel, { passive: false });
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/additive-creature/index.js | examples/additive-creature/index.js | import { animate, createTimeline, createTimer, stagger, utils } from '../../dist/modules/index.js';
const creatureEl = document.querySelector('#creature');
const viewport = { w: window.innerWidth * .5, h: window.innerHeight * .5 };
const cursor = { x: 0, y: 0 };
const rows = 13;
const grid = [rows, rows];
const from = 'center';
const scaleStagger = stagger([2, 5], { ease: 'inQuad', grid, from });
const opacityStagger = stagger([1, .1], { grid, from });
for (let i = 0; i < (rows * rows); i++) {
creatureEl.appendChild(document.createElement('div'));
}
const particuleEls = creatureEl.querySelectorAll('div');
utils.set(creatureEl, {
width: rows * 10 + 'em',
height: rows * 10 + 'em'
});
utils.set(particuleEls, {
x: 0,
y: 0,
scale: scaleStagger,
opacity: opacityStagger,
background: stagger([80, 20], { grid, from,
modifier: v => `hsl(4, 70%, ${v}%)`,
}),
boxShadow: stagger([8, 1], { grid, from,
modifier: v => `0px 0px ${utils.round(v, 0)}em 0px var(--red)`,
}),
zIndex: stagger([rows * rows, 1], { grid, from, modifier: utils.round(0) }),
});
const pulse = () => {
animate(particuleEls, {
keyframes: [
{
scale: 5,
opacity: 1,
delay: stagger(90, { start: 1650, grid, from }),
duration: 150,
}, {
scale: scaleStagger,
opacity: opacityStagger,
ease: 'inOutQuad',
duration: 600
}
],
});
}
const mainLoop = createTimer({
frameRate: 15, // Animate to the new cursor position every 250ms
onUpdate: () => {
animate(particuleEls, {
x: cursor.x,
y: cursor.y,
delay: stagger(40, { grid, from }),
duration: stagger(120, { start: 750, ease: 'inQuad', grid, from }),
ease: 'inOut',
composition: 'blend', // This allows the animations to overlap nicely
});
}
});
const autoMove = createTimeline()
.add(cursor, {
x: [-viewport.w * .45, viewport.w * .45],
modifier: x => x + Math.sin(mainLoop.currentTime * .0007) * viewport.w * .5,
duration: 3000,
ease: 'inOutExpo',
alternate: true,
loop: true,
onBegin: pulse,
onLoop: pulse,
}, 0)
.add(cursor, {
y: [-viewport.h * .45, viewport.h * .45],
modifier: y => y + Math.cos(mainLoop.currentTime * .00012) * viewport.h * .5,
duration: 1000,
ease: 'inOutQuad',
alternate: true,
loop: true,
}, 0);
const manualMovementTimeout = createTimer({
duration: 1500,
onComplete: () => autoMove.play(),
});
const followPointer = e => {
const event = e.type === 'touchmove' ? e.touches[0] : e;
cursor.x = event.pageX - viewport.w;
cursor.y = event.pageY - viewport.h;
autoMove.pause();
manualMovementTimeout.restart();
}
document.addEventListener('mousemove', followPointer);
document.addEventListener('touchmove', followPointer);
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/canvas-2d/index.js | examples/canvas-2d/index.js | import { animate, createTimer, utils } from '../../dist/modules/index.js';
const canvasEl = document.querySelector('canvas');
const ctx = canvasEl.getContext('2d', { alpha: false });
const maxParticules = Number(location.href.split('?')[1]) || 4000;
const colors = ['#FF4B4B','#FF8F42','#FFC730','#F6FF56'];
const viewport = { width: 0, height: 0 };
const particules = [];
const squarePi = 2 * 2 * Math.PI;
function setCanvasSize() {
const { innerWidth, innerHeight } = window;
const ratio = 2;
canvasEl.width = innerWidth * ratio;
canvasEl.height = innerHeight * ratio;
canvasEl.style.width = innerWidth + 'px';
canvasEl.style.height = innerHeight + 'px';
canvasEl.getContext('2d').scale(ratio, ratio);
viewport.width = innerWidth;
viewport.height = innerHeight;
}
function createParticule(x, y) {
return {
x,
y,
color: utils.randomPick(colors),
radius: 1,
}
}
function drawParticule(p) {
ctx.beginPath();
ctx.fillStyle = p.color;
ctx.arc(p.x, p.y, p.radius, 0, squarePi, true);
ctx.fill();
}
setCanvasSize();
window.addEventListener('resize', setCanvasSize);
function animateParticule(p, i) {
const newX = utils.random(0, viewport.width);
const diffX = newX - p.x;
const durX = Math.abs(diffX * 20);
const newY = utils.random(0, viewport.height);
const diffY = newY - p.y;
const durY = Math.abs(diffY * 20);
animate(p, {
x: { to: newX, duration: durX },
y: { to: newY, duration: durY },
radius: utils.random(2, 6),
ease: 'out(1)',
onComplete: () => { animateParticule(p, i); }
});
}
for (let i = 0; i < maxParticules; i++) {
const p = createParticule(viewport.width * .5, viewport.height * .5);
particules.push(p);
animateParticule(p, i);
}
createTimer({
onUpdate: self => {
ctx.globalCompositeOperation = 'source-over';
ctx.globalAlpha = .1;
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, viewport.width, viewport.height);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'screen';
for (let i = 0; i < maxParticules; i++) {
drawParticule(particules[i]);
}
},
})
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/layered-css-transforms/index.js | examples/layered-css-transforms/index.js | import { createTimeline, utils, createSpring } from '../../dist/modules/index.js';
const shapeEls = document.querySelectorAll('.shape');
const triangleEl = document.querySelector('.layered-animations polygon');
const points = triangleEl.getAttribute('points').split(' ').map( v => +v );
const eases = ['inOutQuad', 'inOutCirc', 'inOutSine', createSpring()];
function createKeyframes(value) {
var keyframes = [];
for (let i = 0; i < 100; i++) {
keyframes.push({
to: value,
ease: utils.randomPick(eases),
duration: utils.random(300, 1600)
});
}
return keyframes;
}
function animateShape(el) {
const circleEl = el.querySelector('circle');
const rectEl = el.querySelector('rect');
const polyEl = el.querySelector('polygon');
const animation = createTimeline({
onComplete: () => animateShape(el),
})
.add(el, {
translateX: createKeyframes(() => utils.random(-4, 4) + 'rem'),
translateY: createKeyframes(() => utils.random(-4, 4) + 'rem'),
rotate: createKeyframes(() => utils.random(-180, 180)),
}, 0)
if (circleEl) {
animation.add(circleEl, {
r: createKeyframes(() => utils.random(24, 56)),
}, 0);
}
if (rectEl) {
animation.add(rectEl, {
width: createKeyframes(() => utils.random(56, 96)),
height: createKeyframes(() => utils.random(56, 96)),
}, 0);
}
if (polyEl) {
animation.add(polyEl, {
points: createKeyframes(() => {
const s = utils.random(.9, 1.6, 3);
return `
${points[0]*s} ${points[1]*s} ${points[2]*s} ${points[3]*s} ${points[4]*s} ${points[5]*s}
`;
}),
}, 0);
}
animation.init();
}
for (var i = 0; i < shapeEls.length; i++) {
animateShape(shapeEls[i]);
}
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/clock-playback-controls/index.js | examples/clock-playback-controls/index.js | import { animate, createTimeline, utils, cubicBezier } from '../../dist/modules/index.js';
const [ $digitalClock ] = utils.$('#digital');
const s = 1000;
const m = 60*s;
const h = 60*m;
const oneday = h * 24;
const masterTL = createTimeline({ defaults: { ease: 'linear' }, autoplay: false });
[h * 10, h, 0, m * 10, m, 0, s * 10, s, 0, 100, 10].forEach(d => {
const $el = document.createElement('div');
$digitalClock.appendChild($el);
$el.classList.add('slot');
if (!d) {
$el.classList.add('colon');
$el.textContent = ':';
} else {
$el.classList.add('numbers');
for (let i = 0; i < 10; i++) {
const $num = document.createElement('div');
$num.textContent = `${i}`;
utils.set($num, { rotateX: (i * 36), z: '3ch' });
$el.appendChild($num);
}
const canStop = d > 100;
const ease = canStop ? cubicBezier(1,0,.6,1.2) : 'linear';
const duration = canStop ? 650 : d;
const position = `+=${canStop ? d - 650 : 0}`;
const numTL = createTimeline({ defaults: { ease }, loop: true });
const t = d === h*10 ? 4 : d === h ? 25 : d === m*10 || d === s*10 ? 7 : 11;
for (let i = 1; i < t; i++) {
const rotateX = -((i * 36) + (i === t - 1 ? (360 - i * 36) : 0));
numTL.add($el, { rotateX, duration }, d === h*10 && i === t - 1 ? '+=' + ((h * 4) - 650) : position);
}
masterTL.sync(numTL, 0);
}
});
masterTL.duration = oneday;
masterTL.iterationDuration = oneday;
const getNow = () => new Date().getTime() % oneday;
const [ $currentTimeRange ] = /** @type {Array<HTMLInputElement>} */(utils.$('#currentTime .range'));
const [ $currentTimeValue ] = /** @type {Array<HTMLInputElement>} */(utils.$('#currentTime .value'));
const [ $speedRange ] = /** @type {Array<HTMLInputElement>} */(utils.$('#speed .range'));
const [ $speedValue ] = /** @type {Array<HTMLInputElement>} */(utils.$('#speed .value'));
masterTL.currentTime = getNow();
// masterTL.currentTime = oneday - 3000;
masterTL.onUpdate = ({currentTime, speed}) => {
$currentTimeRange.value = `${currentTime}`;
$currentTimeValue.value = `${currentTime}`;
$speedRange.value = `${speed}`;
$speedValue.value = `${utils.round(speed, 0)}`;
}
utils.$('#controls button').forEach($button => {
const id = $button.id;
$button.onclick = () => {
if (id === 'seek') {
animate(masterTL, {
currentTime: getNow(),
ease: 'inOut(3)',
duration: 1500
})
} else if (id === 'slowmo') {
animate(masterTL, {
speed: .1,
ease: 'out(3)',
duration: 1500
})
} else if (id === 'speedup') {
animate(masterTL, {
speed: 5,
ease: 'out(3)',
duration: 1500
})
} else if (id === 'normalspeed') {
animate(masterTL, {
speed: 1,
ease: 'out(3)',
duration: 1500
})
} else {
masterTL[id]();
}
}
});
utils.$('fieldset').forEach($el => {
const $range = /** @type {HTMLInputElement} */($el.querySelector('.range'));
const $value = /** @type {HTMLInputElement} */($el.querySelector('.value'));
const prop = $el.id;
const value = masterTL[prop];
$range.value = value;
$value.value = masterTL[prop];
$range.oninput = () => {
const newValue = prop === 'currentTime' ? +$range.value % oneday : +$range.value;
utils.sync(() => masterTL[prop] = newValue);
$value.value = `${utils.round(newValue, 0)}`;
};
}); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/onscroll-sticky/index.js | examples/onscroll-sticky/index.js | import {
utils,
stagger,
onScroll,
createTimeline,
animate,
} from '../../dist/modules/index.js';
utils.set('.card', {
rotate: () => utils.random(-1, 1, 2),
rotateZ: () => utils.random(-1, 1, 2),
y: stagger(-.5, { from: 'last' }),
z: stagger(1),
});
const brightness = v => `brightness(${v})`;
utils.set('.front', { filter: stagger([.75, 1], { modifier: brightness }) });
utils.set('.back', { filter: stagger([1, .75], { modifier: brightness }) });
createTimeline({
defaults: {
ease: 'linear',
duration: 500,
composition: 'blend',
},
autoplay: onScroll({
target: '.sticky-container',
enter: 'top top',
leave: 'bottom bottom',
sync: .5,
debug: true,
}),
})
.add('.stack', {
rotateY: [-180, 0],
ease: 'in(2)',
}, 0)
.add('.card', {
rotate: 0,
rotateZ: { to: stagger([0, -360], { from: 'last' }), ease: 'inOut(2)' },
y: { to: '-60%', duration: 400 },
transformOrigin: ['50% 100%', '50% 50%'],
delay: stagger(1, { from: 'first' }),
}, 0)
.init()
utils.$('.card').forEach($card => {
$card.onmouseenter = () => animate($card, {
y: '-70%', duration: 350, composition: 'blend',
});
$card.onmouseleave = () => animate($card, {
y: '-60%', duration: 750, composition: 'blend', delay: 75,
});
})
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/text/hover-effects/index.js | examples/text/hover-effects/index.js | import {
animate,
createScope,
createSpring,
createTimeline,
stagger,
splitText,
utils,
} from '../../../dist/modules/index.js';
createScope({
root: '#horizontal-split',
defaults: {
ease: 'outQuad',
duration: 500,
}
}).add((scope) => {
const { root, methods } = scope;
splitText('h2', {
chars: {
class: 'char',
clone: 'left',
wrap: 'clip',
},
});
const rotateAnim = createTimeline({
autoplay: false,
defaults: { ease: 'inOutQuad', duration: 400, }
})
.add('.char > span', { x: '100%' }, stagger(5, { use: 'data-char' }))
scope.add('onEnter', () => animate(rotateAnim, { progress: 1 }));
scope.add('onLeave', () => animate(rotateAnim, { progress: 0 }));
root.addEventListener('pointerenter', /** @type {EventListener} */(methods.onEnter));
root.addEventListener('pointerleave', /** @type {EventListener} */(methods.onLeave));
});
createScope({
root: '#wavy-text-effect',
defaults: { ease: 'inOut(3)', duration: 350 },
}).add((scope) => {
const { root } = scope;
const params = {
split: splitText('h2', { chars: true }),
strength: 0,
};
const waveAnim = createTimeline().add(params.split.chars, {
y: [`-50%`, `50%`],
duration: 500,
loop: true,
alternate: true,
ease: 'inOut(2)',
autoplay: false,
modifier: v => v * params.strength,
}, stagger(50)).seek(1000);
root.addEventListener('pointerenter', () => animate(params, {
strength: 1,
onBegin: () => waveAnim.play(),
}));
root.addEventListener('pointerleave', () => animate(params, {
strength: 0,
onComplete: () => waveAnim.pause(),
}));
});
createScope({
root: '#raining-letters',
}).add((scope) => {
const { root, methods } = scope;
splitText('h2', {
chars: {
class: 'char',
clone: 'top',
wrap: 'clip',
},
});
const ease = createSpring({ stiffness: 90, damping: 11 });
scope.add('onEnter', () => {
createTimeline().add('.char > span', {
y: '100%',
composition: 'blend',
ease,
}, stagger(10, { use: 'data-char', from: 'random' }));
});
scope.add('onLeave', () => {
createTimeline().add('.char > span', {
y: '0%',
composition: 'blend',
ease,
}, stagger(10, { use: 'data-char', from: 'random' }));
});
root.addEventListener('pointerenter', methods.onEnter);
root.addEventListener('pointerleave', methods.onLeave);
});
createScope({
root: '#subtle-highlight',
defaults: { ease: 'out(3)', duration: 350, composition: 'blend' },
}).add((scope) => {
const { root, methods } = scope;
const { chars } = splitText('h2', { chars: true });
utils.set(chars, { opacity: .25 });
scope.add('onEnter', () => createTimeline().add(chars, { opacity: 1, textShadow: '0 0 30px rgba(255,255,255,.9)' }, stagger(12)));
scope.add('onLeave', () => createTimeline().add(chars, { opacity: .25, textShadow: '0 0 0px rgba(255,255,255,0)' }, stagger(12)));
root.addEventListener('pointerenter', methods.onEnter);
root.addEventListener('pointerleave', methods.onLeave);
});
createScope({
root: '#words-3d-jp',
defaults: {
ease: 'outQuad',
}
}).add((scope) => {
const { root, methods } = scope;
splitText('h2', {
words: `<span class="word-3d word-{i}">
<em class="face face-top">{value}</em>
<em class="face-front">{value}</em>
<em class="face face-bottom">{value}</em>
<em class="face face-back">{value}</em>
</span>`,
});
const wordStagger = stagger(50, { use: 'data-word', start: 0 });
const rotateAnim = createTimeline({
autoplay: false,
defaults: { ease: 'inOut(2)', duration: 750 }
})
.add('.word-3d', { rotateX: -180 }, wordStagger)
.add('.word-3d .face-top', { opacity: [0, 0, 0] }, wordStagger)
.add('.word-3d .face-front', { opacity: [1, 0, 0] }, wordStagger)
.add('.word-3d .face-bottom', { opacity: [0, 1, 0] }, wordStagger)
.add('.word-3d .face-back', { opacity: [0, 0, 1] }, wordStagger)
scope.add('onEnter', () => animate(rotateAnim, { progress: 1 }));
scope.add('onLeave', () => animate(rotateAnim, { progress: 0 }));
root.addEventListener('pointerenter', /** @type {EventListener} */(methods.onEnter));
root.addEventListener('pointerleave', /** @type {EventListener} */(methods.onLeave));
});
createScope({
root: '#exploding-characters',
}).add((scope) => {
const { root, methods } = scope;
const { chars } = splitText('h2', { chars: true });
scope.add('onEnter', () => {
createTimeline().add(chars, {
x: {
to: () => utils.random(-3, 3) + 'rem',
duration: () => utils.random(150, 500),
},
y: () => utils.random(-5, 5) + 'rem',
rotate: () => utils.random(-180, 180),
duration: () => utils.random(200, 750),
ease: 'outCirc', composition: 'blend',
}, stagger(5, { from: 'random' }));
});
scope.add('onLeave', () => {
createTimeline().add(chars, {
x: { to: 0, delay: 75 },
y: 0,
duration: () => utils.random(200, 400),
rotate: {
to: 0,
delay: 150,
duration: () => utils.random(300, 400),
},
ease: 'inOut(2)', composition: 'blend',
}, stagger(10, { from: 'random' }));
});
root.addEventListener('pointerenter', methods.onEnter);
root.addEventListener('pointerleave', methods.onLeave);
}); | javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/text/split-playground/index.js | examples/text/split-playground/index.js | import {
animate,
createTimeline,
createScope,
stagger,
splitText,
utils,
Scope,
} from '../../../dist/modules/index.js';
let split;
const form = document.getElementById('splitForm');
const $revert = document.getElementById('revert');
const $split = document.getElementById('split');
const config = {
split: {
lines: false,
words: false,
chars: false,
includeSpaces: false,
accessible: false,
debug: false
},
animation: {
lines: false,
words: false,
chars: false,
}
};
const animateSplit = (targets, type) => {
const param = config.split[type];
const anim = config.animation[type];
const dir = param.clone;
const randomStagger = anim.stagger === 'random';
return animate(targets, {
x: dir === 'left' ? '100%' : dir === 'right' ? '-100%' : 0,
y: dir === 'top' ? '100%' : dir === 'bottom' ? '-100%' : !dir ? '-100%' : 0,
loop: true,
alternate: true,
duration: anim.duration,
delay: stagger(randomStagger ? 10 : anim.stagger, { from: randomStagger ? 'random' : 0 }),
});
}
function updateSplitConfig() {
const data = new FormData(/** @type {HTMLFormElement} */(document.getElementById('splitForm')));
['lines', 'words', 'chars'].forEach(type => {
config.split[type] = false;
if (data.has(type)) {
const wrap = data.get(`${type}-wrap`);
const clone = data.get(`${type}-clone`);
const animate = data.get(`${type}-animate`);
config.split[type] = {
wrap: wrap === 'false' ? false : wrap,
clone: clone === 'false' ? false : clone
};
config.animation[type] = !+animate ? false : {
duration: +animate,
stagger: data.get(`${type}-stagger`)
};
}
});
config.split.includeSpaces = data.has('includeSpaces');
config.split.accessible = data.has('accessible');
config.split.debug = data.has('debug');
if (split) split.revert();
split = splitText('article', { ...config.split })
.addEffect(self => config.animation.lines && self.lines.length && animateSplit(self.lines, 'lines'))
.addEffect(self => config.animation.words && self.words.length && animateSplit(self.words, 'words'))
.addEffect(self => config.animation.chars && self.chars.length && animateSplit(self.chars, 'chars'))
$revert.removeAttribute('disabled');
}
document.fonts.ready.then(() => {
document.body.classList.add('is-ready');
['lines', 'words', 'chars'].forEach(type => {
const checkbox = /** @type {HTMLInputElement} */(document.getElementById(type));
const fieldset = /** @type {HTMLInputElement} */(document.getElementById(`${type}-options`));
checkbox.addEventListener('change', () => fieldset.disabled = !checkbox.checked);
fieldset.disabled = !checkbox.checked;
});
form.addEventListener('change', updateSplitConfig);
$revert.addEventListener('click', () => {split && split.revert(); $revert.setAttribute('disabled', 'false'); });
$split.addEventListener('click', updateSplitConfig);
updateSplitConfig();
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/text/split-effects/index.js | examples/text/split-effects/index.js | import {
animate,
createTimeline,
stagger,
splitText,
utils,
} from '../../../dist/modules/index.js';
const coords = [];
const [ $revert ] = utils.$('#revert');
const [ $split ] = utils.$('#split');
const [ $reorder ] = utils.$('#reorder');
const [ $debug ] = utils.$('#debug');
$revert.disabled = true;
$split.disabled = false;
$reorder.disabled = true;
let split;
const splitAndAnimate = () => {
$revert.disabled = false;
$split.disabled = true;
split = splitText('p', {
lines: true,
});
split.addEffect(split => {
// Returning the timeline syncs it with the splitter between lines split
return createTimeline({
defaults: {
alternate: true,
loop: true,
loopDelay: 75,
duration: 1500,
ease: 'inOutQuad',
},
})
.add(split.lines, {
color: { from: '#61C3FF' },
y: -10,
scale: 1.1,
}, stagger(100, { start: 0 }))
.add(split.words, {
scale: [.98, 1.04],
}, stagger(100, { use: 'data-line', start: 0 }))
.init()
});
split.addEffect(split => {
split.words.forEach(($el, i) => {
const c = coords[i];
if (c) utils.set($el, { x: c.x, y: c.y });
$el.addEventListener('pointerenter', () => {
$reorder.disabled = false;
animate($el, {
x: utils.random(-50, 50),
y: utils.random(-50, 50),
})
});
});
return () => {
// Store the words coordinates before the new split
split.words.forEach((w, i) => coords[i] = { x: utils.get(w, 'x'), y: utils.get(w, 'y') });
}
});
}
splitAndAnimate();
$revert.addEventListener('click', () => {
split.revert();
coords.length = 0;
$revert.disabled = true;
$split.disabled = false;
});
$split.addEventListener('click', splitAndAnimate);
$reorder.addEventListener('click', () => {
animate(split.words, {
x: 0, y: 0, ease: 'inOutExpo'
});
$reorder.disabled = true;
});
$debug.addEventListener('click', () => {
split.debug = !split.debug;
split.refresh();
$debug.innerText = split.debug ? 'HIDE DEBUG' : 'SHOW DEBUG';
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/draggable-mouse-scroll-snap-carousel/index.js | examples/draggable-mouse-scroll-snap-carousel/index.js | import {
createTimer,
createDraggable,
utils,
} from '../../dist/modules/index.js';
const carousel = {
totalWidth: 0,
itemWidth: 0,
spacing: 0,
released: false,
deltaX: 0,
deltaY: 0,
prevX: 0,
prevY: 0,
wheeling: false,
wheelable: true,
};
const [ $carousel ] = /** @type {Array<HTMLElement>} */(utils.$('.carousel'));
const carouselItems = /** @type {Array<HTMLElement>} */(utils.$('.carousel-item'));
const updateDimensions = () => {
carousel.spacing = utils.get('#snap-carousel', '--spacing', false);
carousel.totalWidth = carouselItems.reduce((total, $el) => {
return total + $el.offsetWidth + carousel.spacing;
}, 0);
carousel.itemWidth = carouselItems[0].offsetWidth + carousel.spacing;
}
updateDimensions();
const draggable = createDraggable($carousel, {
trigger: document.body,
container: () => [0, 0, 0, -carousel.totalWidth + $carousel.offsetWidth - carousel.spacing],
x: { snap: () => carousel.itemWidth },
y: false,
onResize: () => updateDimensions(),
onAfterResize: self => self.setX(utils.snap(self.x, self.snapX)),
onGrab: () => carousel.wheelable = false,
onRelease: () => carousel.wheelable = true,
releaseStiffness: 100,
velocityMultiplier: 1.5,
containerFriction: .5,
});
// Mousewheel Support
// Debouncing wheel delta calculation prevent false positives for the carousel.wheeling flag
const wheelTimer = createTimer({
frameRate: 30,
duration: 100,
autoplay: false,
onUpdate: () => {
const newDeltaX = Math.abs(carousel.deltaX);
const newDeltaY = Math.abs(carousel.deltaY);
carousel.wheeling = carousel.prevY < newDeltaY || carousel.prevX < newDeltaX;
carousel.prevX = newDeltaX;
carousel.prevY = newDeltaY;
}
});
const wheelVelocityTimer = createTimer({
duration: 500,
autoplay: false,
onUpdate: () => {
if (!carousel.wheelable) return;
const [ _, cr, __, cl ] = draggable.containerBounds;
const cf = (1 - draggable.containerFriction) * draggable.dragSpeed;
const cx = draggable.x + carousel.deltaX + carousel.deltaY;
// Apply friction when out of bounds
const x = cx > cr ? cr + (cx - cr) * cf : cx < cl ? cl + (cx - cl) * cf : cx;
const dx = x - draggable.coords[2];
draggable.pointer[2] = draggable.pointer[0];
draggable.pointer[4] = draggable.pointer[0];
draggable.pointer[0] = x;
draggable.computeVelocity(dx, 0);
draggable.angle = 0;
}
});
/** @param {WheelEvent} e */
function onWheel(e) {
e.preventDefault();
carousel.deltaX = utils.lerp(carousel.deltaX, -e.deltaX, .5);
carousel.deltaY = utils.lerp(carousel.deltaY, -e.deltaY, .5);
wheelTimer.restart();
wheelVelocityTimer.restart();
if (!carousel.wheelable) return;
if (carousel.wheeling) {
draggable.stop();
draggable.setX(draggable.pointer[0], true);
carousel.released = false;
draggable.grabbed = true; // Needed to trigger handleUp();
} else if (!carousel.released) {
draggable.handleUp();
}
}
window.addEventListener('wheel', onWheel, { passive: false });
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/examples/irregular-playback-typewriter/index.js | examples/irregular-playback-typewriter/index.js | import {
animate,
createTimeline,
utils,
stagger,
easings,
} from '../../dist/modules/index.js';
const $spans = utils.$('span');
const $cursor = utils.$('.cursor');
const keystrokesSteps = $spans.length - 1;
const keystrokesInterval = 125;
createTimeline({
playbackEase: easings.irregular(keystrokesSteps, 2),
})
.set($spans, { opacity: [0, 1] }, stagger(keystrokesInterval))
.add($cursor, {
left: '100%',
duration: keystrokesSteps * keystrokesInterval,
ease: easings.steps(keystrokesSteps),
}, 0)
.init();
animate($cursor, {
opacity: 0,
duration: 750,
ease: 'inIn(2)',
loop: true,
alternate: true,
});
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | false |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/bundles/anime.umd.min.js | dist/bundles/anime.umd.min.js | /**
* Anime.js - UMD minified bundle
* @version v4.2.2
* @license MIT
* @copyright 2025 - Julian Garnier
*/
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | true |
juliangarnier/anime | https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/bundles/anime.umd.js | dist/bundles/anime.umd.js | /**
* Anime.js - UMD bundle
* @version v4.2.2
* @license MIT
* @copyright 2025 - Julian Garnier
*/
// Global types
/**
* @typedef {Object} DefaultsParams
* @property {Number|String} [id]
* @property {PercentageKeyframes|DurationKeyframes} [keyframes]
* @property {EasingParam} [playbackEase]
* @property {Number} [playbackRate]
* @property {Number} [frameRate]
* @property {Number|Boolean} [loop]
* @property {Boolean} [reversed]
* @property {Boolean} [alternate]
* @property {Boolean} [persist]
* @property {Boolean|ScrollObserver} [autoplay]
* @property {Number|FunctionValue} [duration]
* @property {Number|FunctionValue} [delay]
* @property {Number} [loopDelay]
* @property {EasingParam} [ease]
* @property {'none'|'replace'|'blend'|compositionTypes} [composition]
* @property {(v: any) => any} [modifier]
* @property {Callback<Tickable>} [onBegin]
* @property {Callback<Tickable>} [onBeforeUpdate]
* @property {Callback<Tickable>} [onUpdate]
* @property {Callback<Tickable>} [onLoop]
* @property {Callback<Tickable>} [onPause]
* @property {Callback<Tickable>} [onComplete]
* @property {Callback<Renderable>} [onRender]
*/
/** @typedef {JSAnimation|Timeline} Renderable */
/** @typedef {Timer|Renderable} Tickable */
/** @typedef {Timer&JSAnimation&Timeline} CallbackArgument */
/** @typedef {Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */
// Stagger types
/**
* @template T
* @callback StaggerFunction
* @param {Target} [target]
* @param {Number} [index]
* @param {Number} [length]
* @param {Timeline} [tl]
* @return {T}
*/
/**
* @typedef {Object} StaggerParams
* @property {Number|String} [start]
* @property {Number|'first'|'center'|'last'|'random'} [from]
* @property {Boolean} [reversed]
* @property {Array.<Number>} [grid]
* @property {('x'|'y')} [axis]
* @property {String|((target: Target, i: Number, length: Number) => Number)} [use]
* @property {Number} [total]
* @property {EasingParam} [ease]
* @property {TweenModifier} [modifier]
*/
// Targets types
/** @typedef {HTMLElement|SVGElement} DOMTarget */
/** @typedef {Record<String, any>} JSTarget */
/** @typedef {DOMTarget|JSTarget} Target */
/** @typedef {Target|NodeList|String} TargetSelector */
/** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */
/** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */
/** @typedef {Array.<DOMTarget>} DOMTargetsArray */
/** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */
/** @typedef {Array.<JSTarget>} JSTargetsArray */
/** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */
/** @typedef {Array.<Target>} TargetsArray */
// Eases types
/**
* @callback EasingFunction
* @param {Number} time
* @return {Number}
*/
/**
* @typedef {('linear'|'none'|'in'|'out'|'inOut'|'inQuad'|'outQuad'|'inOutQuad'|'inCubic'|'outCubic'|'inOutCubic'|'inQuart'|'outQuart'|'inOutQuart'|'inQuint'|'outQuint'|'inOutQuint'|'inSine'|'outSine'|'inOutSine'|'inCirc'|'outCirc'|'inOutCirc'|'inExpo'|'outExpo'|'inOutExpo'|'inBounce'|'outBounce'|'inOutBounce'|'inBack'|'outBack'|'inOutBack'|'inElastic'|'outElastic'|'inOutElastic'|'out(p = 1.675)'|'inOut(p = 1.675)'|'inBack(overshoot = 1.7)'|'outBack(overshoot = 1.7)'|'inOutBack(overshoot = 1.7)'|'inElastic(amplitude = 1, period = .3)'|'outElastic(amplitude = 1, period = .3)'|'inOutElastic(amplitude = 1, period = .3)')} EaseStringParamNames
*/
/**
* @typedef {('ease'|'ease-in'|'ease-out'|'ease-in-out'|'linear(0, 0.25, 1)'|'steps'|'steps(6, start)'|'step-start'|'step-end'|'cubic-bezier(0.42, 0, 1, 1)') } WAAPIEaseStringParamNames
*/
/**
* @callback PowerEasing
* @param {Number|String} [power=1.675]
* @return {EasingFunction}
*/
/**
* @callback BackEasing
* @param {Number|String} [overshoot=1.7]
* @return {EasingFunction}
*/
/**
* @callback ElasticEasing
* @param {Number|String} [amplitude=1]
* @param {Number|String} [period=.3]
* @return {EasingFunction}
*/
/** @typedef {PowerEasing|BackEasing|ElasticEasing} EasingFunctionWithParams */
// A hack to get both ease names suggestions AND allow any strings
// https://github.com/microsoft/TypeScript/issues/29729#issuecomment-460346421
/** @typedef {(String & {})|EaseStringParamNames|EasingFunction|Spring} EasingParam */
/** @typedef {(String & {})|EaseStringParamNames|WAAPIEaseStringParamNames|EasingFunction|Spring} WAAPIEasingParam */
// Spring types
/**
* @typedef {Object} SpringParams
* @property {Number} [mass=1] - Mass, default 1
* @property {Number} [stiffness=100] - Stiffness, default 100
* @property {Number} [damping=10] - Damping, default 10
* @property {Number} [velocity=0] - Initial velocity, default 0
* @property {Number} [bounce=0] - Initial bounce, default 0
* @property {Number} [duration=0] - The perceived duration, default 0
* @property {Callback<JSAnimation>} [onComplete] - Callback function called when the spring currentTime hits the perceived duration
*/
// Callback types
/**
* @template T
* @callback Callback
* @param {T} self - Returns itself
* @param {PointerEvent} [e]
* @return {*}
*/
/**
* @template {object} T
* @typedef {Object} TickableCallbacks
* @property {Callback<T>} [onBegin]
* @property {Callback<T>} [onBeforeUpdate]
* @property {Callback<T>} [onUpdate]
* @property {Callback<T>} [onLoop]
* @property {Callback<T>} [onPause]
* @property {Callback<T>} [onComplete]
*/
/**
* @template {object} T
* @typedef {Object} RenderableCallbacks
* @property {Callback<T>} [onRender]
*/
// Timer types
/**
* @typedef {Object} TimerOptions
* @property {Number|String} [id]
* @property {TweenParamValue} [duration]
* @property {TweenParamValue} [delay]
* @property {Number} [loopDelay]
* @property {Boolean} [reversed]
* @property {Boolean} [alternate]
* @property {Boolean|Number} [loop]
* @property {Boolean|ScrollObserver} [autoplay]
* @property {Number} [frameRate]
* @property {Number} [playbackRate]
*/
/**
* @typedef {TimerOptions & TickableCallbacks<Timer>} TimerParams
*/
// Tween types
/**
* @callback FunctionValue
* @param {Target} target - The animated target
* @param {Number} index - The target index
* @param {Number} length - The total number of animated targets
* @return {Number|String|TweenObjectValue|Array.<Number|String|TweenObjectValue>}
*/
/**
* @callback TweenModifier
* @param {Number} value - The animated value
* @return {Number|String}
*/
/** @typedef {[Number, Number, Number, Number]} ColorArray */
/**
* @typedef {Object} Tween
* @property {Number} id
* @property {JSAnimation} parent
* @property {String} property
* @property {Target} target
* @property {String|Number} _value
* @property {Function|null} _func
* @property {EasingFunction} _ease
* @property {Array.<Number>} _fromNumbers
* @property {Array.<Number>} _toNumbers
* @property {Array.<String>} _strings
* @property {Number} _fromNumber
* @property {Number} _toNumber
* @property {Array.<Number>} _numbers
* @property {Number} _number
* @property {String} _unit
* @property {TweenModifier} _modifier
* @property {Number} _currentTime
* @property {Number} _delay
* @property {Number} _updateDuration
* @property {Number} _startTime
* @property {Number} _changeDuration
* @property {Number} _absoluteStartTime
* @property {tweenTypes} _tweenType
* @property {valueTypes} _valueType
* @property {Number} _composition
* @property {Number} _isOverlapped
* @property {Number} _isOverridden
* @property {Number} _renderTransforms
* @property {String} _inlineValue
* @property {Tween} _prevRep
* @property {Tween} _nextRep
* @property {Tween} _prevAdd
* @property {Tween} _nextAdd
* @property {Tween} _prev
* @property {Tween} _next
*/
/**
* @typedef TweenDecomposedValue
* @property {Number} t - Type
* @property {Number} n - Single number value
* @property {String} u - Value unit
* @property {String} o - Value operator
* @property {Array.<Number>} d - Array of Numbers (in case of complex value type)
* @property {Array.<String>} s - Strings (in case of complex value type)
*/
/** @typedef {{_head: null|Tween, _tail: null|Tween}} TweenPropertySiblings */
/** @typedef {Record<String, TweenPropertySiblings>} TweenLookups */
/** @typedef {WeakMap.<Target, TweenLookups>} TweenReplaceLookups */
/** @typedef {Map.<Target, TweenLookups>} TweenAdditiveLookups */
// JSAnimation types
/**
* @typedef {Number|String|FunctionValue} TweenParamValue
*/
/**
* @typedef {TweenParamValue|[TweenParamValue, TweenParamValue]} TweenPropValue
*/
/**
* @typedef {(String & {})|'none'|'replace'|'blend'|compositionTypes} TweenComposition
*/
/**
* @typedef {Object} TweenParamsOptions
* @property {TweenParamValue} [duration]
* @property {TweenParamValue} [delay]
* @property {EasingParam} [ease]
* @property {TweenModifier} [modifier]
* @property {TweenComposition} [composition]
*/
/**
* @typedef {Object} TweenValues
* @property {TweenParamValue} [from]
* @property {TweenPropValue} [to]
* @property {TweenPropValue} [fromTo]
*/
/**
* @typedef {TweenParamsOptions & TweenValues} TweenKeyValue
*/
/**
* @typedef {Array.<TweenKeyValue|TweenPropValue>} ArraySyntaxValue
*/
/**
* @typedef {TweenParamValue|ArraySyntaxValue|TweenKeyValue} TweenOptions
*/
/**
* @typedef {Partial<{to: TweenParamValue|Array.<TweenParamValue>; from: TweenParamValue|Array.<TweenParamValue>; fromTo: TweenParamValue|Array.<TweenParamValue>;}>} TweenObjectValue
*/
/**
* @typedef {Object} PercentageKeyframeOptions
* @property {EasingParam} [ease]
*/
/**
* @typedef {Record<String, TweenParamValue>} PercentageKeyframeParams
*/
/**
* @typedef {Record<String, PercentageKeyframeParams & PercentageKeyframeOptions>} PercentageKeyframes
*/
/**
* @typedef {Array<Record<String, TweenOptions | TweenModifier | boolean> & TweenParamsOptions>} DurationKeyframes
*/
/**
* @typedef {Object} AnimationOptions
* @property {PercentageKeyframes|DurationKeyframes} [keyframes]
* @property {EasingParam} [playbackEase]
*/
// TODO: Currently setting TweenModifier to the intersected Record<> makes the FunctionValue type target param any if only one parameter is set
/**
* @typedef {Record<String, TweenOptions | Callback<JSAnimation> | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & TickableCallbacks<JSAnimation> & RenderableCallbacks<JSAnimation>} AnimationParams
*/
// Timeline types
/**
* Accepts:<br>
* - `Number` - Absolute position in milliseconds (e.g., `500` places element at exactly 500ms)<br>
* - `'+=Number'` - Addition: Position element X ms after the last element (e.g., `'+=100'`)<br>
* - `'-=Number'` - Subtraction: Position element X ms before the last element's end (e.g., `'-=100'`)<br>
* - `'*=Number'` - Multiplier: Position element at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br>
* - `'<'` - Previous end: Position element at the end position of the previous element<br>
* - `'<<'` - Previous start: Position element at the start position of the previous element<br>
* - `'<<+=Number'` - Combined: Position element relative to previous element's start (e.g., `'<<+=250'`)<br>
* - `'label'` - Label: Position element at a named label position (e.g., `'My Label'`)
*
* @typedef {Number|`+=${Number}`|`-=${Number}`|`*=${Number}`|'<'|'<<'|`<<+=${Number}`|`<<-=${Number}`|String} TimelinePosition
*/
/**
* Accepts:<br>
* - `Number` - Absolute position in milliseconds (e.g., `500` places animation at exactly 500ms)<br>
* - `'+=Number'` - Addition: Position animation X ms after the last animation (e.g., `'+=100'`)<br>
* - `'-=Number'` - Subtraction: Position animation X ms before the last animation's end (e.g., `'-=100'`)<br>
* - `'*=Number'` - Multiplier: Position animation at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br>
* - `'<'` - Previous end: Position animation at the end position of the previous animation<br>
* - `'<<'` - Previous start: Position animation at the start position of the previous animation<br>
* - `'<<+=Number'` - Combined: Position animation relative to previous animation's start (e.g., `'<<+=250'`)<br>
* - `'label'` - Label: Position animation at a named label position (e.g., `'My Label'`)<br>
* - `stagger(String|Nummber)` - Stagger multi-elements animation positions (e.g., 10, 20, 30...)
*
* @typedef {TimelinePosition | StaggerFunction<Number|String>} TimelineAnimationPosition
*/
/**
* @typedef {Object} TimelineOptions
* @property {DefaultsParams} [defaults]
* @property {EasingParam} [playbackEase]
*/
/**
* @typedef {TimerOptions & TimelineOptions & TickableCallbacks<Timeline> & RenderableCallbacks<Timeline>} TimelineParams
*/
// WAAPIAnimation types
/**
* @typedef {String|Number|Array<String>|Array<Number>} WAAPITweenValue
*/
/**
* @callback WAAPIFunctionValue
* @param {DOMTarget} target - The animated target
* @param {Number} index - The target index
* @param {Number} length - The total number of animated targets
* @return {WAAPITweenValue}
*/
/**
* @typedef {WAAPITweenValue|WAAPIFunctionValue|Array<String|Number|WAAPIFunctionValue>} WAAPIKeyframeValue
*/
/**
* @typedef {Object} WAAPITweenOptions
* @property {WAAPIKeyframeValue} [to]
* @property {WAAPIKeyframeValue} [from]
* @property {Number|WAAPIFunctionValue} [duration]
* @property {Number|WAAPIFunctionValue} [delay]
* @property {WAAPIEasingParam} [ease]
* @property {CompositeOperation} [composition]
*/
/**
* @typedef {Object} WAAPIAnimationOptions
* @property {Number|Boolean} [loop]
* @property {Boolean} [Reversed]
* @property {Boolean} [Alternate]
* @property {Boolean|ScrollObserver} [autoplay]
* @property {Number} [playbackRate]
* @property {Number|WAAPIFunctionValue} [duration]
* @property {Number|WAAPIFunctionValue} [delay]
* @property {WAAPIEasingParam} [ease]
* @property {CompositeOperation} [composition]
* @property {Boolean} [persist]
* @property {Callback<WAAPIAnimation>} [onComplete]
*/
/**
* @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | Callback<WAAPIAnimation> | WAAPIEasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams
*/
// Animatable types
/**
* @callback AnimatablePropertySetter
* @param {Number|Array.<Number>} to
* @param {Number} [duration]
* @param {EasingParam} [ease]
* @return {AnimatableObject}
*/
/**
* @callback AnimatablePropertyGetter
* @return {Number|Array.<Number>}
*/
/**
* @typedef {AnimatablePropertySetter & AnimatablePropertyGetter} AnimatableProperty
*/
/**
* @typedef {Animatable & Record<String, AnimatableProperty>} AnimatableObject
*/
/**
* @typedef {Object} AnimatablePropertyParamsOptions
* @property {String} [unit]
* @property {TweenParamValue} [duration]
* @property {EasingParam} [ease]
* @property {TweenModifier} [modifier]
* @property {TweenComposition} [composition]
*/
/**
* @typedef {Record<String, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions} AnimatableParams
*/
// Scope types
/**
* @typedef {Object} ReactRef
* @property {HTMLElement|SVGElement|null} [current]
*/
/**
* @typedef {Object} AngularRef
* @property {HTMLElement|SVGElement} [nativeElement]
*/
/**
* @typedef {Object} ScopeParams
* @property {DOMTargetSelector|ReactRef|AngularRef} [root]
* @property {DefaultsParams} [defaults]
* @property {Record<String, String>} [mediaQueries]
*/
/**
* @template T
* @callback ScopedCallback
* @param {Scope} scope
* @return {T}
*/
/**
* @callback ScopeCleanupCallback
* @param {Scope} [scope]
*/
/**
* @callback ScopeConstructorCallback
* @param {Scope} [scope]
* @return {ScopeCleanupCallback|void}
*/
/**
* @callback ScopeMethod
* @param {...*} args
* @return {ScopeCleanupCallback|void}
*/
// Scroll types
/**
* @typedef {String|Number} ScrollThresholdValue
*/
/**
* @typedef {Object} ScrollThresholdParam
* @property {ScrollThresholdValue} [target]
* @property {ScrollThresholdValue} [container]
*/
/**
* @callback ScrollObserverAxisCallback
* @param {ScrollObserver} self
* @return {'x'|'y'}
*/
/**
* @callback ScrollThresholdCallback
* @param {ScrollObserver} self
* @return {ScrollThresholdValue|ScrollThresholdParam}
*/
/**
* @typedef {Object} ScrollObserverParams
* @property {Number|String} [id]
* @property {Boolean|Number|String|EasingParam} [sync]
* @property {TargetsParam} [container]
* @property {TargetsParam} [target]
* @property {'x'|'y'|ScrollObserverAxisCallback|((observer: ScrollObserver) => 'x'|'y'|ScrollObserverAxisCallback)} [axis]
* @property {ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback|((observer: ScrollObserver) => ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback)} [enter]
* @property {ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback|((observer: ScrollObserver) => ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback)} [leave]
* @property {Boolean|((observer: ScrollObserver) => Boolean)} [repeat]
* @property {Boolean} [debug]
* @property {Callback<ScrollObserver>} [onEnter]
* @property {Callback<ScrollObserver>} [onLeave]
* @property {Callback<ScrollObserver>} [onEnterForward]
* @property {Callback<ScrollObserver>} [onLeaveForward]
* @property {Callback<ScrollObserver>} [onEnterBackward]
* @property {Callback<ScrollObserver>} [onLeaveBackward]
* @property {Callback<ScrollObserver>} [onUpdate]
* @property {Callback<ScrollObserver>} [onSyncComplete]
*/
// Draggable types
/**
* @typedef {Object} DraggableAxisParam
* @property {String} [mapTo]
* @property {TweenModifier} [modifier]
* @property {TweenComposition} [composition]
* @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap]
*/
/**
* @typedef {Object} DraggableCursorParams
* @property {String} [onHover]
* @property {String} [onGrab]
*/
/**
* @typedef {Object} DraggableDragThresholdParams
* @property {Number} [mouse]
* @property {Number} [touch]
*/
/**
* @typedef {Object} DraggableParams
* @property {DOMTargetSelector} [trigger]
* @property {DOMTargetSelector|Array<Number>|((draggable: Draggable) => DOMTargetSelector|Array<Number>)} [container]
* @property {Boolean|DraggableAxisParam} [x]
* @property {Boolean|DraggableAxisParam} [y]
* @property {TweenModifier} [modifier]
* @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap]
* @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [containerPadding]
* @property {Number|((draggable: Draggable) => Number)} [containerFriction]
* @property {Number|((draggable: Draggable) => Number)} [releaseContainerFriction]
* @property {Number|((draggable: Draggable) => Number)} [dragSpeed]
* @property {Number|DraggableDragThresholdParams|((draggable: Draggable) => Number|DraggableDragThresholdParams)} [dragThreshold]
* @property {Number|((draggable: Draggable) => Number)} [scrollSpeed]
* @property {Number|((draggable: Draggable) => Number)} [scrollThreshold]
* @property {Number|((draggable: Draggable) => Number)} [minVelocity]
* @property {Number|((draggable: Draggable) => Number)} [maxVelocity]
* @property {Number|((draggable: Draggable) => Number)} [velocityMultiplier]
* @property {Number} [releaseMass]
* @property {Number} [releaseStiffness]
* @property {Number} [releaseDamping]
* @property {Boolean} [releaseDamping]
* @property {EasingParam} [releaseEase]
* @property {Boolean|DraggableCursorParams|((draggable: Draggable) => Boolean|DraggableCursorParams)} [cursor]
* @property {Callback<Draggable>} [onGrab]
* @property {Callback<Draggable>} [onDrag]
* @property {Callback<Draggable>} [onRelease]
* @property {Callback<Draggable>} [onUpdate]
* @property {Callback<Draggable>} [onSettle]
* @property {Callback<Draggable>} [onSnap]
* @property {Callback<Draggable>} [onResize]
* @property {Callback<Draggable>} [onAfterResize]
*/
// Text types
/**
* @typedef {Object} SplitTemplateParams
* @property {false|String} [class]
* @property {Boolean|'hidden'|'clip'|'visible'|'scroll'|'auto'} [wrap]
* @property {Boolean|'top'|'right'|'bottom'|'left'|'center'} [clone]
*/
/**
* @typedef {Boolean|String} SplitValue
*/
/**
* @callback SplitFunctionValue
* @param {Node|HTMLElement} [value]
* @return String
*/
/**
* @typedef {Object} TextSplitterParams
* @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [lines]
* @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [words]
* @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [chars]
* @property {Boolean} [accessible]
* @property {Boolean} [includeSpaces]
* @property {Boolean} [debug]
*/
// SVG types
/**
* @typedef {SVGGeometryElement & {
* setAttribute(name: 'draw', value: `${number} ${number}`): void;
* draw: `${number} ${number}`;
* }} DrawableSVGGeometry
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.anime = {}));
})(this, (function (exports) { 'use strict';
// Environments
// TODO: Do we need to check if we're running inside a worker ?
const isBrowser = typeof window !== 'undefined';
/** @type {Window & {AnimeJS: Array}|null} */
const win = isBrowser ? /** @type {Window & {AnimeJS: Array}} */(/** @type {unknown} */(window)) : null;
/** @type {Document|null} */
const doc = isBrowser ? document : null;
// Enums
/** @enum {Number} */
const tweenTypes = {
OBJECT: 0,
ATTRIBUTE: 1,
CSS: 2,
TRANSFORM: 3,
CSS_VAR: 4,
};
/** @enum {Number} */
const valueTypes = {
NUMBER: 0,
UNIT: 1,
COLOR: 2,
COMPLEX: 3,
};
/** @enum {Number} */
const tickModes = {
NONE: 0,
AUTO: 1,
FORCE: 2,
};
/** @enum {Number} */
const compositionTypes = {
replace: 0,
none: 1,
blend: 2,
};
// Cache symbols
const isRegisteredTargetSymbol = Symbol();
const isDomSymbol = Symbol();
const isSvgSymbol = Symbol();
const transformsSymbol = Symbol();
const morphPointsSymbol = Symbol();
const proxyTargetSymbol = Symbol();
// Numbers
const minValue = 1e-11;
const maxValue = 1e12;
const K = 1e3;
const maxFps = 120;
// Strings
const emptyString = '';
const cssVarPrefix = 'var(';
const shortTransforms = /*#__PURE__*/ (() => {
const map = new Map();
map.set('x', 'translateX');
map.set('y', 'translateY');
map.set('z', 'translateZ');
return map;
})();
const validTransforms = [
'translateX',
'translateY',
'translateZ',
'rotate',
'rotateX',
'rotateY',
'rotateZ',
'scale',
'scaleX',
'scaleY',
'scaleZ',
'skew',
'skewX',
'skewY',
'matrix',
'matrix3d',
'perspective',
];
const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {});
// Functions
/** @return {void} */
const noop = () => {};
// Regex
const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i;
const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i;
const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i;
const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i;
// export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g;
const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi;
// export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i;
const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i;
const lowerCaseRgx = /([a-z])([A-Z])/g;
const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in ()
const relativeValuesExecRgx = /(\*=|\+=|-=)/;
const cssVariableMatchRgx = /var\(\s*(--[\w-]+)(?:\s*,\s*([^)]+))?\s*\)/;
/** @type {DefaultsParams} */
const defaults = {
id: null,
keyframes: null,
playbackEase: null,
playbackRate: 1,
frameRate: maxFps,
loop: 0,
reversed: false,
alternate: false,
autoplay: true,
persist: false,
duration: K,
delay: 0,
loopDelay: 0,
ease: 'out(2)',
composition: compositionTypes.replace,
modifier: v => v,
onBegin: noop,
onBeforeUpdate: noop,
onUpdate: noop,
onLoop: noop,
onPause: noop,
onComplete: noop,
onRender: noop,
};
const scope = {
/** @type {Scope} */
current: null,
/** @type {Document|DOMTarget} */
root: doc,
};
const globals = {
/** @type {DefaultsParams} */
defaults,
/** @type {Number} */
precision: 4,
/** @type {Number} equals 1 in ms mode, 0.001 in s mode */
timeScale: 1,
/** @type {Number} */
tickThreshold: 200,
};
const globalVersions = { version: '4.2.2', engine: null };
if (isBrowser) {
if (!win.AnimeJS) win.AnimeJS = [];
win.AnimeJS.push(globalVersions);
}
// Strings
/**
* @param {String} str
* @return {String}
*/
const toLowerCase = str => str.replace(lowerCaseRgx, '$1-$2').toLowerCase();
/**
* Prioritize this method instead of regex when possible
* @param {String} str
* @param {String} sub
* @return {Boolean}
*/
const stringStartsWith = (str, sub) => str.indexOf(sub) === 0;
// Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement.
const now = Date.now;
// Types checkers
const isArr = Array.isArray;
/**@param {any} a @return {a is Record<String, any>} */
const isObj = a => a && a.constructor === Object;
/**@param {any} a @return {a is Number} */
const isNum = a => typeof a === 'number' && !isNaN(a);
/**@param {any} a @return {a is String} */
const isStr = a => typeof a === 'string';
/**@param {any} a @return {a is Function} */
const isFnc = a => typeof a === 'function';
/**@param {any} a @return {a is undefined} */
const isUnd = a => typeof a === 'undefined';
/**@param {any} a @return {a is null | undefined} */
const isNil = a => isUnd(a) || a === null;
/**@param {any} a @return {a is SVGElement} */
const isSvg = a => isBrowser && a instanceof SVGElement;
/**@param {any} a @return {Boolean} */
const isHex = a => hexTestRgx.test(a);
/**@param {any} a @return {Boolean} */
const isRgb = a => stringStartsWith(a, 'rgb');
/**@param {any} a @return {Boolean} */
const isHsl = a => stringStartsWith(a, 'hsl');
/**@param {any} a @return {Boolean} */
const isCol = a => isHex(a) || isRgb(a) || isHsl(a);
/**@param {any} a @return {Boolean} */
const isKey = a => !globals.defaults.hasOwnProperty(a);
// SVG
// Consider the following as CSS animation
// CSS opacity animation has better default values (opacity: 1 instead of 0))
// rotate is more commonly intended to be used as a transform
const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color'];
/**
* @param {Target} el
* @param {String} propertyName
* @return {Boolean}
*/
const isValidSVGAttribute = (el, propertyName) => {
if (svgCssReservedProperties.includes(propertyName)) return false;
if (el.getAttribute(propertyName) || propertyName in el) {
if (propertyName === 'scale') { // Scale
const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode);
// Only consider scale as a valid SVG attribute on filter element
return elParentNode && elParentNode.tagName === 'filter';
}
return true;
}
};
// Number
/**
* @param {Number|String} str
* @return {Number}
*/
const parseNumber = str => isStr(str) ?
parseFloat(/** @type {String} */(str)) :
/** @type {Number} */(str);
// Math
const pow = Math.pow;
const sqrt = Math.sqrt;
const sin = Math.sin;
const cos = Math.cos;
const abs = Math.abs;
const exp = Math.exp;
const ceil = Math.ceil;
const floor = Math.floor;
const asin = Math.asin;
const max = Math.max;
const atan2 = Math.atan2;
const PI = Math.PI;
const _round = Math.round;
/**
* Clamps a value between min and max bounds
*
* @param {Number} v - Value to clamp
* @param {Number} min - Minimum boundary
* @param {Number} max - Maximum boundary
* @return {Number}
*/
const clamp$1 = (v, min, max) => v < min ? min : v > max ? max : v;
const powCache = {};
/**
* Rounds a number to specified decimal places
*
* @param {Number} v - Value to round
* @param {Number} decimalLength - Number of decimal places
* @return {Number}
*/
const round$1 = (v, decimalLength) => {
if (decimalLength < 0) return v;
if (!decimalLength) return _round(v);
let p = powCache[decimalLength];
if (!p) p = powCache[decimalLength] = 10 ** decimalLength;
return _round(v * p) / p;
};
/**
* Snaps a value to nearest increment or array value
*
* @param {Number} v - Value to snap
* @param {Number|Array<Number>} increment - Step size or array of snap points
* @return {Number}
*/
const snap$1 = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v;
/**
* Linear interpolation between two values
*
* @param {Number} start - Starting value
* @param {Number} end - Ending value
* @param {Number} factor - Interpolation factor in the range [0, 1]
* @return {Number} The interpolated value
*/
const lerp$1 = (start, end, factor) => start + (end - start) * factor;
/**
* Replaces infinity with maximum safe value
*
* @param {Number} v - Value to check
* @return {Number}
*/
const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v;
/**
* Normalizes time value with minimum threshold
*
* @param {Number} v - Time value to normalize
* @return {Number}
*/
const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round$1(v, 11));
// Arrays
/**
* @template T
* @param {T[]} a
* @return {T[]}
*/
const cloneArray = a => isArr(a) ? [ ...a ] : a;
// Objects
/**
* @template T
* @template U
* @param {T} o1
* @param {U} o2
* @return {T & U}
*/
const mergeObjects = (o1, o2) => {
const merged = /** @type {T & U} */({ ...o1 });
for (let p in o2) {
const o1p = /** @type {T & U} */(o1)[p];
merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p;
} return merged;
};
// Linked lists
/**
* @param {Object} parent
* @param {Function} callback
* @param {Boolean} [reverse]
* @param {String} [prevProp]
* @param {String} [nextProp]
* @return {void}
*/
const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => {
let next = parent._head;
let adjustedNextProp = nextProp;
if (reverse) {
next = parent._tail;
adjustedNextProp = prevProp;
}
while (next) {
const currentNext = next[adjustedNextProp];
callback(next);
next = currentNext;
}
};
/**
* @param {Object} parent
* @param {Object} child
* @param {String} [prevProp]
* @param {String} [nextProp]
* @return {void}
*/
const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => {
const prev = child[prevProp];
const next = child[nextProp];
prev ? prev[nextProp] = next : parent._head = next;
next ? next[prevProp] = prev : parent._tail = prev;
child[prevProp] = null;
child[nextProp] = null;
};
/**
* @param {Object} parent
* @param {Object} child
* @param {Function} [sortMethod]
* @param {String} prevProp
* @param {String} nextProp
* @return {void}
*/
const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => {
let prev = parent._tail;
while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp];
const next = prev ? prev[nextProp] : parent._head;
prev ? prev[nextProp] = child : parent._head = child;
| javascript | MIT | b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d | 2026-01-04T14:56:49.711869Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.