code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
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) { // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list tickable.paused = true; if (!tickable.completed) { tickable.completed = true; if (!muteCallbacks) { tickable.onComplete(tickable); tickable._resolve(tickable); } } } } // TODO: return hasRendered * direction (negative for backwards) this way we can remove the tickable._backwards property completly return hasRendered; }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {tickModes} tickMode @return {Number}
render
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
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) { // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list tickable.paused = true; if (!tickable.completed) { tickable.completed = true; if (!muteCallbacks) { tickable.onComplete(tickable); tickable._resolve(tickable); } } } } // TODO: return hasRendered * direction (negative for backwards) this way we can remove the tickable._backwards property completly return hasRendered; }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {tickModes} tickMode @return {Number}
render
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
tick = (tickable, time, muteCallbacks, internalRender, tickMode) => { render(tickable, time, muteCallbacks, internalRender, tickMode); if (tickable._hasChildren) { let hasRendered = 0; // Don't use the iteration time with internalRender // otherwise it will be converted twice further down the line const childrenTime = internalRender ? time : tickable._iterationTime; const childrenTickTime = now(); forEachChildren(tickable, (/** @type {$Animation} */child) => { hasRendered += render( child, (childrenTime - child._offset) * child._speed, muteCallbacks, internalRender, child._fps < tickable._fps ? child.requestTick(childrenTickTime) : tickMode ); }, tickable._backwards); if (tickable.began && hasRendered) { /** @type {Timeline} */(tickable).onRender(/** @type {Timeline} */(tickable)); } } }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {Number} tickMode @return {void}
tick
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
tick = (tickable, time, muteCallbacks, internalRender, tickMode) => { render(tickable, time, muteCallbacks, internalRender, tickMode); if (tickable._hasChildren) { let hasRendered = 0; // Don't use the iteration time with internalRender // otherwise it will be converted twice further down the line const childrenTime = internalRender ? time : tickable._iterationTime; const childrenTickTime = now(); forEachChildren(tickable, (/** @type {$Animation} */child) => { hasRendered += render( child, (childrenTime - child._offset) * child._speed, muteCallbacks, internalRender, child._fps < tickable._fps ? child.requestTick(childrenTickTime) : tickMode ); }, tickable._backwards); if (tickable.began && hasRendered) { /** @type {Timeline} */(tickable).onRender(/** @type {Timeline} */(tickable)); } } }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {Number} tickMode @return {void}
tick
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
function getNodeList(v) { const n = isStr(v) ? globals.root.querySelectorAll(v) : v; if (n instanceof NodeList || n instanceof HTMLCollection) return n; }
@param {DOMTargetsParam|TargetsParam} v @return {NodeList|HTMLCollection}
getNodeList
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
function parseTargets(targets) { if (isNil(targets)) return /** @type {TargetsArray} */([]); if (isArr(targets)) { const flattened = targets.flat(Infinity); /** @type {TargetsArray} */ const parsed = []; for (let i = 0, l = flattened.length; i < l; i++) { const item = flattened[i]; if (!isNil(item)) { const nodeList = getNodeList(item); if (nodeList) { for (let j = 0, jl = nodeList.length; j < jl; j++) { const subItem = nodeList[j]; if (!isNil(subItem)) { let isDuplicate = false; for (let k = 0, kl = parsed.length; k < kl; k++) { if (parsed[k] === subItem) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(subItem); } } } } else { let isDuplicate = false; for (let j = 0, jl = parsed.length; j < jl; j++) { if (parsed[j] === item) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(item); } } } } return parsed; } if (!isBrowser) return /** @type {JSTargetsArray} */([targets]); const nodeList = getNodeList(targets); if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList)); return /** @type {TargetsArray} */([targets]); }
@overload @param {DOMTargetsParam} targets @return {DOMTargetsArray} @overload @param {JSTargetsParam} targets @return {JSTargetsArray} @overload @param {TargetsParam} targets @return {TargetsArray} @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
parseTargets
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
function registerTargets(targets) { const parsedTargetsArray = parseTargets(targets); const parsedTargetsLength = parsedTargetsArray.length; if (parsedTargetsLength) { for (let i = 0; i < parsedTargetsLength; i++) { const target = parsedTargetsArray[i]; if (!target[isRegisteredTargetSymbol]) { target[isRegisteredTargetSymbol] = true; const isSvgType = isSvg(target); const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType; if (isDom) { target[isDomSymbol] = true; target[isSvgSymbol] = isSvgType; target[transformsSymbol] = {}; } } } } return parsedTargetsArray; }
@overload @param {DOMTargetsParam} targets @return {DOMTargetsArray} @overload @param {JSTargetsParam} targets @return {JSTargetsArray} @overload @param {TargetsParam} targets @return {TargetsArray} @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
registerTargets
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
binarySubdivide = (aX, mX1, mX2) => { let aA = 0, aB = 1, currentX, currentT, i = 0; do { currentT = aA + (aB - aA) / 2; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0) { aB = currentT; } else { aA = currentT; } } while (abs(currentX) > .0000001 && ++i < 100); return currentT; }
@param {Number} aX @param {Number} mX1 @param {Number} mX2 @return {Number}
binarySubdivide
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
binarySubdivide = (aX, mX1, mX2) => { let aA = 0, aB = 1, currentX, currentT, i = 0; do { currentT = aA + (aB - aA) / 2; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0) { aB = currentT; } else { aA = currentT; } } while (abs(currentX) > .0000001 && ++i < 100); return currentT; }
@param {Number} aX @param {Number} mX1 @param {Number} mX2 @return {Number}
binarySubdivide
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none : t => t === 0 || t === 1 ? t : calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2)
@param {Number} [mX1] @param {Number} [mY1] @param {Number} [mX2] @param {Number} [mY2] @return {EasingFunction}
cubicBezier
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none : t => t === 0 || t === 1 ? t : calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2)
@param {Number} [mX1] @param {Number} [mY1] @param {Number} [mX2] @param {Number} [mY2] @return {EasingFunction}
cubicBezier
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
linear = (...args) => { const argsLength = args.length; if (!argsLength) return none; const totalPoints = argsLength - 1; const firstArg = args[0]; const lastArg = args[totalPoints]; const xPoints = [0]; const yPoints = [parseNumber(firstArg)]; for (let i = 1; i < totalPoints; i++) { const arg = args[i]; const splitValue = isStr(arg) ? /** @type {String} */(arg).trim().split(' ') : [arg]; const value = splitValue[0]; const percent = splitValue[1]; xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints); yPoints.push(parseNumber(value)); } yPoints.push(parseNumber(lastArg)); xPoints.push(1); return function easeLinear(t) { for (let i = 1, l = xPoints.length; i < l; i++) { const currentX = xPoints[i]; if (t <= currentX) { const prevX = xPoints[i - 1]; const prevY = yPoints[i - 1]; return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX); } } return yPoints[yPoints.length - 1]; } }
Without parameters, the linear function creates a non-eased transition. Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points. @param {...String|Number} [args] - Points @return {EasingFunction}
linear
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
linear = (...args) => { const argsLength = args.length; if (!argsLength) return none; const totalPoints = argsLength - 1; const firstArg = args[0]; const lastArg = args[totalPoints]; const xPoints = [0]; const yPoints = [parseNumber(firstArg)]; for (let i = 1; i < totalPoints; i++) { const arg = args[i]; const splitValue = isStr(arg) ? /** @type {String} */(arg).trim().split(' ') : [arg]; const value = splitValue[0]; const percent = splitValue[1]; xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints); yPoints.push(parseNumber(value)); } yPoints.push(parseNumber(lastArg)); xPoints.push(1); return function easeLinear(t) { for (let i = 1, l = xPoints.length; i < l; i++) { const currentX = xPoints[i]; if (t <= currentX) { const prevX = xPoints[i - 1]; const prevY = yPoints[i - 1]; return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX); } } return yPoints[yPoints.length - 1]; } }
Without parameters, the linear function creates a non-eased transition. Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points. @param {...String|Number} [args] - Points @return {EasingFunction}
linear
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
irregular = (length = 10, randomness = 1) => { const values = [0]; const total = length - 1; for (let i = 1; i < total; i++) { const previousValue = values[i - 1]; const spacing = i / total; const segmentEnd = (i + 1) / total; const randomVariation = spacing + (segmentEnd - spacing) * Math.random(); // Mix the even spacing and random variation based on the randomness parameter const randomValue = spacing * (1 - randomness) + randomVariation * randomness; values.push(clamp(randomValue, previousValue, 1)); } values.push(1); return linear(...values); }
Generate random steps @param {Number} [length] - The number of steps @param {Number} [randomness] - How strong the randomness is @return {EasingFunction}
irregular
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
irregular = (length = 10, randomness = 1) => { const values = [0]; const total = length - 1; for (let i = 1; i < total; i++) { const previousValue = values[i - 1]; const spacing = i / total; const segmentEnd = (i + 1) / total; const randomVariation = spacing + (segmentEnd - spacing) * Math.random(); // Mix the even spacing and random variation based on the randomness parameter const randomValue = spacing * (1 - randomness) + randomVariation * randomness; values.push(clamp(randomValue, previousValue, 1)); } values.push(1); return linear(...values); }
Generate random steps @param {Number} [length] - The number of steps @param {Number} [randomness] - How strong the randomness is @return {EasingFunction}
irregular
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } } return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue : stringStartsWith(propName, 'scale') ? '1' : stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px'; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
parseInlineTransforms
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } } return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue : stringStartsWith(propName, 'scale') ? '1' : stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px'; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
parseInlineTransforms
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getPath = path => { const parsedTargets = parseTargets(path); const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]); if (!$parsedSvg || !isSvg($parsedSvg)) return; return $parsedSvg; }
@param {TargetsParam} path @return {SVGGeometryElement|undefined}
getPath
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getPath = path => { const parsedTargets = parseTargets(path); const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]); if (!$parsedSvg || !isSvg($parsedSvg)) return; return $parsedSvg; }
@param {TargetsParam} path @return {SVGGeometryElement|undefined}
getPath
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
morphTo = (path2, precision = .33) => ($path1) => { const $path2 = /** @type {SVGGeometryElement} */(getPath(path2)); if (!$path2) return; const isPath = $path1.tagName === 'path'; const separator = isPath ? ' ' : ','; const previousPoints = $path1[morphPointsSymbol]; if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints); let v1 = '', v2 = ''; if (!precision) { v1 = $path1.getAttribute(isPath ? 'd' : 'points'); v2 = $path2.getAttribute(isPath ? 'd' : 'points'); } else { const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength(); const length2 = $path2.getTotalLength(); const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision)); for (let i = 0; i < maxPoints; i++) { const t = i / (maxPoints - 1); const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t); const pointOnPath2 = $path2.getPointAtLength(length2 * t); const prefix = isPath ? (i === 0 ? 'M' : 'L') : ''; v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' '; v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' '; } } $path1[morphPointsSymbol] = v2; return [v1, v2]; }
@param {TargetsParam} path2 @param {Number} [precision] @return {FunctionValue}
morphTo
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
morphTo = (path2, precision = .33) => ($path1) => { const $path2 = /** @type {SVGGeometryElement} */(getPath(path2)); if (!$path2) return; const isPath = $path1.tagName === 'path'; const separator = isPath ? ' ' : ','; const previousPoints = $path1[morphPointsSymbol]; if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints); let v1 = '', v2 = ''; if (!precision) { v1 = $path1.getAttribute(isPath ? 'd' : 'points'); v2 = $path2.getAttribute(isPath ? 'd' : 'points'); } else { const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength(); const length2 = $path2.getTotalLength(); const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision)); for (let i = 0; i < maxPoints; i++) { const t = i / (maxPoints - 1); const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t); const pointOnPath2 = $path2.getPointAtLength(length2 * t); const prefix = isPath ? (i === 0 ? 'M' : 'L') : ''; v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' '; v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' '; } } $path1[morphPointsSymbol] = v2; return [v1, v2]; }
@param {TargetsParam} path2 @param {Number} [precision] @return {FunctionValue}
morphTo
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
function createDrawableProxy($el, start, end) { const strokeLineCap = getComputedStyle($el).strokeLinecap; const pathLength = 100000; let currentCap = strokeLineCap; const proxy = new Proxy($el, { get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { /** @param {any[]} args */ return (...args) => { if (args[0] === 'draw') { const value = args[1]; const precision = globals.precision; const values = value.split(' '); const v1 = round(+values[0], precision); const v2 = round(+values[1], precision); // 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 os = round((v1 * -pathLength), 0); const d1 = round((v2 * pathLength) + os, 0); const d2 = round(pathLength - d1, 0); // Handle cases where the cap is still visible when the line is completly hidden if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.setAttribute('stroke-linecap', `${newCap}`); currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { /** @param {any[]} args */ 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 {typeof Proxy} */(/** @type {unknown} */(proxy)); }
@param {SVGGeometryElement} $el @param {Number} start @param {Number} end @return {Proxy}
createDrawableProxy
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { /** @param {any[]} args */ return (...args) => { if (args[0] === 'draw') { const value = args[1]; const precision = globals.precision; const values = value.split(' '); const v1 = round(+values[0], precision); const v2 = round(+values[1], precision); // 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 os = round((v1 * -pathLength), 0); const d1 = round((v2 * pathLength) + os, 0); const d2 = round(pathLength - d1, 0); // Handle cases where the cap is still visible when the line is completly hidden if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.setAttribute('stroke-linecap', `${newCap}`); currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { /** @param {any[]} args */ return (...args) => Reflect.apply(value, target, args); } else { return value; } }
@param {SVGGeometryElement} $el @param {Number} start @param {Number} end @return {Proxy}
get
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
createDrawable = (selector, start = 0, end = 0) => { const els = /** @type {Array.<Proxy>} */((/** @type {unknown} */(parseTargets(selector)))); els.forEach(($el, i) => els[i] = createDrawableProxy(/** @type {SVGGeometryElement} */(/** @type {unknown} */($el)), start, end)); return els; }
@param {TargetsParam} selector @param {Number} [start=0] @param {Number} [end=0] @return {Array.<Proxy>}
createDrawable
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
createDrawable = (selector, start = 0, end = 0) => { const els = /** @type {Array.<Proxy>} */((/** @type {unknown} */(parseTargets(selector)))); els.forEach(($el, i) => els[i] = createDrawableProxy(/** @type {SVGGeometryElement} */(/** @type {unknown} */($el)), start, end)); return els; }
@param {TargetsParam} selector @param {Number} [start=0] @param {Number} [end=0] @return {Array.<Proxy>}
createDrawable
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getPathPoint = ($path, progress, lookup = 0) => { return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0); }
@param {SVGGeometryElement} $path @param {Number} progress @param {Number}lookup @return {DOMPoint}
getPathPoint
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getPathPoint = ($path, progress, lookup = 0) => { return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0); }
@param {SVGGeometryElement} $path @param {Number} progress @param {Number}lookup @return {DOMPoint}
getPathPoint
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getPathProgess = ($path, pathProperty) => { return $el => { const totalLength = +($path.getTotalLength()); const inSvg = $el[isSvgSymbol]; const ctm = $path.getCTM(); /** @type {TweenObjectValue} */ return { from: 0, to: totalLength, /** @type {TweenModifier} */ modifier: progress => { if (pathProperty === 'a') { const p0 = getPathPoint($path, progress, -1); const p1 = getPathPoint($path, progress, +1); return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI; } else { const p = getPathPoint($path, progress, 0); return pathProperty === 'x' ? inSvg ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e : inSvg ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f } } } } }
@param {SVGGeometryElement} $path @param {String} pathProperty @return {FunctionValue}
getPathProgess
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getPathProgess = ($path, pathProperty) => { return $el => { const totalLength = +($path.getTotalLength()); const inSvg = $el[isSvgSymbol]; const ctm = $path.getCTM(); /** @type {TweenObjectValue} */ return { from: 0, to: totalLength, /** @type {TweenModifier} */ modifier: progress => { if (pathProperty === 'a') { const p0 = getPathPoint($path, progress, -1); const p1 = getPathPoint($path, progress, +1); return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI; } else { const p = getPathPoint($path, progress, 0); return pathProperty === 'x' ? inSvg ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e : inSvg ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f } } } } }
@param {SVGGeometryElement} $path @param {String} pathProperty @return {FunctionValue}
getPathProgess
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
isValidSVGAttribute = (el, propertyName) => { // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform if (cssReservedProperties.includes(propertyName)) return false; if (propertyName in /** @type {DOMTarget} */(el).style || 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; } }
@param {Target} el @param {String} propertyName @return {Boolean}
isValidSVGAttribute
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
isValidSVGAttribute = (el, propertyName) => { // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform if (cssReservedProperties.includes(propertyName)) return false; if (propertyName in /** @type {DOMTarget} */(el).style || 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; } }
@param {Target} el @param {String} propertyName @return {Boolean}
isValidSVGAttribute
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
rgbToRgba = rgbValue => { const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue); const a = !isUnd(rgba[4]) ? +rgba[4] : 1; return [ +rgba[1], +rgba[2], +rgba[3], a ] }
RGB / RGBA Color value string -> RGBA values array @param {String} rgbValue @return {ColorArray}
rgbToRgba
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
rgbToRgba = rgbValue => { const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue); const a = !isUnd(rgba[4]) ? +rgba[4] : 1; return [ +rgba[1], +rgba[2], +rgba[3], a ] }
RGB / RGBA Color value string -> RGBA values array @param {String} rgbValue @return {ColorArray}
rgbToRgba
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
hexToRgba = hexValue => { const hexLength = hexValue.length; const isShort = hexLength === 4 || hexLength === 5; return [ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]), +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]), +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]), ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1) ] }
HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array @param {String} hexValue @return {ColorArray}
hexToRgba
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
hexToRgba = hexValue => { const hexLength = hexValue.length; const isShort = hexLength === 4 || hexLength === 5; return [ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]), +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]), +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]), ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1) ] }
HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array @param {String} hexValue @return {ColorArray}
hexToRgba
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
hue2rgb = (p, q, t) => { if (t < 0) t += 1; if (t > 1) t -= 1; return t < 1 / 6 ? p + (q - p) * 6 * t : t < 1 / 2 ? q : t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 : p; }
@param {Number} p @param {Number} q @param {Number} t @return {Number}
hue2rgb
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
hue2rgb = (p, q, t) => { if (t < 0) t += 1; if (t > 1) t -= 1; return t < 1 / 6 ? p + (q - p) * 6 * t : t < 1 / 2 ? q : t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 : p; }
@param {Number} p @param {Number} q @param {Number} t @return {Number}
hue2rgb
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
hslToRgba = hslValue => { const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue); const h = +hsla[1] / 360; const s = +hsla[2] / 100; const l = +hsla[3] / 100; const a = !isUnd(hsla[4]) ? +hsla[4] : 1; let r, g, b; if (s === 0) { r = g = b = l; } else { const q = l < .5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = round(hue2rgb(p, q, h + 1 / 3) * 255, 0); g = round(hue2rgb(p, q, h) * 255, 0); b = round(hue2rgb(p, q, h - 1 / 3) * 255, 0); } return [r, g, b, a]; }
HSL / HSLA Color value string -> RGBA values array @param {String} hslValue @return {ColorArray}
hslToRgba
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
hslToRgba = hslValue => { const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue); const h = +hsla[1] / 360; const s = +hsla[2] / 100; const l = +hsla[3] / 100; const a = !isUnd(hsla[4]) ? +hsla[4] : 1; let r, g, b; if (s === 0) { r = g = b = l; } else { const q = l < .5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = round(hue2rgb(p, q, h + 1 / 3) * 255, 0); g = round(hue2rgb(p, q, h) * 255, 0); b = round(hue2rgb(p, q, h - 1 / 3) * 255, 0); } return [r, g, b, a]; }
HSL / HSLA Color value string -> RGBA values array @param {String} hslValue @return {ColorArray}
hslToRgba
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
convertColorStringValuesToRgbaArray = colorString => { return isRgb(colorString) ? rgbToRgba(colorString) : isHex(colorString) ? hexToRgba(colorString) : isHsl(colorString) ? hslToRgba(colorString) : [0, 0, 0, 1]; }
All in one color converter that converts a color string value into an array of RGBA values @param {String} colorString @return {ColorArray}
convertColorStringValuesToRgbaArray
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
convertColorStringValuesToRgbaArray = colorString => { return isRgb(colorString) ? rgbToRgba(colorString) : isHex(colorString) ? hexToRgba(colorString) : isHsl(colorString) ? hslToRgba(colorString) : [0, 0, 0, 1]; }
All in one color converter that converts a color string value into an array of RGBA values @param {String} colorString @return {ColorArray}
convertColorStringValuesToRgbaArray
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
setValue = (targetValue, defaultValue) => { return isUnd(targetValue) ? defaultValue : targetValue; }
@template T, D @param {T|undefined} targetValue @param {D} defaultValue @return {T|D}
setValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
setValue = (targetValue, defaultValue) => { return isUnd(targetValue) ? defaultValue : targetValue; }
@template T, D @param {T|undefined} targetValue @param {D} defaultValue @return {T|D}
setValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getFunctionValue = (value, target, index, total, store) => { if (isFnc(value)) { const func = () => { const computed = /** @type {Function} */(value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }; if (store) { store.func = func; } return func(); } else { return value; } }
@param {TweenPropValue} value @param {Target} target @param {Number} index @param {Number} total @param {Object} [store] @return {any}
getFunctionValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getFunctionValue = (value, target, index, total, store) => { if (isFnc(value)) { const func = () => { const computed = /** @type {Function} */(value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }; if (store) { store.func = func; } return func(); } else { return value; } }
@param {TweenPropValue} value @param {Target} target @param {Number} index @param {Number} total @param {Object} [store] @return {any}
getFunctionValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
func = () => { const computed = /** @type {Function} */(value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }
@param {TweenPropValue} value @param {Target} target @param {Number} index @param {Number} total @param {Object} [store] @return {any}
func
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
func = () => { const computed = /** @type {Function} */(value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }
@param {TweenPropValue} value @param {Target} target @param {Number} index @param {Number} total @param {Object} [store] @return {any}
func
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getTweenType = (target, prop) => { const type = !target[isDomSymbol] ? tweenTypes.OBJECT : // Handle SVG attributes target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE : // Handle CSS Transform properties differently than CSS to allow individual animations validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM : // CSS variables stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR : // All other CSS properties prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS : // Handle DOM Attributes !isNil(/** @type {DOMTarget} */(target).getAttribute(prop)) ? tweenTypes.ATTRIBUTE : !isUnd(target[prop]) ? tweenTypes.OBJECT : tweenTypes.INVALID; if (type === tweenTypes.INVALID) console.warn(`Can't find property '${prop}' on target '${target}'.`); return type; }
@param {Target} target @param {String} prop @return {tweenTypes}
getTweenType
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getTweenType = (target, prop) => { const type = !target[isDomSymbol] ? tweenTypes.OBJECT : // Handle SVG attributes target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE : // Handle CSS Transform properties differently than CSS to allow individual animations validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM : // CSS variables stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR : // All other CSS properties prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS : // Handle DOM Attributes !isNil(/** @type {DOMTarget} */(target).getAttribute(prop)) ? tweenTypes.ATTRIBUTE : !isUnd(target[prop]) ? tweenTypes.OBJECT : tweenTypes.INVALID; if (type === tweenTypes.INVALID) console.warn(`Can't find property '${prop}' on target '${target}'.`); return type; }
@param {Target} target @param {String} prop @return {tweenTypes}
getTweenType
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getCSSValue = (target, propName, animationInlineStyles) => { const inlineStyles = target.style[propName]; if (inlineStyles && animationInlineStyles) { animationInlineStyles[propName] = inlineStyles; } const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName); return value === 'auto' ? '0' : value; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
getCSSValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getCSSValue = (target, propName, animationInlineStyles) => { const inlineStyles = target.style[propName]; if (inlineStyles && animationInlineStyles) { animationInlineStyles[propName] = inlineStyles; } const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName); return value === 'auto' ? '0' : value; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
getCSSValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => { const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName); return type === tweenTypes.OBJECT ? target[propName] || 0 : type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) : type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) : type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() : getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles); }
@param {Target} target @param {String} propName @param {tweenTypes} [tweenType] @param {Object|void} [animationInlineStyles] @return {String|Number}
getOriginalAnimatableValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => { const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName); return type === tweenTypes.OBJECT ? target[propName] || 0 : type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) : type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) : type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() : getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles); }
@param {Target} target @param {String} propName @param {tweenTypes} [tweenType] @param {Object|void} [animationInlineStyles] @return {String|Number}
getOriginalAnimatableValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getRelativeValue = (x, y, operator) => { return operator === '-' ? x - y : operator === '+' ? x + y : x * y; }
@param {Number} x @param {Number} y @param {String} operator @return {Number}
getRelativeValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getRelativeValue = (x, y, operator) => { return operator === '-' ? x - y : operator === '+' ? x + y : x * y; }
@param {Number} x @param {Number} y @param {String} operator @return {Number}
getRelativeValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
decomposeRawValue = (rawValue, targetObject) => { /** @type {valueTypes} */ targetObject.t = valueTypes.NUMBER; targetObject.n = 0; targetObject.u = null; targetObject.o = null; targetObject.d = null; targetObject.s = null; if (!rawValue) return targetObject; const num = +rawValue; if (!isNaN(num)) { // It's a number targetObject.n = num; return targetObject; } else { // let str = /** @type {String} */(rawValue).trim(); let str = /** @type {String} */(rawValue); // Parsing operators (+=, -=, *=) manually is much faster than using regex here if (str[1] === '=') { targetObject.o = str[0]; str = str.slice(2); } // Skip exec regex if the value type is complex or color to avoid long regex backtracking const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str); if (unitMatch) { // Has a number and a unit targetObject.t = valueTypes.UNIT; targetObject.n = +unitMatch[1]; targetObject.u = unitMatch[2]; return targetObject; } else if (targetObject.o) { // Has an operator (+=, -=, *=) targetObject.n = +str; return targetObject; } else if (isCol(str)) { // Is a color targetObject.t = valueTypes.COLOR; targetObject.d = convertColorStringValuesToRgbaArray(str); return targetObject; } else { // Is a more complex string (generally svg coords, calc() or filters CSS values) const matchedNumbers = str.match(digitWithExponentRgx); targetObject.t = valueTypes.COMPLEX; targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : []; targetObject.s = str.split(digitWithExponentRgx) || []; return targetObject; } } }
@param {String|Number} rawValue @param {TweenDecomposedValue} targetObject @return {TweenDecomposedValue}
decomposeRawValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
decomposeRawValue = (rawValue, targetObject) => { /** @type {valueTypes} */ targetObject.t = valueTypes.NUMBER; targetObject.n = 0; targetObject.u = null; targetObject.o = null; targetObject.d = null; targetObject.s = null; if (!rawValue) return targetObject; const num = +rawValue; if (!isNaN(num)) { // It's a number targetObject.n = num; return targetObject; } else { // let str = /** @type {String} */(rawValue).trim(); let str = /** @type {String} */(rawValue); // Parsing operators (+=, -=, *=) manually is much faster than using regex here if (str[1] === '=') { targetObject.o = str[0]; str = str.slice(2); } // Skip exec regex if the value type is complex or color to avoid long regex backtracking const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str); if (unitMatch) { // Has a number and a unit targetObject.t = valueTypes.UNIT; targetObject.n = +unitMatch[1]; targetObject.u = unitMatch[2]; return targetObject; } else if (targetObject.o) { // Has an operator (+=, -=, *=) targetObject.n = +str; return targetObject; } else if (isCol(str)) { // Is a color targetObject.t = valueTypes.COLOR; targetObject.d = convertColorStringValuesToRgbaArray(str); return targetObject; } else { // Is a more complex string (generally svg coords, calc() or filters CSS values) const matchedNumbers = str.match(digitWithExponentRgx); targetObject.t = valueTypes.COMPLEX; targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : []; targetObject.s = str.split(digitWithExponentRgx) || []; return targetObject; } } }
@param {String|Number} rawValue @param {TweenDecomposedValue} targetObject @return {TweenDecomposedValue}
decomposeRawValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
decomposeTweenValue = (tween, targetObject) => { targetObject.t = tween._valueType; targetObject.n = tween._toNumber; targetObject.u = tween._unit; targetObject.o = null; targetObject.d = cloneArray(tween._toNumbers); targetObject.s = cloneArray(tween._strings); return targetObject; }
@param {Tween} tween @param {TweenDecomposedValue} targetObject @return {TweenDecomposedValue}
decomposeTweenValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
decomposeTweenValue = (tween, targetObject) => { targetObject.t = tween._valueType; targetObject.n = tween._toNumber; targetObject.u = tween._unit; targetObject.o = null; targetObject.d = cloneArray(tween._toNumbers); targetObject.s = cloneArray(tween._strings); return targetObject; }
@param {Tween} tween @param {TweenDecomposedValue} targetObject @return {TweenDecomposedValue}
decomposeTweenValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
sanitizePropertyName = (propertyName, target, tweenType) => { if (tweenType === tweenTypes.TRANSFORM) { const t = shortTransforms.get(propertyName); return t ? t : propertyName; } else if ( tweenType === tweenTypes.CSS || // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset" // but properties like "baseFrequency" should stay in lowerCamelCase (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style)) ) { const cachedPropertyName = propertyNamesCache[propertyName]; if (cachedPropertyName) { return cachedPropertyName; } else { const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName; propertyNamesCache[propertyName] = lowerCaseName; return lowerCaseName; } } else { return propertyName; } }
@param {String} propertyName @param {Target} target @param {tweenTypes} tweenType @return {String}
sanitizePropertyName
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
sanitizePropertyName = (propertyName, target, tweenType) => { if (tweenType === tweenTypes.TRANSFORM) { const t = shortTransforms.get(propertyName); return t ? t : propertyName; } else if ( tweenType === tweenTypes.CSS || // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset" // but properties like "baseFrequency" should stay in lowerCamelCase (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style)) ) { const cachedPropertyName = propertyNamesCache[propertyName]; if (cachedPropertyName) { return cachedPropertyName; } else { const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName; propertyNamesCache[propertyName] = lowerCaseName; return lowerCaseName; } } else { return propertyName; } }
@param {String} propertyName @param {Target} target @param {tweenTypes} tweenType @return {String}
sanitizePropertyName
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
convertValueUnit = (el, decomposedValue, unit, force = false) => { const currentUnit = decomposedValue.u; const currentNumber = decomposedValue.n; if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary return decomposedValue; } const cachedKey = currentNumber + currentUnit + unit; const cached = convertedValuesCache[cachedKey]; if (!isUnd(cached) && !force) { decomposedValue.n = cached; } else { let convertedValue; if (currentUnit in angleUnitsMap) { convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit]; } else { const baseline = 100; const tempEl = /** @type {DOMTarget} */(el.cloneNode()); const parentNode = el.parentNode; const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body; parentEl.appendChild(tempEl); const elStyle = tempEl.style; elStyle.width = baseline + currentUnit; const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline; elStyle.width = baseline + unit; const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline; const factor = currentUnitWidth / newUnitWidth; parentEl.removeChild(tempEl); convertedValue = factor * currentNumber; } decomposedValue.n = convertedValue; convertedValuesCache[cachedKey] = convertedValue; } decomposedValue.t === valueTypes.UNIT; decomposedValue.u = unit; return decomposedValue; }
@param {DOMTarget} el @param {TweenDecomposedValue} decomposedValue @param {String} unit @param {Boolean} [force] @return {TweenDecomposedValue}
convertValueUnit
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
convertValueUnit = (el, decomposedValue, unit, force = false) => { const currentUnit = decomposedValue.u; const currentNumber = decomposedValue.n; if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary return decomposedValue; } const cachedKey = currentNumber + currentUnit + unit; const cached = convertedValuesCache[cachedKey]; if (!isUnd(cached) && !force) { decomposedValue.n = cached; } else { let convertedValue; if (currentUnit in angleUnitsMap) { convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit]; } else { const baseline = 100; const tempEl = /** @type {DOMTarget} */(el.cloneNode()); const parentNode = el.parentNode; const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body; parentEl.appendChild(tempEl); const elStyle = tempEl.style; elStyle.width = baseline + currentUnit; const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline; elStyle.width = baseline + unit; const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline; const factor = currentUnitWidth / newUnitWidth; parentEl.removeChild(tempEl); convertedValue = factor * currentNumber; } decomposedValue.n = convertedValue; convertedValuesCache[cachedKey] = convertedValue; } decomposedValue.t === valueTypes.UNIT; decomposedValue.u = unit; return decomposedValue; }
@param {DOMTarget} el @param {TweenDecomposedValue} decomposedValue @param {String} unit @param {Boolean} [force] @return {TweenDecomposedValue}
convertValueUnit
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getTweenSiblings = (target, property, lookup = '_rep') => { const lookupMap = lookups[lookup]; let targetLookup = lookupMap.get(target); if (!targetLookup) { targetLookup = {}; lookupMap.set(target, targetLookup); } return targetLookup[property] ? targetLookup[property] : targetLookup[property] = { _head: null, _tail: null, } }
@param {Target} target @param {String} property @param {String} lookup @return {TweenPropertySiblings}
getTweenSiblings
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getTweenSiblings = (target, property, lookup = '_rep') => { const lookupMap = lookups[lookup]; let targetLookup = lookupMap.get(target); if (!targetLookup) { targetLookup = {}; lookupMap.set(target, targetLookup); } return targetLookup[property] ? targetLookup[property] : targetLookup[property] = { _head: null, _tail: null, } }
@param {Target} target @param {String} property @param {String} lookup @return {TweenPropertySiblings}
getTweenSiblings
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
addTweenSortMethod = (p, c) => { return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime; }
@param {Tween} p @param {Tween} c @return {Number|Boolean}
addTweenSortMethod
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
addTweenSortMethod = (p, c) => { return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime; }
@param {Tween} p @param {Tween} c @return {Number|Boolean}
addTweenSortMethod
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
composeTween = (tween, siblings) => { const tweenCompositionType = tween._composition; // Handle replaced tweens if (tweenCompositionType === compositionTypes.replace) { const tweenAbsStartTime = tween._absoluteStartTime; addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep'); const prevSibling = tween._prevRep; // Update the previous siblings for composition replace tweens if (prevSibling) { const prevParent = prevSibling.parent; const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration; // Handle looped animations tween if ( // Check if the previous tween is from a different animation tween.parent.id !== prevParent.id && // Check if the animation has loops prevParent._iterationCount > 1 && // Check if _absoluteChangeEndTime of last loop overlaps the current tween prevAbsEndTime + (prevParent.duration - prevParent._iterationDuration) > tweenAbsStartTime ) { // TODO: Find a way to only override the iterations overlapping with the tween overrideTween(prevSibling); let prevPrevSibling = prevSibling._prevRep; // If the tween was part of a set of keyframes, override its siblings while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) { overrideTween(prevPrevSibling); prevPrevSibling = prevPrevSibling._prevRep; } } const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay; if (prevAbsEndTime > absoluteUpdateStartTime) { const prevChangeStartTime = prevSibling._startTime; const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration); // prevSibling._absoluteEndTime = absoluteUpdateStartTime; prevSibling._changeDuration = absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime; prevSibling._currentTime = prevSibling._changeDuration; prevSibling._isOverlapped = 1; if (prevSibling._changeDuration < minValue) { overrideTween(prevSibling); // removeChild(siblings, prevSibling, '_prevRep', '_nextRep'); // addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep'); } } // Pause (and cancel) the parent if it only contains overriden tweens let parentActiveAnimation = 0; forEachChildren(prevParent, (/** @type Tween */t) => { parentActiveAnimation -= t._isOverridden - 1; }); if (parentActiveAnimation === 0) { // Calling .cancel() on a TL child might alter the other children render order // So instead, we mark it as completed + .pause() // This way we let the engine taking care of removing it safely prevParent.completed = true; prevParent.pause(); } } // let nextSibling = tween._nextRep; // // All the next siblings are automatically overridden // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // nextSibling = nextSibling._nextRep; // } // } // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // console.log(tween.id, nextSibling.id); // nextSibling = nextSibling._nextRep; // } // } // Handle additive tweens composition } else if (tweenCompositionType === compositionTypes.blend) { const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add'); const additiveAnimation = addAdditiveAnimation(lookups._add); let lookupTween = additiveTweenSiblings._head; if (!lookupTween) { lookupTween = { ...tween }; lookupTween._composition = compositionTypes.replace; lookupTween._updateDuration = minValue; lookupTween._startTime = 0; lookupTween._numbers = cloneArray(tween._fromNumbers); lookupTween._number = 0; lookupTween._next = null; lookupTween._prev = null; addChild(additiveTweenSiblings, lookupTween); addChild(additiveAnimation, lookupTween); } // Convert the values of TO to FROM and set TO to 0 const toNumber = tween._toNumber; tween._fromNumber = lookupTween._fromNumber - toNumber; tween._toNumber = 0; tween._numbers = cloneArray(tween._fromNumbers); tween._number = 0; lookupTween._fromNumber = toNumber; if (tween._toNumbers) { const toNumbers = cloneArray(tween._toNumbers); if (toNumbers) { toNumbers.forEach((value, i) => { tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value; tween._toNumbers[i] = 0; }); } lookupTween._fromNumbers = toNumbers; } addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd'); } return tween; }
@param {Tween} tween @param {TweenPropertySiblings} siblings @return {Tween}
composeTween
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
composeTween = (tween, siblings) => { const tweenCompositionType = tween._composition; // Handle replaced tweens if (tweenCompositionType === compositionTypes.replace) { const tweenAbsStartTime = tween._absoluteStartTime; addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep'); const prevSibling = tween._prevRep; // Update the previous siblings for composition replace tweens if (prevSibling) { const prevParent = prevSibling.parent; const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration; // Handle looped animations tween if ( // Check if the previous tween is from a different animation tween.parent.id !== prevParent.id && // Check if the animation has loops prevParent._iterationCount > 1 && // Check if _absoluteChangeEndTime of last loop overlaps the current tween prevAbsEndTime + (prevParent.duration - prevParent._iterationDuration) > tweenAbsStartTime ) { // TODO: Find a way to only override the iterations overlapping with the tween overrideTween(prevSibling); let prevPrevSibling = prevSibling._prevRep; // If the tween was part of a set of keyframes, override its siblings while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) { overrideTween(prevPrevSibling); prevPrevSibling = prevPrevSibling._prevRep; } } const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay; if (prevAbsEndTime > absoluteUpdateStartTime) { const prevChangeStartTime = prevSibling._startTime; const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration); // prevSibling._absoluteEndTime = absoluteUpdateStartTime; prevSibling._changeDuration = absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime; prevSibling._currentTime = prevSibling._changeDuration; prevSibling._isOverlapped = 1; if (prevSibling._changeDuration < minValue) { overrideTween(prevSibling); // removeChild(siblings, prevSibling, '_prevRep', '_nextRep'); // addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep'); } } // Pause (and cancel) the parent if it only contains overriden tweens let parentActiveAnimation = 0; forEachChildren(prevParent, (/** @type Tween */t) => { parentActiveAnimation -= t._isOverridden - 1; }); if (parentActiveAnimation === 0) { // Calling .cancel() on a TL child might alter the other children render order // So instead, we mark it as completed + .pause() // This way we let the engine taking care of removing it safely prevParent.completed = true; prevParent.pause(); } } // let nextSibling = tween._nextRep; // // All the next siblings are automatically overridden // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // nextSibling = nextSibling._nextRep; // } // } // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // console.log(tween.id, nextSibling.id); // nextSibling = nextSibling._nextRep; // } // } // Handle additive tweens composition } else if (tweenCompositionType === compositionTypes.blend) { const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add'); const additiveAnimation = addAdditiveAnimation(lookups._add); let lookupTween = additiveTweenSiblings._head; if (!lookupTween) { lookupTween = { ...tween }; lookupTween._composition = compositionTypes.replace; lookupTween._updateDuration = minValue; lookupTween._startTime = 0; lookupTween._numbers = cloneArray(tween._fromNumbers); lookupTween._number = 0; lookupTween._next = null; lookupTween._prev = null; addChild(additiveTweenSiblings, lookupTween); addChild(additiveAnimation, lookupTween); } // Convert the values of TO to FROM and set TO to 0 const toNumber = tween._toNumber; tween._fromNumber = lookupTween._fromNumber - toNumber; tween._toNumber = 0; tween._numbers = cloneArray(tween._fromNumbers); tween._number = 0; lookupTween._fromNumber = toNumber; if (tween._toNumbers) { const toNumbers = cloneArray(tween._toNumbers); if (toNumbers) { toNumbers.forEach((value, i) => { tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value; tween._toNumbers[i] = 0; }); } lookupTween._fromNumbers = toNumbers; } addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd'); } return tween; }
@param {Tween} tween @param {TweenPropertySiblings} siblings @return {Tween}
composeTween
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
constructor(parameters = {}, parent = null, parentPosition = 0) { super(); const { id, delay, duration, reversed, alternate, loop, loopDelay, autoplay, frameRate, playbackRate, onComplete, onLoop, onBegin, onUpdate, } = parameters; if (globals.scope) globals.scope.revertibles.push(this); const timerInitTime = parent ? 0 : engine._elapsedTime; const timerDefaults = parent ? parent.defaults : globals.defaults; const timerDelay = /** @type {Number} */(isFnc(delay) || isUnd(delay) ? timerDefaults.delay : +delay); const timerDuration = isFnc(duration) || isUnd(duration) ? Infinity : +duration; const timerLoop = setValue(loop, timerDefaults.loop); const timerLoopDelay = setValue(loopDelay, timerDefaults.loopDelay); const timerIterationCount = timerLoop === true || timerLoop === Infinity || /** @type {Number} */(timerLoop) < 0 ? Infinity : /** @type {Number} */(timerLoop) + 1; // Timer's parameters this.id = !isUnd(id) ? id : duration === minValue ? 0 : ++timerId; /** @type {Timeline} */ this.parent = parent; // Total duration of the timer this.duration = clampInfinity(((timerDuration + timerLoopDelay) * timerIterationCount) - timerLoopDelay) || minValue; /** @type {Boolean} */ this.paused = true; /** @type {Boolean} */ this.began = false; /** @type {Boolean} */ this.completed = false; /** @type {Number} */ this.reversed = +setValue(reversed, timerDefaults.reversed); /** @type {TimerCallback} */ this.onBegin = onBegin || timerDefaults.onBegin; /** @type {TimerCallback} */ this.onUpdate = onUpdate || timerDefaults.onUpdate; /** @type {TimerCallback} */ this.onLoop = onLoop || timerDefaults.onLoop; /** @type {TimerCallback} */ this.onComplete = onComplete || timerDefaults.onComplete; /** @type {Boolean|ScrollObserver} */ this._autoplay = parent ? false : setValue(autoplay, timerDefaults.autoplay); /** @type {Number} */ this._offset = parent ? parentPosition : engine._elapsedTime - engine._startTime; /** @type {Number} */ this._delay = timerDelay; /** @type {Number} */ this._loopDelay = timerLoopDelay; /** @type {Number} */ this._iterationTime = 0; /** @type {Number} */ this._iterationDuration = timerDuration; // Duration of one loop /** @type {Number} */ this._iterationCount = timerIterationCount; // Number of loops /** @type {Number} */ this._currentIteration = 0; // Current loop index /** @type {Function} */ this._resolve = noop; // Used by .then() /** @type {Boolean} */ this._hasChildren = false; /** @type {Boolean} */ this._running = false; /** @type {Number} */ this._cancelled = 0; /** @type {Number} */ this._reversed = this.reversed; /** @type {Boolean} */ this._alternate = setValue(alternate, timerDefaults.alternate); /** @type {Boolean} */ this._backwards = false; /** @type {Renderable} */ this._prev = null; /** @type {Renderable} */ this._next = null; // Clock's parameters /** @type {Number} */ this._elapsedTime = timerInitTime; /** @type {Number} */ this._startTime = timerInitTime; /** @type {Number} */ this._lastTime = timerInitTime; /** @type {Number} */ this._fps = setValue(frameRate, timerDefaults.frameRate); /** @type {Number} */ this._speed = setValue(playbackRate, timerDefaults.playbackRate); }
@param {TimerParams} [parameters] @param {Timeline} [parent] @param {Number} [parentPosition]
constructor
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
seek(time, muteCallbacks = 0, internalRender = 0) { // Recompose the tween siblings in case the timer has been cancelled reviveTimer(this); // If you seek a completed animation, otherwise the next play will starts at 0 this.completed = false; const isPaused = this.paused; this.paused = true; // timer, time, muteCallbacks, internalRender, tickMode tick(this, time + this._delay, ~~muteCallbacks, ~~internalRender, tickModes.AUTO); return isPaused ? this : this.play(); }
@param {Number} time @param {Boolean|Number} [muteCallbacks] @param {Boolean|Number} [internalRender] @return {this}
seek
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
revert() { tick(this, 0, 1, 0, tickModes.FORCE); // this.cancel(); return this.cancel(); }
Cancel the timer by seeking it back to 0 and reverting the attached scroller if necessary @return {this}
revert
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
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]; const currentEase = prop.ease; if (prevEase) prop.ease = prevEase; 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; }
@param {DurationKeyframes | PercentageKeyframes} keyframes @param {AnimationParams} parameters @return {AnimationParams}
generateKeyframes
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
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]; const currentEase = prop.ease; if (prevEase) prop.ease = prevEase; 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; }
@param {DurationKeyframes | PercentageKeyframes} keyframes @param {AnimationParams} parameters @return {AnimationParams}
generateKeyframes
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
constructor( targets, parameters, parent, parentPosition, fastSet = false, index = 0, length = 0 ) { super(/** @type {TimerParams} */(parameters), parent, parentPosition); /** @type {Tween} */ this._head = null; /** @type {Tween} */ this._tail = null; const parsedTargets = registerTargets(targets); const targetsLength = parsedTargets.length; // If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties const kfParams = /** @type {AnimationParams} */(parameters).keyframes; const params = /** @type {AnimationParams} */(kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters); const { delay, duration, ease, playbackEase, modifier, composition, onRender } = params; const animDefaults = parent ? parent.defaults : globals.defaults; const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase); const animEase = animaPlaybackEase ? parseEasings(animaPlaybackEase) : null; const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease); const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease); const tDuration = hasSpring ? /** @type {Spring} */(ease).duration : setValue(duration, animDefaults.duration); const tDelay = setValue(delay, animDefaults.delay); const tModifier = modifier || animDefaults.modifier; // If no composition is defined and the targets length is high (>= 1000) set the composition to 'none' (0) for faster tween creation const tComposition = isUnd(composition) && targetsLength >= K ? compositionTypes.none : !isUnd(composition) ? composition : animDefaults.composition; // TODO: Do not create an empty object until we know the animation will generate inline styles const animInlineStyles = {}; // const absoluteOffsetTime = this._offset; const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0); let iterationDuration = NaN; let iterationDelay = NaN; let animationAnimationLength = 0; 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); if (tweenType !== tweenTypes.INVALID) { const propName = sanitizePropertyName(p, target, tweenType); let propValue = params[p]; if (fastSet) { fastSetValuesArray[0] = propValue; fastSetValuesArray[1] = propValue; propValue = fastSetValuesArray; } // 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 (isArr(propValue)) { const arrayLength = /** @type {Array} */(propValue).length; const isNotObjectValue = !isObj(propValue[0]); // Convert [x, y] to [{to: [x, y]}] if (arrayLength === 2 && isNotObjectValue) { keyObjectTarget.to = /** @type {TweenParamValue} */(/** @type {unknown} */(propValue)); keyframesTargetArray[0] = keyObjectTarget; keyframes = keyframesTargetArray; // Convert [x, y, z] to [[x, y], z] } else if (arrayLength > 2 && isNotObjectValue) { keyframes = []; /** @type {Array.<Number>} */(propValue).forEach((v, i) => { if (!i) { fastSetValuesArray[0] = v; } else if (i === 1) { fastSetValuesArray[1] = v; keyframes.push(fastSetValuesArray); } else { keyframes.push(v); } }); } else { keyframes = /** @type {Array.<TweenKeyValue>} */(propValue); } } else { keyframesTargetArray[0] = propValue; keyframes = keyframesTargetArray; } let siblings = null; let prevTween = null; let firstTweenChangeStartTime = NaN; let lastTweenChangeEndTime = 0; let tweenIndex = 0; for (let l = keyframes.length; tweenIndex < l; tweenIndex++) { const keyframe = keyframes[tweenIndex]; if (isObj(keyframe)) { key = keyframe; } else { keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe); key = keyObjectTarget; } toFunctionStore.func = null; const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore); let tweenToValue; // Allows function based values to return an object syntax value ({to: v}) if (isObj(computedToValue) && !isUnd(computedToValue.to)) { key = computedToValue; tweenToValue = computedToValue.to; } else { tweenToValue = computedToValue; } const tweenFromValue = getFunctionValue(key.from, target, ti, tl); const keyEasing = key.ease; const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */(keyEasing).ease); // Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing || tEasing; // Calculate default individual keyframe duration by dividing the tl of keyframes const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).duration : getFunctionValue(setValue(key.duration, (l > 1 ? getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl); // Default delay value should only be applied to the first tween const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl); const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl); const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition]; // Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper const tweenModifier = key.modifier || tModifier; const isFromToArray = isArr(tweenToValue); const isFromToValue = isFromToArray || (!isUnd(tweenFromValue) && !isUnd(tweenToValue)); const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay; const absoluteStartTime = absoluteOffsetTime + tweenStartTime; let prevSibling = prevTween; if (tweenComposition !== compositionTypes.none) { if (!siblings) siblings = getTweenSiblings(target, propName); let nextSibling = siblings._head; // Iterate trough all the next siblings until we find a sibling with an equal or inferior start time while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) { prevSibling = nextSibling; nextSibling = nextSibling._nextRep; // Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) { while (nextSibling) { overrideTween(nextSibling); // This will ends both the current while loop and the upper one once all the next sibllings have been overriden nextSibling = nextSibling._nextRep; } } } } // Decompose values if (isFromToValue) { decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject); decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject); if (fromTargetObject.t === valueTypes.NUMBER) { if (prevSibling) { if (prevSibling._valueType === valueTypes.UNIT) { fromTargetObject.t = valueTypes.UNIT; fromTargetObject.u = prevSibling._unit; } } else { decomposeRawValue( getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), decomposedOriginalValue ); if (decomposedOriginalValue.t === valueTypes.UNIT) { fromTargetObject.t = valueTypes.UNIT; fromTargetObject.u = decomposedOriginalValue.u; } } } } else { if (!isUnd(tweenToValue)) { decomposeRawValue(tweenToValue, toTargetObject); } else { if (prevTween) { decomposeTweenValue(prevTween, toTargetObject); } else { // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value : getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), toTargetObject); } } if (!isUnd(tweenFromValue)) { decomposeRawValue(tweenFromValue, fromTargetObject); } else { if (prevTween) { decomposeTweenValue(prevTween, fromTargetObject); } else { decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value : // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), fromTargetObject); } } } // Apply operators if (fromTargetObject.o) { fromTargetObject.n = getRelativeValue( !prevSibling ? decomposeRawValue( getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), decomposedOriginalValue ).n : prevSibling._toNumber, fromTargetObject.n, fromTargetObject.o ); } if (toTargetObject.o) { toTargetObject.n = getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o); } // Values omogenisation in cases of type difference between "from" and "to" if (fromTargetObject.t !== toTargetObject.t) { if (fromTargetObject.t === valueTypes.COMPLEX || toTargetObject.t === valueTypes.COMPLEX) { const complexValue = fromTargetObject.t === valueTypes.COMPLEX ? fromTargetObject : toTargetObject; const notComplexValue = fromTargetObject.t === valueTypes.COMPLEX ? toTargetObject : fromTargetObject; notComplexValue.t = valueTypes.COMPLEX; notComplexValue.s = cloneArray(complexValue.s); notComplexValue.d = complexValue.d.map(() => notComplexValue.n); } else if (fromTargetObject.t === valueTypes.UNIT || toTargetObject.t === valueTypes.UNIT) { const unitValue = fromTargetObject.t === valueTypes.UNIT ? fromTargetObject : toTargetObject; const notUnitValue = fromTargetObject.t === valueTypes.UNIT ? toTargetObject : fromTargetObject; notUnitValue.t = valueTypes.UNIT; notUnitValue.u = unitValue.u; } else if (fromTargetObject.t === valueTypes.COLOR || toTargetObject.t === valueTypes.COLOR) { const colorValue = fromTargetObject.t === valueTypes.COLOR ? fromTargetObject : toTargetObject; const notColorValue = fromTargetObject.t === valueTypes.COLOR ? toTargetObject : fromTargetObject; notColorValue.t = valueTypes.COLOR; notColorValue.s = colorValue.s; notColorValue.d = [0, 0, 0, 1]; } } // Unit conversion if (fromTargetObject.u !== toTargetObject.u) { let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject; valueToConvert = convertValueUnit(/** @type {DOMTarget} */(target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false); // TODO: // convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u); } // Fill in non existing complex values if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) { const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject; const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject; // TODO: Check if n should be used instead of 0 for default complex values shortestValue.d = longestValue.d.map((_, i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]); shortestValue.s = cloneArray(longestValue.s); } // Tween factory const tweenUpdateDuration = +tweenDuration || minValue; /** @type {Tween} */ const tween = { parent: this, id: tweenId++, property: propName, target: target, _value: null, _func: toFunctionStore.func, _ease: parseEasings(tweenEasing), _fromNumbers: cloneArray(fromTargetObject.d), _toNumbers: cloneArray(toTargetObject.d), _strings: cloneArray(toTargetObject.s), _fromNumber: fromTargetObject.n, _toNumber: toTargetObject.n, _numbers: cloneArray(fromTargetObject.d), // For additive tween and animatables _number: fromTargetObject.n, // For additive tween and animatables _unit: toTargetObject.u, _modifier: tweenModifier, _currentTime: 0, _startTime: tweenStartTime, _delay: +tweenDelay, _updateDuration: tweenUpdateDuration, _changeDuration: tweenUpdateDuration, _absoluteStartTime: absoluteStartTime, // NOTE: Investigate bit packing to stores ENUM / BOOL _tweenType: tweenType, _valueType: toTargetObject.t, _composition: tweenComposition, _isOverlapped: 0, _isOverridden: 0, _renderTransforms: 0, _prevRep: null, // For replaced tween _nextRep: null, // For replaced tween _prevAdd: null, // For additive tween _nextAdd: null, // For additive tween _prev: null, _next: null, }; if (tweenComposition !== compositionTypes.none) { composeTween(tween, siblings); } if (isNaN(firstTweenChangeStartTime)) { firstTweenChangeStartTime = tween._startTime; } // Rounding is necessary here to minimize floating point errors lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12); prevTween = tween; animationAnimationLength++; addChild(this, tween); } // Update animation timings with the added tweens properties if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) { iterationDelay = firstTweenChangeStartTime; } if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) { iterationDuration = lastTweenChangeEndTime; } // TODO: Find a way to inline tween._renderTransforms = 1 here if (tweenType === tweenTypes.TRANSFORM) { lastTransformGroupIndex = animationAnimationLength - tweenIndex; lastTransformGroupLength = animationAnimationLength; } } } } // Set _renderTransforms to last transform property to correctly render the transforms list if (!isNaN(lastTransformGroupIndex)) { let i = 0; forEachChildren(this, (/** @type {Tween} */tween) => { if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) { tween._renderTransforms = 1; if (tween._composition === compositionTypes.blend) { forEachChildren(additive.animation, (/** @type {Tween} */additiveTween) => { if (additiveTween.id === tween.id) { additiveTween._renderTransforms = 1; } }); } } i++; }); } } if (!targetsLength) { console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`); } if (iterationDelay) { forEachChildren(this, (/** @type {Tween} */tween) => { // If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too if (!(tween._startTime - tween._delay)) { tween._delay -= iterationDelay; } tween._startTime -= iterationDelay; }); iterationDuration -= iterationDelay; } else { iterationDelay = 0; } // Prevents iterationDuration to be NaN if no valid animatable props have been provided // Prevents _iterationCount to be NaN if no valid animatable props have been provided if (!iterationDuration) { iterationDuration = minValue; this._iterationCount = 0; } /** @type {TargetsArray} */ this.targets = parsedTargets; this.duration = iterationDuration === minValue ? minValue : clampInfinity(((iterationDuration + this._loopDelay) * this._iterationCount) - this._loopDelay) || minValue; /** @type {AnimationCallback} */ this.onRender = onRender || animDefaults.onRender; /** @type {EasingFunction} */ this._ease = animEase; 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; this._iterationDuration = iterationDuration; this._inlineStyles = animInlineStyles; }
@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
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
revert() { super.revert(); return cleanInlineStyles(this); }
Cancel the animation and revert all the values affected by this animation to their original state @return {this}
revert
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
function getTargetValue(targetSelector, propName, unit) { const targets = registerTargets(targetSelector); if (!targets.length) return; const [ target ] = targets; const tweenType = getTweenType(target, propName); const normalizePropName = sanitizePropertyName(propName, target, tweenType); let originalValue = getOriginalAnimatableValue(target, normalizePropName); if (isUnd(unit)) { return originalValue; } else { decomposeRawValue(originalValue, decomposedOriginalValue); if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) { if (unit === false) { return decomposedOriginalValue.n; } else { const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false); return `${round(convertedValue.n, globals.precision)}${convertedValue.u}`; } } } }
@overload @param {DOMTargetSelector} targetSelector @param {String} propName @return {String} @overload @param {JSTargetsParam} targetSelector @param {String} propName @return {Number|String} @overload @param {DOMTargetsParam} targetSelector @param {String} propName @param {String} unit @return {String} @overload @param {TargetsParam} targetSelector @param {String} propName @param {Boolean} unit @return {Number} @param {TargetsParam} targetSelector @param {String} propName @param {String|Boolean} [unit]
getTargetValue
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
setTargetValues = (targets, parameters) => { if (isUnd(parameters)) return; parameters.duration = minValue; // Do not overrides currently active tweens by default parameters.composition = setValue(parameters.composition, compositionTypes.none); // Skip init() and force rendering by playing the animation return new Animation(targets, parameters, null, 0, true).play(); }
@param {TargetsParam} targets @param {AnimationParams} parameters @return {Animation}
setTargetValues
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
setTargetValues = (targets, parameters) => { if (isUnd(parameters)) return; parameters.duration = minValue; // Do not overrides currently active tweens by default parameters.composition = setValue(parameters.composition, compositionTypes.none); // Skip init() and force rendering by playing the animation return new Animation(targets, parameters, null, 0, true).play(); }
@param {TargetsParam} targets @param {AnimationParams} parameters @return {Animation}
setTargetValues
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
removeTargetsFromAnimation = (targetsArray, animation, propertyName) => { let tweensMatchesTargets = false; forEachChildren(animation, (/**@type {Tween} */tween) => { const tweenTarget = tween.target; if (targetsArray.includes(tweenTarget)) { const tweenName = tween.property; const tweenType = tween._tweenType; const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType); if (!normalizePropName || normalizePropName && normalizePropName === tweenName) { // Removes the tween from the selected animation removeChild(animation, tween); // Detach the tween from its siblings to make sure blended tweens are correctlly removed removeTweenSliblings(tween); tweensMatchesTargets = true; } } }, true); return tweensMatchesTargets; }
@param {TargetsArray} targetsArray @param {Animation} animation @param {String} [propertyName] @return {Boolean}
removeTargetsFromAnimation
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
removeTargetsFromAnimation = (targetsArray, animation, propertyName) => { let tweensMatchesTargets = false; forEachChildren(animation, (/**@type {Tween} */tween) => { const tweenTarget = tween.target; if (targetsArray.includes(tweenTarget)) { const tweenName = tween.property; const tweenType = tween._tweenType; const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType); if (!normalizePropName || normalizePropName && normalizePropName === tweenName) { // Removes the tween from the selected animation removeChild(animation, tween); // Detach the tween from its siblings to make sure blended tweens are correctlly removed removeTweenSliblings(tween); tweensMatchesTargets = true; } } }, true); return tweensMatchesTargets; }
@param {TargetsArray} targetsArray @param {Animation} animation @param {String} [propertyName] @return {Boolean}
removeTargetsFromAnimation
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
remove = (targets, renderable, propertyName) => { const targetsArray = parseTargets(targets); const parent = renderable ? renderable : engine; let removeMatches; if (parent._hasChildren) { forEachChildren(parent, (/** @type {Renderable} */child) => { if (!child._hasChildren) { removeMatches = removeTargetsFromAnimation(targetsArray, /** @type {Animation} */(child), propertyName); // Remove the child from its parent if no tweens and no children left after the removal if (removeMatches && !child._head) { // TODO: Call child.onInterupt() here when implemented child.cancel(); removeChild(parent, child); } } // Make sure to also remove engine's children targets // NOTE: Avoid recursion? if (child._head) { remove(targets, child); } else { child._hasChildren = false; } }, true); } else { removeMatches = removeTargetsFromAnimation( targetsArray, /** @type {Animation} */(parent), propertyName ); } if (removeMatches && !parent._head) { parent._hasChildren = false; // TODO: Call child.onInterupt() here when implemented // Cancel the parent if there are no tweens and no children left after the removal // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel(); } return targetsArray; }
@param {TargetsParam} targets @param {Renderable} [renderable] @param {String} [propertyName] @return {TargetsArray}
remove
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
remove = (targets, renderable, propertyName) => { const targetsArray = parseTargets(targets); const parent = renderable ? renderable : engine; let removeMatches; if (parent._hasChildren) { forEachChildren(parent, (/** @type {Renderable} */child) => { if (!child._hasChildren) { removeMatches = removeTargetsFromAnimation(targetsArray, /** @type {Animation} */(child), propertyName); // Remove the child from its parent if no tweens and no children left after the removal if (removeMatches && !child._head) { // TODO: Call child.onInterupt() here when implemented child.cancel(); removeChild(parent, child); } } // Make sure to also remove engine's children targets // NOTE: Avoid recursion? if (child._head) { remove(targets, child); } else { child._hasChildren = false; } }, true); } else { removeMatches = removeTargetsFromAnimation( targetsArray, /** @type {Animation} */(parent), propertyName ); } if (removeMatches && !parent._head) { parent._hasChildren = false; // TODO: Call child.onInterupt() here when implemented // Cancel the parent if there are no tweens and no children left after the removal // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel(); } return targetsArray; }
@param {TargetsParam} targets @param {Renderable} [renderable] @param {String} [propertyName] @return {TargetsArray}
remove
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
shuffle = items => { let m = items.length, t, i; while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; } return items; }
Adapted from https://bost.ocks.org/mike/shuffle/ @param {Array} items @return {Array}
shuffle
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
shuffle = items => { let m = items.length, t, i; while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; } return items; }
Adapted from https://bost.ocks.org/mike/shuffle/ @param {Array} items @return {Array}
shuffle
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
lerp = (start, end, amount, renderable) => { let dt = K / globals.defaults.frameRate; if (renderable !== false) { const ticker = /** @type Renderable */ (renderable) || (engine._hasChildren && engine); if (ticker && ticker.deltaTime) { dt = ticker.deltaTime; } } const t = 1 - Math.exp(-amount * dt * .1); return !amount ? start : amount === 1 ? end : (1 - t) * start + t * end; }
https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ @param {Number} start @param {Number} end @param {Number} amount @param {Renderable|Boolean} [renderable] @return {Number}
lerp
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
lerp = (start, end, amount, renderable) => { let dt = K / globals.defaults.frameRate; if (renderable !== false) { const ticker = /** @type Renderable */ (renderable) || (engine._hasChildren && engine); if (ticker && ticker.deltaTime) { dt = ticker.deltaTime; } } const t = 1 - Math.exp(-amount * dt * .1); return !amount ? start : amount === 1 ? end : (1 - t) * start + t * end; }
https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ @param {Number} start @param {Number} end @param {Number} amount @param {Renderable|Boolean} [renderable] @return {Number}
lerp
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
chain = fn => { return (...args) => { const result = fn(...args); return new Proxy(noop, { apply: (_, __, [v]) => result(v), get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => { const nextResult = utils[prop](...nextArgs); return (/**@type {Number|String} */v) => nextResult(result(v)); }) }); } }
@param {Function} fn @return {function(...(Number|String))}
chain
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
chain = fn => { return (...args) => { const result = fn(...args); return new Proxy(noop, { apply: (_, __, [v]) => result(v), get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => { const nextResult = utils[prop](...nextArgs); return (/**@type {Number|String} */v) => nextResult(result(v)); }) }); } }
@param {Function} fn @return {function(...(Number|String))}
chain
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getPrevChildOffset = (timeline, timePosition) => { if (stringStartsWith(timePosition, '<')) { const goToPrevAnimationOffset = timePosition[1] === '<'; const prevAnimation = timeline._tail; const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0; return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration; } }
Timeline's children offsets positions parser @param {Timeline} timeline @param {String} timePosition @return {Number}
getPrevChildOffset
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
getPrevChildOffset = (timeline, timePosition) => { if (stringStartsWith(timePosition, '<')) { const goToPrevAnimationOffset = timePosition[1] === '<'; const prevAnimation = timeline._tail; const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0; return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration; } }
Timeline's children offsets positions parser @param {Timeline} timeline @param {String} timePosition @return {Number}
getPrevChildOffset
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
parseTimelinePosition = (timeline, timePosition) => { let tlDuration = timeline._iterationDuration; if (tlDuration === minValue) tlDuration = 0; if (isUnd(timePosition)) return tlDuration; if (isNum(+timePosition)) return +timePosition; const timePosStr = /** @type {String} */(timePosition); const tlLabels = timeline ? timeline.labels : null; const hasLabels = !isNil(tlLabels); const prevOffset = getPrevChildOffset(timeline, timePosStr); const hasSibling = !isUnd(prevOffset); const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr); if (matchedRelativeOperator) { const fullOperator = matchedRelativeOperator[0]; const split = timePosStr.split(fullOperator); const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration; const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration; const parsedNumericalOffset = +split[1]; return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]); } else { return hasSibling ? prevOffset : hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] : tlDuration : tlDuration; } }
@param {Timeline} timeline @param {TimePosition} [timePosition] @return {Number}
parseTimelinePosition
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
parseTimelinePosition = (timeline, timePosition) => { let tlDuration = timeline._iterationDuration; if (tlDuration === minValue) tlDuration = 0; if (isUnd(timePosition)) return tlDuration; if (isNum(+timePosition)) return +timePosition; const timePosStr = /** @type {String} */(timePosition); const tlLabels = timeline ? timeline.labels : null; const hasLabels = !isNil(tlLabels); const prevOffset = getPrevChildOffset(timeline, timePosStr); const hasSibling = !isUnd(prevOffset); const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr); if (matchedRelativeOperator) { const fullOperator = matchedRelativeOperator[0]; const split = timePosStr.split(fullOperator); const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration; const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration; const parsedNumericalOffset = +split[1]; return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]); } else { return hasSibling ? prevOffset : hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] : tlDuration : tlDuration; } }
@param {Timeline} timeline @param {TimePosition} [timePosition] @return {Number}
parseTimelinePosition
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
function addTlChild(childParams, tl, parsedTLPosition, targets, index, length) { // Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position const TLPosition = isNum(childParams.duration) && /** @type {Number} */(childParams.duration) <= minValue ? parsedTLPosition - minValue : parsedTLPosition; tick(tl, TLPosition, 1, 1, tickModes.AUTO); const tlChild = targets ? new Animation(targets,/** @type {AnimationParams} */(childParams), tl, TLPosition, false, index, length) : new Timer(/** @type {TimerParams} */(childParams), tl, TLPosition); tlChild.init(1); // TODO: Might be better to insert at a position relative to startTime? addChild(tl, tlChild); forEachChildren(tl, (/** @type {Renderable} */child) => { const childTLOffset = child._offset + child._delay; const childDur = childTLOffset + child.duration; if (childDur > tl._iterationDuration) { tl._iterationDuration = childDur; } }); tl.duration = clampInfinity(((tl._iterationDuration + tl._loopDelay) * tl._iterationCount) - tl._loopDelay) || minValue; return tl; }
@overload @param {TimerParams} childParams @param {Timeline} tl @param {Number} parsedTLPosition @return {Timeline} @overload @param {AnimationParams} childParams @param {Timeline} tl @param {Number} parsedTLPosition @param {TargetsParam} targets @param {Number} [index] @param {Number} [length] @return {Timeline} @param {TimerParams|AnimationParams} childParams @param {Timeline} tl @param {Number} parsedTLPosition @param {TargetsParam} [targets] @param {Number} [index] @param {Number} [length]
addTlChild
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
add(a1, a2, a3) { const isAnim = isObj(a2); const isTimer = isObj(a1); const isFunc = isFnc(a1); if (isAnim || isTimer || isFunc) { this._hasChildren = true; if (isAnim) { const childParams = /** @type {AnimationParams} */(a2); // Check for function for children stagger positions if (isFnc(a3)) { const staggeredPosition = /** @type {Function} */(a3); const parsedTargetsArray = parseTargets(/** @type {TargetsParam} */(a1)); // Store initial duration before adding new children that will change the duration const tlDuration = this.duration; // Store initial _iterationDuration before adding new children that will change the duration const tlIterationDuration = this._iterationDuration; // Store the original id in order to add specific indexes to the new animations ids const id = childParams.id; let i = 0; const parsedLength = parsedTargetsArray.length; parsedTargetsArray.forEach((/** @type {Target} */target) => { // Create a new parameter object for each staggered children const staggeredChildParams = { ...childParams }; // Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation this.duration = tlDuration; this._iterationDuration = tlIterationDuration; if (!isUnd(id)) staggeredChildParams.id = id + '-' + i; addTlChild( staggeredChildParams, this, staggeredPosition(target, i, parsedLength, this), target, i, parsedLength ); i++; }); } else { addTlChild( childParams, this, parseTimelinePosition(this, a3), /** @type {TargetsParam} */(a1), ); } } else { // It's a Timer or a Function addTlChild( /** @type TimerParams */(isTimer ? a1 : { onComplete: a1, duration: minValue }), this, parseTimelinePosition(this,/** @type TimePosition */(a2)), ); } this.init(1); // 1 = internalRender return this._autoplay === true ? this.play() : this; } else if (isStr(a1)) { this.labels[a1] = parseTimelinePosition(this,/** @type TimePosition */(a2)); return this; } }
@overload @param {TargetsParam} a1 @param {AnimationParams} a2 @param {TimePosition} [a3] @return {this} @overload @param {TimerParams} a1 @param {TimePosition} [a2] @return {this} @overload @param {String} a1 @param {TimePosition} [a2] @return {this} @overload @param {TimerCallback} a1 @param {TimePosition} [a2] @return {this} @param {TargetsParam|TimerParams|String|TimerCallback} a1 @param {AnimationParams|TimePosition} a2 @param {TimePosition} [a3]
add
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
set(targets, parameters, position) { if (isUnd(parameters)) return this; parameters.duration = minValue; parameters.composition = compositionTypes.replace; return this.add(targets, parameters, position); }
@param {TargetsParam} targets @param {AnimationParams} parameters @param {TimePosition} [position] @return {this}
set
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
stagger = (val, params = {}) => { let values = []; let maxValue = 0; const from = params.from; const reversed = params.reversed; const ease = params.ease; const hasEasing = !isUnd(ease); const hasSpring = hasEasing && !isUnd(/** @type {Spring} */(ease).ease); const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEasings(ease) : null; const grid = params.grid; const axis = params.axis; const fromFirst = isUnd(from) || from === 0 || from === 'first'; const fromCenter = from === 'center'; const fromLast = from === 'last'; const isRange = isArr(val); const val1 = isRange ? parseNumber(val[0]) : parseNumber(val); const val2 = isRange ? parseNumber(val[1]) : 0; const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString); const start = params.start || 0 + (isRange ? val1 : 0); let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0; return (_, i, t, tl) => { if (fromCenter) fromIndex = (t - 1) / 2; if (fromLast) fromIndex = t - 1; if (!values.length) { for (let index = 0; index < t; index++) { if (!grid) { values.push(abs(fromIndex - index)); } else { const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2; const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2; const toX = index % grid[0]; const toY = floor(index / grid[0]); const distanceX = fromX - toX; const distanceY = fromY - toY; let value = sqrt(distanceX * distanceX + distanceY * distanceY); if (axis === 'x') value = -distanceX; if (axis === 'y') value = -distanceY; values.push(value); } maxValue = max(...values); } if (staggerEase) values = values.map(val => staggerEase(val / maxValue) * maxValue); if (reversed) values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val)); } const spacing = isRange ? (val2 - val1) / maxValue : val1; const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl._iterationDuration : start) : /** @type {Number} */(start); /** @type {String|Number} */ let output = offset + ((spacing * round(values[i], 2)) || 0); if (params.modifier) output = params.modifier(output); if (unitMatch) output = `${output}${unitMatch[2]}`; return output; } }
@param {Number|String|[Number|String,Number|String]} val @param {StaggerParameters} params @return {StaggerFunction}
stagger
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
stagger = (val, params = {}) => { let values = []; let maxValue = 0; const from = params.from; const reversed = params.reversed; const ease = params.ease; const hasEasing = !isUnd(ease); const hasSpring = hasEasing && !isUnd(/** @type {Spring} */(ease).ease); const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEasings(ease) : null; const grid = params.grid; const axis = params.axis; const fromFirst = isUnd(from) || from === 0 || from === 'first'; const fromCenter = from === 'center'; const fromLast = from === 'last'; const isRange = isArr(val); const val1 = isRange ? parseNumber(val[0]) : parseNumber(val); const val2 = isRange ? parseNumber(val[1]) : 0; const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString); const start = params.start || 0 + (isRange ? val1 : 0); let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0; return (_, i, t, tl) => { if (fromCenter) fromIndex = (t - 1) / 2; if (fromLast) fromIndex = t - 1; if (!values.length) { for (let index = 0; index < t; index++) { if (!grid) { values.push(abs(fromIndex - index)); } else { const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2; const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2; const toX = index % grid[0]; const toY = floor(index / grid[0]); const distanceX = fromX - toX; const distanceY = fromY - toY; let value = sqrt(distanceX * distanceX + distanceY * distanceY); if (axis === 'x') value = -distanceX; if (axis === 'y') value = -distanceY; values.push(value); } maxValue = max(...values); } if (staggerEase) values = values.map(val => staggerEase(val / maxValue) * maxValue); if (reversed) values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val)); } const spacing = isRange ? (val2 - val1) / maxValue : val1; const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl._iterationDuration : start) : /** @type {Number} */(start); /** @type {String|Number} */ let output = offset + ((spacing * round(values[i], 2)) || 0); if (params.modifier) output = params.modifier(output); if (unitMatch) output = `${output}${unitMatch[2]}`; return output; } }
@param {Number|String|[Number|String,Number|String]} val @param {StaggerParameters} params @return {StaggerFunction}
stagger
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
convertValueToPx = ($el, v, size, under, over) => { const clampMin = v === 'min'; const clampMax = v === 'max'; const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 : v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' : v === 'center' ? '50%' : v; const { n, u } = decomposeRawValue(value, decomposedOriginalValue); let px = n; if (u === '%') { px = (n / 100) * size; } else if (u) { px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n; } if (clampMax && under < 0) px += under; if (clampMin && over > 0) px += over; return px; }
@param {HTMLElement} $el @param {Number|string} v @param {Number} size @param {Number} [under] @param {Number} [over] @return {Number}
convertValueToPx
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
convertValueToPx = ($el, v, size, under, over) => { const clampMin = v === 'min'; const clampMax = v === 'max'; const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 : v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' : v === 'center' ? '50%' : v; const { n, u } = decomposeRawValue(value, decomposedOriginalValue); let px = n; if (u === '%') { px = (n / 100) * size; } else if (u) { px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n; } if (clampMax && under < 0) px += under; if (clampMin && over > 0) px += over; return px; }
@param {HTMLElement} $el @param {Number|string} v @param {Number} size @param {Number} [under] @param {Number} [over] @return {Number}
convertValueToPx
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT