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
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
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
call(callback, position) { if (isUnd(callback) || callback && !isFnc(callback)) return this; return this.add({ duration: 0, onComplete: () => callback(this) }, position); }
@param {Callback<Timer>} callback @param {TimePosition} [position] @return {this}
call
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
label(labelName, position) { if (isUnd(labelName) || labelName && !isStr(labelName)) return this; this.labels[labelName] = parseTimelinePosition(this,/** @type TimePosition */(position)); return this; }
@param {String} labelName @param {TimePosition} [position] @return {this}
label
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
remove(targets, propertyName) { remove(targets, this, propertyName); return this; }
@param {TargetsParam} targets @param {String} [propertyName] @return {this}
remove
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
then(callback) { return super.then(callback); }
@param {Callback<this>} [callback] @return {Promise}
then
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
constructor(targets, parameters) { if (globals.scope) globals.scope.revertibles.push(this); /** @type {AnimationParams} */ const globalParams = {}; const properties = {}; this.targets = []; this.animations = {}; if (isUnd(targets) || isUnd(parameters)) return; for (let propName in parameters) { const paramValue = parameters[propName]; if (isKey(propName)) { properties[propName] = paramValue; } else { globalParams[propName] = paramValue; } } for (let propName in properties) { const propValue = properties[propName]; const isObjValue = isObj(propValue); /** @type {TweenParamsOptions} */ let propParams = {}; let to = '+=0'; if (isObjValue) { const unit = propValue.unit; if (isStr(unit)) to += unit; } else { propParams.duration = propValue; } propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to; const animParams = mergeObjects(globalParams, propParams); animParams.composition = compositionTypes.replace; animParams.autoplay = false; const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init(); if (!this.targets.length) this.targets.push(...animation.targets); /** @type {AnimatableProperty} */ this[propName] = (to, duration, ease) => { const tween = /** @type {Tween} */(animation._head); if (isUnd(to) && tween) { const numbers = tween._numbers; if (numbers && numbers.length) { return numbers; } else { return tween._modifier(tween._number); } } else { forEachChildren(animation, (/** @type {Tween} */tween) => { if (isArr(to)) { for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) { if (!isUnd(tween._numbers[i])) { tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i])); tween._toNumbers[i] = to[i]; } } } else { tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number)); tween._toNumber = /** @type {Number} */(to); } if (!isUnd(ease)) tween._ease = parseEasings(ease); tween._currentTime = 0; }); if (!isUnd(duration)) animation.stretch(duration); animation.reset(1).resume(); return this; } }; } }
@param {TargetsParam} targets @param {AnimatableParams} parameters
constructor
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
normalizePoint(x, y) { this.point.x = x; this.point.y = y; return this.point.matrixTransform(this.inversedMatrix); }
@param {Number} x @param {Number} y @return {DOMPoint}
normalizePoint
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
constructor(target, parameters = {}) { if (!target) return; if (globals.scope) globals.scope.revertibles.push(this); const paramX = parameters.x; const paramY = parameters.y; const trigger = parameters.trigger; const modifier = parameters.modifier; const ease = parameters.releaseEase; const customEase = ease && parseEasings(ease); const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease); const xProp = /** @type {String} */(isObj(paramX) && !isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX'); const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY'); const container = parseDraggableFunctionParameter(parameters.container, this); this.containerArray = isArr(container) ? container : null; this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body); this.useWin = this.$container === doc.body; /** @type {Window | HTMLElement} */ this.$scrollContainer = this.useWin ? win : this.$container; this.$target = /** @type {HTMLElement} */(isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]); this.$trigger = /** @type {HTMLElement} */(parseTargets(trigger ? trigger : target)[0]); this.fixed = getTargetValue(this.$target, 'position') === 'fixed'; // Refreshable parameters this.isFinePointer = true; /** @type {[Number, Number, Number, Number]} */ this.containerPadding = [0, 0, 0, 0]; /** @type {Number} */ this.containerFriction = 0; /** @type {Number} */ this.releaseContainerFriction = 0; /** @type {Number|Array<Number>} */ this.snapX = 0; /** @type {Number|Array<Number>} */ this.snapY = 0; /** @type {Number} */ this.scrollSpeed = 0; /** @type {Number} */ this.scrollThreshold = 0; /** @type {Number} */ this.dragSpeed = 0; /** @type {Number} */ this.maxVelocity = 0; /** @type {Number} */ this.minVelocity = 0; /** @type {Number} */ this.velocityMultiplier = 0; /** @type {Boolean|DraggableCursorParams} */ this.cursor = false; /** @type {Spring} */ this.releaseXSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); /** @type {Spring} */ this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); /** @type {EasingFunction} */ this.releaseEase = customEase || eases.outQuint; /** @type {Boolean} */ this.hasReleaseSpring = hasSpring; /** @type {Callback<this>} */ this.onGrab = parameters.onGrab || noop; /** @type {Callback<this>} */ this.onDrag = parameters.onDrag || noop; /** @type {Callback<this>} */ this.onRelease = parameters.onRelease || noop; /** @type {Callback<this>} */ this.onUpdate = parameters.onUpdate || noop; /** @type {Callback<this>} */ this.onSettle = parameters.onSettle || noop; /** @type {Callback<this>} */ this.onSnap = parameters.onSnap || noop; /** @type {Callback<this>} */ this.onResize = parameters.onResize || noop; /** @type {Callback<this>} */ this.onAfterResize = parameters.onAfterResize || noop; /** @type {[Number, Number]} */ this.disabled = [0, 0]; /** @type {AnimatableParams} */ const animatableParams = {}; if (modifier) animatableParams.modifier = modifier; if (isUnd(paramX) || paramX === true) { animatableParams[xProp] = 0; } else if (isObj(paramX)) { const paramXObject = /** @type {DraggableAxisParam} */(paramX); const animatableXParams = {}; if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier; if (paramXObject.composition) animatableXParams.composition = paramXObject.composition; animatableParams[xProp] = animatableXParams; } else if (paramX === false) { animatableParams[xProp] = 0; this.disabled[0] = 1; } if (isUnd(paramY) || paramY === true) { animatableParams[yProp] = 0; } else if (isObj(paramY)) { const paramYObject = /** @type {DraggableAxisParam} */(paramY); const animatableYParams = {}; if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier; if (paramYObject.composition) animatableYParams.composition = paramYObject.composition; animatableParams[yProp] = animatableYParams; } else if (paramY === false) { animatableParams[yProp] = 0; this.disabled[1] = 1; } /** @type {AnimatableObject} */ this.animate = /** @type {AnimatableObject} */(new Animatable(this.$target, animatableParams)); // Internal props this.xProp = xProp; this.yProp = yProp; this.destX = 0; this.destY = 0; this.deltaX = 0; this.deltaY = 0; this.scroll = {x: 0, y: 0}; /** @type {[Number, Number, Number, Number]} */ this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y /** @type {[Number, Number]} */ this.snapped = [0, 0]; // x, y /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */ this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2 /** @type {[Number, Number]} */ this.scrollView = [0, 0]; // w, h /** @type {[Number, Number, Number, Number]} */ this.dragArea = [0, 0, 0, 0]; // x, y, w, h /** @type {[Number, Number, Number, Number]} */ this.containerBounds = [-1e12, maxValue, maxValue, -1e12]; // t, r, b, l /** @type {[Number, Number, Number, Number]} */ this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l /** @type {[Number, Number, Number, Number]} */ this.targetBounds = [0, 0, 0, 0]; // t, r, b, l /** @type {[Number, Number]} */ this.window = [0, 0]; // w, h /** @type {[Number, Number, Number]} */ this.velocityStack = [0, 0, 0]; /** @type {Number} */ this.velocityStackIndex = 0; /** @type {Number} */ this.velocityTime = now(); /** @type {Number} */ this.velocity = 0; /** @type {Number} */ this.angle = 0; /** @type {JSAnimation} */ this.cursorStyles = null; /** @type {JSAnimation} */ this.triggerStyles = null; /** @type {JSAnimation} */ this.bodyStyles = null; /** @type {JSAnimation} */ this.targetStyles = null; /** @type {JSAnimation} */ this.touchActionStyles = null; this.transforms = new Transforms(this.$target); this.overshootCoords = { x: 0, y: 0 }; this.overshootXTicker = new Timer({ autoplay: false }, null, 0).init(); this.overshootYTicker = new Timer({ autoplay: false }, null, 0).init(); this.updateTicker = new Timer({ autoplay: false }, null, 0).init(); this.overshootXTicker.onUpdate = () => { if (this.disabled[0]) return; this.updated = true; this.manual = true; this.animate[this.xProp](this.overshootCoords.x, 0); }; this.overshootXTicker.onComplete = () => { if (this.disabled[0]) return; this.manual = false; this.animate[this.xProp](this.overshootCoords.x, 0); }; this.overshootYTicker.onUpdate = () => { if (this.disabled[1]) return; this.updated = true; this.manual = true; this.animate[this.yProp](this.overshootCoords.y, 0); }; this.overshootYTicker.onComplete = () => { if (this.disabled[1]) return; this.manual = false; this.animate[this.yProp](this.overshootCoords.y, 0); }; this.updateTicker.onUpdate = () => this.update(); this.contained = !isUnd(container); this.manual = false; this.grabbed = false; this.dragged = false; this.updated = false; this.released = false; this.canScroll = false; this.enabled = false; this.initialized = false; this.activeProp = this.disabled[1] ? xProp : yProp; this.animate.animations[this.activeProp].onRender = () => { const hasUpdated = this.updated; const hasMoved = this.grabbed && hasUpdated; const hasReleased = !hasMoved && this.released; const x = this.x; const y = this.y; const dx = x - this.coords[2]; const dy = y - this.coords[3]; this.deltaX = dx; this.deltaY = dy; this.coords[2] = x; this.coords[3] = y; if (hasUpdated) { this.onUpdate(this); } if (!hasReleased) { this.updated = false; } else { this.computeVelocity(dx, dy); this.angle = atan2(dy, dx); } }; this.animate.animations[this.activeProp].onComplete = () => { if ((!this.grabbed && this.released)) { // Set eleased to false before calling onSettle to avoid recursion this.released = false; } if (!this.manual) { this.deltaX = 0; this.deltaY = 0; this.velocity = 0; this.velocityStack[0] = 0; this.velocityStack[1] = 0; this.velocityStack[2] = 0; this.velocityStackIndex = 0; this.onSettle(this); } }; this.resizeTicker = new Timer({ autoplay: false, duration: 150 * globals.timeScale, onComplete: () => { this.onResize(this); this.refresh(); this.onAfterResize(this); }, }).init(); this.parameters = parameters; this.resizeObserver = new ResizeObserver(() => { if (this.initialized) { this.resizeTicker.restart(); } else { this.initialized = true; } }); this.enable(); this.refresh(); this.resizeObserver.observe(this.$container); if (!isObj(target)) this.resizeObserver.observe(this.$target); }
@param {TargetsParam} target @param {DraggableParams} [parameters]
constructor
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
computeVelocity(dx, dy) { const prevTime = this.velocityTime; const curTime = now(); const elapsed = curTime - prevTime; if (elapsed < 17) return this.velocity; this.velocityTime = curTime; const velocityStack = this.velocityStack; const vMul = this.velocityMultiplier; const minV = this.minVelocity; const maxV = this.maxVelocity; const vi = this.velocityStackIndex; velocityStack[vi] = round(clamp((sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5); const velocity = max(velocityStack[0], velocityStack[1], velocityStack[2]); this.velocity = velocity; this.velocityStackIndex = (vi + 1) % 3; return velocity; }
@param {Number} dx @param {Number} dy @return {Number}
computeVelocity
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
setX(x, muteUpdateCallback = false) { if (this.disabled[0]) return; const v = round(x, 5); this.overshootXTicker.pause(); this.manual = true; this.updated = !muteUpdateCallback; this.destX = v; this.snapped[0] = snap(v, this.snapX); this.animate[this.xProp](v, 0); this.manual = false; return this; }
@param {Number} x @param {Boolean} [muteUpdateCallback] @return {this}
setX
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
setY(y, muteUpdateCallback = false) { if (this.disabled[1]) return; const v = round(y, 5); this.overshootYTicker.pause(); this.manual = true; this.updated = !muteUpdateCallback; this.destY = v; this.snapped[1] = snap(v, this.snapY); this.animate[this.yProp](v, 0); this.manual = false; return this; }
@param {Number} y @param {Boolean} [muteUpdateCallback] @return {this}
setY
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
get x() { return round(/** @type {Number} */(this.animate[this.xProp]()), globals.precision); }
@param {Number} y @param {Boolean} [muteUpdateCallback] @return {this}
x
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
isOutOfBounds(bounds, x, y) { if (!this.contained) return 0; const [ bt, br, bb, bl ] = bounds; const [ dx, dy ] = this.disabled; const obx = !dx && x < bl || !dx && x > br; const oby = !dy && y < bt || !dy && y > bb; return obx && !oby ? 1 : !obx && oby ? 2 : obx && oby ? 3 : 0; }
Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB @param {Array} bounds @param {Number} x @param {Number} y @return {Number}
isOutOfBounds
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
refresh() { const params = this.parameters; const paramX = params.x; const paramY = params.y; const container = parseDraggableFunctionParameter(params.container, this); const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0; const containerPadding = /** @type {[Number, Number, Number, Number]} */(isArr(cp) ? cp : [cp, cp, cp, cp]); const cx = this.x; const cy = this.y; const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this); const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' }; if (parsedCursorStyles) { const { onHover, onGrab } = /** @type {DraggableCursorParams} */(parsedCursorStyles); if (onHover) cursorStyles.onHover = onHover; if (onGrab) cursorStyles.onGrab = onGrab; } this.containerArray = isArr(container) ? container : null; this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body); this.useWin = this.$container === doc.body; /** @type {Window | HTMLElement} */ this.$scrollContainer = this.useWin ? win : this.$container; this.isFinePointer = matchMedia('(pointer:fine)').matches; this.containerPadding = setValue(containerPadding, [0, 0, 0, 0]); this.containerFriction = clamp(setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1); this.releaseContainerFriction = clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1); this.snapX = parseDraggableFunctionParameter(isObj(paramX) && !isUnd(paramX.snap) ? paramX.snap : params.snap, this); this.snapY = parseDraggableFunctionParameter(isObj(paramY) && !isUnd(paramY.snap) ? paramY.snap : params.snap, this); this.scrollSpeed = setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5); this.scrollThreshold = setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20); this.dragSpeed = setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1); this.minVelocity = setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0); this.maxVelocity = setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50); this.velocityMultiplier = setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1); this.cursor = parsedCursorStyles === false ? false : cursorStyles; this.updateBoundingValues(); // const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y); // if (ob === 1 || ob === 3) this.progressX = px; // if (ob === 2 || ob === 3) this.progressY = py; // if (this.initialized && this.contained) { // if (this.progressX !== px) this.progressX = px; // if (this.progressY !== py) this.progressY = py; // } const [ bt, br, bb, bl ] = this.containerBounds; this.setX(clamp(cx, bl, br), true); this.setY(clamp(cy, bt, bb), true); }
Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB @param {Array} bounds @param {Number} x @param {Number} y @return {Number}
refresh
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
scrollInView(duration, gap = 0, ease = eases.inOutQuad) { this.updateScrollCoords(); const x = this.destX; const y = this.destY; const scroll = this.scroll; const scrollBounds = this.scrollBounds; const canScroll = this.canScroll; if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) { const [ st, sr, sb, sl ] = scrollBounds; const t = round(clamp(y - st, -1e12, 0), 0); const r = round(clamp(x - sr, 0, maxValue), 0); const b = round(clamp(y - sb, 0, maxValue), 0); const l = round(clamp(x - sl, -1e12, 0), 0); new JSAnimation(scroll, { x: round(scroll.x + (l ? l - gap : r ? r + gap : 0), 0), y: round(scroll.y + (t ? t - gap : b ? b + gap : 0), 0), duration: isUnd(duration) ? 350 * globals.timeScale : duration, ease, onUpdate: () => { this.canScroll = false; this.$scrollContainer.scrollTo(scroll.x, scroll.y); } }).init().then(() => { this.canScroll = canScroll; }); } return this; }
@param {Number} [duration] @param {Number} [gap] @param {EasingParam} [ease] @return {this}
scrollInView
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
handleHover() { if (this.isFinePointer && this.cursor && !this.cursorStyles) { this.cursorStyles = setTargetValues(this.$trigger, { cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover }); } }
@param {Number} [duration] @param {Number} [gap] @param {EasingParam} [ease] @return {this}
handleHover
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
animateInView(duration, gap = 0, ease = eases.inOutQuad) { this.stop(); this.updateBoundingValues(); const x = this.x; const y = this.y; const [ cpt, cpr, cpb, cpl ] = this.containerPadding; const bt = this.scroll.y - this.targetBounds[0] + cpt + gap; const br = this.scroll.x - this.targetBounds[1] - cpr - gap; const bb = this.scroll.y - this.targetBounds[2] - cpb - gap; const bl = this.scroll.x - this.targetBounds[3] + cpl + gap; const ob = this.isOutOfBounds([bt, br, bb, bl], x, y); if (ob) { const [ disabledX, disabledY ] = this.disabled; const destX = clamp(snap(x, this.snapX), bl, br); const destY = clamp(snap(y, this.snapY), bt, bb); const dur = isUnd(duration) ? 350 * globals.timeScale : duration; if (!disabledX && (ob === 1 || ob === 3)) this.animate[this.xProp](destX, dur, ease); if (!disabledY && (ob === 2 || ob === 3)) this.animate[this.yProp](destY, dur, ease); } return this; }
@param {Number} [duration] @param {Number} [gap] @param {EasingParam} [ease] @return {this}
animateInView
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
execute(cb) { let activeScope = globals.scope; let activeRoot = globals.root; let activeDefaults = globals.defaults; globals.scope = this; globals.root = this.root; globals.defaults = this.defaults; const mqs = this.mediaQueryLists; for (let mq in mqs) this.matches[mq] = mqs[mq].matches; const returned = cb(this); globals.scope = activeScope; globals.root = activeRoot; globals.defaults = activeDefaults; return returned; }
@callback ScoppedCallback @param {this} scope @return {any} @param {ScoppedCallback} cb @return {this}
execute
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
add(a1, a2) { if (isFnc(a1)) { const constructor = /** @type {contructorCallback} */(a1); this.constructors.push(constructor); this.execute(() => { const revertConstructor = constructor(this); if (revertConstructor) { this.revertConstructors.push(revertConstructor); } }); } else { this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args)); } return this; }
@callback contructorCallback @param {this} self @overload @param {String} a1 @param {ScopeMethod} a2 @return {this} @overload @param {contructorCallback} a1 @return {this} @param {String|contructorCallback} a1 @param {ScopeMethod} [a2]
add
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/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
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/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
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
parseBoundValue = ($el, v, size, under, over) => { /** @type {Number} */ let value; if (isStr(v)) { const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v)); if (matchedOperator) { const splitter = matchedOperator[0]; const operator = splitter[0]; const splitted = /** @type {String} */(v).split(splitter); const clampMin = splitted[0] === 'min'; const clampMax = splitted[0] === 'max'; const valueAPx = convertValueToPx($el, splitted[0], size, under, over); const valueBPx = convertValueToPx($el, splitted[1], size, under, over); if (clampMin) { const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator); value = min < valueAPx ? valueAPx : min; } else if (clampMax) { const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator); value = max > valueAPx ? valueAPx : max; } else { value = getRelativeValue(valueAPx, valueBPx, operator); } } else { value = convertValueToPx($el, v, size, under, over); } } else { value = /** @type {Number} */(v); } return round(value, 0); }
@param {HTMLElement} $el @param {ScrollThresholdValue} v @param {Number} size @param {Number} [under] @param {Number} [over] @return {Number}
parseBoundValue
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
parseBoundValue = ($el, v, size, under, over) => { /** @type {Number} */ let value; if (isStr(v)) { const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v)); if (matchedOperator) { const splitter = matchedOperator[0]; const operator = splitter[0]; const splitted = /** @type {String} */(v).split(splitter); const clampMin = splitted[0] === 'min'; const clampMax = splitted[0] === 'max'; const valueAPx = convertValueToPx($el, splitted[0], size, under, over); const valueBPx = convertValueToPx($el, splitted[1], size, under, over); if (clampMin) { const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator); value = min < valueAPx ? valueAPx : min; } else if (clampMax) { const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator); value = max > valueAPx ? valueAPx : max; } else { value = getRelativeValue(valueAPx, valueBPx, operator); } } else { value = convertValueToPx($el, v, size, under, over); } } else { value = /** @type {Number} */(v); } return round(value, 0); }
@param {HTMLElement} $el @param {ScrollThresholdValue} v @param {Number} size @param {Number} [under] @param {Number} [over] @return {Number}
parseBoundValue
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
updateBounds() { if (this._debug) { this.removeDebug(); } let stickys; const $target = this.target; const container = this.container; const isHori = this.horizontal; const linked = this.linked; let linkedTime; let $el = $target; let offsetX = 0; let offsetY = 0; /** @type {Element} */ let $offsetParent = $el; if (linked) { linkedTime = linked.currentTime; linked.seek(0, true); } const isContainerStatic = getTargetValue(container.element, 'position') === 'static' ? setTargetValues(container.element, { position: 'relative '}) : false; while ($el && $el !== container.element && $el !== doc.body) { const isSticky = getTargetValue($el, 'position') === 'sticky' ? setTargetValues($el, { position: 'static' }) : false; if ($el === $offsetParent) { offsetX += $el.offsetLeft || 0; offsetY += $el.offsetTop || 0; $offsetParent = $el.offsetParent; } $el = /** @type {HTMLElement} */($el.parentElement); if (isSticky) { if (!stickys) stickys = []; stickys.push(isSticky); } } if (isContainerStatic) isContainerStatic.revert(); const offset = isHori ? offsetX : offsetY; const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight; const containerSize = isHori ? container.width : container.height; const scrollSize = isHori ? container.scrollWidth : container.scrollHeight; const maxScroll = scrollSize - containerSize; const enter = this.enter; const leave = this.leave; /** @type {ScrollThresholdValue} */ let enterTarget = 'start'; /** @type {ScrollThresholdValue} */ let leaveTarget = 'end'; /** @type {ScrollThresholdValue} */ let enterContainer = 'end'; /** @type {ScrollThresholdValue} */ let leaveContainer = 'start'; if (isStr(enter)) { const splitted = /** @type {String} */(enter).split(' '); enterContainer = splitted[0]; enterTarget = splitted.length > 1 ? splitted[1] : enterTarget; } else if (isObj(enter)) { const e = /** @type {ScrollThresholdParam} */(enter); if (!isUnd(e.container)) enterContainer = e.container; if (!isUnd(e.target)) enterTarget = e.target; } else if (isNum(enter)) { enterContainer = /** @type {Number} */(enter); } if (isStr(leave)) { const splitted = /** @type {String} */(leave).split(' '); leaveContainer = splitted[0]; leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget; } else if (isObj(leave)) { const t = /** @type {ScrollThresholdParam} */(leave); if (!isUnd(t.container)) leaveContainer = t.container; if (!isUnd(t.target)) leaveTarget = t.target; } else if (isNum(leave)) { leaveContainer = /** @type {Number} */(leave); } const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize); const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize); const under = (parsedEnterTarget + offset) - containerSize; const over = (parsedLeaveTarget + offset) - maxScroll; const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over); const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over); const offsetStart = parsedEnterTarget + offset - parsedEnterContainer; const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer; const scrollDelta = offsetEnd - offsetStart; this.offsets[0] = offsetX; this.offsets[1] = offsetY; this.offset = offset; this.offsetStart = offsetStart; this.offsetEnd = offsetEnd; this.distance = scrollDelta <= 0 ? 0 : scrollDelta; this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer]; this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer]; if (stickys) { stickys.forEach(sticky => sticky.revert()); } if (linked) { linked.seek(linkedTime, true); } if (this._debug) { this.debug(); } }
@param {String} p @param {Number} l @param {Number} t @param {Number} w @param {Number} h @return {String}
updateBounds
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/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
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/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
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
constructor(targets, parameters) { if (globals.scope) globals.scope.revertibles.push(this); /** @type {AnimationParams} */ const globalParams = {}; const properties = {}; this.targets = []; this.animations = {}; if (isUnd(targets) || isUnd(parameters)) return; for (let propName in parameters) { const paramValue = parameters[propName]; if (isKey(propName)) { properties[propName] = paramValue; } else { globalParams[propName] = paramValue; } } for (let propName in properties) { const propValue = properties[propName]; const isObjValue = isObj(propValue); /** @type {TweenParamsOptions} */ let propParams = {}; let to = '+=0'; if (isObjValue) { const unit = propValue.unit; if (isStr(unit)) to += unit; } else { propParams.duration = propValue; } propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to; const animParams = mergeObjects(globalParams, propParams); animParams.composition = compositionTypes.replace; animParams.autoplay = false; const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init(); if (!this.targets.length) this.targets.push(...animation.targets); /** @type {AnimatableProperty} */ this[propName] = (to, duration, ease) => { const tween = /** @type {Tween} */(animation._head); if (isUnd(to) && tween) { const numbers = tween._numbers; if (numbers && numbers.length) { return numbers; } else { return tween._modifier(tween._number); } } else { forEachChildren(animation, (/** @type {Tween} */tween) => { if (isArr(to)) { for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) { if (!isUnd(tween._numbers[i])) { tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i])); tween._toNumbers[i] = to[i]; } } } else { tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number)); tween._toNumber = /** @type {Number} */(to); } if (!isUnd(ease)) tween._ease = parseEasings(ease); tween._currentTime = 0; }); if (!isUnd(duration)) animation.stretch(duration); animation.reset(1).resume(); return this; } }; } }
@param {TargetsParam} targets @param {AnimatableParams} parameters
constructor
javascript
juliangarnier/anime
src/animatable.js
https://github.com/juliangarnier/anime/blob/master/src/animatable.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]; // Emulate WAPPI easing parameter position const currentEase = prop.ease; prop.ease = prevEase ? prevEase : undefined; prevEase = currentEase; // durProgress += prop.duration; // if (i === l - 1 && durProgress !== totalDuration) { // propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress }) // } } if (!propArray[0].duration) { propArray.shift(); } } } return properties; }
@param {DurationKeyframes | PercentageKeyframes} keyframes @param {AnimationParams} parameters @return {AnimationParams}
generateKeyframes
javascript
juliangarnier/anime
src/animation.js
https://github.com/juliangarnier/anime/blob/master/src/animation.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]; // Emulate WAPPI easing parameter position const currentEase = prop.ease; prop.ease = prevEase ? prevEase : undefined; prevEase = currentEase; // durProgress += prop.duration; // if (i === l - 1 && durProgress !== totalDuration) { // propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress }) // } } if (!propArray[0].duration) { propArray.shift(); } } } return properties; }
@param {DurationKeyframes | PercentageKeyframes} keyframes @param {AnimationParams} parameters @return {AnimationParams}
generateKeyframes
javascript
juliangarnier/anime
src/animation.js
https://github.com/juliangarnier/anime/blob/master/src/animation.js
MIT
constructor( targets, parameters, parent, parentPosition, fastSet = false, index = 0, length = 0 ) { super(/** @type {TimerParams&AnimationParams} */(parameters), parent, parentPosition); const parsedTargets = registerTargets(targets); const targetsLength = parsedTargets.length; // If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties const kfParams = /** @type {AnimationParams} */(parameters).keyframes; const params = /** @type {AnimationParams} */(kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters); const { delay, duration, ease, playbackEase, modifier, composition, onRender, } = params; const animDefaults = parent ? parent.defaults : globals.defaults; const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase); const animEase = animaPlaybackEase ? parseEasings(animaPlaybackEase) : null; const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease); const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease); const tDuration = hasSpring ? /** @type {Spring} */(ease).duration : setValue(duration, animDefaults.duration); const tDelay = setValue(delay, animDefaults.delay); const tModifier = modifier || animDefaults.modifier; // If no composition is defined and the targets length is high (>= 1000) set the composition to 'none' (0) for faster tween creation const tComposition = isUnd(composition) && targetsLength >= K ? compositionTypes.none : !isUnd(composition) ? composition : animDefaults.composition; // TODO: Do not create an empty object until we know the animation will generate inline styles const animInlineStyles = {}; // const absoluteOffsetTime = this._offset; const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0); let iterationDuration = NaN; let iterationDelay = NaN; let animationAnimationLength = 0; let shouldTriggerRender = 0; for (let targetIndex = 0; targetIndex < targetsLength; targetIndex++) { const target = parsedTargets[targetIndex]; const ti = index || targetIndex; const tl = length || targetsLength; let lastTransformGroupIndex = NaN; let lastTransformGroupLength = NaN; for (let p in params) { if (isKey(p)) { const tweenType = getTweenType(target, p); const propName = sanitizePropertyName(p, target, tweenType); let propValue = params[p]; const isPropValueArray = isArr(propValue); if (fastSet && !isPropValueArray) { fastSetValuesArray[0] = propValue; fastSetValuesArray[1] = propValue; propValue = fastSetValuesArray; } // TODO: Allow nested keyframes inside ObjectValue value (prop: { to: [.5, 1, .75, 2, 3] }) // Normalize property values to valid keyframe syntax: // [x, y] to [{to: [x, y]}] or {to: x} to [{to: x}] or keep keys syntax [{}, {}, {}...] // const keyframes = isArr(propValue) ? propValue.length === 2 && !isObj(propValue[0]) ? [{ to: propValue }] : propValue : [propValue]; if (isPropValueArray) { const arrayLength = /** @type {Array} */(propValue).length; const isNotObjectValue = !isObj(propValue[0]); // Convert [x, y] to [{to: [x, y]}] if (arrayLength === 2 && isNotObjectValue) { keyObjectTarget.to = /** @type {TweenParamValue} */(/** @type {unknown} */(propValue)); keyframesTargetArray[0] = keyObjectTarget; keyframes = keyframesTargetArray; // Convert [x, y, z] to [[x, y], z] } else if (arrayLength > 2 && isNotObjectValue) { keyframes = []; /** @type {Array.<Number>} */(propValue).forEach((v, i) => { if (!i) { fastSetValuesArray[0] = v; } else if (i === 1) { fastSetValuesArray[1] = v; keyframes.push(fastSetValuesArray); } else { keyframes.push(v); } }); } else { keyframes = /** @type {Array.<TweenKeyValue>} */(propValue); } } else { keyframesTargetArray[0] = propValue; keyframes = keyframesTargetArray; } let siblings = null; let prevTween = null; let firstTweenChangeStartTime = NaN; let lastTweenChangeEndTime = 0; let tweenIndex = 0; for (let l = keyframes.length; tweenIndex < l; tweenIndex++) { const keyframe = keyframes[tweenIndex]; if (isObj(keyframe)) { key = keyframe; } else { keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe); key = keyObjectTarget; } toFunctionStore.func = null; const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore); let tweenToValue; // Allows function based values to return an object syntax value ({to: v}) if (isObj(computedToValue) && !isUnd(computedToValue.to)) { key = computedToValue; tweenToValue = computedToValue.to; } else { tweenToValue = computedToValue; } const tweenFromValue = getFunctionValue(key.from, target, ti, tl); const keyEasing = key.ease; const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */(keyEasing).ease); // Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing || tEasing; // Calculate default individual keyframe duration by dividing the tl of keyframes const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).duration : getFunctionValue(setValue(key.duration, (l > 1 ? getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl); // Default delay value should only be applied to the first tween const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl); const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl); const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition]; // Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper const tweenModifier = key.modifier || tModifier; const hasFromvalue = !isUnd(tweenFromValue); const hasToValue = !isUnd(tweenToValue); const isFromToArray = isArr(tweenToValue); const isFromToValue = isFromToArray || (hasFromvalue && hasToValue); const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay; const absoluteStartTime = absoluteOffsetTime + tweenStartTime; // Force a onRender callback if the animation contains at least one from value and autoplay is set to false if (!shouldTriggerRender && (hasFromvalue || isFromToArray)) shouldTriggerRender = 1; let prevSibling = prevTween; if (tweenComposition !== compositionTypes.none) { if (!siblings) siblings = getTweenSiblings(target, propName); let nextSibling = siblings._head; // Iterate trough all the next siblings until we find a sibling with an equal or inferior start time while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) { prevSibling = nextSibling; nextSibling = nextSibling._nextRep; // Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) { while (nextSibling) { overrideTween(nextSibling); // This will ends both the current while loop and the upper one once all the next sibllings have been overriden nextSibling = nextSibling._nextRep; } } } } // Decompose values if (isFromToValue) { decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject); decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject); if (fromTargetObject.t === valueTypes.NUMBER) { if (prevSibling) { if (prevSibling._valueType === valueTypes.UNIT) { fromTargetObject.t = valueTypes.UNIT; fromTargetObject.u = prevSibling._unit; } } else { decomposeRawValue( getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), decomposedOriginalValue ); if (decomposedOriginalValue.t === valueTypes.UNIT) { fromTargetObject.t = valueTypes.UNIT; fromTargetObject.u = decomposedOriginalValue.u; } } } } else { if (hasToValue) { decomposeRawValue(tweenToValue, toTargetObject); } else { if (prevTween) { decomposeTweenValue(prevTween, toTargetObject); } else { // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value : getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), toTargetObject); } } if (hasFromvalue) { decomposeRawValue(tweenFromValue, fromTargetObject); } else { if (prevTween) { decomposeTweenValue(prevTween, fromTargetObject); } else { decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value : // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), fromTargetObject); } } } // Apply operators if (fromTargetObject.o) { fromTargetObject.n = getRelativeValue( !prevSibling ? decomposeRawValue( getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), decomposedOriginalValue ).n : prevSibling._toNumber, fromTargetObject.n, fromTargetObject.o ); } if (toTargetObject.o) { toTargetObject.n = getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o); } // Values omogenisation in cases of type difference between "from" and "to" if (fromTargetObject.t !== toTargetObject.t) { if (fromTargetObject.t === valueTypes.COMPLEX || toTargetObject.t === valueTypes.COMPLEX) { const complexValue = fromTargetObject.t === valueTypes.COMPLEX ? fromTargetObject : toTargetObject; const notComplexValue = fromTargetObject.t === valueTypes.COMPLEX ? toTargetObject : fromTargetObject; notComplexValue.t = valueTypes.COMPLEX; notComplexValue.s = cloneArray(complexValue.s); notComplexValue.d = complexValue.d.map(() => notComplexValue.n); } else if (fromTargetObject.t === valueTypes.UNIT || toTargetObject.t === valueTypes.UNIT) { const unitValue = fromTargetObject.t === valueTypes.UNIT ? fromTargetObject : toTargetObject; const notUnitValue = fromTargetObject.t === valueTypes.UNIT ? toTargetObject : fromTargetObject; notUnitValue.t = valueTypes.UNIT; notUnitValue.u = unitValue.u; } else if (fromTargetObject.t === valueTypes.COLOR || toTargetObject.t === valueTypes.COLOR) { const colorValue = fromTargetObject.t === valueTypes.COLOR ? fromTargetObject : toTargetObject; const notColorValue = fromTargetObject.t === valueTypes.COLOR ? toTargetObject : fromTargetObject; notColorValue.t = valueTypes.COLOR; notColorValue.s = colorValue.s; notColorValue.d = [0, 0, 0, 1]; } } // Unit conversion if (fromTargetObject.u !== toTargetObject.u) { let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject; valueToConvert = convertValueUnit(/** @type {DOMTarget} */(target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false); // TODO: // convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u); } // Fill in non existing complex values if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) { const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject; const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject; // TODO: Check if n should be used instead of 0 for default complex values shortestValue.d = longestValue.d.map((_, i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]); shortestValue.s = cloneArray(longestValue.s); } // Tween factory // Rounding is necessary here to minimize floating point errors const tweenUpdateDuration = round(+tweenDuration || minValue, 12); /** @type {Tween} */ const tween = { parent: this, id: tweenId++, property: propName, target: target, _value: null, _func: toFunctionStore.func, _ease: parseEasings(tweenEasing), _fromNumbers: cloneArray(fromTargetObject.d), _toNumbers: cloneArray(toTargetObject.d), _strings: cloneArray(toTargetObject.s), _fromNumber: fromTargetObject.n, _toNumber: toTargetObject.n, _numbers: cloneArray(fromTargetObject.d), // For additive tween and animatables _number: fromTargetObject.n, // For additive tween and animatables _unit: toTargetObject.u, _modifier: tweenModifier, _currentTime: 0, _startTime: tweenStartTime, _delay: +tweenDelay, _updateDuration: tweenUpdateDuration, _changeDuration: tweenUpdateDuration, _absoluteStartTime: absoluteStartTime, // NOTE: Investigate bit packing to stores ENUM / BOOL _tweenType: tweenType, _valueType: toTargetObject.t, _composition: tweenComposition, _isOverlapped: 0, _isOverridden: 0, _renderTransforms: 0, _prevRep: null, // For replaced tween _nextRep: null, // For replaced tween _prevAdd: null, // For additive tween _nextAdd: null, // For additive tween _prev: null, _next: null, } if (tweenComposition !== compositionTypes.none) { composeTween(tween, siblings); } if (isNaN(firstTweenChangeStartTime)) { firstTweenChangeStartTime = tween._startTime; } // Rounding is necessary here to minimize floating point errors lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12); prevTween = tween; animationAnimationLength++; addChild(this, tween); } // Update animation timings with the added tweens properties if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) { iterationDelay = firstTweenChangeStartTime; } if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) { iterationDuration = lastTweenChangeEndTime; } // TODO: Find a way to inline tween._renderTransforms = 1 here if (tweenType === tweenTypes.TRANSFORM) { lastTransformGroupIndex = animationAnimationLength - tweenIndex; lastTransformGroupLength = animationAnimationLength; } } } // Set _renderTransforms to last transform property to correctly render the transforms list if (!isNaN(lastTransformGroupIndex)) { let i = 0; forEachChildren(this, (/** @type {Tween} */tween) => { if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) { tween._renderTransforms = 1; if (tween._composition === compositionTypes.blend) { forEachChildren(additive.animation, (/** @type {Tween} */additiveTween) => { if (additiveTween.id === tween.id) { additiveTween._renderTransforms = 1; } }); } } i++; }); } } if (!targetsLength) { console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`); } if (iterationDelay) { forEachChildren(this, (/** @type {Tween} */tween) => { // If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too if (!(tween._startTime - tween._delay)) { tween._delay -= iterationDelay; } tween._startTime -= iterationDelay; }); iterationDuration -= iterationDelay; } else { iterationDelay = 0; } // Prevents iterationDuration to be NaN if no valid animatable props have been provided // Prevents _iterationCount to be NaN if no valid animatable props have been provided if (!iterationDuration) { iterationDuration = minValue; this.iterationCount = 0; } /** @type {TargetsArray} */ this.targets = parsedTargets; /** @type {Number} */ this.duration = iterationDuration === minValue ? minValue : clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || minValue; /** @type {Callback<this>} */ this.onRender = onRender || animDefaults.onRender; /** @type {EasingFunction} */ this._ease = animEase; /** @type {Number} */ this._delay = iterationDelay; // NOTE: I'm keeping delay values separated from offsets in timelines because delays can override previous tweens and it could be confusing to debug a timeline with overridden tweens and no associated visible delays. // this._delay = parent ? 0 : iterationDelay; // this._offset += parent ? iterationDelay : 0; /** @type {Number} */ this.iterationDuration = iterationDuration; /** @type {{}} */ this._inlineStyles = animInlineStyles; if (!this._autoplay && shouldTriggerRender) this.onRender(this); }
@param {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
src/animation.js
https://github.com/juliangarnier/anime/blob/master/src/animation.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
src/animation.js
https://github.com/juliangarnier/anime/blob/master/src/animation.js
MIT
then(callback) { return super.then(callback); }
@param {Callback<this>} [callback] @return {Promise}
then
javascript
juliangarnier/anime
src/animation.js
https://github.com/juliangarnier/anime/blob/master/src/animation.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/colors.js
https://github.com/juliangarnier/anime/blob/master/src/colors.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
src/compositions.js
https://github.com/juliangarnier/anime/blob/master/src/compositions.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
src/compositions.js
https://github.com/juliangarnier/anime/blob/master/src/compositions.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
src/compositions.js
https://github.com/juliangarnier/anime/blob/master/src/compositions.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
src/compositions.js
https://github.com/juliangarnier/anime/blob/master/src/compositions.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._changeDuration = absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime; prevSibling._currentTime = prevSibling._changeDuration; prevSibling._isOverlapped = 1; if (prevSibling._changeDuration < minValue) { overrideTween(prevSibling); } } // Pause (and cancel) the parent if it only contains overlapped tweens let pausePrevParentAnimation = true; forEachChildren(prevParent, (/** @type Tween */t) => { if (!t._isOverlapped) pausePrevParentAnimation = false; }); if (pausePrevParentAnimation) { const prevParentTL = prevParent.parent; if (prevParentTL) { let pausePrevParentTL = true; forEachChildren(prevParentTL, (/** @type JSAnimation */a) => { if (a !== prevParent) { forEachChildren(a, (/** @type Tween */t) => { if (!t._isOverlapped) pausePrevParentTL = false; }); } }); if (pausePrevParentTL) { prevParentTL.cancel(); } } else { prevParent.cancel(); // Previously, calling .cancel() on a timeline child would affect the render order of other children // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop // This is no longer needed since timeline tween composition is now handled separatly // Keeping this here for reference // prevParent.completed = true; // prevParent.pause(); } } } // let nextSibling = tween._nextRep; // // All the next siblings are automatically overridden // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // nextSibling = nextSibling._nextRep; // } // } // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // console.log(tween.id, nextSibling.id); // nextSibling = nextSibling._nextRep; // } // } // Handle additive tweens composition } else if (tweenCompositionType === compositionTypes.blend) { const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add'); const additiveAnimation = addAdditiveAnimation(lookups._add); let lookupTween = additiveTweenSiblings._head; if (!lookupTween) { lookupTween = { ...tween }; lookupTween._composition = compositionTypes.replace; lookupTween._updateDuration = minValue; lookupTween._startTime = 0; lookupTween._numbers = cloneArray(tween._fromNumbers); lookupTween._number = 0; lookupTween._next = null; lookupTween._prev = null; addChild(additiveTweenSiblings, lookupTween); addChild(additiveAnimation, lookupTween); } // Convert the values of TO to FROM and set TO to 0 const toNumber = tween._toNumber; tween._fromNumber = lookupTween._fromNumber - toNumber; tween._toNumber = 0; tween._numbers = cloneArray(tween._fromNumbers); tween._number = 0; lookupTween._fromNumber = toNumber; if (tween._toNumbers) { const toNumbers = cloneArray(tween._toNumbers); if (toNumbers) { toNumbers.forEach((value, i) => { tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value; tween._toNumbers[i] = 0; }); } lookupTween._fromNumbers = toNumbers; } addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd'); } return tween; }
@param {Tween} tween @param {TweenPropertySiblings} siblings @return {Tween}
composeTween
javascript
juliangarnier/anime
src/compositions.js
https://github.com/juliangarnier/anime/blob/master/src/compositions.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._changeDuration = absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime; prevSibling._currentTime = prevSibling._changeDuration; prevSibling._isOverlapped = 1; if (prevSibling._changeDuration < minValue) { overrideTween(prevSibling); } } // Pause (and cancel) the parent if it only contains overlapped tweens let pausePrevParentAnimation = true; forEachChildren(prevParent, (/** @type Tween */t) => { if (!t._isOverlapped) pausePrevParentAnimation = false; }); if (pausePrevParentAnimation) { const prevParentTL = prevParent.parent; if (prevParentTL) { let pausePrevParentTL = true; forEachChildren(prevParentTL, (/** @type JSAnimation */a) => { if (a !== prevParent) { forEachChildren(a, (/** @type Tween */t) => { if (!t._isOverlapped) pausePrevParentTL = false; }); } }); if (pausePrevParentTL) { prevParentTL.cancel(); } } else { prevParent.cancel(); // Previously, calling .cancel() on a timeline child would affect the render order of other children // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop // This is no longer needed since timeline tween composition is now handled separatly // Keeping this here for reference // prevParent.completed = true; // prevParent.pause(); } } } // let nextSibling = tween._nextRep; // // All the next siblings are automatically overridden // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // nextSibling = nextSibling._nextRep; // } // } // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // console.log(tween.id, nextSibling.id); // nextSibling = nextSibling._nextRep; // } // } // Handle additive tweens composition } else if (tweenCompositionType === compositionTypes.blend) { const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add'); const additiveAnimation = addAdditiveAnimation(lookups._add); let lookupTween = additiveTweenSiblings._head; if (!lookupTween) { lookupTween = { ...tween }; lookupTween._composition = compositionTypes.replace; lookupTween._updateDuration = minValue; lookupTween._startTime = 0; lookupTween._numbers = cloneArray(tween._fromNumbers); lookupTween._number = 0; lookupTween._next = null; lookupTween._prev = null; addChild(additiveTweenSiblings, lookupTween); addChild(additiveAnimation, lookupTween); } // Convert the values of TO to FROM and set TO to 0 const toNumber = tween._toNumber; tween._fromNumber = lookupTween._fromNumber - toNumber; tween._toNumber = 0; tween._numbers = cloneArray(tween._fromNumbers); tween._number = 0; lookupTween._fromNumber = toNumber; if (tween._toNumbers) { const toNumbers = cloneArray(tween._toNumbers); if (toNumbers) { toNumbers.forEach((value, i) => { tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value; tween._toNumbers[i] = 0; }); } lookupTween._fromNumbers = toNumbers; } addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd'); } return tween; }
@param {Tween} tween @param {TweenPropertySiblings} siblings @return {Tween}
composeTween
javascript
juliangarnier/anime
src/compositions.js
https://github.com/juliangarnier/anime/blob/master/src/compositions.js
MIT
normalizePoint(x, y) { this.point.x = x; this.point.y = y; return this.point.matrixTransform(this.inversedMatrix); }
@param {Number} x @param {Number} y @return {DOMPoint}
normalizePoint
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
constructor(target, parameters = {}) { if (!target) return; if (globals.scope) globals.scope.revertibles.push(this); const paramX = parameters.x; const paramY = parameters.y; const trigger = parameters.trigger; const modifier = parameters.modifier; const ease = parameters.releaseEase; const customEase = ease && parseEasings(ease); const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease); const xProp = /** @type {String} */(isObj(paramX) && !isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX'); const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY'); const container = parseDraggableFunctionParameter(parameters.container, this); this.containerArray = isArr(container) ? container : null; this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body); this.useWin = this.$container === doc.body; /** @type {Window | HTMLElement} */ this.$scrollContainer = this.useWin ? win : this.$container; this.$target = /** @type {HTMLElement} */(isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]); this.$trigger = /** @type {HTMLElement} */(parseTargets(trigger ? trigger : target)[0]); this.fixed = getTargetValue(this.$target, 'position') === 'fixed'; // Refreshable parameters this.isFinePointer = true; /** @type {[Number, Number, Number, Number]} */ this.containerPadding = [0, 0, 0, 0]; /** @type {Number} */ this.containerFriction = 0; /** @type {Number} */ this.releaseContainerFriction = 0; /** @type {Number|Array<Number>} */ this.snapX = 0; /** @type {Number|Array<Number>} */ this.snapY = 0; /** @type {Number} */ this.scrollSpeed = 0; /** @type {Number} */ this.scrollThreshold = 0; /** @type {Number} */ this.dragSpeed = 0; /** @type {Number} */ this.maxVelocity = 0; /** @type {Number} */ this.minVelocity = 0; /** @type {Number} */ this.velocityMultiplier = 0; /** @type {Boolean|DraggableCursorParams} */ this.cursor = false; /** @type {Spring} */ this.releaseXSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); /** @type {Spring} */ this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); /** @type {EasingFunction} */ this.releaseEase = customEase || eases.outQuint; /** @type {Boolean} */ this.hasReleaseSpring = hasSpring; /** @type {Callback<this>} */ this.onGrab = parameters.onGrab || noop; /** @type {Callback<this>} */ this.onDrag = parameters.onDrag || noop; /** @type {Callback<this>} */ this.onRelease = parameters.onRelease || noop; /** @type {Callback<this>} */ this.onUpdate = parameters.onUpdate || noop; /** @type {Callback<this>} */ this.onSettle = parameters.onSettle || noop; /** @type {Callback<this>} */ this.onSnap = parameters.onSnap || noop; /** @type {Callback<this>} */ this.onResize = parameters.onResize || noop; /** @type {Callback<this>} */ this.onAfterResize = parameters.onAfterResize || noop; /** @type {[Number, Number]} */ this.disabled = [0, 0]; /** @type {AnimatableParams} */ const animatableParams = {}; if (modifier) animatableParams.modifier = modifier; if (isUnd(paramX) || paramX === true) { animatableParams[xProp] = 0; } else if (isObj(paramX)) { const paramXObject = /** @type {DraggableAxisParam} */(paramX); const animatableXParams = {}; if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier; if (paramXObject.composition) animatableXParams.composition = paramXObject.composition; animatableParams[xProp] = animatableXParams; } else if (paramX === false) { animatableParams[xProp] = 0; this.disabled[0] = 1; } if (isUnd(paramY) || paramY === true) { animatableParams[yProp] = 0; } else if (isObj(paramY)) { const paramYObject = /** @type {DraggableAxisParam} */(paramY); const animatableYParams = {}; if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier; if (paramYObject.composition) animatableYParams.composition = paramYObject.composition; animatableParams[yProp] = animatableYParams; } else if (paramY === false) { animatableParams[yProp] = 0; this.disabled[1] = 1; } /** @type {AnimatableObject} */ this.animate = /** @type {AnimatableObject} */(new Animatable(this.$target, animatableParams)); // Internal props this.xProp = xProp; this.yProp = yProp; this.destX = 0; this.destY = 0; this.deltaX = 0; this.deltaY = 0; this.scroll = {x: 0, y: 0}; /** @type {[Number, Number, Number, Number]} */ this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y /** @type {[Number, Number]} */ this.snapped = [0, 0]; // x, y /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */ this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2 /** @type {[Number, Number]} */ this.scrollView = [0, 0]; // w, h /** @type {[Number, Number, Number, Number]} */ this.dragArea = [0, 0, 0, 0]; // x, y, w, h /** @type {[Number, Number, Number, Number]} */ this.containerBounds = [-maxValue, maxValue, maxValue, -maxValue]; // t, r, b, l /** @type {[Number, Number, Number, Number]} */ this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l /** @type {[Number, Number, Number, Number]} */ this.targetBounds = [0, 0, 0, 0]; // t, r, b, l /** @type {[Number, Number]} */ this.window = [0, 0]; // w, h /** @type {[Number, Number, Number]} */ this.velocityStack = [0, 0, 0]; /** @type {Number} */ this.velocityStackIndex = 0; /** @type {Number} */ this.velocityTime = now(); /** @type {Number} */ this.velocity = 0; /** @type {Number} */ this.angle = 0; /** @type {JSAnimation} */ this.cursorStyles = null; /** @type {JSAnimation} */ this.triggerStyles = null; /** @type {JSAnimation} */ this.bodyStyles = null; /** @type {JSAnimation} */ this.targetStyles = null; /** @type {JSAnimation} */ this.touchActionStyles = null; this.transforms = new Transforms(this.$target); this.overshootCoords = { x: 0, y: 0 }; this.overshootXTicker = new Timer({ autoplay: false }, null, 0).init(); this.overshootYTicker = new Timer({ autoplay: false }, null, 0).init(); this.updateTicker = new Timer({ autoplay: false }, null, 0).init(); this.overshootXTicker.onUpdate = () => { if (this.disabled[0]) return; this.updated = true; this.manual = true; this.animate[this.xProp](this.overshootCoords.x, 0); } this.overshootXTicker.onComplete = () => { if (this.disabled[0]) return; this.manual = false; this.animate[this.xProp](this.overshootCoords.x, 0); } this.overshootYTicker.onUpdate = () => { if (this.disabled[1]) return; this.updated = true; this.manual = true; this.animate[this.yProp](this.overshootCoords.y, 0); } this.overshootYTicker.onComplete = () => { if (this.disabled[1]) return; this.manual = false; this.animate[this.yProp](this.overshootCoords.y, 0); } this.updateTicker.onUpdate = () => this.update(); this.contained = !isUnd(container); this.manual = false; this.grabbed = false; this.dragged = false; this.updated = false; this.released = false; this.canScroll = false; this.enabled = false; this.initialized = false; this.activeProp = this.disabled[1] ? xProp : yProp; this.animate.animations[this.activeProp].onRender = () => { const hasUpdated = this.updated; const hasMoved = this.grabbed && hasUpdated; const hasReleased = !hasMoved && this.released; const x = this.x; const y = this.y; const dx = x - this.coords[2]; const dy = y - this.coords[3]; this.deltaX = dx; this.deltaY = dy; this.coords[2] = x; this.coords[3] = y; if (hasUpdated) { this.onUpdate(this); } if (!hasReleased) { this.updated = false; } else { this.computeVelocity(dx, dy); this.angle = atan2(dy, dx); } } this.animate.animations[this.activeProp].onComplete = () => { if ((!this.grabbed && this.released)) { // Set eleased to false before calling onSettle to avoid recursion this.released = false; } if (!this.manual) { this.deltaX = 0; this.deltaY = 0; this.velocity = 0; this.velocityStack[0] = 0; this.velocityStack[1] = 0; this.velocityStack[2] = 0; this.velocityStackIndex = 0; this.onSettle(this); } }; this.resizeTicker = new Timer({ autoplay: false, duration: 150 * globals.timeScale, onComplete: () => { this.onResize(this); this.refresh(); this.onAfterResize(this); }, }).init(); this.parameters = parameters; this.resizeObserver = new ResizeObserver(() => { if (this.initialized) { this.resizeTicker.restart(); } else { this.initialized = true; } }); this.enable(); this.refresh(); this.resizeObserver.observe(this.$container); if (!isObj(target)) this.resizeObserver.observe(this.$target); }
@param {TargetsParam} target @param {DraggableParams} [parameters]
constructor
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
computeVelocity(dx, dy) { const prevTime = this.velocityTime; const curTime = now(); const elapsed = curTime - prevTime; if (elapsed < 17) return this.velocity; this.velocityTime = curTime; const velocityStack = this.velocityStack; const vMul = this.velocityMultiplier; const minV = this.minVelocity; const maxV = this.maxVelocity; const vi = this.velocityStackIndex; velocityStack[vi] = round(clamp((sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5); const velocity = max(velocityStack[0], velocityStack[1], velocityStack[2]); this.velocity = velocity; this.velocityStackIndex = (vi + 1) % 3; return velocity; }
@param {Number} dx @param {Number} dy @return {Number}
computeVelocity
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
setX(x, muteUpdateCallback = false) { if (this.disabled[0]) return; const v = round(x, 5); this.overshootXTicker.pause(); this.manual = true; this.updated = !muteUpdateCallback; this.destX = v; this.snapped[0] = snap(v, this.snapX); this.animate[this.xProp](v, 0); this.manual = false; return this; }
@param {Number} x @param {Boolean} [muteUpdateCallback] @return {this}
setX
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
setY(y, muteUpdateCallback = false) { if (this.disabled[1]) return; const v = round(y, 5); this.overshootYTicker.pause(); this.manual = true; this.updated = !muteUpdateCallback; this.destY = v; this.snapped[1] = snap(v, this.snapY); this.animate[this.yProp](v, 0); this.manual = false; return this; }
@param {Number} y @param {Boolean} [muteUpdateCallback] @return {this}
setY
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
get x() { return round(/** @type {Number} */(this.animate[this.xProp]()), globals.precision); }
@param {Number} y @param {Boolean} [muteUpdateCallback] @return {this}
x
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
isOutOfBounds(bounds, x, y) { if (!this.contained) return 0; const [ bt, br, bb, bl ] = bounds; const [ dx, dy ] = this.disabled; const obx = !dx && x < bl || !dx && x > br; const oby = !dy && y < bt || !dy && y > bb; return obx && !oby ? 1 : !obx && oby ? 2 : obx && oby ? 3 : 0; }
Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB @param {Array} bounds @param {Number} x @param {Number} y @return {Number}
isOutOfBounds
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
refresh() { const params = this.parameters; const paramX = params.x; const paramY = params.y; const container = parseDraggableFunctionParameter(params.container, this); const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0; const containerPadding = /** @type {[Number, Number, Number, Number]} */(isArr(cp) ? cp : [cp, cp, cp, cp]); const cx = this.x; const cy = this.y; const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this); const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' }; if (parsedCursorStyles) { const { onHover, onGrab } = /** @type {DraggableCursorParams} */(parsedCursorStyles); if (onHover) cursorStyles.onHover = onHover; if (onGrab) cursorStyles.onGrab = onGrab; } this.containerArray = isArr(container) ? container : null; this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body); this.useWin = this.$container === doc.body; /** @type {Window | HTMLElement} */ this.$scrollContainer = this.useWin ? win : this.$container; this.isFinePointer = matchMedia('(pointer:fine)').matches; this.containerPadding = setValue(containerPadding, [0, 0, 0, 0]); this.containerFriction = clamp(setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1); this.releaseContainerFriction = clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1); this.snapX = parseDraggableFunctionParameter(isObj(paramX) && !isUnd(paramX.snap) ? paramX.snap : params.snap, this); this.snapY = parseDraggableFunctionParameter(isObj(paramY) && !isUnd(paramY.snap) ? paramY.snap : params.snap, this); this.scrollSpeed = setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5); this.scrollThreshold = setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20); this.dragSpeed = setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1); this.minVelocity = setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0); this.maxVelocity = setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50); this.velocityMultiplier = setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1); this.cursor = parsedCursorStyles === false ? false : cursorStyles; this.updateBoundingValues(); // const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y); // if (ob === 1 || ob === 3) this.progressX = px; // if (ob === 2 || ob === 3) this.progressY = py; // if (this.initialized && this.contained) { // if (this.progressX !== px) this.progressX = px; // if (this.progressY !== py) this.progressY = py; // } const [ bt, br, bb, bl ] = this.containerBounds; this.setX(clamp(cx, bl, br), true); this.setY(clamp(cy, bt, bb), true); }
Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB @param {Array} bounds @param {Number} x @param {Number} y @return {Number}
refresh
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
scrollInView(duration, gap = 0, ease = eases.inOutQuad) { this.updateScrollCoords(); const x = this.destX; const y = this.destY; const scroll = this.scroll; const scrollBounds = this.scrollBounds; const canScroll = this.canScroll; if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) { const [ st, sr, sb, sl ] = scrollBounds; const t = round(clamp(y - st, -maxValue, 0), 0); const r = round(clamp(x - sr, 0, maxValue), 0); const b = round(clamp(y - sb, 0, maxValue), 0); const l = round(clamp(x - sl, -maxValue, 0), 0); new JSAnimation(scroll, { x: round(scroll.x + (l ? l - gap : r ? r + gap : 0), 0), y: round(scroll.y + (t ? t - gap : b ? b + gap : 0), 0), duration: isUnd(duration) ? 350 * globals.timeScale : duration, ease, onUpdate: () => { this.canScroll = false; this.$scrollContainer.scrollTo(scroll.x, scroll.y); } }).init().then(() => { this.canScroll = canScroll; }) } return this; }
@param {Number} [duration] @param {Number} [gap] @param {EasingParam} [ease] @return {this}
scrollInView
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
handleHover() { if (this.isFinePointer && this.cursor && !this.cursorStyles) { this.cursorStyles = setTargetValues(this.$trigger, { cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover }); } }
@param {Number} [duration] @param {Number} [gap] @param {EasingParam} [ease] @return {this}
handleHover
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.js
MIT
animateInView(duration, gap = 0, ease = eases.inOutQuad) { this.stop(); this.updateBoundingValues(); const x = this.x; const y = this.y; const [ cpt, cpr, cpb, cpl ] = this.containerPadding; const bt = this.scroll.y - this.targetBounds[0] + cpt + gap; const br = this.scroll.x - this.targetBounds[1] - cpr - gap; const bb = this.scroll.y - this.targetBounds[2] - cpb - gap; const bl = this.scroll.x - this.targetBounds[3] + cpl + gap; const ob = this.isOutOfBounds([bt, br, bb, bl], x, y); if (ob) { const [ disabledX, disabledY ] = this.disabled; const destX = clamp(snap(x, this.snapX), bl, br); const destY = clamp(snap(y, this.snapY), bt, bb); const dur = isUnd(duration) ? 350 * globals.timeScale : duration; if (!disabledX && (ob === 1 || ob === 3)) this.animate[this.xProp](destX, dur, ease); if (!disabledY && (ob === 2 || ob === 3)) this.animate[this.yProp](destY, dur, ease); } return this; }
@param {Number} [duration] @param {Number} [gap] @param {EasingParam} [ease] @return {this}
animateInView
javascript
juliangarnier/anime
src/draggable.js
https://github.com/juliangarnier/anime/blob/master/src/draggable.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
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.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
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.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
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.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
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.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
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.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
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.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
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.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
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.js
MIT
parseEaseString = (string, easesFunctions, easesLookups) => { if (easesLookups[string]) return easesLookups[string]; if (string.indexOf('(') <= -1) { const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic'); const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasesFactory} */(easesFunctions[string])() : easesFunctions[string]); return parsedFn ? easesLookups[string] = parsedFn : none; } else { const split = string.slice(0, -1).split('('); const parsedFn = /** @type {EasesFactory} */(easesFunctions[split[0]]); return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none; } }
@param {String} string @param {Record<String, EasesFactory|EasingFunction>} easesFunctions @param {Object} easesLookups @return {EasingFunction}
parseEaseString
javascript
juliangarnier/anime
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.js
MIT
parseEaseString = (string, easesFunctions, easesLookups) => { if (easesLookups[string]) return easesLookups[string]; if (string.indexOf('(') <= -1) { const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic'); const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasesFactory} */(easesFunctions[string])() : easesFunctions[string]); return parsedFn ? easesLookups[string] = parsedFn : none; } else { const split = string.slice(0, -1).split('('); const parsedFn = /** @type {EasesFactory} */(easesFunctions[split[0]]); return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none; } }
@param {String} string @param {Record<String, EasesFactory|EasingFunction>} easesFunctions @param {Object} easesLookups @return {EasingFunction}
parseEaseString
javascript
juliangarnier/anime
src/eases.js
https://github.com/juliangarnier/anime/blob/master/src/eases.js
MIT
parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */(str)) : /** @type {Number} */(str)
@param {Number|String} str @return {Number}
parseNumber
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */(str)) : /** @type {Number} */(str)
@param {Number|String} str @return {Number}
parseNumber
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
round = (v, decimalLength) => { if (decimalLength < 0) return v; if (!decimalLength) return _round(v); let p = powCache[decimalLength]; if (!p) p = powCache[decimalLength] = 10 ** decimalLength; return _round(v * p) / p; }
@param {Number} v @param {Number} decimalLength @return {Number}
round
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
round = (v, decimalLength) => { if (decimalLength < 0) return v; if (!decimalLength) return _round(v); let p = powCache[decimalLength]; if (!p) p = powCache[decimalLength] = 10 ** decimalLength; return _round(v * p) / p; }
@param {Number} v @param {Number} decimalLength @return {Number}
round
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => { let next = parent._head; let adjustedNextProp = nextProp; if (reverse) { next = parent._tail; adjustedNextProp = prevProp; } while (next) { const currentNext = next[adjustedNextProp]; callback(next); next = currentNext; } }
@param {Object} parent @param {Function} callback @param {Boolean} [reverse] @param {String} [prevProp] @param {String} [nextProp] @return {void}
forEachChildren
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => { let next = parent._head; let adjustedNextProp = nextProp; if (reverse) { next = parent._tail; adjustedNextProp = prevProp; } while (next) { const currentNext = next[adjustedNextProp]; callback(next); next = currentNext; } }
@param {Object} parent @param {Function} callback @param {Boolean} [reverse] @param {String} [prevProp] @param {String} [nextProp] @return {void}
forEachChildren
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => { const prev = child[prevProp]; const next = child[nextProp]; prev ? prev[nextProp] = next : parent._head = next; next ? next[prevProp] = prev : parent._tail = prev; child[prevProp] = null; child[nextProp] = null; }
@param {Object} parent @param {Object} child @param {String} [prevProp] @param {String} [nextProp] @return {void}
removeChild
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => { const prev = child[prevProp]; const next = child[nextProp]; prev ? prev[nextProp] = next : parent._head = next; next ? next[prevProp] = prev : parent._tail = prev; child[prevProp] = null; child[nextProp] = null; }
@param {Object} parent @param {Object} child @param {String} [prevProp] @param {String} [nextProp] @return {void}
removeChild
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => { let prev = parent._tail; while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp]; const next = prev ? prev[nextProp] : parent._head; prev ? prev[nextProp] = child : parent._head = child; next ? next[prevProp] = child : parent._tail = child; child[prevProp] = prev; child[nextProp] = next; }
@param {Object} parent @param {Object} child @param {Function} [sortMethod] @param {String} prevProp @param {String} nextProp @return {void}
addChild
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.js
MIT
addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => { let prev = parent._tail; while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp]; const next = prev ? prev[nextProp] : parent._head; prev ? prev[nextProp] = child : parent._head = child; next ? next[prevProp] = child : parent._tail = child; child[prevProp] = prev; child[nextProp] = next; }
@param {Object} parent @param {Object} child @param {Function} [sortMethod] @param {String} prevProp @param {String} nextProp @return {void}
addChild
javascript
juliangarnier/anime
src/helpers.js
https://github.com/juliangarnier/anime/blob/master/src/helpers.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
src/properties.js
https://github.com/juliangarnier/anime/blob/master/src/properties.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
src/properties.js
https://github.com/juliangarnier/anime/blob/master/src/properties.js
MIT
render = (tickable, time, muteCallbacks, internalRender, tickMode) => { const parent = tickable.parent; const duration = tickable.duration; const completed = tickable.completed; const iterationDuration = tickable.iterationDuration; const iterationCount = tickable.iterationCount; const _currentIteration = tickable._currentIteration; const _loopDelay = tickable._loopDelay; const _reversed = tickable._reversed; const _alternate = tickable._alternate; const _hasChildren = tickable._hasChildren; const tickableDelay = tickable._delay; const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime const tickableEndTime = tickableDelay + iterationDuration; const tickableAbsoluteTime = time - tickableDelay; const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration); const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration); const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime; const isCurrentTimeAboveZero = tickableCurrentTime > 0; const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration; const isSetter = duration <= minValue; const forcedTick = tickMode === tickModes.FORCE; let isOdd = 0; let iterationElapsedTime = tickableAbsoluteTime; // Render checks // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer let hasRendered = 0; // Execute the "expensive" iterations calculations only when necessary if (iterationCount > 1) { // bitwise NOT operator seems to be generally faster than Math.floor() across browsers const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay))); tickable._currentIteration = clamp(currentIteration, 0, iterationCount); // Prevent the iteration count to go above the max iterations when reaching the end of the animation if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--; isOdd = tickable._currentIteration % 2; iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0; } // Checks if exactly one of _reversed and (_alternate && isOdd) is true const isReversed = _reversed ^ (_alternate && isOdd); const _ease = /** @type {Renderable} */(tickable)._ease; let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime; if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0; const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed; tickable._currentTime = tickableAbsoluteTime; tickable._iterationTime = iterationTime; tickable.backwards = isRunningBackwards; if (isCurrentTimeAboveZero && !tickable.began) { tickable.began = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onBegin(/** @type {CallbackArgument} */(tickable)); } } else if (tickableAbsoluteTime <= 0) { tickable.began = false; } // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) { tickable.onLoop(/** @type {CallbackArgument} */(tickable)); } if ( forcedTick || tickMode === tickModes.AUTO && ( time >= tickableDelay && time <= tickableEndTime || // Normal render time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state ) || iterationTime >= tickableEndTime && tickablePrevTime !== duration || iterationTime <= tickableDelay && tickablePrevTime > 0 || time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped ) { if (isCurrentTimeAboveZero) { // Trigger onUpdate callback before rendering tickable.computeDeltaTime(tickablePrevTime); if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable)); } // Start tweens rendering if (!_hasChildren) { // Time has jumped more than globals.tickThreshold so consider this tick manual const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold; const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime; // Only Animation can have tweens, Timer returns undefined let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head); let tweenTarget; let tweenStyle; let tweenTargetTransforms; let tweenTargetTransformsProperties; let tweenTransformsNeedUpdate = 0; while (tween) { const tweenComposition = tween._composition; const tweenCurrentTime = tween._currentTime; const tweenChangeDuration = tween._changeDuration; const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration; const tweenNextRep = tween._nextRep; const tweenPrevRep = tween._prevRep; const tweenHasComposition = tweenComposition !== compositionTypes.none; if ((forcedRender || ( (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) && (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime) )) && (!tweenHasComposition || ( !tween._isOverridden && (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) && (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) && (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay))) )) ) { const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration); const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration); const tweenModifier = tween._modifier; const tweenValueType = tween._valueType; const tweenType = tween._tweenType; const tweenIsObject = tweenType === tweenTypes.OBJECT; const tweenIsNumber = tweenValueType === valueTypes.NUMBER; // Only round the in-between frames values if the final value is a string const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision; // Recompose tween value /** @type {String|Number} */ let value; /** @type {Number} */ let number; if (tweenIsNumber) { value = number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision ))); } else if (tweenValueType === valueTypes.UNIT) { // Rounding the values speed up string composition number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision))); value = `${number}${tween._unit}`; } else if (tweenValueType === valueTypes.COLOR) { const fn = tween._fromNumbers; const tn = tween._toNumbers; const r = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[0], tn[0], tweenProgress))), 0, 255), 0); const g = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[1], tn[1], tweenProgress))), 0, 255), 0); const b = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[2], tn[2], tweenProgress))), 0, 255), 0); const a = clamp(/** @type {Number} */(tweenModifier(round(interpolate(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1); value = `rgba(${r},${g},${b},${a})`; if (tweenHasComposition) { const ns = tween._numbers; ns[0] = r; ns[1] = g; ns[2] = b; ns[3] = a; } } else if (tweenValueType === valueTypes.COMPLEX) { value = tween._strings[0]; for (let j = 0, l = tween._toNumbers.length; j < l; j++) { const n = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision))); const s = tween._strings[j + 1]; value += `${s ? n + s : n}`; if (tweenHasComposition) { tween._numbers[j] = n; } } } // For additive tweens and Animatables if (tweenHasComposition) { tween._number = number; } if (!internalRender && tweenComposition !== compositionTypes.blend) { const tweenProperty = tween.property; tweenTarget = tween.target; if (tweenIsObject) { tweenTarget[tweenProperty] = value; } else if (tweenType === tweenTypes.ATTRIBUTE) { /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value)); } else { tweenStyle = /** @type {DOMTarget} */(tweenTarget).style; if (tweenType === tweenTypes.TRANSFORM) { if (tweenTarget !== tweenTargetTransforms) { tweenTargetTransforms = tweenTarget; // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage. tweenTargetTransformsProperties = tweenTarget[transformsSymbol]; } tweenTargetTransformsProperties[tweenProperty] = value; tweenTransformsNeedUpdate = 1; } else if (tweenType === tweenTypes.CSS) { tweenStyle[tweenProperty] = value; } else if (tweenType === tweenTypes.CSS_VAR) { tweenStyle.setProperty(tweenProperty,/** @type {String} */(value)); } } if (isCurrentTimeAboveZero) hasRendered = 1; } else { // Used for composing timeline tweens without having to do a real render tween._value = value; } } // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax // to reduce memory usage on string composition if (tweenTransformsNeedUpdate && tween._renderTransforms) { let str = emptyString; for (let key in tweenTargetTransformsProperties) { str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `; } tweenStyle.transform = str; tweenTransformsNeedUpdate = 0; } tween = tween._next; } if (!muteCallbacks && hasRendered) { /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable)); } } if (!muteCallbacks && isCurrentTimeAboveZero) { tickable.onUpdate(/** @type {CallbackArgument} */(tickable)); } } // End tweens rendering // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards if (parent && isSetter) { if (!muteCallbacks && ( (parent.began && !isRunningBackwards && tickableAbsoluteTime >= duration && !completed) || (isRunningBackwards && tickableAbsoluteTime <= minValue && completed) )) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable.completed = !isRunningBackwards; } // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) { if (iterationCount === Infinity) { // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer tickable._startTime += tickable.duration; } else if (tickable._currentIteration >= iterationCount - 1) { // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick tickable.paused = true; if (!completed && !_hasChildren) { // If the tickable has children, triggers onComplete() only when all children have completed in the tick function tickable.completed = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable._resolve(/** @type {CallbackArgument} */(tickable)); } } } // Otherwise set the completed flag to false } else { tickable.completed = false; } // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ? return hasRendered; }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {tickModes} tickMode @return {Number}
render
javascript
juliangarnier/anime
src/render.js
https://github.com/juliangarnier/anime/blob/master/src/render.js
MIT
render = (tickable, time, muteCallbacks, internalRender, tickMode) => { const parent = tickable.parent; const duration = tickable.duration; const completed = tickable.completed; const iterationDuration = tickable.iterationDuration; const iterationCount = tickable.iterationCount; const _currentIteration = tickable._currentIteration; const _loopDelay = tickable._loopDelay; const _reversed = tickable._reversed; const _alternate = tickable._alternate; const _hasChildren = tickable._hasChildren; const tickableDelay = tickable._delay; const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime const tickableEndTime = tickableDelay + iterationDuration; const tickableAbsoluteTime = time - tickableDelay; const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration); const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration); const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime; const isCurrentTimeAboveZero = tickableCurrentTime > 0; const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration; const isSetter = duration <= minValue; const forcedTick = tickMode === tickModes.FORCE; let isOdd = 0; let iterationElapsedTime = tickableAbsoluteTime; // Render checks // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer let hasRendered = 0; // Execute the "expensive" iterations calculations only when necessary if (iterationCount > 1) { // bitwise NOT operator seems to be generally faster than Math.floor() across browsers const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay))); tickable._currentIteration = clamp(currentIteration, 0, iterationCount); // Prevent the iteration count to go above the max iterations when reaching the end of the animation if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--; isOdd = tickable._currentIteration % 2; iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0; } // Checks if exactly one of _reversed and (_alternate && isOdd) is true const isReversed = _reversed ^ (_alternate && isOdd); const _ease = /** @type {Renderable} */(tickable)._ease; let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime; if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0; const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed; tickable._currentTime = tickableAbsoluteTime; tickable._iterationTime = iterationTime; tickable.backwards = isRunningBackwards; if (isCurrentTimeAboveZero && !tickable.began) { tickable.began = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onBegin(/** @type {CallbackArgument} */(tickable)); } } else if (tickableAbsoluteTime <= 0) { tickable.began = false; } // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) { tickable.onLoop(/** @type {CallbackArgument} */(tickable)); } if ( forcedTick || tickMode === tickModes.AUTO && ( time >= tickableDelay && time <= tickableEndTime || // Normal render time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state ) || iterationTime >= tickableEndTime && tickablePrevTime !== duration || iterationTime <= tickableDelay && tickablePrevTime > 0 || time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped ) { if (isCurrentTimeAboveZero) { // Trigger onUpdate callback before rendering tickable.computeDeltaTime(tickablePrevTime); if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable)); } // Start tweens rendering if (!_hasChildren) { // Time has jumped more than globals.tickThreshold so consider this tick manual const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold; const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime; // Only Animation can have tweens, Timer returns undefined let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head); let tweenTarget; let tweenStyle; let tweenTargetTransforms; let tweenTargetTransformsProperties; let tweenTransformsNeedUpdate = 0; while (tween) { const tweenComposition = tween._composition; const tweenCurrentTime = tween._currentTime; const tweenChangeDuration = tween._changeDuration; const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration; const tweenNextRep = tween._nextRep; const tweenPrevRep = tween._prevRep; const tweenHasComposition = tweenComposition !== compositionTypes.none; if ((forcedRender || ( (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) && (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime) )) && (!tweenHasComposition || ( !tween._isOverridden && (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) && (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) && (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay))) )) ) { const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration); const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration); const tweenModifier = tween._modifier; const tweenValueType = tween._valueType; const tweenType = tween._tweenType; const tweenIsObject = tweenType === tweenTypes.OBJECT; const tweenIsNumber = tweenValueType === valueTypes.NUMBER; // Only round the in-between frames values if the final value is a string const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision; // Recompose tween value /** @type {String|Number} */ let value; /** @type {Number} */ let number; if (tweenIsNumber) { value = number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision ))); } else if (tweenValueType === valueTypes.UNIT) { // Rounding the values speed up string composition number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision))); value = `${number}${tween._unit}`; } else if (tweenValueType === valueTypes.COLOR) { const fn = tween._fromNumbers; const tn = tween._toNumbers; const r = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[0], tn[0], tweenProgress))), 0, 255), 0); const g = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[1], tn[1], tweenProgress))), 0, 255), 0); const b = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[2], tn[2], tweenProgress))), 0, 255), 0); const a = clamp(/** @type {Number} */(tweenModifier(round(interpolate(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1); value = `rgba(${r},${g},${b},${a})`; if (tweenHasComposition) { const ns = tween._numbers; ns[0] = r; ns[1] = g; ns[2] = b; ns[3] = a; } } else if (tweenValueType === valueTypes.COMPLEX) { value = tween._strings[0]; for (let j = 0, l = tween._toNumbers.length; j < l; j++) { const n = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision))); const s = tween._strings[j + 1]; value += `${s ? n + s : n}`; if (tweenHasComposition) { tween._numbers[j] = n; } } } // For additive tweens and Animatables if (tweenHasComposition) { tween._number = number; } if (!internalRender && tweenComposition !== compositionTypes.blend) { const tweenProperty = tween.property; tweenTarget = tween.target; if (tweenIsObject) { tweenTarget[tweenProperty] = value; } else if (tweenType === tweenTypes.ATTRIBUTE) { /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value)); } else { tweenStyle = /** @type {DOMTarget} */(tweenTarget).style; if (tweenType === tweenTypes.TRANSFORM) { if (tweenTarget !== tweenTargetTransforms) { tweenTargetTransforms = tweenTarget; // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage. tweenTargetTransformsProperties = tweenTarget[transformsSymbol]; } tweenTargetTransformsProperties[tweenProperty] = value; tweenTransformsNeedUpdate = 1; } else if (tweenType === tweenTypes.CSS) { tweenStyle[tweenProperty] = value; } else if (tweenType === tweenTypes.CSS_VAR) { tweenStyle.setProperty(tweenProperty,/** @type {String} */(value)); } } if (isCurrentTimeAboveZero) hasRendered = 1; } else { // Used for composing timeline tweens without having to do a real render tween._value = value; } } // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax // to reduce memory usage on string composition if (tweenTransformsNeedUpdate && tween._renderTransforms) { let str = emptyString; for (let key in tweenTargetTransformsProperties) { str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `; } tweenStyle.transform = str; tweenTransformsNeedUpdate = 0; } tween = tween._next; } if (!muteCallbacks && hasRendered) { /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable)); } } if (!muteCallbacks && isCurrentTimeAboveZero) { tickable.onUpdate(/** @type {CallbackArgument} */(tickable)); } } // End tweens rendering // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards if (parent && isSetter) { if (!muteCallbacks && ( (parent.began && !isRunningBackwards && tickableAbsoluteTime >= duration && !completed) || (isRunningBackwards && tickableAbsoluteTime <= minValue && completed) )) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable.completed = !isRunningBackwards; } // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) { if (iterationCount === Infinity) { // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer tickable._startTime += tickable.duration; } else if (tickable._currentIteration >= iterationCount - 1) { // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick tickable.paused = true; if (!completed && !_hasChildren) { // If the tickable has children, triggers onComplete() only when all children have completed in the tick function tickable.completed = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable._resolve(/** @type {CallbackArgument} */(tickable)); } } } // Otherwise set the completed flag to false } else { tickable.completed = false; } // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ? return hasRendered; }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {tickModes} tickMode @return {Number}
render
javascript
juliangarnier/anime
src/render.js
https://github.com/juliangarnier/anime/blob/master/src/render.js
MIT
tick = (tickable, time, muteCallbacks, internalRender, tickMode) => { const _currentIteration = tickable._currentIteration; render(tickable, time, muteCallbacks, internalRender, tickMode); if (tickable._hasChildren) { const tl = /** @type {Timeline} */(tickable); const tlIsRunningBackwards = tl.backwards; const tlChildrenTime = internalRender ? time : tl._iterationTime; const tlCildrenTickTime = now(); let tlChildrenHasRendered = 0; let tlChildrenHaveCompleted = true; // If the timeline has looped forward, we need to manually triggers children skipped callbacks if (!internalRender && tl._currentIteration !== _currentIteration) { const tlIterationDuration = tl.iterationDuration; forEachChildren(tl, (/** @type {JSAnimation} */child) => { if (!tlIsRunningBackwards) { // Force an internal render to trigger the callbacks if the child has not completed on loop if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) { render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE); } // Reset their began and completed flags to allow retrigering callbacks on the next iteration child.began = false; child.completed = false; } else { const childDuration = child.duration; const childStartTime = child._offset + child._delay; const childEndTime = childStartTime + childDuration; // Triggers the onComplete callback on reverse for children on the edges of the timeline if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) { child.onComplete(child); } } }); if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl)); } forEachChildren(tl, (/** @type {JSAnimation} */child) => { const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode; tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode); if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false; }, tlIsRunningBackwards); // Renders on timeline are triggered by its children so it needs to be set after rendering the children if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl)); // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end if (tlChildrenHaveCompleted && tl._currentTime >= tl.duration) { // Make sure the paused flag is false in case it has been skipped in the render function tl.paused = true; if (!tl.completed) { tl.completed = true; if (!muteCallbacks) { tl.onComplete(/** @type {CallbackArgument} */(tl)); tl._resolve(/** @type {CallbackArgument} */(tl)); } } } } }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {Number} tickMode @return {void}
tick
javascript
juliangarnier/anime
src/render.js
https://github.com/juliangarnier/anime/blob/master/src/render.js
MIT
tick = (tickable, time, muteCallbacks, internalRender, tickMode) => { const _currentIteration = tickable._currentIteration; render(tickable, time, muteCallbacks, internalRender, tickMode); if (tickable._hasChildren) { const tl = /** @type {Timeline} */(tickable); const tlIsRunningBackwards = tl.backwards; const tlChildrenTime = internalRender ? time : tl._iterationTime; const tlCildrenTickTime = now(); let tlChildrenHasRendered = 0; let tlChildrenHaveCompleted = true; // If the timeline has looped forward, we need to manually triggers children skipped callbacks if (!internalRender && tl._currentIteration !== _currentIteration) { const tlIterationDuration = tl.iterationDuration; forEachChildren(tl, (/** @type {JSAnimation} */child) => { if (!tlIsRunningBackwards) { // Force an internal render to trigger the callbacks if the child has not completed on loop if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) { render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE); } // Reset their began and completed flags to allow retrigering callbacks on the next iteration child.began = false; child.completed = false; } else { const childDuration = child.duration; const childStartTime = child._offset + child._delay; const childEndTime = childStartTime + childDuration; // Triggers the onComplete callback on reverse for children on the edges of the timeline if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) { child.onComplete(child); } } }); if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl)); } forEachChildren(tl, (/** @type {JSAnimation} */child) => { const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode; tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode); if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false; }, tlIsRunningBackwards); // Renders on timeline are triggered by its children so it needs to be set after rendering the children if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl)); // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end if (tlChildrenHaveCompleted && tl._currentTime >= tl.duration) { // Make sure the paused flag is false in case it has been skipped in the render function tl.paused = true; if (!tl.completed) { tl.completed = true; if (!muteCallbacks) { tl.onComplete(/** @type {CallbackArgument} */(tl)); tl._resolve(/** @type {CallbackArgument} */(tl)); } } } } }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {Number} tickMode @return {void}
tick
javascript
juliangarnier/anime
src/render.js
https://github.com/juliangarnier/anime/blob/master/src/render.js
MIT
execute(cb) { let activeScope = globals.scope; let activeRoot = globals.root; let activeDefaults = globals.defaults; globals.scope = this; globals.root = this.root; globals.defaults = this.defaults; const mqs = this.mediaQueryLists; for (let mq in mqs) this.matches[mq] = mqs[mq].matches; const returned = cb(this); globals.scope = activeScope; globals.root = activeRoot; globals.defaults = activeDefaults; return returned; }
@callback ScoppedCallback @param {this} scope @return {any} @param {ScoppedCallback} cb @return {this}
execute
javascript
juliangarnier/anime
src/scope.js
https://github.com/juliangarnier/anime/blob/master/src/scope.js
MIT
add(a1, a2) { if (isFnc(a1)) { const constructor = /** @type {contructorCallback} */(a1); this.constructors.push(constructor); this.execute(() => { const revertConstructor = constructor(this); if (revertConstructor) { this.revertConstructors.push(revertConstructor); } }); } else { this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args)); } return this; }
@callback contructorCallback @param {this} self @overload @param {String} a1 @param {ScopeMethod} a2 @return {this} @overload @param {contructorCallback} a1 @return {this} @param {String|contructorCallback} a1 @param {ScopeMethod} [a2]
add
javascript
juliangarnier/anime
src/scope.js
https://github.com/juliangarnier/anime/blob/master/src/scope.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
src/scroll.js
https://github.com/juliangarnier/anime/blob/master/src/scroll.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
src/scroll.js
https://github.com/juliangarnier/anime/blob/master/src/scroll.js
MIT
parseBoundValue = ($el, v, size, under, over) => { /** @type {Number} */ let value; if (isStr(v)) { const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v)); if (matchedOperator) { const splitter = matchedOperator[0]; const operator = splitter[0]; const splitted = /** @type {String} */(v).split(splitter); const clampMin = splitted[0] === 'min'; const clampMax = splitted[0] === 'max'; const valueAPx = convertValueToPx($el, splitted[0], size, under, over); const valueBPx = convertValueToPx($el, splitted[1], size, under, over); if (clampMin) { const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator); value = min < valueAPx ? valueAPx : min; } else if (clampMax) { const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator); value = max > valueAPx ? valueAPx : max; } else { value = getRelativeValue(valueAPx, valueBPx, operator); } } else { value = convertValueToPx($el, v, size, under, over); } } else { value = /** @type {Number} */(v); } return round(value, 0); }
@param {HTMLElement} $el @param {ScrollThresholdValue} v @param {Number} size @param {Number} [under] @param {Number} [over] @return {Number}
parseBoundValue
javascript
juliangarnier/anime
src/scroll.js
https://github.com/juliangarnier/anime/blob/master/src/scroll.js
MIT
parseBoundValue = ($el, v, size, under, over) => { /** @type {Number} */ let value; if (isStr(v)) { const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v)); if (matchedOperator) { const splitter = matchedOperator[0]; const operator = splitter[0]; const splitted = /** @type {String} */(v).split(splitter); const clampMin = splitted[0] === 'min'; const clampMax = splitted[0] === 'max'; const valueAPx = convertValueToPx($el, splitted[0], size, under, over); const valueBPx = convertValueToPx($el, splitted[1], size, under, over); if (clampMin) { const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator); value = min < valueAPx ? valueAPx : min; } else if (clampMax) { const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator); value = max > valueAPx ? valueAPx : max; } else { value = getRelativeValue(valueAPx, valueBPx, operator); } } else { value = convertValueToPx($el, v, size, under, over); } } else { value = /** @type {Number} */(v); } return round(value, 0); }
@param {HTMLElement} $el @param {ScrollThresholdValue} v @param {Number} size @param {Number} [under] @param {Number} [over] @return {Number}
parseBoundValue
javascript
juliangarnier/anime
src/scroll.js
https://github.com/juliangarnier/anime/blob/master/src/scroll.js
MIT
updateBounds() { if (this._debug) { this.removeDebug(); } let stickys; const $target = this.target; const container = this.container; const isHori = this.horizontal; const linked = this.linked; let linkedTime; let $el = $target; let offsetX = 0; let offsetY = 0; /** @type {Element} */ let $offsetParent = $el; if (linked) { linkedTime = linked.currentTime; linked.seek(0, true); } const isContainerStatic = getTargetValue(container.element, 'position') === 'static' ? setTargetValues(container.element, { position: 'relative '}) : false; while ($el && $el !== container.element && $el !== doc.body) { const isSticky = getTargetValue($el, 'position') === 'sticky' ? setTargetValues($el, { position: 'static' }) : false; if ($el === $offsetParent) { offsetX += $el.offsetLeft || 0; offsetY += $el.offsetTop || 0; $offsetParent = $el.offsetParent; } $el = /** @type {HTMLElement} */($el.parentElement); if (isSticky) { if (!stickys) stickys = []; stickys.push(isSticky); } } if (isContainerStatic) isContainerStatic.revert(); const offset = isHori ? offsetX : offsetY; const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight; const containerSize = isHori ? container.width : container.height; const scrollSize = isHori ? container.scrollWidth : container.scrollHeight; const maxScroll = scrollSize - containerSize; const enter = this.enter; const leave = this.leave; /** @type {ScrollThresholdValue} */ let enterTarget = 'start'; /** @type {ScrollThresholdValue} */ let leaveTarget = 'end'; /** @type {ScrollThresholdValue} */ let enterContainer = 'end'; /** @type {ScrollThresholdValue} */ let leaveContainer = 'start'; if (isStr(enter)) { const splitted = /** @type {String} */(enter).split(' '); enterContainer = splitted[0]; enterTarget = splitted.length > 1 ? splitted[1] : enterTarget; } else if (isObj(enter)) { const e = /** @type {ScrollThresholdParam} */(enter); if (!isUnd(e.container)) enterContainer = e.container; if (!isUnd(e.target)) enterTarget = e.target; } else if (isNum(enter)) { enterContainer = /** @type {Number} */(enter); } if (isStr(leave)) { const splitted = /** @type {String} */(leave).split(' '); leaveContainer = splitted[0]; leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget; } else if (isObj(leave)) { const t = /** @type {ScrollThresholdParam} */(leave); if (!isUnd(t.container)) leaveContainer = t.container; if (!isUnd(t.target)) leaveTarget = t.target; } else if (isNum(leave)) { leaveContainer = /** @type {Number} */(leave); } const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize); const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize); const under = (parsedEnterTarget + offset) - containerSize; const over = (parsedLeaveTarget + offset) - maxScroll; const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over); const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over); const offsetStart = parsedEnterTarget + offset - parsedEnterContainer; const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer; const scrollDelta = offsetEnd - offsetStart; this.offsets[0] = offsetX; this.offsets[1] = offsetY; this.offset = offset; this.offsetStart = offsetStart; this.offsetEnd = offsetEnd; this.distance = scrollDelta <= 0 ? 0 : scrollDelta; this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer]; this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer]; if (stickys) { stickys.forEach(sticky => sticky.revert()); } if (linked) { linked.seek(linkedTime, true); } if (this._debug) { this.debug(); } }
@param {String} p @param {Number} l @param {Number} t @param {Number} w @param {Number} h @return {String}
updateBounds
javascript
juliangarnier/anime
src/scroll.js
https://github.com/juliangarnier/anime/blob/master/src/scroll.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
src/stagger.js
https://github.com/juliangarnier/anime/blob/master/src/stagger.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
src/stagger.js
https://github.com/juliangarnier/anime/blob/master/src/stagger.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
src/svg.js
https://github.com/juliangarnier/anime/blob/master/src/svg.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
src/svg.js
https://github.com/juliangarnier/anime/blob/master/src/svg.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
src/svg.js
https://github.com/juliangarnier/anime/blob/master/src/svg.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
src/svg.js
https://github.com/juliangarnier/anime/blob/master/src/svg.js
MIT
createDrawableProxy = ($el, start, end) => { const pathLength = K; const computedStyles = getComputedStyle($el); const strokeLineCap = computedStyles.strokeLinecap; // @ts-ignore const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null; let currentCap = strokeLineCap; const proxy = new Proxy($el, { get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { return (...args) => { if (args[0] === 'draw') { const value = args[1]; const values = value.split(' '); const v1 = +values[0]; const v2 = +values[1]; // TOTO: Benchmark if performing two slices is more performant than one split // const spaceIndex = value.indexOf(' '); // const v1 = round(+value.slice(0, spaceIndex), precision); // const v2 = round(+value.slice(spaceIndex + 1), precision); const scaleFactor = getScaleFactor($scalled); const os = v1 * -pathLength * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } } }); if ($el.getAttribute('pathLength') !== `${pathLength}`) { $el.setAttribute('pathLength', `${pathLength}`); proxy.setAttribute('draw', `${start} ${end}`); } return /** @type {DrawableSVGGeometry} */(proxy); }
Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality. @param {SVGGeometryElement} $el - The SVG element to transform into a drawable @param {number} start - Starting position (0-1) @param {number} end - Ending position (0-1) @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
createDrawableProxy
javascript
juliangarnier/anime
src/svg.js
https://github.com/juliangarnier/anime/blob/master/src/svg.js
MIT
createDrawableProxy = ($el, start, end) => { const pathLength = K; const computedStyles = getComputedStyle($el); const strokeLineCap = computedStyles.strokeLinecap; // @ts-ignore const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null; let currentCap = strokeLineCap; const proxy = new Proxy($el, { get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { return (...args) => { if (args[0] === 'draw') { const value = args[1]; const values = value.split(' '); const v1 = +values[0]; const v2 = +values[1]; // TOTO: Benchmark if performing two slices is more performant than one split // const spaceIndex = value.indexOf(' '); // const v1 = round(+value.slice(0, spaceIndex), precision); // const v2 = round(+value.slice(spaceIndex + 1), precision); const scaleFactor = getScaleFactor($scalled); const os = v1 * -pathLength * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } } }); if ($el.getAttribute('pathLength') !== `${pathLength}`) { $el.setAttribute('pathLength', `${pathLength}`); proxy.setAttribute('draw', `${start} ${end}`); } return /** @type {DrawableSVGGeometry} */(proxy); }
Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality. @param {SVGGeometryElement} $el - The SVG element to transform into a drawable @param {number} start - Starting position (0-1) @param {number} end - Ending position (0-1) @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
createDrawableProxy
javascript
juliangarnier/anime
src/svg.js
https://github.com/juliangarnier/anime/blob/master/src/svg.js
MIT