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 |
---|---|---|---|---|---|---|---|
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 |
sanitizePropertyName = (propertyName, target, tweenType) => {
if (tweenType === tweenTypes.TRANSFORM) {
const t = shortTransforms.get(propertyName);
return t ? t : propertyName;
}
else if (tweenType === tweenTypes.CSS ||
// Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
// but properties like "baseFrequency" should stay in lowerCamelCase
(tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */ (target).style))) {
const cachedPropertyName = propertyNamesCache[propertyName];
if (cachedPropertyName) {
return cachedPropertyName;
}
else {
const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
propertyNamesCache[propertyName] = lowerCaseName;
return lowerCaseName;
}
}
else {
return propertyName;
}
} | @param {String} propertyName
@param {Target} target
@param {tweenTypes} tweenType
@return {String} | sanitizePropertyName | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
sanitizePropertyName = (propertyName, target, tweenType) => {
if (tweenType === tweenTypes.TRANSFORM) {
const t = shortTransforms.get(propertyName);
return t ? t : propertyName;
}
else if (tweenType === tweenTypes.CSS ||
// Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset"
// but properties like "baseFrequency" should stay in lowerCamelCase
(tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */ (target).style))) {
const cachedPropertyName = propertyNamesCache[propertyName];
if (cachedPropertyName) {
return cachedPropertyName;
}
else {
const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName;
propertyNamesCache[propertyName] = lowerCaseName;
return lowerCaseName;
}
}
else {
return propertyName;
}
} | @param {String} propertyName
@param {Target} target
@param {tweenTypes} tweenType
@return {String} | sanitizePropertyName | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
convertValueUnit = (el, decomposedValue, unit, force = false) => {
const currentUnit = decomposedValue.u;
const currentNumber = decomposedValue.n;
if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary
return decomposedValue;
}
const cachedKey = currentNumber + currentUnit + unit;
const cached = convertedValuesCache[cachedKey];
if (!isUnd(cached) && !force) {
decomposedValue.n = cached;
}
else {
let convertedValue;
if (currentUnit in angleUnitsMap) {
convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit];
}
else {
const baseline = 100;
const tempEl = /** @type {DOMTarget} */ (el.cloneNode());
const parentNode = el.parentNode;
const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body;
parentEl.appendChild(tempEl);
const elStyle = tempEl.style;
elStyle.width = baseline + currentUnit;
const currentUnitWidth = /** @type {HTMLElement} */ (tempEl).offsetWidth || baseline;
elStyle.width = baseline + unit;
const newUnitWidth = /** @type {HTMLElement} */ (tempEl).offsetWidth || baseline;
const factor = currentUnitWidth / newUnitWidth;
parentEl.removeChild(tempEl);
convertedValue = factor * currentNumber;
}
decomposedValue.n = convertedValue;
convertedValuesCache[cachedKey] = convertedValue;
}
decomposedValue.t === valueTypes.UNIT;
decomposedValue.u = unit;
return decomposedValue;
} | @param {DOMTarget} el
@param {TweenDecomposedValue} decomposedValue
@param {String} unit
@param {Boolean} [force]
@return {TweenDecomposedValue} | convertValueUnit | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
convertValueUnit = (el, decomposedValue, unit, force = false) => {
const currentUnit = decomposedValue.u;
const currentNumber = decomposedValue.n;
if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary
return decomposedValue;
}
const cachedKey = currentNumber + currentUnit + unit;
const cached = convertedValuesCache[cachedKey];
if (!isUnd(cached) && !force) {
decomposedValue.n = cached;
}
else {
let convertedValue;
if (currentUnit in angleUnitsMap) {
convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit];
}
else {
const baseline = 100;
const tempEl = /** @type {DOMTarget} */ (el.cloneNode());
const parentNode = el.parentNode;
const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body;
parentEl.appendChild(tempEl);
const elStyle = tempEl.style;
elStyle.width = baseline + currentUnit;
const currentUnitWidth = /** @type {HTMLElement} */ (tempEl).offsetWidth || baseline;
elStyle.width = baseline + unit;
const newUnitWidth = /** @type {HTMLElement} */ (tempEl).offsetWidth || baseline;
const factor = currentUnitWidth / newUnitWidth;
parentEl.removeChild(tempEl);
convertedValue = factor * currentNumber;
}
decomposedValue.n = convertedValue;
convertedValuesCache[cachedKey] = convertedValue;
}
decomposedValue.t === valueTypes.UNIT;
decomposedValue.u = unit;
return decomposedValue;
} | @param {DOMTarget} el
@param {TweenDecomposedValue} decomposedValue
@param {String} unit
@param {Boolean} [force]
@return {TweenDecomposedValue} | convertValueUnit | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
generateKeyframes = (keyframes, parameters) => {
/** @type {AnimationParams} */
const properties = {};
if (isArr(keyframes)) {
const propertyNames = [].concat(... /** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(isKey);
for (let i = 0, l = propertyNames.length; i < l; i++) {
const propName = propertyNames[i];
const propArray = /** @type {DurationKeyframes} */ (keyframes).map(key => {
/** @type {TweenKeyValue} */
const newKey = {};
for (let p in key) {
const keyValue = /** @type {TweenPropValue} */ (key[p]);
if (isKey(p)) {
if (p === propName) {
newKey.to = keyValue;
}
}
else {
newKey[p] = keyValue;
}
}
return newKey;
});
properties[propName] = /** @type {ArraySyntaxValue} */ (propArray);
}
}
else {
const totalDuration = /** @type {Number} */ (setValue(parameters.duration, globals.defaults.duration));
const keys = Object.keys(keyframes)
.map(key => { return { o: parseFloat(key) / 100, p: keyframes[key] }; })
.sort((a, b) => a.o - b.o);
keys.forEach(key => {
const offset = key.o;
const prop = key.p;
for (let name in prop) {
if (isKey(name)) {
let propArray = /** @type {Array} */ (properties[name]);
if (!propArray)
propArray = properties[name] = [];
const duration = offset * totalDuration;
let length = propArray.length;
let prevKey = propArray[length - 1];
const keyObj = { to: prop[name] };
let durProgress = 0;
for (let i = 0; i < length; i++) {
durProgress += propArray[i].duration;
}
if (length === 1) {
keyObj.from = prevKey.to;
}
if (prop.ease) {
keyObj.ease = prop.ease;
}
keyObj.duration = duration - (length ? durProgress : 0);
propArray.push(keyObj);
}
}
return key;
});
for (let name in properties) {
const propArray = /** @type {Array} */ (properties[name]);
let prevEase;
// let durProgress = 0
for (let i = 0, l = propArray.length; i < l; i++) {
const prop = propArray[i];
// Emulate WAPPI easing parameter position
const currentEase = prop.ease;
prop.ease = prevEase ? prevEase : undefined;
prevEase = currentEase;
// durProgress += prop.duration;
// if (i === l - 1 && durProgress !== totalDuration) {
// propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress })
// }
}
if (!propArray[0].duration) {
propArray.shift();
}
}
}
return properties;
} | @param {DurationKeyframes | PercentageKeyframes} keyframes
@param {AnimationParams} parameters
@return {AnimationParams} | generateKeyframes | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
generateKeyframes = (keyframes, parameters) => {
/** @type {AnimationParams} */
const properties = {};
if (isArr(keyframes)) {
const propertyNames = [].concat(... /** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(isKey);
for (let i = 0, l = propertyNames.length; i < l; i++) {
const propName = propertyNames[i];
const propArray = /** @type {DurationKeyframes} */ (keyframes).map(key => {
/** @type {TweenKeyValue} */
const newKey = {};
for (let p in key) {
const keyValue = /** @type {TweenPropValue} */ (key[p]);
if (isKey(p)) {
if (p === propName) {
newKey.to = keyValue;
}
}
else {
newKey[p] = keyValue;
}
}
return newKey;
});
properties[propName] = /** @type {ArraySyntaxValue} */ (propArray);
}
}
else {
const totalDuration = /** @type {Number} */ (setValue(parameters.duration, globals.defaults.duration));
const keys = Object.keys(keyframes)
.map(key => { return { o: parseFloat(key) / 100, p: keyframes[key] }; })
.sort((a, b) => a.o - b.o);
keys.forEach(key => {
const offset = key.o;
const prop = key.p;
for (let name in prop) {
if (isKey(name)) {
let propArray = /** @type {Array} */ (properties[name]);
if (!propArray)
propArray = properties[name] = [];
const duration = offset * totalDuration;
let length = propArray.length;
let prevKey = propArray[length - 1];
const keyObj = { to: prop[name] };
let durProgress = 0;
for (let i = 0; i < length; i++) {
durProgress += propArray[i].duration;
}
if (length === 1) {
keyObj.from = prevKey.to;
}
if (prop.ease) {
keyObj.ease = prop.ease;
}
keyObj.duration = duration - (length ? durProgress : 0);
propArray.push(keyObj);
}
}
return key;
});
for (let name in properties) {
const propArray = /** @type {Array} */ (properties[name]);
let prevEase;
// let durProgress = 0
for (let i = 0, l = propArray.length; i < l; i++) {
const prop = propArray[i];
// Emulate WAPPI easing parameter position
const currentEase = prop.ease;
prop.ease = prevEase ? prevEase : undefined;
prevEase = currentEase;
// durProgress += prop.duration;
// if (i === l - 1 && durProgress !== totalDuration) {
// propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress })
// }
}
if (!propArray[0].duration) {
propArray.shift();
}
}
}
return properties;
} | @param {DurationKeyframes | PercentageKeyframes} keyframes
@param {AnimationParams} parameters
@return {AnimationParams} | generateKeyframes | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
constructor(targets, parameters, parent, parentPosition, fastSet = false, index = 0, length = 0) {
super(/** @type {TimerParams&AnimationParams} */ (parameters), parent, parentPosition);
const parsedTargets = registerTargets(targets);
const targetsLength = parsedTargets.length;
// If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties
const kfParams = /** @type {AnimationParams} */ (parameters).keyframes;
const params = /** @type {AnimationParams} */ (kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */ (kfParams), parameters), parameters) : parameters);
const { delay, duration, ease, playbackEase, modifier, composition, onRender, } = params;
const animDefaults = parent ? parent.defaults : globals.defaults;
const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
const animEase = animaPlaybackEase ? parseEasings(animaPlaybackEase) : null;
const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */ (ease).ease);
const tEasing = hasSpring ? /** @type {Spring} */ (ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease);
const tDuration = hasSpring ? /** @type {Spring} */ (ease).duration : setValue(duration, animDefaults.duration);
const tDelay = setValue(delay, animDefaults.delay);
const tModifier = modifier || animDefaults.modifier;
// If no composition is defined and the targets length is high (>= 1000) set the composition to 'none' (0) for faster tween creation
const tComposition = isUnd(composition) && targetsLength >= K ? compositionTypes.none : !isUnd(composition) ? composition : animDefaults.composition;
// TODO: Do not create an empty object until we know the animation will generate inline styles
const animInlineStyles = {};
// const absoluteOffsetTime = this._offset;
const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0);
let iterationDuration = NaN;
let iterationDelay = NaN;
let animationAnimationLength = 0;
let shouldTriggerRender = 0;
for (let targetIndex = 0; targetIndex < targetsLength; targetIndex++) {
const target = parsedTargets[targetIndex];
const ti = index || targetIndex;
const tl = length || targetsLength;
let lastTransformGroupIndex = NaN;
let lastTransformGroupLength = NaN;
for (let p in params) {
if (isKey(p)) {
const tweenType = getTweenType(target, p);
const propName = sanitizePropertyName(p, target, tweenType);
let propValue = params[p];
const isPropValueArray = isArr(propValue);
if (fastSet && !isPropValueArray) {
fastSetValuesArray[0] = propValue;
fastSetValuesArray[1] = propValue;
propValue = fastSetValuesArray;
}
// TODO: Allow nested keyframes inside ObjectValue value (prop: { to: [.5, 1, .75, 2, 3] })
// Normalize property values to valid keyframe syntax:
// [x, y] to [{to: [x, y]}] or {to: x} to [{to: x}] or keep keys syntax [{}, {}, {}...]
// const keyframes = isArr(propValue) ? propValue.length === 2 && !isObj(propValue[0]) ? [{ to: propValue }] : propValue : [propValue];
if (isPropValueArray) {
const arrayLength = /** @type {Array} */ (propValue).length;
const isNotObjectValue = !isObj(propValue[0]);
// Convert [x, y] to [{to: [x, y]}]
if (arrayLength === 2 && isNotObjectValue) {
keyObjectTarget.to = /** @type {TweenParamValue} */ ( /** @type {unknown} */(propValue));
keyframesTargetArray[0] = keyObjectTarget;
keyframes = keyframesTargetArray;
// Convert [x, y, z] to [[x, y], z]
}
else if (arrayLength > 2 && isNotObjectValue) {
keyframes = [];
/** @type {Array.<Number>} */ (propValue).forEach((v, i) => {
if (!i) {
fastSetValuesArray[0] = v;
}
else if (i === 1) {
fastSetValuesArray[1] = v;
keyframes.push(fastSetValuesArray);
}
else {
keyframes.push(v);
}
});
}
else {
keyframes = /** @type {Array.<TweenKeyValue>} */ (propValue);
}
}
else {
keyframesTargetArray[0] = propValue;
keyframes = keyframesTargetArray;
}
let siblings = null;
let prevTween = null;
let firstTweenChangeStartTime = NaN;
let lastTweenChangeEndTime = 0;
let tweenIndex = 0;
for (let l = keyframes.length; tweenIndex < l; tweenIndex++) {
const keyframe = keyframes[tweenIndex];
if (isObj(keyframe)) {
key = keyframe;
}
else {
keyObjectTarget.to = /** @type {TweenParamValue} */ (keyframe);
key = keyObjectTarget;
}
toFunctionStore.func = null;
const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore);
let tweenToValue;
// Allows function based values to return an object syntax value ({to: v})
if (isObj(computedToValue) && !isUnd(computedToValue.to)) {
key = computedToValue;
tweenToValue = computedToValue.to;
}
else {
tweenToValue = computedToValue;
}
const tweenFromValue = getFunctionValue(key.from, target, ti, tl);
const keyEasing = key.ease;
const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */ (keyEasing).ease);
// Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time
const tweenEasing = hasSpring ? /** @type {Spring} */ (keyEasing).ease : keyEasing || tEasing;
// Calculate default individual keyframe duration by dividing the tl of keyframes
const tweenDuration = hasSpring ? /** @type {Spring} */ (keyEasing).duration : getFunctionValue(setValue(key.duration, (l > 1 ? getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl);
// Default delay value should only be applied to the first tween
const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl);
const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl);
const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition];
// Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper
const tweenModifier = key.modifier || tModifier;
const hasFromvalue = !isUnd(tweenFromValue);
const hasToValue = !isUnd(tweenToValue);
const isFromToArray = isArr(tweenToValue);
const isFromToValue = isFromToArray || (hasFromvalue && hasToValue);
const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay;
const absoluteStartTime = absoluteOffsetTime + tweenStartTime;
// Force a onRender callback if the animation contains at least one from value and autoplay is set to false
if (!shouldTriggerRender && (hasFromvalue || isFromToArray))
shouldTriggerRender = 1;
let prevSibling = prevTween;
if (tweenComposition !== compositionTypes.none) {
if (!siblings)
siblings = getTweenSiblings(target, propName);
let nextSibling = siblings._head;
// Iterate trough all the next siblings until we find a sibling with an equal or inferior start time
while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) {
prevSibling = nextSibling;
nextSibling = nextSibling._nextRep;
// Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time
if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) {
while (nextSibling) {
overrideTween(nextSibling);
// This will ends both the current while loop and the upper one once all the next sibllings have been overriden
nextSibling = nextSibling._nextRep;
}
}
}
}
// Decompose values
if (isFromToValue) {
decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject);
decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject);
if (fromTargetObject.t === valueTypes.NUMBER) {
if (prevSibling) {
if (prevSibling._valueType === valueTypes.UNIT) {
fromTargetObject.t = valueTypes.UNIT;
fromTargetObject.u = prevSibling._unit;
}
}
else {
decomposeRawValue(getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), decomposedOriginalValue);
if (decomposedOriginalValue.t === valueTypes.UNIT) {
fromTargetObject.t = valueTypes.UNIT;
fromTargetObject.u = decomposedOriginalValue.u;
}
}
}
}
else {
if (hasToValue) {
decomposeRawValue(tweenToValue, toTargetObject);
}
else {
if (prevTween) {
decomposeTweenValue(prevTween, toTargetObject);
}
else {
// No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), toTargetObject);
}
}
if (hasFromvalue) {
decomposeRawValue(tweenFromValue, fromTargetObject);
}
else {
if (prevTween) {
decomposeTweenValue(prevTween, fromTargetObject);
}
else {
decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
// No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline
getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), fromTargetObject);
}
}
}
// Apply operators
if (fromTargetObject.o) {
fromTargetObject.n = getRelativeValue(!prevSibling ? decomposeRawValue(getOriginalAnimatableValue(target, propName, tweenType, animInlineStyles), decomposedOriginalValue).n : prevSibling._toNumber, fromTargetObject.n, fromTargetObject.o);
}
if (toTargetObject.o) {
toTargetObject.n = getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o);
}
// Values omogenisation in cases of type difference between "from" and "to"
if (fromTargetObject.t !== toTargetObject.t) {
if (fromTargetObject.t === valueTypes.COMPLEX || toTargetObject.t === valueTypes.COMPLEX) {
const complexValue = fromTargetObject.t === valueTypes.COMPLEX ? fromTargetObject : toTargetObject;
const notComplexValue = fromTargetObject.t === valueTypes.COMPLEX ? toTargetObject : fromTargetObject;
notComplexValue.t = valueTypes.COMPLEX;
notComplexValue.s = cloneArray(complexValue.s);
notComplexValue.d = complexValue.d.map(() => notComplexValue.n);
}
else if (fromTargetObject.t === valueTypes.UNIT || toTargetObject.t === valueTypes.UNIT) {
const unitValue = fromTargetObject.t === valueTypes.UNIT ? fromTargetObject : toTargetObject;
const notUnitValue = fromTargetObject.t === valueTypes.UNIT ? toTargetObject : fromTargetObject;
notUnitValue.t = valueTypes.UNIT;
notUnitValue.u = unitValue.u;
}
else if (fromTargetObject.t === valueTypes.COLOR || toTargetObject.t === valueTypes.COLOR) {
const colorValue = fromTargetObject.t === valueTypes.COLOR ? fromTargetObject : toTargetObject;
const notColorValue = fromTargetObject.t === valueTypes.COLOR ? toTargetObject : fromTargetObject;
notColorValue.t = valueTypes.COLOR;
notColorValue.s = colorValue.s;
notColorValue.d = [0, 0, 0, 1];
}
}
// Unit conversion
if (fromTargetObject.u !== toTargetObject.u) {
let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject;
valueToConvert = convertValueUnit(/** @type {DOMTarget} */ (target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false);
// TODO:
// convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u);
}
// Fill in non existing complex values
if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) {
const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject;
const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject;
// TODO: Check if n should be used instead of 0 for default complex values
shortestValue.d = longestValue.d.map((_, i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
shortestValue.s = cloneArray(longestValue.s);
}
// Tween factory
// Rounding is necessary here to minimize floating point errors
const tweenUpdateDuration = round(+tweenDuration || minValue, 12);
/** @type {Tween} */
const tween = {
parent: this,
id: tweenId++,
property: propName,
target: target,
_value: null,
_func: toFunctionStore.func,
_ease: parseEasings(tweenEasing),
_fromNumbers: cloneArray(fromTargetObject.d),
_toNumbers: cloneArray(toTargetObject.d),
_strings: cloneArray(toTargetObject.s),
_fromNumber: fromTargetObject.n,
_toNumber: toTargetObject.n,
_numbers: cloneArray(fromTargetObject.d),
_number: fromTargetObject.n,
_unit: toTargetObject.u,
_modifier: tweenModifier,
_currentTime: 0,
_startTime: tweenStartTime,
_delay: +tweenDelay,
_updateDuration: tweenUpdateDuration,
_changeDuration: tweenUpdateDuration,
_absoluteStartTime: absoluteStartTime,
// NOTE: Investigate bit packing to stores ENUM / BOOL
_tweenType: tweenType,
_valueType: toTargetObject.t,
_composition: tweenComposition,
_isOverlapped: 0,
_isOverridden: 0,
_renderTransforms: 0,
_prevRep: null,
_nextRep: null,
_prevAdd: null,
_nextAdd: null,
_prev: null,
_next: null,
};
if (tweenComposition !== compositionTypes.none) {
composeTween(tween, siblings);
}
if (isNaN(firstTweenChangeStartTime)) {
firstTweenChangeStartTime = tween._startTime;
}
// Rounding is necessary here to minimize floating point errors
lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12);
prevTween = tween;
animationAnimationLength++;
addChild(this, tween);
}
// Update animation timings with the added tweens properties
if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) {
iterationDelay = firstTweenChangeStartTime;
}
if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) {
iterationDuration = lastTweenChangeEndTime;
}
// TODO: Find a way to inline tween._renderTransforms = 1 here
if (tweenType === tweenTypes.TRANSFORM) {
lastTransformGroupIndex = animationAnimationLength - tweenIndex;
lastTransformGroupLength = animationAnimationLength;
}
}
}
// Set _renderTransforms to last transform property to correctly render the transforms list
if (!isNaN(lastTransformGroupIndex)) {
let i = 0;
forEachChildren(this, (/** @type {Tween} */ tween) => {
if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) {
tween._renderTransforms = 1;
if (tween._composition === compositionTypes.blend) {
forEachChildren(additive.animation, (/** @type {Tween} */ additiveTween) => {
if (additiveTween.id === tween.id) {
additiveTween._renderTransforms = 1;
}
});
}
}
i++;
});
}
}
if (!targetsLength) {
console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
}
if (iterationDelay) {
forEachChildren(this, (/** @type {Tween} */ tween) => {
// If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too
if (!(tween._startTime - tween._delay)) {
tween._delay -= iterationDelay;
}
tween._startTime -= iterationDelay;
});
iterationDuration -= iterationDelay;
}
else {
iterationDelay = 0;
}
// Prevents iterationDuration to be NaN if no valid animatable props have been provided
// Prevents _iterationCount to be NaN if no valid animatable props have been provided
if (!iterationDuration) {
iterationDuration = minValue;
this.iterationCount = 0;
}
/** @type {TargetsArray} */
this.targets = parsedTargets;
/** @type {Number} */
this.duration = iterationDuration === minValue ? minValue : clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || minValue;
/** @type {Callback<this>} */
this.onRender = onRender || animDefaults.onRender;
/** @type {EasingFunction} */
this._ease = animEase;
/** @type {Number} */
this._delay = iterationDelay;
// NOTE: I'm keeping delay values separated from offsets in timelines because delays can override previous tweens and it could be confusing to debug a timeline with overridden tweens and no associated visible delays.
// this._delay = parent ? 0 : iterationDelay;
// this._offset += parent ? iterationDelay : 0;
/** @type {Number} */
this.iterationDuration = iterationDuration;
/** @type {{}} */
this._inlineStyles = animInlineStyles;
if (!this._autoplay && shouldTriggerRender)
this.onRender(this);
} | @param {TargetsParam} targets
@param {AnimationParams} parameters
@param {Timeline} [parent]
@param {Number} [parentPosition]
@param {Boolean} [fastSet=false]
@param {Number} [index=0]
@param {Number} [length=0] | constructor | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
revert() {
super.revert();
return cleanInlineStyles(this);
} | Cancel the animation and revert all the values affected by this animation to their original state
@return {this} | revert | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
then(callback) {
return super.then(callback);
} | @param {Callback<this>} [callback]
@return {Promise} | then | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
easingToLinear = (fn, samples = 100) => {
const points = [];
for (let i = 0; i <= samples; i++)
points.push(fn(i / samples));
return `linear(${points.join(', ')})`;
} | Converts an easing function into a valid CSS linear() timing function string
@param {EasingFunction} fn
@param {number} [samples=100]
@returns {string} CSS linear() timing function | easingToLinear | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
easingToLinear = (fn, samples = 100) => {
const points = [];
for (let i = 0; i <= samples; i++)
points.push(fn(i / samples));
return `linear(${points.join(', ')})`;
} | Converts an easing function into a valid CSS linear() timing function string
@param {EasingFunction} fn
@param {number} [samples=100]
@returns {string} CSS linear() timing function | easingToLinear | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
registerTransformsProperties = () => {
if (transformsPropertiesRegistered)
return;
validTransforms.forEach(t => {
const isSkew = stringStartsWith(t, 'skew');
const isScale = stringStartsWith(t, 'scale');
const isRotate = stringStartsWith(t, 'rotate');
const isTranslate = stringStartsWith(t, 'translate');
const isAngle = isRotate || isSkew;
const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*";
try {
CSS.registerProperty({
name: '--' + t,
syntax,
inherits: false,
initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0',
});
}
catch { }
});
transformsPropertiesRegistered = true;
} | @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | WAAPICallback | EasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams | registerTransformsProperties | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
registerTransformsProperties = () => {
if (transformsPropertiesRegistered)
return;
validTransforms.forEach(t => {
const isSkew = stringStartsWith(t, 'skew');
const isScale = stringStartsWith(t, 'scale');
const isRotate = stringStartsWith(t, 'rotate');
const isTranslate = stringStartsWith(t, 'translate');
const isAngle = isRotate || isSkew;
const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*";
try {
CSS.registerProperty({
name: '--' + t,
syntax,
inherits: false,
initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0',
});
}
catch { }
});
transformsPropertiesRegistered = true;
} | @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | WAAPICallback | EasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams | registerTransformsProperties | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
removeWAAPIAnimation = ($el, property, parent) => {
let nextLookup = WAAPIAnimationsLookups._head;
while (nextLookup) {
const next = nextLookup._next;
const matchTarget = nextLookup.$el === $el;
const matchProperty = !property || nextLookup.property === property;
const matchParent = !parent || nextLookup.parent === parent;
if (matchTarget && matchProperty && matchParent) {
const anim = nextLookup.animation;
try {
anim.commitStyles();
}
catch { }
anim.cancel();
removeChild(WAAPIAnimationsLookups, nextLookup);
const lookupParent = nextLookup.parent;
if (lookupParent) {
lookupParent._completed++;
if (lookupParent.animations.length === lookupParent._completed) {
lookupParent.completed = true;
if (!lookupParent.muteCallbacks) {
lookupParent.paused = true;
lookupParent.onComplete(lookupParent);
lookupParent._resolve(lookupParent);
}
}
}
}
nextLookup = next;
}
} | @param {DOMTarget} $el
@param {String} [property]
@param {WAAPIAnimation} [parent] | removeWAAPIAnimation | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
removeWAAPIAnimation = ($el, property, parent) => {
let nextLookup = WAAPIAnimationsLookups._head;
while (nextLookup) {
const next = nextLookup._next;
const matchTarget = nextLookup.$el === $el;
const matchProperty = !property || nextLookup.property === property;
const matchParent = !parent || nextLookup.parent === parent;
if (matchTarget && matchProperty && matchParent) {
const anim = nextLookup.animation;
try {
anim.commitStyles();
}
catch { }
anim.cancel();
removeChild(WAAPIAnimationsLookups, nextLookup);
const lookupParent = nextLookup.parent;
if (lookupParent) {
lookupParent._completed++;
if (lookupParent.animations.length === lookupParent._completed) {
lookupParent.completed = true;
if (!lookupParent.muteCallbacks) {
lookupParent.paused = true;
lookupParent.onComplete(lookupParent);
lookupParent._resolve(lookupParent);
}
}
}
}
nextLookup = next;
}
} | @param {DOMTarget} $el
@param {String} [property]
@param {WAAPIAnimation} [parent] | removeWAAPIAnimation | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
const animation = $el.animate(keyframes, params);
const animTotalDuration = params.delay + (+params.duration * params.iterations);
animation.playbackRate = parent._speed;
if (parent.paused)
animation.pause();
if (parent.duration < animTotalDuration) {
parent.duration = animTotalDuration;
parent.controlAnimation = animation;
}
parent.animations.push(animation);
removeWAAPIAnimation($el, property);
addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null });
const handleRemove = () => { removeWAAPIAnimation($el, property, parent); };
animation.onremove = handleRemove;
animation.onfinish = handleRemove;
return animation;
} | @param {WAAPIAnimation} parent
@param {DOMTarget} $el
@param {String} property
@param {PropertyIndexedKeyframes} keyframes
@param {KeyframeAnimationOptions} params
@retun {Animation} | addWAAPIAnimation | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
addWAAPIAnimation = (parent, $el, property, keyframes, params) => {
const animation = $el.animate(keyframes, params);
const animTotalDuration = params.delay + (+params.duration * params.iterations);
animation.playbackRate = parent._speed;
if (parent.paused)
animation.pause();
if (parent.duration < animTotalDuration) {
parent.duration = animTotalDuration;
parent.controlAnimation = animation;
}
parent.animations.push(animation);
removeWAAPIAnimation($el, property);
addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null });
const handleRemove = () => { removeWAAPIAnimation($el, property, parent); };
animation.onremove = handleRemove;
animation.onfinish = handleRemove;
return animation;
} | @param {WAAPIAnimation} parent
@param {DOMTarget} $el
@param {String} property
@param {PropertyIndexedKeyframes} keyframes
@param {KeyframeAnimationOptions} params
@retun {Animation} | addWAAPIAnimation | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
normalizeTweenValue = (propName, value, $el, i, targetsLength) => {
let v = getFunctionValue(/** @type {any} */ (value), $el, i, targetsLength);
if (!isNum(v))
return v;
if (commonDefaultPXProperties.includes(propName) || stringStartsWith(propName, 'translate'))
return `${v}px`;
if (stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew'))
return `${v}deg`;
return `${v}`;
} | @param {String} propName
@param {WAAPIKeyframeValue} value
@param {DOMTarget} $el
@param {Number} i
@param {Number} targetsLength
@return {String} | normalizeTweenValue | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
normalizeTweenValue = (propName, value, $el, i, targetsLength) => {
let v = getFunctionValue(/** @type {any} */ (value), $el, i, targetsLength);
if (!isNum(v))
return v;
if (commonDefaultPXProperties.includes(propName) || stringStartsWith(propName, 'translate'))
return `${v}px`;
if (stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew'))
return `${v}deg`;
return `${v}`;
} | @param {String} propName
@param {WAAPIKeyframeValue} value
@param {DOMTarget} $el
@param {Number} i
@param {Number} targetsLength
@return {String} | normalizeTweenValue | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => {
/** @type {WAAPITweenValue} */
let tweenValue = '0';
const computedTo = !isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName];
if (!isUnd(from)) {
const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength);
tweenValue = [computedFrom, computedTo];
}
else {
tweenValue = isArr(to) ? to.map((/** @type {any} */ v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo;
}
return tweenValue;
} | @param {DOMTarget} $el
@param {String} propName
@param {WAAPIKeyframeValue} from
@param {WAAPIKeyframeValue} to
@param {Number} i
@param {Number} targetsLength
@return {WAAPITweenValue} | parseIndividualTweenValue | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => {
/** @type {WAAPITweenValue} */
let tweenValue = '0';
const computedTo = !isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName];
if (!isUnd(from)) {
const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength);
tweenValue = [computedFrom, computedTo];
}
else {
tweenValue = isArr(to) ? to.map((/** @type {any} */ v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo;
}
return tweenValue;
} | @param {DOMTarget} $el
@param {String} propName
@param {WAAPIKeyframeValue} from
@param {WAAPIKeyframeValue} to
@param {Number} i
@param {Number} targetsLength
@return {WAAPITweenValue} | parseIndividualTweenValue | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
constructor(targets, params) {
if (globals.scope)
globals.scope.revertibles.push(this);
registerTransformsProperties();
const parsedTargets = registerTargets(targets);
const targetsLength = parsedTargets.length;
if (!targetsLength) {
console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`);
}
const ease = setValue(params.ease, parseWAAPIEasing(globals.defaults.ease));
const spring = /** @type {Spring} */ (ease).ease && ease;
const autoplay = setValue(params.autoplay, globals.defaults.autoplay);
const scroll = autoplay && /** @type {ScrollObserver} */ (autoplay).link ? autoplay : false;
const alternate = params.alternate && /** @type {Boolean} */ (params.alternate) === true;
const reversed = params.reversed && /** @type {Boolean} */ (params.reversed) === true;
const loop = setValue(params.loop, globals.defaults.loop);
const iterations = /** @type {Number} */ ((loop === true || loop === Infinity) ? Infinity : isNum(loop) ? loop + 1 : 1);
/** @type {PlaybackDirection} */
const direction = alternate ? reversed ? 'alternate-reverse' : 'alternate' : reversed ? 'reverse' : 'normal';
/** @type {FillMode} */
const fill = 'forwards';
/** @type {String} */
const easing = parseWAAPIEasing(ease);
const timeScale = (globals.timeScale === 1 ? 1 : K);
/** @type {DOMTargetsArray}] */
this.targets = parsedTargets;
/** @type {Array<globalThis.Animation>}] */
this.animations = [];
/** @type {globalThis.Animation}] */
this.controlAnimation = null;
/** @type {Callback<this>} */
this.onComplete = params.onComplete || noop;
/** @type {Number} */
this.duration = 0;
/** @type {Boolean} */
this.muteCallbacks = false;
/** @type {Boolean} */
this.completed = false;
/** @type {Boolean} */
this.paused = !autoplay || scroll !== false;
/** @type {Boolean} */
this.reversed = reversed;
/** @type {Boolean|ScrollObserver} */
this.autoplay = autoplay;
/** @type {Number} */
this._speed = setValue(params.playbackRate, globals.defaults.playbackRate);
/** @type {Function} */
this._resolve = noop; // Used by .then()
/** @type {Number} */
this._completed = 0;
/** @type {Array<Object>}] */
this._inlineStyles = parsedTargets.map($el => $el.getAttribute('style'));
parsedTargets.forEach(($el, i) => {
const cachedTransforms = $el[transformsSymbol];
const hasIndividualTransforms = validIndividualTransforms.some(t => params.hasOwnProperty(t));
/** @type {Number} */
const duration = (spring ? /** @type {Spring} */ (spring).duration : getFunctionValue(setValue(params.duration, globals.defaults.duration), $el, i, targetsLength)) * timeScale;
/** @type {Number} */
const delay = getFunctionValue(setValue(params.delay, globals.defaults.delay), $el, i, targetsLength) * timeScale;
/** @type {CompositeOperation} */
const composite = /** @type {CompositeOperation} */ (setValue(params.composition, 'replace'));
for (let name in params) {
if (!isKey(name))
continue;
/** @type {PropertyIndexedKeyframes} */
const keyframes = {};
/** @type {KeyframeAnimationOptions} */
const tweenParams = { iterations, direction, fill, easing, duration, delay, composite };
const propertyValue = params[name];
const individualTransformProperty = hasIndividualTransforms ? validTransforms.includes(name) ? name : shortTransforms.get(name) : false;
let parsedPropertyValue;
if (isObj(propertyValue)) {
const tweenOptions = /** @type {WAAPITweenOptions} */ (propertyValue);
const tweenOptionsEase = setValue(tweenOptions.ease, ease);
const tweenOptionsSpring = /** @type {Spring} */ (tweenOptionsEase).ease && tweenOptionsEase;
const to = /** @type {WAAPITweenOptions} */ (tweenOptions).to;
const from = /** @type {WAAPITweenOptions} */ (tweenOptions).from;
/** @type {Number} */
tweenParams.duration = (tweenOptionsSpring ? /** @type {Spring} */ (tweenOptionsSpring).duration : getFunctionValue(setValue(tweenOptions.duration, duration), $el, i, targetsLength)) * timeScale;
/** @type {Number} */
tweenParams.delay = getFunctionValue(setValue(tweenOptions.delay, delay), $el, i, targetsLength) * timeScale;
/** @type {CompositeOperation} */
tweenParams.composite = /** @type {CompositeOperation} */ (setValue(tweenOptions.composition, composite));
/** @type {String} */
tweenParams.easing = parseWAAPIEasing(tweenOptionsEase);
parsedPropertyValue = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
if (individualTransformProperty) {
keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
cachedTransforms[individualTransformProperty] = parsedPropertyValue;
}
else {
keyframes[name] = parseIndividualTweenValue($el, name, from, to, i, targetsLength);
}
addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
if (!isUnd(from)) {
if (!individualTransformProperty) {
$el.style[name] = keyframes[name][0];
}
else {
const key = `--${individualTransformProperty}`;
$el.style.setProperty(key, keyframes[key][0]);
}
}
}
else {
parsedPropertyValue = isArr(propertyValue) ?
propertyValue.map((/** @type {any} */ v) => normalizeTweenValue(name, v, $el, i, targetsLength)) :
normalizeTweenValue(name, /** @type {any} */ (propertyValue), $el, i, targetsLength);
if (individualTransformProperty) {
keyframes[`--${individualTransformProperty}`] = parsedPropertyValue;
cachedTransforms[individualTransformProperty] = parsedPropertyValue;
}
else {
keyframes[name] = parsedPropertyValue;
}
addWAAPIAnimation(this, $el, name, keyframes, tweenParams);
}
}
if (hasIndividualTransforms) {
let transforms = emptyString;
for (let t in cachedTransforms) {
transforms += `${transformsFragmentStrings[t]}var(--${t})) `;
}
$el.style.transform = transforms;
}
});
if (scroll) {
/** @type {ScrollObserver} */ (this.autoplay).link(this);
}
} | @param {DOMTargetsParam} targets
@param {WAAPIAnimationParams} params | constructor | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
forEach(callback) {
const cb = isStr(callback) ? a => a[callback]() : callback;
this.animations.forEach(cb);
return this;
} | @param {forEachCallback|String} callback
@return {this} | forEach | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
get speed() {
return this._speed;
} | @param {forEachCallback|String} callback
@return {this} | speed | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
seek(time, muteCallbacks = false) {
if (muteCallbacks)
this.muteCallbacks = true;
if (time < this.duration)
this.completed = false;
this.currentTime = time;
this.muteCallbacks = false;
if (this.paused)
this.pause();
return this;
} | @param {Number} time
@param {Boolean} muteCallbacks | seek | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
restart() {
this.completed = false;
return this.seek(0, true).resume();
} | @param {Number} time
@param {Boolean} muteCallbacks | restart | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
commitStyles() {
return this.forEach('commitStyles');
} | @param {Number} time
@param {Boolean} muteCallbacks | commitStyles | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
complete() {
return this.seek(this.duration);
} | @param {Number} time
@param {Boolean} muteCallbacks | complete | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
cancel() {
this.forEach('cancel');
return this.pause();
} | @param {Number} time
@param {Boolean} muteCallbacks | cancel | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
revert() {
this.cancel();
this.targets.forEach(($el, i) => $el.setAttribute('style', this._inlineStyles[i]));
return this;
} | @param {Number} time
@param {Boolean} muteCallbacks | revert | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
sync = (callback = noop) => {
return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
} | @param {Callback<Timer>} [callback]
@return {Timer} | sync | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
sync = (callback = noop) => {
return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume();
} | @param {Callback<Timer>} [callback]
@return {Timer} | sync | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
function getTargetValue(targetSelector, propName, unit) {
const targets = registerTargets(targetSelector);
if (!targets.length)
return;
const [target] = targets;
const tweenType = getTweenType(target, propName);
const normalizePropName = sanitizePropertyName(propName, target, tweenType);
let originalValue = getOriginalAnimatableValue(target, normalizePropName);
if (isUnd(unit)) {
return originalValue;
}
else {
decomposeRawValue(originalValue, decomposedOriginalValue);
if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) {
if (unit === false) {
return decomposedOriginalValue.n;
}
else {
const convertedValue = convertValueUnit(/** @type {DOMTarget} */ (target), decomposedOriginalValue, /** @type {String} */ (unit), false);
return `${round(convertedValue.n, globals.precision)}${convertedValue.u}`;
}
}
}
} | @overload
@param {DOMTargetSelector} targetSelector
@param {String} propName
@return {String}
@overload
@param {JSTargetsParam} targetSelector
@param {String} propName
@return {Number|String}
@overload
@param {DOMTargetsParam} targetSelector
@param {String} propName
@param {String} unit
@return {String}
@overload
@param {TargetsParam} targetSelector
@param {String} propName
@param {Boolean} unit
@return {Number}
@param {TargetsParam} targetSelector
@param {String} propName
@param {String|Boolean} [unit] | getTargetValue | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
setTargetValues = (targets, parameters) => {
if (isUnd(parameters))
return;
parameters.duration = minValue;
// Do not overrides currently active tweens by default
parameters.composition = setValue(parameters.composition, compositionTypes.none);
// Skip init() and force rendering by playing the animation
return new JSAnimation(targets, parameters, null, 0, true).resume();
} | @param {TargetsParam} targets
@param {AnimationParams} parameters
@return {JSAnimation} | setTargetValues | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
setTargetValues = (targets, parameters) => {
if (isUnd(parameters))
return;
parameters.duration = minValue;
// Do not overrides currently active tweens by default
parameters.composition = setValue(parameters.composition, compositionTypes.none);
// Skip init() and force rendering by playing the animation
return new JSAnimation(targets, parameters, null, 0, true).resume();
} | @param {TargetsParam} targets
@param {AnimationParams} parameters
@return {JSAnimation} | setTargetValues | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
removeTargetsFromAnimation = (targetsArray, animation, propertyName) => {
let tweensMatchesTargets = false;
forEachChildren(animation, (/**@type {Tween} */ tween) => {
const tweenTarget = tween.target;
if (targetsArray.includes(tweenTarget)) {
const tweenName = tween.property;
const tweenType = tween._tweenType;
const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
// Make sure to flag the previous CSS transform tween to renderTransform
if (tween.parent._tail === tween &&
tween._tweenType === tweenTypes.TRANSFORM &&
tween._prev &&
tween._prev._tweenType === tweenTypes.TRANSFORM) {
tween._prev._renderTransforms = 1;
}
// Removes the tween from the selected animation
removeChild(animation, tween);
// Detach the tween from its siblings to make sure blended tweens are correctlly removed
removeTweenSliblings(tween);
tweensMatchesTargets = true;
}
}
}, true);
return tweensMatchesTargets;
} | @param {TargetsArray} targetsArray
@param {JSAnimation} animation
@param {String} [propertyName]
@return {Boolean} | removeTargetsFromAnimation | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
removeTargetsFromAnimation = (targetsArray, animation, propertyName) => {
let tweensMatchesTargets = false;
forEachChildren(animation, (/**@type {Tween} */ tween) => {
const tweenTarget = tween.target;
if (targetsArray.includes(tweenTarget)) {
const tweenName = tween.property;
const tweenType = tween._tweenType;
const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType);
if (!normalizePropName || normalizePropName && normalizePropName === tweenName) {
// Make sure to flag the previous CSS transform tween to renderTransform
if (tween.parent._tail === tween &&
tween._tweenType === tweenTypes.TRANSFORM &&
tween._prev &&
tween._prev._tweenType === tweenTypes.TRANSFORM) {
tween._prev._renderTransforms = 1;
}
// Removes the tween from the selected animation
removeChild(animation, tween);
// Detach the tween from its siblings to make sure blended tweens are correctlly removed
removeTweenSliblings(tween);
tweensMatchesTargets = true;
}
}
}, true);
return tweensMatchesTargets;
} | @param {TargetsArray} targetsArray
@param {JSAnimation} animation
@param {String} [propertyName]
@return {Boolean} | removeTargetsFromAnimation | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
remove = (targets, renderable, propertyName) => {
const targetsArray = parseTargets(targets);
const parent = /** @type {Renderable|typeof engine} **/ (renderable ? renderable : engine);
const waapiAnimation = renderable && /** @type {WAAPIAnimation} */ (renderable).controlAnimation && /** @type {WAAPIAnimation} */ (renderable);
for (let i = 0, l = targetsArray.length; i < l; i++) {
const $el = /** @type {DOMTarget} */ (targetsArray[i]);
removeWAAPIAnimation($el, propertyName, waapiAnimation);
}
let removeMatches;
if (parent._hasChildren) {
let iterationDuration = 0;
forEachChildren(parent, (/** @type {Renderable} */ child) => {
if (!child._hasChildren) {
removeMatches = removeTargetsFromAnimation(targetsArray, /** @type {JSAnimation} */ (child), propertyName);
// Remove the child from its parent if no tweens and no children left after the removal
if (removeMatches && !child._head) {
child.cancel();
removeChild(parent, child);
}
else {
// Calculate the new iterationDuration value to handle onComplete with last child in render()
const childTLOffset = child._offset + child._delay;
const childDur = childTLOffset + child.duration;
if (childDur > iterationDuration) {
iterationDuration = childDur;
}
}
}
// Make sure to also remove engine's children targets
// NOTE: Avoid recursion?
if (child._head) {
remove(targets, child, propertyName);
}
else {
child._hasChildren = false;
}
}, true);
// Update iterationDuration value to handle onComplete with last child in render()
if (!isUnd(/** @type {Renderable} */ (parent).iterationDuration)) {
/** @type {Renderable} */ (parent).iterationDuration = iterationDuration;
}
}
else {
removeMatches = removeTargetsFromAnimation(targetsArray,
/** @type {JSAnimation} */ (parent), propertyName);
}
if (removeMatches && !parent._head) {
parent._hasChildren = false;
// Cancel the parent if there are no tweens and no children left after the removal
// We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
if ( /** @type {Renderable} */(parent).cancel) /** @type {Renderable} */
(parent).cancel();
}
return targetsArray;
} | @param {TargetsParam} targets
@param {Renderable|WAAPIAnimation} [renderable]
@param {String} [propertyName]
@return {TargetsArray} | remove | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
remove = (targets, renderable, propertyName) => {
const targetsArray = parseTargets(targets);
const parent = /** @type {Renderable|typeof engine} **/ (renderable ? renderable : engine);
const waapiAnimation = renderable && /** @type {WAAPIAnimation} */ (renderable).controlAnimation && /** @type {WAAPIAnimation} */ (renderable);
for (let i = 0, l = targetsArray.length; i < l; i++) {
const $el = /** @type {DOMTarget} */ (targetsArray[i]);
removeWAAPIAnimation($el, propertyName, waapiAnimation);
}
let removeMatches;
if (parent._hasChildren) {
let iterationDuration = 0;
forEachChildren(parent, (/** @type {Renderable} */ child) => {
if (!child._hasChildren) {
removeMatches = removeTargetsFromAnimation(targetsArray, /** @type {JSAnimation} */ (child), propertyName);
// Remove the child from its parent if no tweens and no children left after the removal
if (removeMatches && !child._head) {
child.cancel();
removeChild(parent, child);
}
else {
// Calculate the new iterationDuration value to handle onComplete with last child in render()
const childTLOffset = child._offset + child._delay;
const childDur = childTLOffset + child.duration;
if (childDur > iterationDuration) {
iterationDuration = childDur;
}
}
}
// Make sure to also remove engine's children targets
// NOTE: Avoid recursion?
if (child._head) {
remove(targets, child, propertyName);
}
else {
child._hasChildren = false;
}
}, true);
// Update iterationDuration value to handle onComplete with last child in render()
if (!isUnd(/** @type {Renderable} */ (parent).iterationDuration)) {
/** @type {Renderable} */ (parent).iterationDuration = iterationDuration;
}
}
else {
removeMatches = removeTargetsFromAnimation(targetsArray,
/** @type {JSAnimation} */ (parent), propertyName);
}
if (removeMatches && !parent._head) {
parent._hasChildren = false;
// Cancel the parent if there are no tweens and no children left after the removal
// We have to check if the .cancel() method exist to handle cases where the parent is the engine itself
if ( /** @type {Renderable} */(parent).cancel) /** @type {Renderable} */
(parent).cancel();
}
return targetsArray;
} | @param {TargetsParam} targets
@param {Renderable|WAAPIAnimation} [renderable]
@param {String} [propertyName]
@return {TargetsArray} | remove | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
shuffle = items => {
let m = items.length, t, i;
while (m) {
i = random(0, --m);
t = items[m];
items[m] = items[i];
items[i] = t;
}
return items;
} | Adapted from https://bost.ocks.org/mike/shuffle/
@param {Array} items
@return {Array} | shuffle | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
shuffle = items => {
let m = items.length, t, i;
while (m) {
i = random(0, --m);
t = items[m];
items[m] = items[i];
items[i] = t;
}
return items;
} | Adapted from https://bost.ocks.org/mike/shuffle/
@param {Array} items
@return {Array} | shuffle | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
lerp = (start, end, amount, renderable) => {
let dt = K / globals.defaults.frameRate;
if (renderable !== false) {
const ticker = /** @type Renderable */ (renderable) ||
(engine._hasChildren && engine);
if (ticker && ticker.deltaTime) {
dt = ticker.deltaTime;
}
}
const t = 1 - Math.exp(-amount * dt * .1);
return !amount ? start : amount === 1 ? end : (1 - t) * start + t * end;
} | https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
@param {Number} start
@param {Number} end
@param {Number} amount
@param {Renderable|Boolean} [renderable]
@return {Number} | lerp | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
lerp = (start, end, amount, renderable) => {
let dt = K / globals.defaults.frameRate;
if (renderable !== false) {
const ticker = /** @type Renderable */ (renderable) ||
(engine._hasChildren && engine);
if (ticker && ticker.deltaTime) {
dt = ticker.deltaTime;
}
}
const t = 1 - Math.exp(-amount * dt * .1);
return !amount ? start : amount === 1 ? end : (1 - t) * start + t * end;
} | https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
@param {Number} start
@param {Number} end
@param {Number} amount
@param {Renderable|Boolean} [renderable]
@return {Number} | lerp | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
chain = fn => {
return (...args) => {
const result = fn(...args);
return new Proxy(noop, {
apply: (_, __, [v]) => result(v),
get: (_, prop) => chain(/**@param {...Number|String} nextArgs */ (...nextArgs) => {
const nextResult = utils[prop](...nextArgs);
return (/**@type {Number|String} */ v) => nextResult(result(v));
})
});
};
} | @param {Function} fn
@return {function(...(Number|String))} | chain | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
chain = fn => {
return (...args) => {
const result = fn(...args);
return new Proxy(noop, {
apply: (_, __, [v]) => result(v),
get: (_, prop) => chain(/**@param {...Number|String} nextArgs */ (...nextArgs) => {
const nextResult = utils[prop](...nextArgs);
return (/**@type {Number|String} */ v) => nextResult(result(v));
})
});
};
} | @param {Function} fn
@return {function(...(Number|String))} | chain | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
getPrevChildOffset = (timeline, timePosition) => {
if (stringStartsWith(timePosition, '<')) {
const goToPrevAnimationOffset = timePosition[1] === '<';
const prevAnimation = /** @type {Tickable} */ (timeline._tail);
const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
}
} | Timeline's children offsets positions parser
@param {Timeline} timeline
@param {String} timePosition
@return {Number} | getPrevChildOffset | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
getPrevChildOffset = (timeline, timePosition) => {
if (stringStartsWith(timePosition, '<')) {
const goToPrevAnimationOffset = timePosition[1] === '<';
const prevAnimation = /** @type {Tickable} */ (timeline._tail);
const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0;
return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration;
}
} | Timeline's children offsets positions parser
@param {Timeline} timeline
@param {String} timePosition
@return {Number} | getPrevChildOffset | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
parseTimelinePosition = (timeline, timePosition) => {
let tlDuration = timeline.iterationDuration;
if (tlDuration === minValue)
tlDuration = 0;
if (isUnd(timePosition))
return tlDuration;
if (isNum(+timePosition))
return +timePosition;
const timePosStr = /** @type {String} */ (timePosition);
const tlLabels = timeline ? timeline.labels : null;
const hasLabels = !isNil(tlLabels);
const prevOffset = getPrevChildOffset(timeline, timePosStr);
const hasSibling = !isUnd(prevOffset);
const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
if (matchedRelativeOperator) {
const fullOperator = matchedRelativeOperator[0];
const split = timePosStr.split(fullOperator);
const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
const parsedNumericalOffset = +split[1];
return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
}
else {
return hasSibling ? prevOffset :
hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
tlDuration : tlDuration;
}
} | @param {Timeline} timeline
@param {TimePosition} [timePosition]
@return {Number} | parseTimelinePosition | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
parseTimelinePosition = (timeline, timePosition) => {
let tlDuration = timeline.iterationDuration;
if (tlDuration === minValue)
tlDuration = 0;
if (isUnd(timePosition))
return tlDuration;
if (isNum(+timePosition))
return +timePosition;
const timePosStr = /** @type {String} */ (timePosition);
const tlLabels = timeline ? timeline.labels : null;
const hasLabels = !isNil(tlLabels);
const prevOffset = getPrevChildOffset(timeline, timePosStr);
const hasSibling = !isUnd(prevOffset);
const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr);
if (matchedRelativeOperator) {
const fullOperator = matchedRelativeOperator[0];
const split = timePosStr.split(fullOperator);
const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration;
const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration;
const parsedNumericalOffset = +split[1];
return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]);
}
else {
return hasSibling ? prevOffset :
hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] :
tlDuration : tlDuration;
}
} | @param {Timeline} timeline
@param {TimePosition} [timePosition]
@return {Number} | parseTimelinePosition | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
function addTlChild(childParams, tl, timePosition, targets, index, length) {
const isSetter = isNum(childParams.duration) && /** @type {Number} */ (childParams.duration) <= minValue;
// Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position
const adjustedPosition = isSetter ? timePosition - minValue : timePosition;
tick(tl, adjustedPosition, 1, 1, tickModes.AUTO);
const tlChild = targets ?
new JSAnimation(targets, /** @type {AnimationParams} */ (childParams), tl, adjustedPosition, false, index, length) :
new Timer(/** @type {TimerParams} */ (childParams), tl, adjustedPosition);
tlChild.init(1);
// TODO: Might be better to insert at a position relative to startTime?
addChild(tl, tlChild);
forEachChildren(tl, (/** @type {Renderable} */ child) => {
const childTLOffset = child._offset + child._delay;
const childDur = childTLOffset + child.duration;
if (childDur > tl.iterationDuration)
tl.iterationDuration = childDur;
});
tl.duration = getTimelineTotalDuration(tl);
return tl;
} | @overload
@param {TimerParams} childParams
@param {Timeline} tl
@param {Number} timePosition
@return {Timeline}
@overload
@param {AnimationParams} childParams
@param {Timeline} tl
@param {Number} timePosition
@param {TargetsParam} targets
@param {Number} [index]
@param {Number} [length]
@return {Timeline}
@param {TimerParams|AnimationParams} childParams
@param {Timeline} tl
@param {Number} timePosition
@param {TargetsParam} [targets]
@param {Number} [index]
@param {Number} [length] | addTlChild | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
add(a1, a2, a3) {
const isAnim = isObj(a2);
const isTimer = isObj(a1);
if (isAnim || isTimer) {
this._hasChildren = true;
if (isAnim) {
const childParams = /** @type {AnimationParams} */ (a2);
// Check for function for children stagger positions
if (isFnc(a3)) {
const staggeredPosition = /** @type {Function} */ (a3);
const parsedTargetsArray = parseTargets(/** @type {TargetsParam} */ (a1));
// Store initial duration before adding new children that will change the duration
const tlDuration = this.duration;
// Store initial _iterationDuration before adding new children that will change the duration
const tlIterationDuration = this.iterationDuration;
// Store the original id in order to add specific indexes to the new animations ids
const id = childParams.id;
let i = 0;
const parsedLength = parsedTargetsArray.length;
parsedTargetsArray.forEach((/** @type {Target} */ target) => {
// Create a new parameter object for each staggered children
const staggeredChildParams = { ...childParams };
// Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation
this.duration = tlDuration;
this.iterationDuration = tlIterationDuration;
if (!isUnd(id))
staggeredChildParams.id = id + '-' + i;
addTlChild(staggeredChildParams, this, staggeredPosition(target, i, parsedLength, this), target, i, parsedLength);
i++;
});
}
else {
addTlChild(childParams, this, parseTimelinePosition(this, a3),
/** @type {TargetsParam} */ (a1));
}
}
else {
// It's a Timer
addTlChild(
/** @type TimerParams */ (a1), this, parseTimelinePosition(this, /** @type TimePosition */ (a2)));
}
return this.init(1); // 1 = internalRender
}
} | @overload
@param {TargetsParam} a1
@param {AnimationParams} a2
@param {TimePosition} [a3]
@return {this}
@overload
@param {TimerParams} a1
@param {TimePosition} [a2]
@return {this}
@param {TargetsParam|TimerParams} a1
@param {AnimationParams|TimePosition} a2
@param {TimePosition} [a3] | add | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
sync(synced, position) {
if (isUnd(synced) || synced && isUnd(synced.pause))
return this;
synced.pause();
const duration = +( /** @type {globalThis.Animation} */(synced).effect ? /** @type {globalThis.Animation} */ (synced).effect.getTiming().duration : /** @type {Tickable} */ (synced).duration);
return this.add(synced, { currentTime: [0, duration], duration, ease: 'linear' }, position);
} | @overload
@param {Tickable} [synced]
@param {TimePosition} [position]
@return {this}
@overload
@param {globalThis.Animation} [synced]
@param {TimePosition} [position]
@return {this}
@overload
@param {WAAPIAnimation} [synced]
@param {TimePosition} [position]
@return {this}
@param {Tickable|WAAPIAnimation|globalThis.Animation} [synced]
@param {TimePosition} [position] | sync | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
set(targets, parameters, position) {
if (isUnd(parameters))
return this;
parameters.duration = minValue;
parameters.composition = compositionTypes.replace;
return this.add(targets, parameters, position);
} | @param {TargetsParam} targets
@param {AnimationParams} parameters
@param {TimePosition} [position]
@return {this} | set | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
call(callback, position) {
if (isUnd(callback) || callback && !isFnc(callback))
return this;
return this.add({ duration: 0, onComplete: () => callback(this) }, position);
} | @param {Callback<Timer>} callback
@param {TimePosition} [position]
@return {this} | call | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
label(labelName, position) {
if (isUnd(labelName) || labelName && !isStr(labelName))
return this;
this.labels[labelName] = parseTimelinePosition(this, /** @type TimePosition */ (position));
return this;
} | @param {String} labelName
@param {TimePosition} [position]
@return {this} | label | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
remove(targets, propertyName) {
remove(targets, this, propertyName);
return this;
} | @param {TargetsParam} targets
@param {String} [propertyName]
@return {this} | remove | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
then(callback) {
return super.then(callback);
} | @param {Callback<this>} [callback]
@return {Promise} | then | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
constructor(targets, parameters) {
if (globals.scope)
globals.scope.revertibles.push(this);
/** @type {AnimationParams} */
const globalParams = {};
const properties = {};
this.targets = [];
this.animations = {};
if (isUnd(targets) || isUnd(parameters))
return;
for (let propName in parameters) {
const paramValue = parameters[propName];
if (isKey(propName)) {
properties[propName] = paramValue;
}
else {
globalParams[propName] = paramValue;
}
}
for (let propName in properties) {
const propValue = properties[propName];
const isObjValue = isObj(propValue);
/** @type {TweenParamsOptions} */
let propParams = {};
let to = '+=0';
if (isObjValue) {
const unit = propValue.unit;
if (isStr(unit))
to += unit;
}
else {
propParams.duration = propValue;
}
propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to;
const animParams = mergeObjects(globalParams, propParams);
animParams.composition = compositionTypes.replace;
animParams.autoplay = false;
const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init();
if (!this.targets.length)
this.targets.push(...animation.targets);
/** @type {AnimatableProperty} */
this[propName] = (to, duration, ease) => {
const tween = /** @type {Tween} */ (animation._head);
if (isUnd(to) && tween) {
const numbers = tween._numbers;
if (numbers && numbers.length) {
return numbers;
}
else {
return tween._modifier(tween._number);
}
}
else {
forEachChildren(animation, (/** @type {Tween} */ tween) => {
if (isArr(to)) {
for (let i = 0, l = /** @type {Array} */ (to).length; i < l; i++) {
if (!isUnd(tween._numbers[i])) {
tween._fromNumbers[i] = /** @type {Number} */ (tween._modifier(tween._numbers[i]));
tween._toNumbers[i] = to[i];
}
}
}
else {
tween._fromNumber = /** @type {Number} */ (tween._modifier(tween._number));
tween._toNumber = /** @type {Number} */ (to);
}
if (!isUnd(ease))
tween._ease = parseEasings(ease);
tween._currentTime = 0;
});
if (!isUnd(duration))
animation.stretch(duration);
animation.reset(1).resume();
return this;
}
};
}
} | @param {TargetsParam} targets
@param {AnimatableParams} parameters | constructor | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.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 | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
constructor(target, parameters = {}) {
if (!target)
return;
if (globals.scope)
globals.scope.revertibles.push(this);
const paramX = parameters.x;
const paramY = parameters.y;
const trigger = parameters.trigger;
const modifier = parameters.modifier;
const ease = parameters.releaseEase;
const customEase = ease && parseEasings(ease);
const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */ (ease).ease);
const xProp = /** @type {String} */ (isObj(paramX) && !isUnd(/** @type {Object} */ (paramX).mapTo) ? /** @type {Object} */ (paramX).mapTo : 'translateX');
const yProp = /** @type {String} */ (isObj(paramY) && !isUnd(/** @type {Object} */ (paramY).mapTo) ? /** @type {Object} */ (paramY).mapTo : 'translateY');
const container = parseDraggableFunctionParameter(parameters.container, this);
this.containerArray = isArr(container) ? container : null;
this.$container = /** @type {HTMLElement} */ (container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */ (container))[0] : doc.body);
this.useWin = this.$container === doc.body;
/** @type {Window | HTMLElement} */
this.$scrollContainer = this.useWin ? win : this.$container;
this.$target = /** @type {HTMLElement} */ (isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]);
this.$trigger = /** @type {HTMLElement} */ (parseTargets(trigger ? trigger : target)[0]);
this.fixed = getTargetValue(this.$target, 'position') === 'fixed';
// Refreshable parameters
this.isFinePointer = true;
/** @type {[Number, Number, Number, Number]} */
this.containerPadding = [0, 0, 0, 0];
/** @type {Number} */
this.containerFriction = 0;
/** @type {Number} */
this.releaseContainerFriction = 0;
/** @type {Number|Array<Number>} */
this.snapX = 0;
/** @type {Number|Array<Number>} */
this.snapY = 0;
/** @type {Number} */
this.scrollSpeed = 0;
/** @type {Number} */
this.scrollThreshold = 0;
/** @type {Number} */
this.dragSpeed = 0;
/** @type {Number} */
this.maxVelocity = 0;
/** @type {Number} */
this.minVelocity = 0;
/** @type {Number} */
this.velocityMultiplier = 0;
/** @type {Boolean|DraggableCursorParams} */
this.cursor = false;
/** @type {Spring} */
this.releaseXSpring = hasSpring ? /** @type {Spring} */ (ease) : createSpring({
mass: setValue(parameters.releaseMass, 1),
stiffness: setValue(parameters.releaseStiffness, 80),
damping: setValue(parameters.releaseDamping, 20),
});
/** @type {Spring} */
this.releaseYSpring = hasSpring ? /** @type {Spring} */ (ease) : createSpring({
mass: setValue(parameters.releaseMass, 1),
stiffness: setValue(parameters.releaseStiffness, 80),
damping: setValue(parameters.releaseDamping, 20),
});
/** @type {EasingFunction} */
this.releaseEase = customEase || eases.outQuint;
/** @type {Boolean} */
this.hasReleaseSpring = hasSpring;
/** @type {Callback<this>} */
this.onGrab = parameters.onGrab || noop;
/** @type {Callback<this>} */
this.onDrag = parameters.onDrag || noop;
/** @type {Callback<this>} */
this.onRelease = parameters.onRelease || noop;
/** @type {Callback<this>} */
this.onUpdate = parameters.onUpdate || noop;
/** @type {Callback<this>} */
this.onSettle = parameters.onSettle || noop;
/** @type {Callback<this>} */
this.onSnap = parameters.onSnap || noop;
/** @type {Callback<this>} */
this.onResize = parameters.onResize || noop;
/** @type {Callback<this>} */
this.onAfterResize = parameters.onAfterResize || noop;
/** @type {[Number, Number]} */
this.disabled = [0, 0];
/** @type {AnimatableParams} */
const animatableParams = {};
if (modifier)
animatableParams.modifier = modifier;
if (isUnd(paramX) || paramX === true) {
animatableParams[xProp] = 0;
}
else if (isObj(paramX)) {
const paramXObject = /** @type {DraggableAxisParam} */ (paramX);
const animatableXParams = {};
if (paramXObject.modifier)
animatableXParams.modifier = paramXObject.modifier;
if (paramXObject.composition)
animatableXParams.composition = paramXObject.composition;
animatableParams[xProp] = animatableXParams;
}
else if (paramX === false) {
animatableParams[xProp] = 0;
this.disabled[0] = 1;
}
if (isUnd(paramY) || paramY === true) {
animatableParams[yProp] = 0;
}
else if (isObj(paramY)) {
const paramYObject = /** @type {DraggableAxisParam} */ (paramY);
const animatableYParams = {};
if (paramYObject.modifier)
animatableYParams.modifier = paramYObject.modifier;
if (paramYObject.composition)
animatableYParams.composition = paramYObject.composition;
animatableParams[yProp] = animatableYParams;
}
else if (paramY === false) {
animatableParams[yProp] = 0;
this.disabled[1] = 1;
}
/** @type {AnimatableObject} */
this.animate = /** @type {AnimatableObject} */ (new Animatable(this.$target, animatableParams));
// Internal props
this.xProp = xProp;
this.yProp = yProp;
this.destX = 0;
this.destY = 0;
this.deltaX = 0;
this.deltaY = 0;
this.scroll = { x: 0, y: 0 };
/** @type {[Number, Number, Number, Number]} */
this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y
/** @type {[Number, Number]} */
this.snapped = [0, 0]; // x, y
/** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */
this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2
/** @type {[Number, Number]} */
this.scrollView = [0, 0]; // w, h
/** @type {[Number, Number, Number, Number]} */
this.dragArea = [0, 0, 0, 0]; // x, y, w, h
/** @type {[Number, Number, Number, Number]} */
this.containerBounds = [-1e12, maxValue, maxValue, -1e12]; // t, r, b, l
/** @type {[Number, Number, Number, Number]} */
this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l
/** @type {[Number, Number, Number, Number]} */
this.targetBounds = [0, 0, 0, 0]; // t, r, b, l
/** @type {[Number, Number]} */
this.window = [0, 0]; // w, h
/** @type {[Number, Number, Number]} */
this.velocityStack = [0, 0, 0];
/** @type {Number} */
this.velocityStackIndex = 0;
/** @type {Number} */
this.velocityTime = now();
/** @type {Number} */
this.velocity = 0;
/** @type {Number} */
this.angle = 0;
/** @type {JSAnimation} */
this.cursorStyles = null;
/** @type {JSAnimation} */
this.triggerStyles = null;
/** @type {JSAnimation} */
this.bodyStyles = null;
/** @type {JSAnimation} */
this.targetStyles = null;
/** @type {JSAnimation} */
this.touchActionStyles = null;
this.transforms = new Transforms(this.$target);
this.overshootCoords = { x: 0, y: 0 };
this.overshootXTicker = new Timer({ autoplay: false }, null, 0).init();
this.overshootYTicker = new Timer({ autoplay: false }, null, 0).init();
this.updateTicker = new Timer({ autoplay: false }, null, 0).init();
this.overshootXTicker.onUpdate = () => {
if (this.disabled[0])
return;
this.updated = true;
this.manual = true;
this.animate[this.xProp](this.overshootCoords.x, 0);
};
this.overshootXTicker.onComplete = () => {
if (this.disabled[0])
return;
this.manual = false;
this.animate[this.xProp](this.overshootCoords.x, 0);
};
this.overshootYTicker.onUpdate = () => {
if (this.disabled[1])
return;
this.updated = true;
this.manual = true;
this.animate[this.yProp](this.overshootCoords.y, 0);
};
this.overshootYTicker.onComplete = () => {
if (this.disabled[1])
return;
this.manual = false;
this.animate[this.yProp](this.overshootCoords.y, 0);
};
this.updateTicker.onUpdate = () => this.update();
this.contained = !isUnd(container);
this.manual = false;
this.grabbed = false;
this.dragged = false;
this.updated = false;
this.released = false;
this.canScroll = false;
this.enabled = false;
this.initialized = false;
this.activeProp = this.disabled[1] ? xProp : yProp;
this.animate.animations[this.activeProp].onRender = () => {
const hasUpdated = this.updated;
const hasMoved = this.grabbed && hasUpdated;
const hasReleased = !hasMoved && this.released;
const x = this.x;
const y = this.y;
const dx = x - this.coords[2];
const dy = y - this.coords[3];
this.deltaX = dx;
this.deltaY = dy;
this.coords[2] = x;
this.coords[3] = y;
if (hasUpdated) {
this.onUpdate(this);
}
if (!hasReleased) {
this.updated = false;
}
else {
this.computeVelocity(dx, dy);
this.angle = atan2(dy, dx);
}
};
this.animate.animations[this.activeProp].onComplete = () => {
if ((!this.grabbed && this.released)) {
// Set eleased to false before calling onSettle to avoid recursion
this.released = false;
}
if (!this.manual) {
this.deltaX = 0;
this.deltaY = 0;
this.velocity = 0;
this.velocityStack[0] = 0;
this.velocityStack[1] = 0;
this.velocityStack[2] = 0;
this.velocityStackIndex = 0;
this.onSettle(this);
}
};
this.resizeTicker = new Timer({
autoplay: false,
duration: 150 * globals.timeScale,
onComplete: () => {
this.onResize(this);
this.refresh();
this.onAfterResize(this);
},
}).init();
this.parameters = parameters;
this.resizeObserver = new ResizeObserver(() => {
if (this.initialized) {
this.resizeTicker.restart();
}
else {
this.initialized = true;
}
});
this.enable();
this.refresh();
this.resizeObserver.observe(this.$container);
if (!isObj(target))
this.resizeObserver.observe(this.$target);
} | @param {TargetsParam} target
@param {DraggableParams} [parameters] | constructor | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
computeVelocity(dx, dy) {
const prevTime = this.velocityTime;
const curTime = now();
const elapsed = curTime - prevTime;
if (elapsed < 17)
return this.velocity;
this.velocityTime = curTime;
const velocityStack = this.velocityStack;
const vMul = this.velocityMultiplier;
const minV = this.minVelocity;
const maxV = this.maxVelocity;
const vi = this.velocityStackIndex;
velocityStack[vi] = round(clamp((sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5);
const velocity = max(velocityStack[0], velocityStack[1], velocityStack[2]);
this.velocity = velocity;
this.velocityStackIndex = (vi + 1) % 3;
return velocity;
} | @param {Number} dx
@param {Number} dy
@return {Number} | computeVelocity | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
setX(x, muteUpdateCallback = false) {
if (this.disabled[0])
return;
const v = round(x, 5);
this.overshootXTicker.pause();
this.manual = true;
this.updated = !muteUpdateCallback;
this.destX = v;
this.snapped[0] = snap(v, this.snapX);
this.animate[this.xProp](v, 0);
this.manual = false;
return this;
} | @param {Number} x
@param {Boolean} [muteUpdateCallback]
@return {this} | setX | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
setY(y, muteUpdateCallback = false) {
if (this.disabled[1])
return;
const v = round(y, 5);
this.overshootYTicker.pause();
this.manual = true;
this.updated = !muteUpdateCallback;
this.destY = v;
this.snapped[1] = snap(v, this.snapY);
this.animate[this.yProp](v, 0);
this.manual = false;
return this;
} | @param {Number} y
@param {Boolean} [muteUpdateCallback]
@return {this} | setY | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.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 | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.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 | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
refresh() {
const params = this.parameters;
const paramX = params.x;
const paramY = params.y;
const container = parseDraggableFunctionParameter(params.container, this);
const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0;
const containerPadding = /** @type {[Number, Number, Number, Number]} */ (isArr(cp) ? cp : [cp, cp, cp, cp]);
const cx = this.x;
const cy = this.y;
const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this);
const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' };
if (parsedCursorStyles) {
const { onHover, onGrab } = /** @type {DraggableCursorParams} */ (parsedCursorStyles);
if (onHover)
cursorStyles.onHover = onHover;
if (onGrab)
cursorStyles.onGrab = onGrab;
}
this.containerArray = isArr(container) ? container : null;
this.$container = /** @type {HTMLElement} */ (container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */ (container))[0] : doc.body);
this.useWin = this.$container === doc.body;
/** @type {Window | HTMLElement} */
this.$scrollContainer = this.useWin ? win : this.$container;
this.isFinePointer = matchMedia('(pointer:fine)').matches;
this.containerPadding = setValue(containerPadding, [0, 0, 0, 0]);
this.containerFriction = clamp(setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1);
this.releaseContainerFriction = clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1);
this.snapX = parseDraggableFunctionParameter(isObj(paramX) && !isUnd(paramX.snap) ? paramX.snap : params.snap, this);
this.snapY = parseDraggableFunctionParameter(isObj(paramY) && !isUnd(paramY.snap) ? paramY.snap : params.snap, this);
this.scrollSpeed = setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5);
this.scrollThreshold = setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20);
this.dragSpeed = setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1);
this.minVelocity = setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0);
this.maxVelocity = setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50);
this.velocityMultiplier = setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1);
this.cursor = parsedCursorStyles === false ? false : cursorStyles;
this.updateBoundingValues();
// const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y);
// if (ob === 1 || ob === 3) this.progressX = px;
// if (ob === 2 || ob === 3) this.progressY = py;
// if (this.initialized && this.contained) {
// if (this.progressX !== px) this.progressX = px;
// if (this.progressY !== py) this.progressY = py;
// }
const [bt, br, bb, bl] = this.containerBounds;
this.setX(clamp(cx, bl, br), true);
this.setY(clamp(cy, bt, bb), true);
} | Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB
@param {Array} bounds
@param {Number} x
@param {Number} y
@return {Number} | refresh | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
scrollInView(duration, gap = 0, ease = eases.inOutQuad) {
this.updateScrollCoords();
const x = this.destX;
const y = this.destY;
const scroll = this.scroll;
const scrollBounds = this.scrollBounds;
const canScroll = this.canScroll;
if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) {
const [st, sr, sb, sl] = scrollBounds;
const t = round(clamp(y - st, -1e12, 0), 0);
const r = round(clamp(x - sr, 0, maxValue), 0);
const b = round(clamp(y - sb, 0, maxValue), 0);
const l = round(clamp(x - sl, -1e12, 0), 0);
new JSAnimation(scroll, {
x: round(scroll.x + (l ? l - gap : r ? r + gap : 0), 0),
y: round(scroll.y + (t ? t - gap : b ? b + gap : 0), 0),
duration: isUnd(duration) ? 350 * globals.timeScale : duration,
ease,
onUpdate: () => {
this.canScroll = false;
this.$scrollContainer.scrollTo(scroll.x, scroll.y);
}
}).init().then(() => {
this.canScroll = canScroll;
});
}
return this;
} | @param {Number} [duration]
@param {Number} [gap]
@param {EasingParam} [ease]
@return {this} | scrollInView | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.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 | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.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 | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.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 | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
add(a1, a2) {
if (isFnc(a1)) {
const constructor = /** @type {contructorCallback} */ (a1);
this.constructors.push(constructor);
this.execute(() => {
const revertConstructor = constructor(this);
if (revertConstructor) {
this.revertConstructors.push(revertConstructor);
}
});
}
else {
this.methods[ /** @type {String} */(a1)] = (/** @type {any} */ ...args) => this.execute(() => a2(...args));
}
return this;
} | @callback contructorCallback
@param {this} self
@overload
@param {String} a1
@param {ScopeMethod} a2
@return {this}
@overload
@param {contructorCallback} a1
@return {this}
@param {String|contructorCallback} a1
@param {ScopeMethod} [a2] | add | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
convertValueToPx = ($el, v, size, under, over) => {
const clampMin = v === 'min';
const clampMax = v === 'max';
const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 :
v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' :
v === 'center' ? '50%' :
v;
const { n, u } = decomposeRawValue(value, decomposedOriginalValue);
let px = n;
if (u === '%') {
px = (n / 100) * size;
}
else if (u) {
px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n;
}
if (clampMax && under < 0)
px += under;
if (clampMin && over > 0)
px += over;
return px;
} | @param {HTMLElement} $el
@param {Number|string} v
@param {Number} size
@param {Number} [under]
@param {Number} [over]
@return {Number} | convertValueToPx | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
convertValueToPx = ($el, v, size, under, over) => {
const clampMin = v === 'min';
const clampMax = v === 'max';
const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 :
v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' :
v === 'center' ? '50%' :
v;
const { n, u } = decomposeRawValue(value, decomposedOriginalValue);
let px = n;
if (u === '%') {
px = (n / 100) * size;
}
else if (u) {
px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n;
}
if (clampMax && under < 0)
px += under;
if (clampMin && over > 0)
px += over;
return px;
} | @param {HTMLElement} $el
@param {Number|string} v
@param {Number} size
@param {Number} [under]
@param {Number} [over]
@return {Number} | convertValueToPx | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.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 | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.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 | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
updateBounds() {
if (this._debug) {
this.removeDebug();
}
let stickys;
const $target = this.target;
const container = this.container;
const isHori = this.horizontal;
const linked = this.linked;
let linkedTime;
let $el = $target;
let offsetX = 0;
let offsetY = 0;
/** @type {Element} */
let $offsetParent = $el;
if (linked) {
linkedTime = linked.currentTime;
linked.seek(0, true);
}
const isContainerStatic = getTargetValue(container.element, 'position') === 'static' ? setTargetValues(container.element, { position: 'relative ' }) : false;
while ($el && $el !== container.element && $el !== doc.body) {
const isSticky = getTargetValue($el, 'position') === 'sticky' ?
setTargetValues($el, { position: 'static' }) :
false;
if ($el === $offsetParent) {
offsetX += $el.offsetLeft || 0;
offsetY += $el.offsetTop || 0;
$offsetParent = $el.offsetParent;
}
$el = /** @type {HTMLElement} */ ($el.parentElement);
if (isSticky) {
if (!stickys)
stickys = [];
stickys.push(isSticky);
}
}
if (isContainerStatic)
isContainerStatic.revert();
const offset = isHori ? offsetX : offsetY;
const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight;
const containerSize = isHori ? container.width : container.height;
const scrollSize = isHori ? container.scrollWidth : container.scrollHeight;
const maxScroll = scrollSize - containerSize;
const enter = this.enter;
const leave = this.leave;
/** @type {ScrollThresholdValue} */
let enterTarget = 'start';
/** @type {ScrollThresholdValue} */
let leaveTarget = 'end';
/** @type {ScrollThresholdValue} */
let enterContainer = 'end';
/** @type {ScrollThresholdValue} */
let leaveContainer = 'start';
if (isStr(enter)) {
const splitted = /** @type {String} */ (enter).split(' ');
enterContainer = splitted[0];
enterTarget = splitted.length > 1 ? splitted[1] : enterTarget;
}
else if (isObj(enter)) {
const e = /** @type {ScrollThresholdParam} */ (enter);
if (!isUnd(e.container))
enterContainer = e.container;
if (!isUnd(e.target))
enterTarget = e.target;
}
else if (isNum(enter)) {
enterContainer = /** @type {Number} */ (enter);
}
if (isStr(leave)) {
const splitted = /** @type {String} */ (leave).split(' ');
leaveContainer = splitted[0];
leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget;
}
else if (isObj(leave)) {
const t = /** @type {ScrollThresholdParam} */ (leave);
if (!isUnd(t.container))
leaveContainer = t.container;
if (!isUnd(t.target))
leaveTarget = t.target;
}
else if (isNum(leave)) {
leaveContainer = /** @type {Number} */ (leave);
}
const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize);
const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize);
const under = (parsedEnterTarget + offset) - containerSize;
const over = (parsedLeaveTarget + offset) - maxScroll;
const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over);
const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over);
const offsetStart = parsedEnterTarget + offset - parsedEnterContainer;
const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer;
const scrollDelta = offsetEnd - offsetStart;
this.offsets[0] = offsetX;
this.offsets[1] = offsetY;
this.offset = offset;
this.offsetStart = offsetStart;
this.offsetEnd = offsetEnd;
this.distance = scrollDelta <= 0 ? 0 : scrollDelta;
this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer];
this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer];
if (stickys) {
stickys.forEach(sticky => sticky.revert());
}
if (linked) {
linked.seek(linkedTime, true);
}
if (this._debug) {
this.debug();
}
} | @param {String} p
@param {Number} l
@param {Number} t
@param {Number} w
@param {Number} h
@return {String} | updateBounds | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
stagger = (val, params = {}) => {
let values = [];
let maxValue = 0;
const from = params.from;
const reversed = params.reversed;
const ease = params.ease;
const hasEasing = !isUnd(ease);
const hasSpring = hasEasing && !isUnd(/** @type {Spring} */ (ease).ease);
const staggerEase = hasSpring ? /** @type {Spring} */ (ease).ease : hasEasing ? parseEasings(ease) : null;
const grid = params.grid;
const axis = params.axis;
const fromFirst = isUnd(from) || from === 0 || from === 'first';
const fromCenter = from === 'center';
const fromLast = from === 'last';
const isRange = isArr(val);
const val1 = isRange ? parseNumber(val[0]) : parseNumber(val);
const val2 = isRange ? parseNumber(val[1]) : 0;
const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString);
const start = params.start || 0 + (isRange ? val1 : 0);
let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0;
return (_, i, t, tl) => {
if (fromCenter)
fromIndex = (t - 1) / 2;
if (fromLast)
fromIndex = t - 1;
if (!values.length) {
for (let index = 0; index < t; index++) {
if (!grid) {
values.push(abs(fromIndex - index));
}
else {
const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2;
const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2;
const toX = index % grid[0];
const toY = floor(index / grid[0]);
const distanceX = fromX - toX;
const distanceY = fromY - toY;
let value = sqrt(distanceX * distanceX + distanceY * distanceY);
if (axis === 'x')
value = -distanceX;
if (axis === 'y')
value = -distanceY;
values.push(value);
}
maxValue = max(...values);
}
if (staggerEase)
values = values.map(val => staggerEase(val / maxValue) * maxValue);
if (reversed)
values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val));
}
const spacing = isRange ? (val2 - val1) / maxValue : val1;
const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl.iterationDuration : start) : /** @type {Number} */ (start);
/** @type {String|Number} */
let output = offset + ((spacing * round(values[i], 2)) || 0);
if (params.modifier)
output = params.modifier(output);
if (unitMatch)
output = `${output}${unitMatch[2]}`;
return output;
};
} | @param {Number|String|[Number|String,Number|String]} val
@param {StaggerParameters} params
@return {StaggerFunction} | stagger | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
stagger = (val, params = {}) => {
let values = [];
let maxValue = 0;
const from = params.from;
const reversed = params.reversed;
const ease = params.ease;
const hasEasing = !isUnd(ease);
const hasSpring = hasEasing && !isUnd(/** @type {Spring} */ (ease).ease);
const staggerEase = hasSpring ? /** @type {Spring} */ (ease).ease : hasEasing ? parseEasings(ease) : null;
const grid = params.grid;
const axis = params.axis;
const fromFirst = isUnd(from) || from === 0 || from === 'first';
const fromCenter = from === 'center';
const fromLast = from === 'last';
const isRange = isArr(val);
const val1 = isRange ? parseNumber(val[0]) : parseNumber(val);
const val2 = isRange ? parseNumber(val[1]) : 0;
const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString);
const start = params.start || 0 + (isRange ? val1 : 0);
let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0;
return (_, i, t, tl) => {
if (fromCenter)
fromIndex = (t - 1) / 2;
if (fromLast)
fromIndex = t - 1;
if (!values.length) {
for (let index = 0; index < t; index++) {
if (!grid) {
values.push(abs(fromIndex - index));
}
else {
const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2;
const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2;
const toX = index % grid[0];
const toY = floor(index / grid[0]);
const distanceX = fromX - toX;
const distanceY = fromY - toY;
let value = sqrt(distanceX * distanceX + distanceY * distanceY);
if (axis === 'x')
value = -distanceX;
if (axis === 'y')
value = -distanceY;
values.push(value);
}
maxValue = max(...values);
}
if (staggerEase)
values = values.map(val => staggerEase(val / maxValue) * maxValue);
if (reversed)
values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val));
}
const spacing = isRange ? (val2 - val1) / maxValue : val1;
const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl.iterationDuration : start) : /** @type {Number} */ (start);
/** @type {String|Number} */
let output = offset + ((spacing * round(values[i], 2)) || 0);
if (params.modifier)
output = params.modifier(output);
if (unitMatch)
output = `${output}${unitMatch[2]}`;
return output;
};
} | @param {Number|String|[Number|String,Number|String]} val
@param {StaggerParameters} params
@return {StaggerFunction} | stagger | javascript | juliangarnier/anime | types/index.js | https://github.com/juliangarnier/anime/blob/master/types/index.js | MIT |
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
} | Mark a function for special use by Sizzle
@param {Function} fn The function to mark | markFunction | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
} | Support testing using an element
@param {Function} fn Passed the created div and expects a boolean result | assert | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
} | Adds the same handler for all of the specified attrs
@param {String} attrs Pipe-separated list of attributes
@param {Function} handler The method that will be applied | addHandle | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
} | Checks document order of two siblings
@param {Element} a
@param {Element} b
@returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b | siblingCheck | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
} | Returns a function to use in pseudos for input types
@param {String} type | createInputPseudo | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
} | Returns a function to use in pseudos for buttons
@param {String} type | createButtonPseudo | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
} | Returns a function to use in pseudos for positionals
@param {Function} fn | createPositionalPseudo | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function testContext( context ) {
return context && typeof context.getElementsByTagName !== strundefined && context;
} | Checks a node for validity as a Sizzle context
@param {Element|Object=} context
@returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value | testContext | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | tokenize | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | toSelector | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | addCombinator | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | elementMatcher | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | condense | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | setMatcher | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | matcherFromTokens | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | matcherFromGroupMatchers | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | superMatcher | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | multipleContexts | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | select | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | winnow | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
} | Utility function for retrieving the text value of an array of DOM nodes
@param {Array|Element} elem | sibling | javascript | documentcloud/visualsearch | build/dependencies.js | https://github.com/documentcloud/visualsearch/blob/master/build/dependencies.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.