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
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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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(' '); enterTarget = splitted[0]; enterContainer = splitted.length > 1 ? splitted[1] : splitted[0]; } else if (isObj(enter)) { const e = /** @type {ScrollThresholdParam} */(enter); if (!isUnd((e).target)) enterTarget = e.target; if (!isUnd(e.container)) enterContainer = e.container; } else if (isNum(enter)) { enterContainer = /** @type {Number} */(enter); } if (isStr(leave)) { const splitted = /** @type {String} */(leave).split(' '); leaveTarget = splitted[0]; leaveContainer = splitted.length > 1 ? splitted[1] : splitted[0]; } else if (isObj(leave)) { const t = /** @type {ScrollThresholdParam} */(leave); if (!isUnd(t.target)) leaveTarget = t.target; if (!isUnd(t.container)) leaveContainer = t.container; } 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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
constructor(targets, parameters) { 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 Animation(targets, animParams, null, 0, false).init(); // console.log(animation, animParams[propName].composition); if (!this.targets.length) this.targets.push(...animation.targets); /** @type {AnimatableProperty} */ this[propName] = (to, duration, ease) => { const tween = animation._head; if (isUnd(to)) { 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).play(); return this; } }; } }
@param {TargetsParam} targets @param {AnimatableParams} parameters
constructor
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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 : 'x'); const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'y'); 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|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; this.releaseSpring = hasSpring ? /** @type {Spring} */(ease) : createSpring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); this.releaseEase = hasSpring ? this.releaseSpring.ease : customEase || eases.outQuint; this.hasReleaseSpring = hasSpring; this.onGrab = parameters.onGrab || noop; this.onDrag = parameters.onDrag || noop; this.onRelease = parameters.onRelease || noop; this.onUpdate = parameters.onUpdate || noop; this.onSettle = parameters.onSettle || noop; this.onSnap = parameters.onSnap || noop; this.onResize = parameters.onResize || noop; this.onAfterResize = parameters.onAfterResize || noop; this.disabled = [0, 0]; /** @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; /** @type {[Number, Number]} */ this.progresses = [0, 0]; // x, y 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]} */ this.pointer = [0, 0, 0, 0]; // x, y, temp x, temp y /** @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 this.pointerVelocity = 0; this.pointerAngle = 0; this.velocity = 0; this.angle = 0; /** @type {Animation} */ this.cursorStyles = null; /** @type {Animation} */ this.triggerStyles = null; /** @type {Animation} */ this.bodyStyles = null; /** @type {Animation} */ this.targetStyles = null; this.transforms = new Transforms(this.$target); this.overshootCoords = { x: 0, y: 0 }; this.overshootTicker = new Timer({ autoplay: false }, null, 0).init(); this.updateTicker = new Timer({ autoplay: false }, null, 0).init(); this.overshootTicker.onUpdate = () => { this.updated = true; this.manual = true; if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0); if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0); }; this.overshootTicker.onComplete = () => { this.manual = false; if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0); if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0); }; this.updateTicker.onUpdate = self => this.update(self); 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[0] ? yProp : xProp; 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]; const dt = engine.deltaTime / globals.timeScale; this.deltaX = dx; this.deltaY = dy; this.coords[2] = x; this.coords[3] = y; this.progresses[0] = round(mapRange(x, this.containerBounds[3], this.containerBounds[1], 0, 1), globals.precision); this.progresses[1] = round(mapRange(y, this.containerBounds[0], this.containerBounds[2], 0, 1), globals.precision); this.velocity = round(clamp((dt > 0 ? Math.sqrt(dx * dx + dy * dy) / dt : 0) * this.velocityMultiplier, this.minVelocity, this.maxVelocity), 5); this.angle = Math.atan2(dy, dx); if (hasUpdated) { this.onUpdate(this); } if (hasMoved) { this.onDrag(this); } if (!hasReleased) { this.updated = false; } }; 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.onUpdate(this); 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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
setX(x, muteUpdateCallback = false) { if (this.disabled[0]) return; const v = round(x, 5); 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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
setY(y, muteUpdateCallback = false) { if (this.disabled[1]) return; const v = round(y, 5); 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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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(0, setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 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), 20); 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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
scrollInView(duration, gap = 0, ease = eases.inOutQuad) { // this.stop(); 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 Animation(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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/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
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
add(a1, a2) { 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 {Function} a2 @return {this} @overload @param {contructorCallback} a1 @return {this} @param {String|contructorCallback} a1 @param {Function} [a2]
add
javascript
juliangarnier/anime
tests/playground/assets/js/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/tests/playground/assets/js/anime.esm.js
MIT
parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */ (str)) : /** @type {Number} */ (str)
@param {Number|String} str @return {Number}
parseNumber
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */ (str)) : /** @type {Number} */ (str)
@param {Number|String} str @return {Number}
parseNumber
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } } return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue : stringStartsWith(propName, 'scale') ? '1' : stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px'; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
parseInlineTransforms
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } } return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue : stringStartsWith(propName, 'scale') ? '1' : stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px'; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
parseInlineTransforms
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
function getNodeList(v) { const n = isStr(v) ? globals.root.querySelectorAll(v) : v; if (n instanceof NodeList || n instanceof HTMLCollection) return n; }
@param {DOMTargetsParam|TargetsParam} v @return {NodeList|HTMLCollection}
getNodeList
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
function parseTargets(targets) { if (isNil(targets)) return /** @type {TargetsArray} */ ([]); if (isArr(targets)) { const flattened = targets.flat(Infinity); /** @type {TargetsArray} */ const parsed = []; for (let i = 0, l = flattened.length; i < l; i++) { const item = flattened[i]; if (!isNil(item)) { const nodeList = getNodeList(item); if (nodeList) { for (let j = 0, jl = nodeList.length; j < jl; j++) { const subItem = nodeList[j]; if (!isNil(subItem)) { let isDuplicate = false; for (let k = 0, kl = parsed.length; k < kl; k++) { if (parsed[k] === subItem) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(subItem); } } } } else { let isDuplicate = false; for (let j = 0, jl = parsed.length; j < jl; j++) { if (parsed[j] === item) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(item); } } } } return parsed; } if (!isBrowser) return /** @type {JSTargetsArray} */ ([targets]); const nodeList = getNodeList(targets); if (nodeList) return /** @type {DOMTargetsArray} */ (Array.from(nodeList)); return /** @type {TargetsArray} */ ([targets]); }
@overload @param {DOMTargetsParam} targets @return {DOMTargetsArray} @overload @param {JSTargetsParam} targets @return {JSTargetsArray} @overload @param {TargetsParam} targets @return {TargetsArray} @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
parseTargets
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
function registerTargets(targets) { const parsedTargetsArray = parseTargets(targets); const parsedTargetsLength = parsedTargetsArray.length; if (parsedTargetsLength) { for (let i = 0; i < parsedTargetsLength; i++) { const target = parsedTargetsArray[i]; if (!target[isRegisteredTargetSymbol]) { target[isRegisteredTargetSymbol] = true; const isSvgType = isSvg(target); const isDom = /** @type {DOMTarget} */ (target).nodeType || isSvgType; if (isDom) { target[isDomSymbol] = true; target[isSvgSymbol] = isSvgType; target[transformsSymbol] = {}; } } } } return parsedTargetsArray; }
@overload @param {DOMTargetsParam} targets @return {DOMTargetsArray} @overload @param {JSTargetsParam} targets @return {JSTargetsArray} @overload @param {TargetsParam} targets @return {TargetsArray} @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
registerTargets
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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 * -1e3 * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } } }); if ($el.getAttribute('pathLength') !== `${pathLength}`) { $el.setAttribute('pathLength', `${pathLength}`); proxy.setAttribute('draw', `${start} ${end}`); } return /** @type {DrawableSVGGeometry} */ (proxy); }
Creates 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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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 * -1e3 * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } } }); if ($el.getAttribute('pathLength') !== `${pathLength}`) { $el.setAttribute('pathLength', `${pathLength}`); proxy.setAttribute('draw', `${start} ${end}`); } return /** @type {DrawableSVGGeometry} */ (proxy); }
Creates 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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { return (...args) => { if (args[0] === 'draw') { const value = args[1]; const values = value.split(' '); const v1 = +values[0]; const v2 = +values[1]; // TOTO: Benchmark if performing two slices is more performant than one split // const spaceIndex = value.indexOf(' '); // const v1 = round(+value.slice(0, spaceIndex), precision); // const v2 = round(+value.slice(spaceIndex + 1), precision); const scaleFactor = getScaleFactor($scalled); const os = v1 * -1e3 * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } }
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
get
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
createDrawable = (selector, start = 0, end = 0) => { const els = parseTargets(selector); return els.map($el => createDrawableProxy( /** @type {SVGGeometryElement} */ ($el), start, end)); }
Creates drawable proxies for multiple SVG elements. @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors @param {number} [start=0] - Starting position (0-1) @param {number} [end=0] - Ending position (0-1) @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
createDrawable
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
createDrawable = (selector, start = 0, end = 0) => { const els = parseTargets(selector); return els.map($el => createDrawableProxy( /** @type {SVGGeometryElement} */ ($el), start, end)); }
Creates drawable proxies for multiple SVG elements. @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors @param {number} [start=0] - Starting position (0-1) @param {number} [end=0] - Ending position (0-1) @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
createDrawable
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getPathPoint = ($path, progress, lookup = 0) => { return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0); }
@param {SVGGeometryElement} $path @param {Number} progress @param {Number}lookup @return {DOMPoint}
getPathPoint
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getPathPoint = ($path, progress, lookup = 0) => { return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0); }
@param {SVGGeometryElement} $path @param {Number} progress @param {Number}lookup @return {DOMPoint}
getPathPoint
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getPathProgess = ($path, pathProperty) => { return $el => { const totalLength = +($path.getTotalLength()); const inSvg = $el[isSvgSymbol]; const ctm = $path.getCTM(); /** @type {TweenObjectValue} */ return { from: 0, to: totalLength, /** @type {TweenModifier} */ modifier: progress => { if (pathProperty === 'a') { const p0 = getPathPoint($path, progress, -1); const p1 = getPathPoint($path, progress, 1); return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI; } else { const p = getPathPoint($path, progress, 0); return pathProperty === 'x' ? inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e : inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f; } } }; }; }
@param {SVGGeometryElement} $path @param {String} pathProperty @return {FunctionValue}
getPathProgess
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getPathProgess = ($path, pathProperty) => { return $el => { const totalLength = +($path.getTotalLength()); const inSvg = $el[isSvgSymbol]; const ctm = $path.getCTM(); /** @type {TweenObjectValue} */ return { from: 0, to: totalLength, /** @type {TweenModifier} */ modifier: progress => { if (pathProperty === 'a') { const p0 = getPathPoint($path, progress, -1); const p1 = getPathPoint($path, progress, 1); return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI; } else { const p = getPathPoint($path, progress, 0); return pathProperty === 'x' ? inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e : inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f; } } }; }; }
@param {SVGGeometryElement} $path @param {String} pathProperty @return {FunctionValue}
getPathProgess
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
isValidSVGAttribute = (el, propertyName) => { // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform if (cssReservedProperties.includes(propertyName)) return false; if (el.getAttribute(propertyName) || propertyName in el) { if (propertyName === 'scale') { // Scale const elParentNode = /** @type {SVGGeometryElement} */ ( /** @type {DOMTarget} */(el).parentNode); // Only consider scale as a valid SVG attribute on filter element return elParentNode && elParentNode.tagName === 'filter'; } return true; } }
@param {Target} el @param {String} propertyName @return {Boolean}
isValidSVGAttribute
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
isValidSVGAttribute = (el, propertyName) => { // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform if (cssReservedProperties.includes(propertyName)) return false; if (el.getAttribute(propertyName) || propertyName in el) { if (propertyName === 'scale') { // Scale const elParentNode = /** @type {SVGGeometryElement} */ ( /** @type {DOMTarget} */(el).parentNode); // Only consider scale as a valid SVG attribute on filter element return elParentNode && elParentNode.tagName === 'filter'; } return true; } }
@param {Target} el @param {String} propertyName @return {Boolean}
isValidSVGAttribute
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
setValue = (targetValue, defaultValue) => { return isUnd(targetValue) ? defaultValue : targetValue; }
@template T, D @param {T|undefined} targetValue @param {D} defaultValue @return {T|D}
setValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
setValue = (targetValue, defaultValue) => { return isUnd(targetValue) ? defaultValue : targetValue; }
@template T, D @param {T|undefined} targetValue @param {D} defaultValue @return {T|D}
setValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getFunctionValue = (value, target, index, total, store) => { if (isFnc(value)) { const func = () => { const computed = /** @type {Function} */ (value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }; if (store) { store.func = func; } return func(); } else { return value; } }
@param {TweenPropValue} value @param {Target} target @param {Number} index @param {Number} total @param {Object} [store] @return {any}
getFunctionValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getFunctionValue = (value, target, index, total, store) => { if (isFnc(value)) { const func = () => { const computed = /** @type {Function} */ (value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }; if (store) { store.func = func; } return func(); } else { return value; } }
@param {TweenPropValue} value @param {Target} target @param {Number} index @param {Number} total @param {Object} [store] @return {any}
getFunctionValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
func = () => { const computed = /** @type {Function} */ (value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }
@param {TweenPropValue} value @param {Target} target @param {Number} index @param {Number} total @param {Object} [store] @return {any}
func
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
func = () => { const computed = /** @type {Function} */ (value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }
@param {TweenPropValue} value @param {Target} target @param {Number} index @param {Number} total @param {Object} [store] @return {any}
func
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getTweenType = (target, prop) => { return !target[isDomSymbol] ? tweenTypes.OBJECT : // Handle SVG attributes target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE : // Handle CSS Transform properties differently than CSS to allow individual animations validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM : // CSS variables stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR : // All other CSS properties prop in /** @type {DOMTarget} */ (target).style ? tweenTypes.CSS : // Handle other DOM Attributes prop in target ? tweenTypes.OBJECT : tweenTypes.ATTRIBUTE; }
@param {Target} target @param {String} prop @return {tweenTypes}
getTweenType
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getTweenType = (target, prop) => { return !target[isDomSymbol] ? tweenTypes.OBJECT : // Handle SVG attributes target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE : // Handle CSS Transform properties differently than CSS to allow individual animations validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM : // CSS variables stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR : // All other CSS properties prop in /** @type {DOMTarget} */ (target).style ? tweenTypes.CSS : // Handle other DOM Attributes prop in target ? tweenTypes.OBJECT : tweenTypes.ATTRIBUTE; }
@param {Target} target @param {String} prop @return {tweenTypes}
getTweenType
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getCSSValue = (target, propName, animationInlineStyles) => { const inlineStyles = target.style[propName]; if (inlineStyles && animationInlineStyles) { animationInlineStyles[propName] = inlineStyles; } const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName); return value === 'auto' ? '0' : value; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
getCSSValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getCSSValue = (target, propName, animationInlineStyles) => { const inlineStyles = target.style[propName]; if (inlineStyles && animationInlineStyles) { animationInlineStyles[propName] = inlineStyles; } const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName); return value === 'auto' ? '0' : value; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
getCSSValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => { const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName); return type === tweenTypes.OBJECT ? target[propName] || 0 : type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */ (target).getAttribute(propName) : type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */ (target), propName, animationInlineStyles) : type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */ (target), propName, animationInlineStyles).trimStart() : getCSSValue(/** @type {DOMTarget} */ (target), propName, animationInlineStyles); }
@param {Target} target @param {String} propName @param {tweenTypes} [tweenType] @param {Object|void} [animationInlineStyles] @return {String|Number}
getOriginalAnimatableValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => { const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName); return type === tweenTypes.OBJECT ? target[propName] || 0 : type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */ (target).getAttribute(propName) : type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */ (target), propName, animationInlineStyles) : type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */ (target), propName, animationInlineStyles).trimStart() : getCSSValue(/** @type {DOMTarget} */ (target), propName, animationInlineStyles); }
@param {Target} target @param {String} propName @param {tweenTypes} [tweenType] @param {Object|void} [animationInlineStyles] @return {String|Number}
getOriginalAnimatableValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getRelativeValue = (x, y, operator) => { return operator === '-' ? x - y : operator === '+' ? x + y : x * y; }
@param {Number} x @param {Number} y @param {String} operator @return {Number}
getRelativeValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
getRelativeValue = (x, y, operator) => { return operator === '-' ? x - y : operator === '+' ? x + y : x * y; }
@param {Number} x @param {Number} y @param {String} operator @return {Number}
getRelativeValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
decomposeRawValue = (rawValue, targetObject) => { /** @type {valueTypes} */ targetObject.t = valueTypes.NUMBER; targetObject.n = 0; targetObject.u = null; targetObject.o = null; targetObject.d = null; targetObject.s = null; if (!rawValue) return targetObject; const num = +rawValue; if (!isNaN(num)) { // It's a number targetObject.n = num; return targetObject; } else { // let str = /** @type {String} */(rawValue).trim(); let str = /** @type {String} */ (rawValue); // Parsing operators (+=, -=, *=) manually is much faster than using regex here if (str[1] === '=') { targetObject.o = str[0]; str = str.slice(2); } // Skip exec regex if the value type is complex or color to avoid long regex backtracking const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str); if (unitMatch) { // Has a number and a unit targetObject.t = valueTypes.UNIT; targetObject.n = +unitMatch[1]; targetObject.u = unitMatch[2]; return targetObject; } else if (targetObject.o) { // Has an operator (+=, -=, *=) targetObject.n = +str; return targetObject; } else if (isCol(str)) { // Is a color targetObject.t = valueTypes.COLOR; targetObject.d = convertColorStringValuesToRgbaArray(str); return targetObject; } else { // Is a more complex string (generally svg coords, calc() or filters CSS values) const matchedNumbers = str.match(digitWithExponentRgx); targetObject.t = valueTypes.COMPLEX; targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : []; targetObject.s = str.split(digitWithExponentRgx) || []; return targetObject; } } }
@param {String|Number} rawValue @param {TweenDecomposedValue} targetObject @return {TweenDecomposedValue}
decomposeRawValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
decomposeRawValue = (rawValue, targetObject) => { /** @type {valueTypes} */ targetObject.t = valueTypes.NUMBER; targetObject.n = 0; targetObject.u = null; targetObject.o = null; targetObject.d = null; targetObject.s = null; if (!rawValue) return targetObject; const num = +rawValue; if (!isNaN(num)) { // It's a number targetObject.n = num; return targetObject; } else { // let str = /** @type {String} */(rawValue).trim(); let str = /** @type {String} */ (rawValue); // Parsing operators (+=, -=, *=) manually is much faster than using regex here if (str[1] === '=') { targetObject.o = str[0]; str = str.slice(2); } // Skip exec regex if the value type is complex or color to avoid long regex backtracking const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str); if (unitMatch) { // Has a number and a unit targetObject.t = valueTypes.UNIT; targetObject.n = +unitMatch[1]; targetObject.u = unitMatch[2]; return targetObject; } else if (targetObject.o) { // Has an operator (+=, -=, *=) targetObject.n = +str; return targetObject; } else if (isCol(str)) { // Is a color targetObject.t = valueTypes.COLOR; targetObject.d = convertColorStringValuesToRgbaArray(str); return targetObject; } else { // Is a more complex string (generally svg coords, calc() or filters CSS values) const matchedNumbers = str.match(digitWithExponentRgx); targetObject.t = valueTypes.COMPLEX; targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : []; targetObject.s = str.split(digitWithExponentRgx) || []; return targetObject; } } }
@param {String|Number} rawValue @param {TweenDecomposedValue} targetObject @return {TweenDecomposedValue}
decomposeRawValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
decomposeTweenValue = (tween, targetObject) => { targetObject.t = tween._valueType; targetObject.n = tween._toNumber; targetObject.u = tween._unit; targetObject.o = null; targetObject.d = cloneArray(tween._toNumbers); targetObject.s = cloneArray(tween._strings); return targetObject; }
@param {Tween} tween @param {TweenDecomposedValue} targetObject @return {TweenDecomposedValue}
decomposeTweenValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
decomposeTweenValue = (tween, targetObject) => { targetObject.t = tween._valueType; targetObject.n = tween._toNumber; targetObject.u = tween._unit; targetObject.o = null; targetObject.d = cloneArray(tween._toNumbers); targetObject.s = cloneArray(tween._strings); return targetObject; }
@param {Tween} tween @param {TweenDecomposedValue} targetObject @return {TweenDecomposedValue}
decomposeTweenValue
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
constructor(parameters = {}, parent = null, parentPosition = 0) { super(0); const { id, delay, duration, reversed, alternate, loop, loopDelay, autoplay, frameRate, playbackRate, onComplete, onLoop, onPause, onBegin, onBeforeUpdate, onUpdate, } = parameters; if (globals.scope) globals.scope.revertibles.push(this); const timerInitTime = parent ? 0 : engine._elapsedTime; const timerDefaults = parent ? parent.defaults : globals.defaults; const timerDelay = /** @type {Number} */ (isFnc(delay) || isUnd(delay) ? timerDefaults.delay : +delay); const timerDuration = isFnc(duration) || isUnd(duration) ? Infinity : +duration; const timerLoop = setValue(loop, timerDefaults.loop); const timerLoopDelay = setValue(loopDelay, timerDefaults.loopDelay); const timerIterationCount = timerLoop === true || timerLoop === Infinity || /** @type {Number} */ (timerLoop) < 0 ? Infinity : /** @type {Number} */ (timerLoop) + 1; let offsetPosition = 0; if (parent) { offsetPosition = parentPosition; } else { let startTime = now(); // Make sure to tick the engine once if suspended to avoid big gaps with the following offsetPosition calculation if (engine.paused) { engine.requestTick(startTime); startTime = engine._elapsedTime; } offsetPosition = startTime - engine._startTime; } // Timer's parameters this.id = !isUnd(id) ? id : ++timerId; /** @type {Timeline} */ this.parent = parent; // Total duration of the timer this.duration = clampInfinity(((timerDuration + timerLoopDelay) * timerIterationCount) - timerLoopDelay) || minValue; /** @type {Boolean} */ this.backwards = false; /** @type {Boolean} */ this.paused = true; /** @type {Boolean} */ this.began = false; /** @type {Boolean} */ this.completed = false; /** @type {Callback<this>} */ this.onBegin = onBegin || timerDefaults.onBegin; /** @type {Callback<this>} */ this.onBeforeUpdate = onBeforeUpdate || timerDefaults.onBeforeUpdate; /** @type {Callback<this>} */ this.onUpdate = onUpdate || timerDefaults.onUpdate; /** @type {Callback<this>} */ this.onLoop = onLoop || timerDefaults.onLoop; /** @type {Callback<this>} */ this.onPause = onPause || timerDefaults.onPause; /** @type {Callback<this>} */ this.onComplete = onComplete || timerDefaults.onComplete; /** @type {Number} */ this.iterationDuration = timerDuration; // Duration of one loop /** @type {Number} */ this.iterationCount = timerIterationCount; // Number of loops /** @type {Boolean|ScrollObserver} */ this._autoplay = parent ? false : setValue(autoplay, timerDefaults.autoplay); /** @type {Number} */ this._offset = offsetPosition; /** @type {Number} */ this._delay = timerDelay; /** @type {Number} */ this._loopDelay = timerLoopDelay; /** @type {Number} */ this._iterationTime = 0; /** @type {Number} */ this._currentIteration = 0; // Current loop index /** @type {Function} */ this._resolve = noop; // Used by .then() /** @type {Boolean} */ this._running = false; /** @type {Number} */ this._reversed = +setValue(reversed, timerDefaults.reversed); /** @type {Number} */ this._reverse = this._reversed; /** @type {Number} */ this._cancelled = 0; /** @type {Boolean} */ this._alternate = setValue(alternate, timerDefaults.alternate); /** @type {Renderable} */ this._prev = null; /** @type {Renderable} */ this._next = null; // Clock's parameters /** @type {Number} */ this._elapsedTime = timerInitTime; /** @type {Number} */ this._startTime = timerInitTime; /** @type {Number} */ this._lastTime = timerInitTime; /** @type {Number} */ this._fps = setValue(frameRate, timerDefaults.frameRate); /** @type {Number} */ this._speed = setValue(playbackRate, timerDefaults.playbackRate); }
@param {TimerParams} [parameters] @param {Timeline} [parent] @param {Number} [parentPosition]
constructor
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
seek(time, muteCallbacks = 0, internalRender = 0) { // Recompose the tween siblings in case the timer has been cancelled reviveTimer(this); // If you seek a completed animation, otherwise the next play will starts at 0 this.completed = false; const isPaused = this.paused; this.paused = true; // timer, time, muteCallbacks, internalRender, tickMode tick(this, time + this._delay, ~~muteCallbacks, ~~internalRender, tickModes.AUTO); return isPaused ? this : this.resume(); }
@param {Number} time @param {Boolean|Number} [muteCallbacks] @param {Boolean|Number} [internalRender] @return {this}
seek
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
revert() { tick(this, 0, 1, 0, tickModes.AUTO); const ap = /** @type {ScrollObserver} */ (this._autoplay); if (ap && ap.linked && ap.linked === this) ap.revert(); return this.cancel(); }
Cancels the timer by seeking it back to 0 and reverting the attached scroller if necessary @return {this}
revert
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
complete() { return this.seek(this.duration).cancel(); }
Imediatly completes the timer, cancels it and triggers the onComplete callback @return {this}
complete
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
then(callback = noop) { const then = this.then; const onResolve = () => { // this.then = null prevents infinite recursion if returned by an async function // https://github.com/juliangarnierorg/anime-beta/issues/26 this.then = null; callback(this); this.then = then; this._resolve = noop; }; return new Promise(r => { this._resolve = () => r(onResolve()); // Make sure to resolve imediatly if the timer has already completed if (this.completed) this._resolve(); return this; }); }
@param {Callback<this>} [callback] @return {Promise}
then
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
onResolve = () => { // this.then = null prevents infinite recursion if returned by an async function // https://github.com/juliangarnierorg/anime-beta/issues/26 this.then = null; callback(this); this.then = then; this._resolve = noop; }
@param {Callback<this>} [callback] @return {Promise}
onResolve
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT
onResolve = () => { // this.then = null prevents infinite recursion if returned by an async function // https://github.com/juliangarnierorg/anime-beta/issues/26 this.then = null; callback(this); this.then = then; this._resolve = noop; }
@param {Callback<this>} [callback] @return {Promise}
onResolve
javascript
juliangarnier/anime
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.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
types/index.js
https://github.com/juliangarnier/anime/blob/master/types/index.js
MIT