repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/bundles/anime.esm.min.js
dist/bundles/anime.esm.min.js
/** * Anime.js - ESM minified bundle * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
true
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/bundles/anime.esm.js
dist/bundles/anime.esm.js
/** * Anime.js - ESM bundle * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ // Global types /** * @typedef {Object} DefaultsParams * @property {Number|String} [id] * @property {PercentageKeyframes|DurationKeyframes} [keyframes] * @property {EasingParam} [playbackEase] * @property {Number} [playbackRate] * @property {Number} [frameRate] * @property {Number|Boolean} [loop] * @property {Boolean} [reversed] * @property {Boolean} [alternate] * @property {Boolean} [persist] * @property {Boolean|ScrollObserver} [autoplay] * @property {Number|FunctionValue} [duration] * @property {Number|FunctionValue} [delay] * @property {Number} [loopDelay] * @property {EasingParam} [ease] * @property {'none'|'replace'|'blend'|compositionTypes} [composition] * @property {(v: any) => any} [modifier] * @property {Callback<Tickable>} [onBegin] * @property {Callback<Tickable>} [onBeforeUpdate] * @property {Callback<Tickable>} [onUpdate] * @property {Callback<Tickable>} [onLoop] * @property {Callback<Tickable>} [onPause] * @property {Callback<Tickable>} [onComplete] * @property {Callback<Renderable>} [onRender] */ /** @typedef {JSAnimation|Timeline} Renderable */ /** @typedef {Timer|Renderable} Tickable */ /** @typedef {Timer&JSAnimation&Timeline} CallbackArgument */ /** @typedef {Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */ // Stagger types /** * @template T * @callback StaggerFunction * @param {Target} [target] * @param {Number} [index] * @param {Number} [length] * @param {Timeline} [tl] * @return {T} */ /** * @typedef {Object} StaggerParams * @property {Number|String} [start] * @property {Number|'first'|'center'|'last'|'random'} [from] * @property {Boolean} [reversed] * @property {Array.<Number>} [grid] * @property {('x'|'y')} [axis] * @property {String|((target: Target, i: Number, length: Number) => Number)} [use] * @property {Number} [total] * @property {EasingParam} [ease] * @property {TweenModifier} [modifier] */ // Targets types /** @typedef {HTMLElement|SVGElement} DOMTarget */ /** @typedef {Record<String, any>} JSTarget */ /** @typedef {DOMTarget|JSTarget} Target */ /** @typedef {Target|NodeList|String} TargetSelector */ /** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */ /** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */ /** @typedef {Array.<DOMTarget>} DOMTargetsArray */ /** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */ /** @typedef {Array.<JSTarget>} JSTargetsArray */ /** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */ /** @typedef {Array.<Target>} TargetsArray */ // Eases types /** * @callback EasingFunction * @param {Number} time * @return {Number} */ /** * @typedef {('linear'|'none'|'in'|'out'|'inOut'|'inQuad'|'outQuad'|'inOutQuad'|'inCubic'|'outCubic'|'inOutCubic'|'inQuart'|'outQuart'|'inOutQuart'|'inQuint'|'outQuint'|'inOutQuint'|'inSine'|'outSine'|'inOutSine'|'inCirc'|'outCirc'|'inOutCirc'|'inExpo'|'outExpo'|'inOutExpo'|'inBounce'|'outBounce'|'inOutBounce'|'inBack'|'outBack'|'inOutBack'|'inElastic'|'outElastic'|'inOutElastic'|'out(p = 1.675)'|'inOut(p = 1.675)'|'inBack(overshoot = 1.7)'|'outBack(overshoot = 1.7)'|'inOutBack(overshoot = 1.7)'|'inElastic(amplitude = 1, period = .3)'|'outElastic(amplitude = 1, period = .3)'|'inOutElastic(amplitude = 1, period = .3)')} EaseStringParamNames */ /** * @typedef {('ease'|'ease-in'|'ease-out'|'ease-in-out'|'linear(0, 0.25, 1)'|'steps'|'steps(6, start)'|'step-start'|'step-end'|'cubic-bezier(0.42, 0, 1, 1)') } WAAPIEaseStringParamNames */ /** * @callback PowerEasing * @param {Number|String} [power=1.675] * @return {EasingFunction} */ /** * @callback BackEasing * @param {Number|String} [overshoot=1.7] * @return {EasingFunction} */ /** * @callback ElasticEasing * @param {Number|String} [amplitude=1] * @param {Number|String} [period=.3] * @return {EasingFunction} */ /** @typedef {PowerEasing|BackEasing|ElasticEasing} EasingFunctionWithParams */ // A hack to get both ease names suggestions AND allow any strings // https://github.com/microsoft/TypeScript/issues/29729#issuecomment-460346421 /** @typedef {(String & {})|EaseStringParamNames|EasingFunction|Spring} EasingParam */ /** @typedef {(String & {})|EaseStringParamNames|WAAPIEaseStringParamNames|EasingFunction|Spring} WAAPIEasingParam */ // Spring types /** * @typedef {Object} SpringParams * @property {Number} [mass=1] - Mass, default 1 * @property {Number} [stiffness=100] - Stiffness, default 100 * @property {Number} [damping=10] - Damping, default 10 * @property {Number} [velocity=0] - Initial velocity, default 0 * @property {Number} [bounce=0] - Initial bounce, default 0 * @property {Number} [duration=0] - The perceived duration, default 0 * @property {Callback<JSAnimation>} [onComplete] - Callback function called when the spring currentTime hits the perceived duration */ // Callback types /** * @template T * @callback Callback * @param {T} self - Returns itself * @param {PointerEvent} [e] * @return {*} */ /** * @template {object} T * @typedef {Object} TickableCallbacks * @property {Callback<T>} [onBegin] * @property {Callback<T>} [onBeforeUpdate] * @property {Callback<T>} [onUpdate] * @property {Callback<T>} [onLoop] * @property {Callback<T>} [onPause] * @property {Callback<T>} [onComplete] */ /** * @template {object} T * @typedef {Object} RenderableCallbacks * @property {Callback<T>} [onRender] */ // Timer types /** * @typedef {Object} TimerOptions * @property {Number|String} [id] * @property {TweenParamValue} [duration] * @property {TweenParamValue} [delay] * @property {Number} [loopDelay] * @property {Boolean} [reversed] * @property {Boolean} [alternate] * @property {Boolean|Number} [loop] * @property {Boolean|ScrollObserver} [autoplay] * @property {Number} [frameRate] * @property {Number} [playbackRate] */ /** * @typedef {TimerOptions & TickableCallbacks<Timer>} TimerParams */ // Tween types /** * @callback FunctionValue * @param {Target} target - The animated target * @param {Number} index - The target index * @param {Number} length - The total number of animated targets * @return {Number|String|TweenObjectValue|Array.<Number|String|TweenObjectValue>} */ /** * @callback TweenModifier * @param {Number} value - The animated value * @return {Number|String} */ /** @typedef {[Number, Number, Number, Number]} ColorArray */ /** * @typedef {Object} Tween * @property {Number} id * @property {JSAnimation} parent * @property {String} property * @property {Target} target * @property {String|Number} _value * @property {Function|null} _func * @property {EasingFunction} _ease * @property {Array.<Number>} _fromNumbers * @property {Array.<Number>} _toNumbers * @property {Array.<String>} _strings * @property {Number} _fromNumber * @property {Number} _toNumber * @property {Array.<Number>} _numbers * @property {Number} _number * @property {String} _unit * @property {TweenModifier} _modifier * @property {Number} _currentTime * @property {Number} _delay * @property {Number} _updateDuration * @property {Number} _startTime * @property {Number} _changeDuration * @property {Number} _absoluteStartTime * @property {tweenTypes} _tweenType * @property {valueTypes} _valueType * @property {Number} _composition * @property {Number} _isOverlapped * @property {Number} _isOverridden * @property {Number} _renderTransforms * @property {String} _inlineValue * @property {Tween} _prevRep * @property {Tween} _nextRep * @property {Tween} _prevAdd * @property {Tween} _nextAdd * @property {Tween} _prev * @property {Tween} _next */ /** * @typedef TweenDecomposedValue * @property {Number} t - Type * @property {Number} n - Single number value * @property {String} u - Value unit * @property {String} o - Value operator * @property {Array.<Number>} d - Array of Numbers (in case of complex value type) * @property {Array.<String>} s - Strings (in case of complex value type) */ /** @typedef {{_head: null|Tween, _tail: null|Tween}} TweenPropertySiblings */ /** @typedef {Record<String, TweenPropertySiblings>} TweenLookups */ /** @typedef {WeakMap.<Target, TweenLookups>} TweenReplaceLookups */ /** @typedef {Map.<Target, TweenLookups>} TweenAdditiveLookups */ // JSAnimation types /** * @typedef {Number|String|FunctionValue} TweenParamValue */ /** * @typedef {TweenParamValue|[TweenParamValue, TweenParamValue]} TweenPropValue */ /** * @typedef {(String & {})|'none'|'replace'|'blend'|compositionTypes} TweenComposition */ /** * @typedef {Object} TweenParamsOptions * @property {TweenParamValue} [duration] * @property {TweenParamValue} [delay] * @property {EasingParam} [ease] * @property {TweenModifier} [modifier] * @property {TweenComposition} [composition] */ /** * @typedef {Object} TweenValues * @property {TweenParamValue} [from] * @property {TweenPropValue} [to] * @property {TweenPropValue} [fromTo] */ /** * @typedef {TweenParamsOptions & TweenValues} TweenKeyValue */ /** * @typedef {Array.<TweenKeyValue|TweenPropValue>} ArraySyntaxValue */ /** * @typedef {TweenParamValue|ArraySyntaxValue|TweenKeyValue} TweenOptions */ /** * @typedef {Partial<{to: TweenParamValue|Array.<TweenParamValue>; from: TweenParamValue|Array.<TweenParamValue>; fromTo: TweenParamValue|Array.<TweenParamValue>;}>} TweenObjectValue */ /** * @typedef {Object} PercentageKeyframeOptions * @property {EasingParam} [ease] */ /** * @typedef {Record<String, TweenParamValue>} PercentageKeyframeParams */ /** * @typedef {Record<String, PercentageKeyframeParams & PercentageKeyframeOptions>} PercentageKeyframes */ /** * @typedef {Array<Record<String, TweenOptions | TweenModifier | boolean> & TweenParamsOptions>} DurationKeyframes */ /** * @typedef {Object} AnimationOptions * @property {PercentageKeyframes|DurationKeyframes} [keyframes] * @property {EasingParam} [playbackEase] */ // TODO: Currently setting TweenModifier to the intersected Record<> makes the FunctionValue type target param any if only one parameter is set /** * @typedef {Record<String, TweenOptions | Callback<JSAnimation> | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & TickableCallbacks<JSAnimation> & RenderableCallbacks<JSAnimation>} AnimationParams */ // Timeline types /** * Accepts:<br> * - `Number` - Absolute position in milliseconds (e.g., `500` places element at exactly 500ms)<br> * - `'+=Number'` - Addition: Position element X ms after the last element (e.g., `'+=100'`)<br> * - `'-=Number'` - Subtraction: Position element X ms before the last element's end (e.g., `'-=100'`)<br> * - `'*=Number'` - Multiplier: Position element at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br> * - `'<'` - Previous end: Position element at the end position of the previous element<br> * - `'<<'` - Previous start: Position element at the start position of the previous element<br> * - `'<<+=Number'` - Combined: Position element relative to previous element's start (e.g., `'<<+=250'`)<br> * - `'label'` - Label: Position element at a named label position (e.g., `'My Label'`) * * @typedef {Number|`+=${Number}`|`-=${Number}`|`*=${Number}`|'<'|'<<'|`<<+=${Number}`|`<<-=${Number}`|String} TimelinePosition */ /** * Accepts:<br> * - `Number` - Absolute position in milliseconds (e.g., `500` places animation at exactly 500ms)<br> * - `'+=Number'` - Addition: Position animation X ms after the last animation (e.g., `'+=100'`)<br> * - `'-=Number'` - Subtraction: Position animation X ms before the last animation's end (e.g., `'-=100'`)<br> * - `'*=Number'` - Multiplier: Position animation at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br> * - `'<'` - Previous end: Position animation at the end position of the previous animation<br> * - `'<<'` - Previous start: Position animation at the start position of the previous animation<br> * - `'<<+=Number'` - Combined: Position animation relative to previous animation's start (e.g., `'<<+=250'`)<br> * - `'label'` - Label: Position animation at a named label position (e.g., `'My Label'`)<br> * - `stagger(String|Nummber)` - Stagger multi-elements animation positions (e.g., 10, 20, 30...) * * @typedef {TimelinePosition | StaggerFunction<Number|String>} TimelineAnimationPosition */ /** * @typedef {Object} TimelineOptions * @property {DefaultsParams} [defaults] * @property {EasingParam} [playbackEase] */ /** * @typedef {TimerOptions & TimelineOptions & TickableCallbacks<Timeline> & RenderableCallbacks<Timeline>} TimelineParams */ // WAAPIAnimation types /** * @typedef {String|Number|Array<String>|Array<Number>} WAAPITweenValue */ /** * @callback WAAPIFunctionValue * @param {DOMTarget} target - The animated target * @param {Number} index - The target index * @param {Number} length - The total number of animated targets * @return {WAAPITweenValue} */ /** * @typedef {WAAPITweenValue|WAAPIFunctionValue|Array<String|Number|WAAPIFunctionValue>} WAAPIKeyframeValue */ /** * @typedef {Object} WAAPITweenOptions * @property {WAAPIKeyframeValue} [to] * @property {WAAPIKeyframeValue} [from] * @property {Number|WAAPIFunctionValue} [duration] * @property {Number|WAAPIFunctionValue} [delay] * @property {WAAPIEasingParam} [ease] * @property {CompositeOperation} [composition] */ /** * @typedef {Object} WAAPIAnimationOptions * @property {Number|Boolean} [loop] * @property {Boolean} [Reversed] * @property {Boolean} [Alternate] * @property {Boolean|ScrollObserver} [autoplay] * @property {Number} [playbackRate] * @property {Number|WAAPIFunctionValue} [duration] * @property {Number|WAAPIFunctionValue} [delay] * @property {WAAPIEasingParam} [ease] * @property {CompositeOperation} [composition] * @property {Boolean} [persist] * @property {Callback<WAAPIAnimation>} [onComplete] */ /** * @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | Callback<WAAPIAnimation> | WAAPIEasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams */ // Animatable types /** * @callback AnimatablePropertySetter * @param {Number|Array.<Number>} to * @param {Number} [duration] * @param {EasingParam} [ease] * @return {AnimatableObject} */ /** * @callback AnimatablePropertyGetter * @return {Number|Array.<Number>} */ /** * @typedef {AnimatablePropertySetter & AnimatablePropertyGetter} AnimatableProperty */ /** * @typedef {Animatable & Record<String, AnimatableProperty>} AnimatableObject */ /** * @typedef {Object} AnimatablePropertyParamsOptions * @property {String} [unit] * @property {TweenParamValue} [duration] * @property {EasingParam} [ease] * @property {TweenModifier} [modifier] * @property {TweenComposition} [composition] */ /** * @typedef {Record<String, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions} AnimatableParams */ // Scope types /** * @typedef {Object} ReactRef * @property {HTMLElement|SVGElement|null} [current] */ /** * @typedef {Object} AngularRef * @property {HTMLElement|SVGElement} [nativeElement] */ /** * @typedef {Object} ScopeParams * @property {DOMTargetSelector|ReactRef|AngularRef} [root] * @property {DefaultsParams} [defaults] * @property {Record<String, String>} [mediaQueries] */ /** * @template T * @callback ScopedCallback * @param {Scope} scope * @return {T} */ /** * @callback ScopeCleanupCallback * @param {Scope} [scope] */ /** * @callback ScopeConstructorCallback * @param {Scope} [scope] * @return {ScopeCleanupCallback|void} */ /** * @callback ScopeMethod * @param {...*} args * @return {ScopeCleanupCallback|void} */ // Scroll types /** * @typedef {String|Number} ScrollThresholdValue */ /** * @typedef {Object} ScrollThresholdParam * @property {ScrollThresholdValue} [target] * @property {ScrollThresholdValue} [container] */ /** * @callback ScrollObserverAxisCallback * @param {ScrollObserver} self * @return {'x'|'y'} */ /** * @callback ScrollThresholdCallback * @param {ScrollObserver} self * @return {ScrollThresholdValue|ScrollThresholdParam} */ /** * @typedef {Object} ScrollObserverParams * @property {Number|String} [id] * @property {Boolean|Number|String|EasingParam} [sync] * @property {TargetsParam} [container] * @property {TargetsParam} [target] * @property {'x'|'y'|ScrollObserverAxisCallback|((observer: ScrollObserver) => 'x'|'y'|ScrollObserverAxisCallback)} [axis] * @property {ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback|((observer: ScrollObserver) => ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback)} [enter] * @property {ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback|((observer: ScrollObserver) => ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback)} [leave] * @property {Boolean|((observer: ScrollObserver) => Boolean)} [repeat] * @property {Boolean} [debug] * @property {Callback<ScrollObserver>} [onEnter] * @property {Callback<ScrollObserver>} [onLeave] * @property {Callback<ScrollObserver>} [onEnterForward] * @property {Callback<ScrollObserver>} [onLeaveForward] * @property {Callback<ScrollObserver>} [onEnterBackward] * @property {Callback<ScrollObserver>} [onLeaveBackward] * @property {Callback<ScrollObserver>} [onUpdate] * @property {Callback<ScrollObserver>} [onSyncComplete] */ // Draggable types /** * @typedef {Object} DraggableAxisParam * @property {String} [mapTo] * @property {TweenModifier} [modifier] * @property {TweenComposition} [composition] * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap] */ /** * @typedef {Object} DraggableCursorParams * @property {String} [onHover] * @property {String} [onGrab] */ /** * @typedef {Object} DraggableDragThresholdParams * @property {Number} [mouse] * @property {Number} [touch] */ /** * @typedef {Object} DraggableParams * @property {DOMTargetSelector} [trigger] * @property {DOMTargetSelector|Array<Number>|((draggable: Draggable) => DOMTargetSelector|Array<Number>)} [container] * @property {Boolean|DraggableAxisParam} [x] * @property {Boolean|DraggableAxisParam} [y] * @property {TweenModifier} [modifier] * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap] * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [containerPadding] * @property {Number|((draggable: Draggable) => Number)} [containerFriction] * @property {Number|((draggable: Draggable) => Number)} [releaseContainerFriction] * @property {Number|((draggable: Draggable) => Number)} [dragSpeed] * @property {Number|DraggableDragThresholdParams|((draggable: Draggable) => Number|DraggableDragThresholdParams)} [dragThreshold] * @property {Number|((draggable: Draggable) => Number)} [scrollSpeed] * @property {Number|((draggable: Draggable) => Number)} [scrollThreshold] * @property {Number|((draggable: Draggable) => Number)} [minVelocity] * @property {Number|((draggable: Draggable) => Number)} [maxVelocity] * @property {Number|((draggable: Draggable) => Number)} [velocityMultiplier] * @property {Number} [releaseMass] * @property {Number} [releaseStiffness] * @property {Number} [releaseDamping] * @property {Boolean} [releaseDamping] * @property {EasingParam} [releaseEase] * @property {Boolean|DraggableCursorParams|((draggable: Draggable) => Boolean|DraggableCursorParams)} [cursor] * @property {Callback<Draggable>} [onGrab] * @property {Callback<Draggable>} [onDrag] * @property {Callback<Draggable>} [onRelease] * @property {Callback<Draggable>} [onUpdate] * @property {Callback<Draggable>} [onSettle] * @property {Callback<Draggable>} [onSnap] * @property {Callback<Draggable>} [onResize] * @property {Callback<Draggable>} [onAfterResize] */ // Text types /** * @typedef {Object} SplitTemplateParams * @property {false|String} [class] * @property {Boolean|'hidden'|'clip'|'visible'|'scroll'|'auto'} [wrap] * @property {Boolean|'top'|'right'|'bottom'|'left'|'center'} [clone] */ /** * @typedef {Boolean|String} SplitValue */ /** * @callback SplitFunctionValue * @param {Node|HTMLElement} [value] * @return String */ /** * @typedef {Object} TextSplitterParams * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [lines] * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [words] * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [chars] * @property {Boolean} [accessible] * @property {Boolean} [includeSpaces] * @property {Boolean} [debug] */ // SVG types /** * @typedef {SVGGeometryElement & { * setAttribute(name: 'draw', value: `${number} ${number}`): void; * draw: `${number} ${number}`; * }} DrawableSVGGeometry */ // Environments // TODO: Do we need to check if we're running inside a worker ? const isBrowser = typeof window !== 'undefined'; /** @type {Window & {AnimeJS: Array}|null} */ const win = isBrowser ? /** @type {Window & {AnimeJS: Array}} */(/** @type {unknown} */(window)) : null; /** @type {Document|null} */ const doc = isBrowser ? document : null; // Enums /** @enum {Number} */ const tweenTypes = { OBJECT: 0, ATTRIBUTE: 1, CSS: 2, TRANSFORM: 3, CSS_VAR: 4, }; /** @enum {Number} */ const valueTypes = { NUMBER: 0, UNIT: 1, COLOR: 2, COMPLEX: 3, }; /** @enum {Number} */ const tickModes = { NONE: 0, AUTO: 1, FORCE: 2, }; /** @enum {Number} */ const compositionTypes = { replace: 0, none: 1, blend: 2, }; // Cache symbols const isRegisteredTargetSymbol = Symbol(); const isDomSymbol = Symbol(); const isSvgSymbol = Symbol(); const transformsSymbol = Symbol(); const morphPointsSymbol = Symbol(); const proxyTargetSymbol = Symbol(); // Numbers const minValue = 1e-11; const maxValue = 1e12; const K = 1e3; const maxFps = 120; // Strings const emptyString = ''; const cssVarPrefix = 'var('; const shortTransforms = /*#__PURE__*/ (() => { const map = new Map(); map.set('x', 'translateX'); map.set('y', 'translateY'); map.set('z', 'translateZ'); return map; })(); const validTransforms = [ 'translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'matrix', 'matrix3d', 'perspective', ]; const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {}); // Functions /** @return {void} */ const noop = () => {}; // Regex const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i; const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i; const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i; const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i; const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i; // export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g; const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi; // export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i; const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i; const lowerCaseRgx = /([a-z])([A-Z])/g; const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in () const relativeValuesExecRgx = /(\*=|\+=|-=)/; const cssVariableMatchRgx = /var\(\s*(--[\w-]+)(?:\s*,\s*([^)]+))?\s*\)/; /** @type {DefaultsParams} */ const defaults = { id: null, keyframes: null, playbackEase: null, playbackRate: 1, frameRate: maxFps, loop: 0, reversed: false, alternate: false, autoplay: true, persist: false, duration: K, delay: 0, loopDelay: 0, ease: 'out(2)', composition: compositionTypes.replace, modifier: v => v, onBegin: noop, onBeforeUpdate: noop, onUpdate: noop, onLoop: noop, onPause: noop, onComplete: noop, onRender: noop, }; const scope = { /** @type {Scope} */ current: null, /** @type {Document|DOMTarget} */ root: doc, }; const globals = { /** @type {DefaultsParams} */ defaults, /** @type {Number} */ precision: 4, /** @type {Number} equals 1 in ms mode, 0.001 in s mode */ timeScale: 1, /** @type {Number} */ tickThreshold: 200, }; const globalVersions = { version: '4.2.2', engine: null }; if (isBrowser) { if (!win.AnimeJS) win.AnimeJS = []; win.AnimeJS.push(globalVersions); } // Strings /** * @param {String} str * @return {String} */ const toLowerCase = str => str.replace(lowerCaseRgx, '$1-$2').toLowerCase(); /** * Prioritize this method instead of regex when possible * @param {String} str * @param {String} sub * @return {Boolean} */ const stringStartsWith = (str, sub) => str.indexOf(sub) === 0; // Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement. const now = Date.now; // Types checkers const isArr = Array.isArray; /**@param {any} a @return {a is Record<String, any>} */ const isObj = a => a && a.constructor === Object; /**@param {any} a @return {a is Number} */ const isNum = a => typeof a === 'number' && !isNaN(a); /**@param {any} a @return {a is String} */ const isStr = a => typeof a === 'string'; /**@param {any} a @return {a is Function} */ const isFnc = a => typeof a === 'function'; /**@param {any} a @return {a is undefined} */ const isUnd = a => typeof a === 'undefined'; /**@param {any} a @return {a is null | undefined} */ const isNil = a => isUnd(a) || a === null; /**@param {any} a @return {a is SVGElement} */ const isSvg = a => isBrowser && a instanceof SVGElement; /**@param {any} a @return {Boolean} */ const isHex = a => hexTestRgx.test(a); /**@param {any} a @return {Boolean} */ const isRgb = a => stringStartsWith(a, 'rgb'); /**@param {any} a @return {Boolean} */ const isHsl = a => stringStartsWith(a, 'hsl'); /**@param {any} a @return {Boolean} */ const isCol = a => isHex(a) || isRgb(a) || isHsl(a); /**@param {any} a @return {Boolean} */ const isKey = a => !globals.defaults.hasOwnProperty(a); // SVG // Consider the following as CSS animation // CSS opacity animation has better default values (opacity: 1 instead of 0)) // rotate is more commonly intended to be used as a transform const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color']; /** * @param {Target} el * @param {String} propertyName * @return {Boolean} */ const isValidSVGAttribute = (el, propertyName) => { if (svgCssReservedProperties.includes(propertyName)) return false; if (el.getAttribute(propertyName) || propertyName in el) { if (propertyName === 'scale') { // Scale const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode); // Only consider scale as a valid SVG attribute on filter element return elParentNode && elParentNode.tagName === 'filter'; } return true; } }; // Number /** * @param {Number|String} str * @return {Number} */ const parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */(str)) : /** @type {Number} */(str); // Math const pow = Math.pow; const sqrt = Math.sqrt; const sin = Math.sin; const cos = Math.cos; const abs = Math.abs; const exp = Math.exp; const ceil = Math.ceil; const floor = Math.floor; const asin = Math.asin; const max = Math.max; const atan2 = Math.atan2; const PI = Math.PI; const _round = Math.round; /** * Clamps a value between min and max bounds * * @param {Number} v - Value to clamp * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {Number} */ const clamp$1 = (v, min, max) => v < min ? min : v > max ? max : v; const powCache = {}; /** * Rounds a number to specified decimal places * * @param {Number} v - Value to round * @param {Number} decimalLength - Number of decimal places * @return {Number} */ const round$1 = (v, decimalLength) => { if (decimalLength < 0) return v; if (!decimalLength) return _round(v); let p = powCache[decimalLength]; if (!p) p = powCache[decimalLength] = 10 ** decimalLength; return _round(v * p) / p; }; /** * Snaps a value to nearest increment or array value * * @param {Number} v - Value to snap * @param {Number|Array<Number>} increment - Step size or array of snap points * @return {Number} */ const snap$1 = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v; /** * Linear interpolation between two values * * @param {Number} start - Starting value * @param {Number} end - Ending value * @param {Number} factor - Interpolation factor in the range [0, 1] * @return {Number} The interpolated value */ const lerp$1 = (start, end, factor) => start + (end - start) * factor; /** * Replaces infinity with maximum safe value * * @param {Number} v - Value to check * @return {Number} */ const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v; /** * Normalizes time value with minimum threshold * * @param {Number} v - Time value to normalize * @return {Number} */ const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round$1(v, 11)); // Arrays /** * @template T * @param {T[]} a * @return {T[]} */ const cloneArray = a => isArr(a) ? [ ...a ] : a; // Objects /** * @template T * @template U * @param {T} o1 * @param {U} o2 * @return {T & U} */ const mergeObjects = (o1, o2) => { const merged = /** @type {T & U} */({ ...o1 }); for (let p in o2) { const o1p = /** @type {T & U} */(o1)[p]; merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p; } return merged; }; // Linked lists /** * @param {Object} parent * @param {Function} callback * @param {Boolean} [reverse] * @param {String} [prevProp] * @param {String} [nextProp] * @return {void} */ const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => { let next = parent._head; let adjustedNextProp = nextProp; if (reverse) { next = parent._tail; adjustedNextProp = prevProp; } while (next) { const currentNext = next[adjustedNextProp]; callback(next); next = currentNext; } }; /** * @param {Object} parent * @param {Object} child * @param {String} [prevProp] * @param {String} [nextProp] * @return {void} */ const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => { const prev = child[prevProp]; const next = child[nextProp]; prev ? prev[nextProp] = next : parent._head = next; next ? next[prevProp] = prev : parent._tail = prev; child[prevProp] = null; child[nextProp] = null; }; /** * @param {Object} parent * @param {Object} child * @param {Function} [sortMethod] * @param {String} prevProp * @param {String} nextProp * @return {void} */ const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => { let prev = parent._tail; while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp]; const next = prev ? prev[nextProp] : parent._head; prev ? prev[nextProp] = child : parent._head = child; next ? next[prevProp] = child : parent._tail = child; child[prevProp] = prev; child[nextProp] = next; }; /** * @param {DOMTarget} target * @param {String} propName * @param {Object} animationInlineStyles * @return {String} */ const parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
true
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/index.js
dist/modules/index.js
/** * Anime.js - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { Timer, createTimer } from './timer/timer.js'; export { JSAnimation, animate } from './animation/animation.js'; export { Timeline, createTimeline } from './timeline/timeline.js'; export { Animatable, createAnimatable } from './animatable/animatable.js'; export { Draggable, createDraggable } from './draggable/draggable.js'; export { Scope, createScope } from './scope/scope.js'; export { ScrollObserver, onScroll, scrollContainers } from './events/scroll.js'; export { engine } from './engine/engine.js'; import * as index from './easings/index.js'; export { index as easings }; import * as index$1 from './utils/index.js'; export { index$1 as utils }; import * as index$2 from './svg/index.js'; export { index$2 as svg }; import * as index$3 from './text/index.js'; export { index$3 as text }; export { WAAPIAnimation, waapi } from './waapi/waapi.js'; export { cubicBezier } from './easings/cubic-bezier/index.js'; export { steps } from './easings/steps/index.js'; export { linear } from './easings/linear/index.js'; export { irregular } from './easings/irregular/index.js'; export { Spring, createSpring, spring } from './easings/spring/index.js'; export { eases } from './easings/eases/parser.js'; export { clamp, damp, degToRad, lerp, mapRange, padEnd, padStart, radToDeg, round, roundPad, snap, wrap } from './utils/chainable.js'; export { createSeededRandom, random, randomPick, shuffle } from './utils/random.js'; export { keepTime, sync } from './utils/time.js'; export { cleanInlineStyles } from './core/styles.js'; export { registerTargets as $ } from './core/targets.js'; export { get, remove, set } from './utils/target.js'; export { stagger } from './utils/stagger.js'; export { createMotionPath } from './svg/motionpath.js'; export { createDrawable } from './svg/drawable.js'; export { morphTo } from './svg/morphto.js'; export { TextSplitter, split, splitText } from './text/split.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/scope/index.js
dist/modules/scope/index.js
/** * Anime.js - scope - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { Scope, createScope } from './scope.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/scope/scope.js
dist/modules/scope/scope.js
/** * Anime.js - scope - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { doc, win } from '../core/consts.js'; import { globals, scope } from '../core/globals.js'; import { mergeObjects, isFnc } from '../core/helpers.js'; import { parseTargets } from '../core/targets.js'; import { keepTime } from '../utils/time.js'; /** * @import { * Tickable, * ScopeParams, * DOMTarget, * ReactRef, * AngularRef, * DOMTargetSelector, * DefaultsParams, * ScopeConstructorCallback, * ScopeCleanupCallback, * Revertible, * ScopeMethod, * ScopedCallback, * } from '../types/index.js' */ class Scope { /** @param {ScopeParams} [parameters] */ constructor(parameters = {}) { if (scope.current) scope.current.register(this); const rootParam = parameters.root; /** @type {Document|DOMTarget} */ let root = doc; if (rootParam) { root = /** @type {ReactRef} */(rootParam).current || /** @type {AngularRef} */(rootParam).nativeElement || parseTargets(/** @type {DOMTargetSelector} */(rootParam))[0] || doc; } const scopeDefaults = parameters.defaults; const globalDefault = globals.defaults; const mediaQueries = parameters.mediaQueries; /** @type {DefaultsParams} */ this.defaults = scopeDefaults ? mergeObjects(scopeDefaults, globalDefault) : globalDefault; /** @type {Document|DOMTarget} */ this.root = root; /** @type {Array<ScopeConstructorCallback>} */ this.constructors = []; /** @type {Array<ScopeCleanupCallback>} */ this.revertConstructors = []; /** @type {Array<Revertible>} */ this.revertibles = []; /** @type {Array<ScopeConstructorCallback | ((scope: this) => Tickable)>} */ this.constructorsOnce = []; /** @type {Array<ScopeCleanupCallback>} */ this.revertConstructorsOnce = []; /** @type {Array<Revertible>} */ this.revertiblesOnce = []; /** @type {Boolean} */ this.once = false; /** @type {Number} */ this.onceIndex = 0; /** @type {Record<String, ScopeMethod>} */ this.methods = {}; /** @type {Record<String, Boolean>} */ this.matches = {}; /** @type {Record<String, MediaQueryList>} */ this.mediaQueryLists = {}; /** @type {Record<String, any>} */ this.data = {}; if (mediaQueries) { for (let mq in mediaQueries) { const _mq = win.matchMedia(mediaQueries[mq]); this.mediaQueryLists[mq] = _mq; _mq.addEventListener('change', this); } } } /** * @param {Revertible} revertible */ register(revertible) { const store = this.once ? this.revertiblesOnce : this.revertibles; store.push(revertible); } /** * @template T * @param {ScopedCallback<T>} cb * @return {T} */ execute(cb) { let activeScope = scope.current; let activeRoot = scope.root; let activeDefaults = globals.defaults; scope.current = this; scope.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); scope.current = activeScope; scope.root = activeRoot; globals.defaults = activeDefaults; return returned; } /** * @return {this} */ refresh() { this.onceIndex = 0; this.execute(() => { let i = this.revertibles.length; let y = this.revertConstructors.length; while (i--) this.revertibles[i].revert(); while (y--) this.revertConstructors[y](this); this.revertibles.length = 0; this.revertConstructors.length = 0; this.constructors.forEach((/** @type {ScopeConstructorCallback} */constructor) => { const revertConstructor = constructor(this); if (isFnc(revertConstructor)) { this.revertConstructors.push(revertConstructor); } }); }); return this; } /** * @overload * @param {String} a1 * @param {ScopeMethod} a2 * @return {this} * * @overload * @param {ScopeConstructorCallback} a1 * @return {this} * * @param {String|ScopeConstructorCallback} a1 * @param {ScopeMethod} [a2] */ add(a1, a2) { this.once = false; if (isFnc(a1)) { const constructor = /** @type {ScopeConstructorCallback} */(a1); this.constructors.push(constructor); this.execute(() => { const revertConstructor = constructor(this); if (isFnc(revertConstructor)) { this.revertConstructors.push(revertConstructor); } }); } else { this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args)); } return this; } /** * @param {ScopeConstructorCallback} scopeConstructorCallback * @return {this} */ addOnce(scopeConstructorCallback) { this.once = true; if (isFnc(scopeConstructorCallback)) { const currentIndex = this.onceIndex++; const tracked = this.constructorsOnce[currentIndex]; if (tracked) return this; const constructor = /** @type {ScopeConstructorCallback} */(scopeConstructorCallback); this.constructorsOnce[currentIndex] = constructor; this.execute(() => { const revertConstructor = constructor(this); if (isFnc(revertConstructor)) { this.revertConstructorsOnce.push(revertConstructor); } }); } return this; } /** * @param {(scope: this) => Tickable} cb * @return {Tickable} */ keepTime(cb) { this.once = true; const currentIndex = this.onceIndex++; const tracked = /** @type {(scope: this) => Tickable} */(this.constructorsOnce[currentIndex]); if (isFnc(tracked)) return tracked(this); const constructor = /** @type {(scope: this) => Tickable} */(keepTime(cb)); this.constructorsOnce[currentIndex] = constructor; let trackedTickable; this.execute(() => { trackedTickable = constructor(this); }); return trackedTickable; } /** * @param {Event} e */ handleEvent(e) { switch (e.type) { case 'change': this.refresh(); break; } } revert() { const revertibles = this.revertibles; const revertConstructors = this.revertConstructors; const revertiblesOnce = this.revertiblesOnce; const revertConstructorsOnce = this.revertConstructorsOnce; const mqs = this.mediaQueryLists; let i = revertibles.length; let j = revertConstructors.length; let k = revertiblesOnce.length; let l = revertConstructorsOnce.length; while (i--) revertibles[i].revert(); while (j--) revertConstructors[j](this); while (k--) revertiblesOnce[k].revert(); while (l--) revertConstructorsOnce[l](this); for (let mq in mqs) mqs[mq].removeEventListener('change', this); revertibles.length = 0; revertConstructors.length = 0; this.constructors.length = 0; revertiblesOnce.length = 0; revertConstructorsOnce.length = 0; this.constructorsOnce.length = 0; this.onceIndex = 0; this.matches = {}; this.methods = {}; this.mediaQueryLists = {}; this.data = {}; } } /** * @param {ScopeParams} [params] * @return {Scope} */ const createScope = params => new Scope(params); export { Scope, createScope };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/draggable/index.js
dist/modules/draggable/index.js
/** * Anime.js - draggable - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { Draggable, createDraggable } from './draggable.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/draggable/draggable.js
dist/modules/draggable/draggable.js
/** * Anime.js - draggable - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { globals, scope } from '../core/globals.js'; import { doc, win, noop, maxValue, compositionTypes } from '../core/consts.js'; import { parseTargets } from '../core/targets.js'; import { isUnd, isObj, isArr, now, atan2, round, max, snap, clamp, isNum, abs, sqrt, cos, sin, isFnc } from '../core/helpers.js'; import { setValue } from '../core/values.js'; import { mapRange } from '../utils/number.js'; import { Timer } from '../timer/timer.js'; import { JSAnimation } from '../animation/animation.js'; import { removeTargetsFromRenderable } from '../animation/composition.js'; import { Animatable } from '../animatable/animatable.js'; import { parseEase, eases } from '../easings/eases/parser.js'; import { spring } from '../easings/spring/index.js'; import { get, set } from '../utils/target.js'; /** * @import { * DOMTarget, * DOMTargetSelector, * DraggableCursorParams, * DraggableDragThresholdParams, * TargetsParam, * DraggableParams, * EasingFunction, * Callback, * AnimatableParams, * DraggableAxisParam, * AnimatableObject, * EasingParam, * } from '../types/index.js' */ /** * @import { * Spring, * } from '../easings/spring/index.js' */ /** * @param {Event} e */ const preventDefault = e => { if (e.cancelable) e.preventDefault(); }; class DOMProxy { /** @param {Object} el */ constructor(el) { this.el = el; this.zIndex = 0; this.parentElement = null; this.classList = { add: noop, remove: noop, }; } get x() { return this.el.x || 0 }; set x(v) { this.el.x = v; }; get y() { return this.el.y || 0 }; set y(v) { this.el.y = v; }; get width() { return this.el.width || 0 }; set width(v) { this.el.width = v; }; get height() { return this.el.height || 0 }; set height(v) { this.el.height = v; }; getBoundingClientRect() { return { top: this.y, right: this.x, bottom: this.y + this.height, left: this.x + this.width, } } } class Transforms { /** * @param {DOMTarget|DOMProxy} $el */ constructor($el) { this.$el = $el; this.inlineTransforms = []; this.point = new DOMPoint(); this.inversedMatrix = this.getMatrix().inverse(); } /** * @param {Number} x * @param {Number} y * @return {DOMPoint} */ normalizePoint(x, y) { this.point.x = x; this.point.y = y; return this.point.matrixTransform(this.inversedMatrix); } /** * @callback TraverseParentsCallback * @param {DOMTarget} $el * @param {Number} i */ /** * @param {TraverseParentsCallback} cb */ traverseUp(cb) { let $el = /** @type {DOMTarget|Document} */(this.$el.parentElement), i = 0; while ($el && $el !== doc) { cb(/** @type {DOMTarget} */($el), i); $el = /** @type {DOMTarget} */($el.parentElement); i++; } } getMatrix() { const matrix = new DOMMatrix(); this.traverseUp($el => { const transformValue = getComputedStyle($el).transform; if (transformValue) { const elMatrix = new DOMMatrix(transformValue); matrix.preMultiplySelf(elMatrix); } }); return matrix; } remove() { this.traverseUp(($el, i) => { this.inlineTransforms[i] = $el.style.transform; $el.style.transform = 'none'; }); } revert() { this.traverseUp(($el, i) => { const ct = this.inlineTransforms[i]; if (ct === '') { $el.style.removeProperty('transform'); } else { $el.style.transform = ct; } }); } } /** * @template {Array<Number>|DOMTargetSelector|String|Number|Boolean|Function|DraggableCursorParams|DraggableDragThresholdParams} T * @param {T | ((draggable: Draggable) => T)} value * @param {Draggable} draggable * @return {T} */ const parseDraggableFunctionParameter = (value, draggable) => value && isFnc(value) ? /** @type {Function} */(value)(draggable) : /** @type {T} */(value); let zIndex = 0; class Draggable { /** * @param {TargetsParam} target * @param {DraggableParams} [parameters] */ constructor(target, parameters = {}) { if (!target) return; if (scope.current) scope.current.register(this); const paramX = parameters.x; const paramY = parameters.y; const trigger = parameters.trigger; const modifier = parameters.modifier; const ease = parameters.releaseEase; const customEase = ease && parseEase(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 = get(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.dragThreshold = 3; /** @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) : spring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); /** @type {Spring} */ this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : spring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); /** @type {EasingFunction} */ this.releaseEase = customEase || eases.outQuint; /** @type {Boolean} */ this.hasReleaseSpring = hasSpring; /** @type {Callback<this>} */ this.onGrab = parameters.onGrab || noop; /** @type {Callback<this>} */ this.onDrag = parameters.onDrag || noop; /** @type {Callback<this>} */ this.onRelease = parameters.onRelease || noop; /** @type {Callback<this>} */ this.onUpdate = parameters.onUpdate || noop; /** @type {Callback<this>} */ this.onSettle = parameters.onSettle || noop; /** @type {Callback<this>} */ this.onSnap = parameters.onSnap || noop; /** @type {Callback<this>} */ this.onResize = parameters.onResize || noop; /** @type {Callback<this>} */ this.onAfterResize = parameters.onAfterResize || noop; /** @type {[Number, Number]} */ this.disabled = [0, 0]; /** @type {AnimatableParams} */ const animatableParams = {}; if (modifier) animatableParams.modifier = modifier; if (isUnd(paramX) || paramX === true) { animatableParams[xProp] = 0; } else if (isObj(paramX)) { const paramXObject = /** @type {DraggableAxisParam} */(paramX); const animatableXParams = {}; if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier; if (paramXObject.composition) animatableXParams.composition = paramXObject.composition; animatableParams[xProp] = animatableXParams; } else if (paramX === false) { animatableParams[xProp] = 0; this.disabled[0] = 1; } if (isUnd(paramY) || paramY === true) { animatableParams[yProp] = 0; } else if (isObj(paramY)) { const paramYObject = /** @type {DraggableAxisParam} */(paramY); const animatableYParams = {}; if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier; if (paramYObject.composition) animatableYParams.composition = paramYObject.composition; animatableParams[yProp] = animatableYParams; } else if (paramY === false) { animatableParams[yProp] = 0; this.disabled[1] = 1; } /** @type {AnimatableObject} */ this.animate = /** @type {AnimatableObject} */(new Animatable(this.$target, animatableParams)); // Internal props this.xProp = xProp; this.yProp = yProp; this.destX = 0; this.destY = 0; this.deltaX = 0; this.deltaY = 0; this.scroll = {x: 0, y: 0}; /** @type {[Number, Number, Number, Number]} */ this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y /** @type {[Number, Number]} */ this.snapped = [0, 0]; // x, y /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */ this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2 /** @type {[Number, Number]} */ this.scrollView = [0, 0]; // w, h /** @type {[Number, Number, Number, Number]} */ this.dragArea = [0, 0, 0, 0]; // x, y, w, h /** @type {[Number, Number, Number, Number]} */ this.containerBounds = [-maxValue, maxValue, maxValue, -maxValue]; // t, r, b, l /** @type {[Number, Number, Number, Number]} */ this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l /** @type {[Number, Number, Number, Number]} */ this.targetBounds = [0, 0, 0, 0]; // t, r, b, l /** @type {[Number, Number]} */ this.window = [0, 0]; // w, h /** @type {[Number, Number, Number]} */ this.velocityStack = [0, 0, 0]; /** @type {Number} */ this.velocityStackIndex = 0; /** @type {Number} */ this.velocityTime = now(); /** @type {Number} */ this.velocity = 0; /** @type {Number} */ this.angle = 0; /** @type {JSAnimation} */ this.cursorStyles = null; /** @type {JSAnimation} */ this.triggerStyles = null; /** @type {JSAnimation} */ this.bodyStyles = null; /** @type {JSAnimation} */ this.targetStyles = null; /** @type {JSAnimation} */ this.touchActionStyles = null; this.transforms = new Transforms(this.$target); this.overshootCoords = { x: 0, y: 0 }; this.overshootTicker = new Timer({ autoplay: false, onUpdate: () => { this.updated = true; this.manual = true; // Use a duration of 1 to prevent the animatable from completing immediately to prevent issues with onSettle() // https://github.com/juliangarnier/anime/issues/1045 if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 1); if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 1); }, onComplete: () => { this.manual = false; if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0); if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0); }, }, null, 0).init(); this.updateTicker = new Timer({ autoplay: false, onUpdate: () => this.update() }, null,0,).init(); 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.callbacks.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; // Check if dx or dy are not 0 to check if the draggable has actually moved // https://github.com/juliangarnier/anime/issues/1032 if (hasUpdated && (dx || dy)) { this.onUpdate(this); } if (!hasReleased) { this.updated = false; } else { this.computeVelocity(dx, dy); this.angle = atan2(dy, dx); } }; this.animate.callbacks.onComplete = () => { if ((!this.grabbed && this.released)) { // Set released 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 {Number} dx * @param {Number} dy * @return {Number} */ 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} x * @param {Boolean} [muteUpdateCallback] * @return {this} */ setX(x, muteUpdateCallback = false) { if (this.disabled[0]) return; const v = round(x, 5); this.overshootTicker.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} y * @param {Boolean} [muteUpdateCallback] * @return {this} */ setY(y, muteUpdateCallback = false) { if (this.disabled[1]) return; const v = round(y, 5); this.overshootTicker.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; } get x() { return round(/** @type {Number} */(this.animate[this.xProp]()), globals.precision); } set x(x) { this.setX(x, false); } get y() { return round(/** @type {Number} */(this.animate[this.yProp]()), globals.precision); } set y(y) { this.setY(y, false); } get progressX() { return mapRange(this.x, this.containerBounds[3], this.containerBounds[1], 0, 1); } set progressX(x) { this.setX(mapRange(x, 0, 1, this.containerBounds[3], this.containerBounds[1]), false); } get progressY() { return mapRange(this.y, this.containerBounds[0], this.containerBounds[2], 0, 1); } set progressY(y) { this.setY(mapRange(y, 0, 1, this.containerBounds[0], this.containerBounds[2]), false); } updateScrollCoords() { const sx = round(this.useWin ? win.scrollX : this.$container.scrollLeft, 0); const sy = round(this.useWin ? win.scrollY : this.$container.scrollTop, 0); const [ cpt, cpr, cpb, cpl ] = this.containerPadding; const threshold = this.scrollThreshold; this.scroll.x = sx; this.scroll.y = sy; this.scrollBounds[0] = sy - this.targetBounds[0] + cpt - threshold; this.scrollBounds[1] = sx - this.targetBounds[1] - cpr + threshold; this.scrollBounds[2] = sy - this.targetBounds[2] - cpb + threshold; this.scrollBounds[3] = sx - this.targetBounds[3] + cpl - threshold; } updateBoundingValues() { const $container = this.$container; // Return early if no $container defined to prevents error when reading scrollWidth / scrollHeight // https://github.com/juliangarnier/anime/issues/1064 if (!$container) return; const cx = this.x; const cy = this.y; const cx2 = this.coords[2]; const cy2 = this.coords[3]; // Prevents interfering with the scroll area in cases the target is outside of the container // Make sure the temp coords are also adjuset to prevents wrong delta calculation on updates this.coords[2] = 0; this.coords[3] = 0; this.setX(0, true); this.setY(0, true); this.transforms.remove(); const iw = this.window[0] = win.innerWidth; const ih = this.window[1] = win.innerHeight; const uw = this.useWin; const sw = $container.scrollWidth; const sh = $container.scrollHeight; const fx = this.fixed; const transformContainerRect = $container.getBoundingClientRect(); const [ cpt, cpr, cpb, cpl ] = this.containerPadding; this.dragArea[0] = uw ? 0 : transformContainerRect.left; this.dragArea[1] = uw ? 0 : transformContainerRect.top; this.scrollView[0] = uw ? clamp(sw, iw, sw) : sw; this.scrollView[1] = uw ? clamp(sh, ih, sh) : sh; this.updateScrollCoords(); const { width, height, left, top, right, bottom } = $container.getBoundingClientRect(); this.dragArea[2] = round(uw ? clamp(width, iw, iw) : width, 0); this.dragArea[3] = round(uw ? clamp(height, ih, ih) : height, 0); const containerOverflow = get($container, 'overflow'); const visibleOverflow = containerOverflow === 'visible'; const hiddenOverflow = containerOverflow === 'hidden'; this.canScroll = fx ? false : this.contained && (($container === doc.body && visibleOverflow) || (!hiddenOverflow && !visibleOverflow)) && (sw > this.dragArea[2] + cpl - cpr || sh > this.dragArea[3] + cpt - cpb) && (!this.containerArray || (this.containerArray && !isArr(this.containerArray))); if (this.contained) { const sx = this.scroll.x; const sy = this.scroll.y; const canScroll = this.canScroll; const targetRect = this.$target.getBoundingClientRect(); const hiddenLeft = canScroll ? uw ? 0 : $container.scrollLeft : 0; const hiddenTop = canScroll ? uw ? 0 : $container.scrollTop : 0; const hiddenRight = canScroll ? this.scrollView[0] - hiddenLeft - width : 0; const hiddenBottom = canScroll ? this.scrollView[1] - hiddenTop - height : 0; this.targetBounds[0] = round((targetRect.top + sy) - (uw ? 0 : top), 0); this.targetBounds[1] = round((targetRect.right + sx) - (uw ? iw : right), 0); this.targetBounds[2] = round((targetRect.bottom + sy) - (uw ? ih : bottom), 0); this.targetBounds[3] = round((targetRect.left + sx) - (uw ? 0 : left), 0); if (this.containerArray) { this.containerBounds[0] = this.containerArray[0] + cpt; this.containerBounds[1] = this.containerArray[1] - cpr; this.containerBounds[2] = this.containerArray[2] - cpb; this.containerBounds[3] = this.containerArray[3] + cpl; } else { this.containerBounds[0] = -round(targetRect.top - (fx ? clamp(top, 0, ih) : top) + hiddenTop - cpt, 0); this.containerBounds[1] = -round(targetRect.right - (fx ? clamp(right, 0, iw) : right) - hiddenRight + cpr, 0); this.containerBounds[2] = -round(targetRect.bottom - (fx ? clamp(bottom, 0, ih) : bottom) - hiddenBottom + cpb, 0); this.containerBounds[3] = -round(targetRect.left - (fx ? clamp(left, 0, iw) : left) + hiddenLeft - cpl, 0); } } this.transforms.revert(); // Restore coordinates this.coords[2] = cx2; this.coords[3] = cy2; this.setX(cx, true); this.setY(cy, true); } /** * @param {Array} bounds * @param {Number} x * @param {Number} y * @return {Number} */ isOutOfBounds(bounds, x, y) { // Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB 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; } 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; } const parsedDragThreshold = parseDraggableFunctionParameter(params.dragThreshold, this); const dragThreshold = { mouse: 3, touch: 7 }; if (isNum(parsedDragThreshold)) { dragThreshold.mouse = parsedDragThreshold; dragThreshold.touch = parsedDragThreshold; } else if (parsedDragThreshold) { const { mouse, touch } = parsedDragThreshold; if (!isUnd(mouse)) dragThreshold.mouse = mouse; if (!isUnd(touch)) dragThreshold.touch = touch; } 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.dragThreshold = this.isFinePointer ? dragThreshold.mouse : dragThreshold.touch; 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); } update() { this.updateScrollCoords(); if (this.canScroll) { const [ cpt, cpr, cpb, cpl ] = this.containerPadding; const [ sw, sh ] = this.scrollView; const daw = this.dragArea[2]; const dah = this.dragArea[3]; const csx = this.scroll.x; const csy = this.scroll.y; const nsw = this.$container.scrollWidth; const nsh = this.$container.scrollHeight; const csw = this.useWin ? clamp(nsw, this.window[0], nsw) : nsw; const csh = this.useWin ? clamp(nsh, this.window[1], nsh) : nsh; const swd = sw - csw; const shd = sh - csh; // Handle cases where the scrollarea dimensions changes during drag if (this.dragged && swd > 0) { this.coords[0] -= swd; this.scrollView[0] = csw; } if (this.dragged && shd > 0) { this.coords[1] -= shd; this.scrollView[1] = csh; } // Handle autoscroll when target is at the edges of the scroll bounds const s = this.scrollSpeed * 10; const threshold = this.scrollThreshold; const [ x, y ] = this.coords; const [ st, sr, sb, sl ] = this.scrollBounds; const t = round(clamp((y - st + cpt) / threshold, -1, 0) * s, 0); const r = round(clamp((x - sr - cpr) / threshold, 0, 1) * s, 0); const b = round(clamp((y - sb - cpb) / threshold, 0, 1) * s, 0); const l = round(clamp((x - sl + cpl) / threshold, -1, 0) * s, 0); if (t || b || l || r) { const [nx, ny] = this.disabled; let scrollX = csx; let scrollY = csy; if (!nx) { scrollX = round(clamp(csx + (l || r), 0, sw - daw), 0); this.coords[0] -= csx - scrollX; } if (!ny) { scrollY = round(clamp(csy + (t || b), 0, sh - dah), 0); this.coords[1] -= csy - scrollY; } // Note: Safari mobile requires to use different scroll methods depending if using the window or not if (this.useWin) { this.$scrollContainer.scrollBy(-(csx - scrollX), -(csy - scrollY)); } else { this.$scrollContainer.scrollTo(scrollX, scrollY); } } } const [ ct, cr, cb, cl ] = this.containerBounds; const [ px1, py1, px2, py2, px3, py3 ] = this.pointer; this.coords[0] += (px1 - px3) * this.dragSpeed; this.coords[1] += (py1 - py3) * this.dragSpeed; this.pointer[4] = px1; this.pointer[5] = py1; const [ cx, cy ] = this.coords; const [ sx, sy ] = this.snapped; const cf = (1 - this.containerFriction) * this.dragSpeed; this.setX(cx > cr ? cr + (cx - cr) * cf : cx < cl ? cl + (cx - cl) * cf : cx, false); this.setY(cy > cb ? cb + (cy - cb) * cf : cy < ct ? ct + (cy - ct) * cf : cy, false); this.computeVelocity(px1 - px3, py1 - py3); this.angle = atan2(py1 - py2, px1 - px2); const [ nsx, nsy ] = this.snapped; if (nsx !== sx && this.snapX || nsy !== sy && this.snapY) { this.onSnap(this); } } stop() { this.updateTicker.pause(); this.overshootTicker.pause(); // Pauses the in bounds onRelease animations for (let prop in this.animate.animations) this.animate.animations[prop].pause(); removeTargetsFromRenderable([this], null, 'x'); removeTargetsFromRenderable([this], null, 'y'); removeTargetsFromRenderable([this], null, 'progressX'); removeTargetsFromRenderable([this], null, 'progressY'); removeTargetsFromRenderable([this.scroll]); // Removes any active animations on the container scroll removeTargetsFromRenderable([this.overshootCoords]); // Removes active overshoot animations return this; } /** * @param {Number} [duration] * @param {Number} [gap] * @param {EasingParam} [ease] * @return {this} */ scrollInView(duration, gap = 0, ease = eases.inOutQuad) { this.updateScrollCoords(); const x = this.destX; const y = this.destY; const scroll = this.scroll; const scrollBounds = this.scrollBounds; const canScroll = this.canScroll; if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) { const [ st, sr, sb, sl ] = scrollBounds; const t = round(clamp(y - st, -maxValue, 0), 0); const r = round(clamp(x - sr, 0, maxValue), 0); const b = round(clamp(y - sb, 0, maxValue), 0); const l = round(clamp(x - sl, -maxValue, 0), 0); new JSAnimation(scroll, { x: round(scroll.x + (l ? l - gap : r ? r + gap : 0), 0), y: round(scroll.y + (t ? t - gap : b ? b + gap : 0), 0), duration: isUnd(duration) ? 350 * globals.timeScale : duration, ease, onUpdate: () => { this.canScroll = false; this.$scrollContainer.scrollTo(scroll.x, scroll.y); } }).init().then(() => { this.canScroll = canScroll; }); } return this; } handleHover() { if (this.isFinePointer && this.cursor && !this.cursorStyles) { this.cursorStyles = set(this.$trigger, { cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover }); } } /** * @param {Number} [duration] * @param {Number} [gap] * @param {EasingParam} [ease] * @return {this} */ 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 {MouseEvent|TouchEvent} e */ handleDown(e) { const $eTarget = /** @type {HTMLElement} */(e.target); if (this.grabbed || /** @type {HTMLInputElement} */($eTarget).type === 'range') return; e.stopPropagation(); this.grabbed = true; this.released = false; this.stop(); this.updateBoundingValues(); const touches = /** @type {TouchEvent} */(e).changedTouches; const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX; const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY; const { x, y } = this.transforms.normalizePoint(eventX, eventY); const [ ct, cr, cb, cl ] = this.containerBounds; const cf = (1 - this.containerFriction) * this.dragSpeed; const cx = this.x; const cy = this.y; this.coords[0] = this.coords[2] = !cf ? cx : cx > cr ? cr + (cx - cr) / cf : cx < cl ? cl + (cx - cl) / cf : cx; this.coords[1] = this.coords[3] = !cf ? cy : cy > cb ? cb + (cy - cb) / cf : cy < ct ? ct + (cy - ct) / cf : cy; this.pointer[0] = x; this.pointer[1] = y; this.pointer[2] = x; this.pointer[3] = y; this.pointer[4] = x; this.pointer[5] = y; this.pointer[6] = x; this.pointer[7] = y; this.deltaX = 0; this.deltaY = 0; this.velocity = 0; this.velocityStack[0] = 0; this.velocityStack[1] = 0; this.velocityStack[2] = 0; this.velocityStackIndex = 0;
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
true
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/index.js
dist/modules/easings/index.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { cubicBezier } from './cubic-bezier/index.js'; export { steps } from './steps/index.js'; export { linear } from './linear/index.js'; export { irregular } from './irregular/index.js'; export { Spring, createSpring, spring } from './spring/index.js'; export { eases } from './eases/parser.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/none.js
dist/modules/easings/none.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ /** * @import { * EasingFunction, * } from '../types/index.js' */ /** @type {EasingFunction} */ const none = t => t; export { none };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/linear/index.js
dist/modules/easings/linear/index.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { isStr, parseNumber, isUnd } from '../../core/helpers.js'; import { none } from '../none.js'; /** * @import { * EasingFunction, * } from '../../types/index.js' */ /** * Without parameters, the linear function creates a non-eased transition. * Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points. * * @param {...(String|Number)} args - Points * @return {EasingFunction} */ const linear = (...args) => { const argsLength = args.length; if (!argsLength) return none; const totalPoints = argsLength - 1; const firstArg = args[0]; const lastArg = args[totalPoints]; const xPoints = [0]; const yPoints = [parseNumber(firstArg)]; for (let i = 1; i < totalPoints; i++) { const arg = args[i]; const splitValue = isStr(arg) ? /** @type {String} */(arg).trim().split(' ') : [arg]; const value = splitValue[0]; const percent = splitValue[1]; xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints); yPoints.push(parseNumber(value)); } yPoints.push(parseNumber(lastArg)); xPoints.push(1); return function easeLinear(t) { for (let i = 1, l = xPoints.length; i < l; i++) { const currentX = xPoints[i]; if (t <= currentX) { const prevX = xPoints[i - 1]; const prevY = yPoints[i - 1]; return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX); } } return yPoints[yPoints.length - 1]; } }; export { linear };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/irregular/index.js
dist/modules/easings/irregular/index.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { clamp } from '../../core/helpers.js'; import { linear } from '../linear/index.js'; /** * @import { * EasingFunction, * } from '../../types/index.js' */ /** * Generate random steps * @param {Number} [length] - The number of steps * @param {Number} [randomness] - How strong the randomness is * @return {EasingFunction} */ const irregular = (length = 10, randomness = 1) => { const values = [0]; const total = length - 1; for (let i = 1; i < total; i++) { const previousValue = values[i - 1]; const spacing = i / total; const segmentEnd = (i + 1) / total; const randomVariation = spacing + (segmentEnd - spacing) * Math.random(); // Mix the even spacing and random variation based on the randomness parameter const randomValue = spacing * (1 - randomness) + randomVariation * randomness; values.push(clamp(randomValue, previousValue, 1)); } values.push(1); return linear(...values); }; export { irregular };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/cubic-bezier/index.js
dist/modules/easings/cubic-bezier/index.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { abs } from '../../core/helpers.js'; import { none } from '../none.js'; /** * @import { * EasingFunction, * } from '../../types/index.js' */ /** * Cubic Bezier solver adapted from https://github.com/gre/bezier-easing * (c) 2014 Gaëtan Renaudeau */ /** * @param {Number} aT * @param {Number} aA1 * @param {Number} aA2 * @return {Number} */ const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT; /** * @param {Number} aX * @param {Number} mX1 * @param {Number} mX2 * @return {Number} */ const binarySubdivide = (aX, mX1, mX2) => { let aA = 0, aB = 1, currentX, currentT, i = 0; do { currentT = aA + (aB - aA) / 2; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0) { aB = currentT; } else { aA = currentT; } } while (abs(currentX) > .0000001 && ++i < 100); return currentT; }; /** * @param {Number} [mX1] The x coordinate of the first point * @param {Number} [mY1] The y coordinate of the first point * @param {Number} [mX2] The x coordinate of the second point * @param {Number} [mY2] The y coordinate of the second point * @return {EasingFunction} */ const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none : t => t === 0 || t === 1 ? t : calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2); export { cubicBezier };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/eases/index.js
dist/modules/easings/eases/index.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { eases } from './parser.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/eases/parser.js
dist/modules/easings/eases/parser.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { emptyString, minValue } from '../../core/consts.js'; import { pow, sin, sqrt, cos, isStr, stringStartsWith, isFnc, clamp, asin, PI } from '../../core/helpers.js'; import { none } from '../none.js'; /** * @import { * EasingFunction, * EasingFunctionWithParams, * EasingParam, * BackEasing, * ElasticEasing, * PowerEasing, * } from '../../types/index.js' */ /** @type {PowerEasing} */ const easeInPower = (p = 1.68) => t => pow(t, +p); /** * @callback EaseType * @param {EasingFunction} Ease * @return {EasingFunction} */ /** @type {Record<String, EaseType>} */ const easeTypes = { in: easeIn => t => easeIn(t), out: easeIn => t => 1 - easeIn(1 - t), inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2, outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2, }; /** * Easing functions adapted and simplified from https://robertpenner.com/easing/ * (c) 2001 Robert Penner */ const halfPI = PI / 2; const doublePI = PI * 2; /** @type {Record<String, EasingFunctionWithParams|EasingFunction>} */ const easeInFunctions = { [emptyString]: easeInPower, Quad: easeInPower(2), Cubic: easeInPower(3), Quart: easeInPower(4), Quint: easeInPower(5), /** @type {EasingFunction} */ Sine: t => 1 - cos(t * halfPI), /** @type {EasingFunction} */ Circ: t => 1 - sqrt(1 - t * t), /** @type {EasingFunction} */ Expo: t => t ? pow(2, 10 * t - 10) : 0, /** @type {EasingFunction} */ Bounce: t => { let pow2, b = 4; while (t < ((pow2 = pow(2, --b)) - 1) / 11); return 1 / pow(4, 3 - b) - 7.5625 * pow((pow2 * 3 - 2) / 22 - t, 2); }, /** @type {BackEasing} */ Back: (overshoot = 1.7) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t, /** @type {ElasticEasing} */ Elastic: (amplitude = 1, period = .3) => { const a = clamp(+amplitude, 1, 10); const p = clamp(+period, minValue, 2); const s = (p / doublePI) * asin(1 / a); const e = doublePI / p; return t => t === 0 || t === 1 ? t : -a * pow(2, -10 * (1 - t)) * sin(((1 - t) - s) * e); } }; /** * @typedef {Object} EasesFunctions * @property {typeof none} linear * @property {typeof none} none * @property {PowerEasing} in * @property {PowerEasing} out * @property {PowerEasing} inOut * @property {PowerEasing} outIn * @property {EasingFunction} inQuad * @property {EasingFunction} outQuad * @property {EasingFunction} inOutQuad * @property {EasingFunction} outInQuad * @property {EasingFunction} inCubic * @property {EasingFunction} outCubic * @property {EasingFunction} inOutCubic * @property {EasingFunction} outInCubic * @property {EasingFunction} inQuart * @property {EasingFunction} outQuart * @property {EasingFunction} inOutQuart * @property {EasingFunction} outInQuart * @property {EasingFunction} inQuint * @property {EasingFunction} outQuint * @property {EasingFunction} inOutQuint * @property {EasingFunction} outInQuint * @property {EasingFunction} inSine * @property {EasingFunction} outSine * @property {EasingFunction} inOutSine * @property {EasingFunction} outInSine * @property {EasingFunction} inCirc * @property {EasingFunction} outCirc * @property {EasingFunction} inOutCirc * @property {EasingFunction} outInCirc * @property {EasingFunction} inExpo * @property {EasingFunction} outExpo * @property {EasingFunction} inOutExpo * @property {EasingFunction} outInExpo * @property {EasingFunction} inBounce * @property {EasingFunction} outBounce * @property {EasingFunction} inOutBounce * @property {EasingFunction} outInBounce * @property {BackEasing} inBack * @property {BackEasing} outBack * @property {BackEasing} inOutBack * @property {BackEasing} outInBack * @property {ElasticEasing} inElastic * @property {ElasticEasing} outElastic * @property {ElasticEasing} inOutElastic * @property {ElasticEasing} outInElastic */ const eases = (/*#__PURE__ */ (() => { const list = { linear: none, none: none }; for (let type in easeTypes) { for (let name in easeInFunctions) { const easeIn = easeInFunctions[name]; const easeType = easeTypes[type]; list[type + name] = /** @type {EasingFunctionWithParams|EasingFunction} */( name === emptyString || name === 'Back' || name === 'Elastic' ? (a, b) => easeType(/** @type {EasingFunctionWithParams} */(easeIn)(a, b)) : easeType(/** @type {EasingFunction} */(easeIn)) ); } } return /** @type {EasesFunctions} */(list); })()); /** @type {Record<String, EasingFunction>} */ const easesLookups = { linear: none, none: none }; /** * @param {String} string * @return {EasingFunction} */ const parseEaseString = (string) => { 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 {EasingFunctionWithParams} */(eases[string])() : eases[string]); return parsedFn ? easesLookups[string] = parsedFn : none; } else { const split = string.slice(0, -1).split('('); const parsedFn = /** @type {EasingFunctionWithParams} */(eases[split[0]]); return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none; } }; const deprecated = ['steps(', 'irregular(', 'linear(', 'cubicBezier(']; /** * @param {EasingParam} ease * @return {EasingFunction} */ const parseEase = ease => { if (isStr(ease)) { for (let i = 0, l = deprecated.length; i < l; i++) { if (stringStartsWith(ease, deprecated[i])) { console.warn(`String syntax for \`ease: "${ease}"\` has been removed from the core and replaced by importing and passing the easing function directly: \`ease: ${ease}\``); return none; } } } const easeFunc = isFnc(ease) ? ease : isStr(ease) ? parseEaseString(/** @type {String} */(ease)) : none; return easeFunc; }; export { easeInPower, easeTypes, eases, parseEase, parseEaseString };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/spring/index.js
dist/modules/easings/spring/index.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { K, minValue, noop } from '../../core/consts.js'; import { globals } from '../../core/globals.js'; import { isUnd, clamp, pow, PI, round, sqrt, abs, exp, cos, sin } from '../../core/helpers.js'; import { setValue } from '../../core/values.js'; /** * @import { * JSAnimation, * } from '../../animation/animation.js' */ /** * @import { * EasingFunction, * SpringParams, * Callback, * } from '../../types/index.js' */ /* * Spring easing solver adapted from https://webkit.org/demos/spring/spring.js * (c) 2016 Webkit - Apple Inc */ const maxSpringParamValue = K * 10; class Spring { /** * @param {SpringParams} [parameters] */ constructor(parameters = {}) { const hasBounceOrDuration = !isUnd(parameters.bounce) || !isUnd(parameters.duration); this.timeStep = .02; // Interval fed to the solver to calculate duration this.restThreshold = .0005; // Values below this threshold are considered resting position this.restDuration = 200; // Duration in ms used to check if the spring is resting after reaching restThreshold this.maxDuration = 60000; // The maximum allowed spring duration in ms (default 1 min) this.maxRestSteps = this.restDuration / this.timeStep / K; // How many steps allowed after reaching restThreshold before stopping the duration calculation this.maxIterations = this.maxDuration / this.timeStep / K; // Calculate the maximum iterations allowed based on maxDuration this.bn = clamp(setValue(parameters.bounce, .5), -1, 1); // The bounce percentage between -1 and 1. this.pd = clamp(setValue(parameters.duration, 628), 10 * globals.timeScale, maxSpringParamValue * globals.timeScale); // The perceived duration this.m = clamp(setValue(parameters.mass, 1), 1, maxSpringParamValue); this.s = clamp(setValue(parameters.stiffness, 100), minValue, maxSpringParamValue); this.d = clamp(setValue(parameters.damping, 10), minValue, maxSpringParamValue); this.v = clamp(setValue(parameters.velocity, 0), -maxSpringParamValue, maxSpringParamValue); this.w0 = 0; this.zeta = 0; this.wd = 0; this.b = 0; this.completed = false; this.solverDuration = 0; this.settlingDuration = 0; /** @type {JSAnimation} */ this.parent = null; /** @type {Callback<JSAnimation>} */ this.onComplete = parameters.onComplete || noop; if (hasBounceOrDuration) this.calculateSDFromBD(); this.compute(); /** @type {EasingFunction} */ this.ease = t => { const currentTime = t * this.settlingDuration; const completed = this.completed; const perceivedTime = this.pd; if (currentTime >= perceivedTime && !completed) { this.completed = true; this.onComplete(this.parent); } if (currentTime < perceivedTime && completed) { this.completed = false; } return t === 0 || t === 1 ? t : this.solve(t * this.solverDuration); }; } /** @type {EasingFunction} */ solve(time) { const { zeta, w0, wd, b } = this; let t = time; if (zeta < 1) { // Underdamped t = exp(-t * zeta * w0) * (1 * cos(wd * t) + b * sin(wd * t)); } else if (zeta === 1) { // Critically damped t = (1 + b * t) * exp(-t * w0); } else { // Overdamped // Using exponential instead of cosh and sinh functions to prevent Infinity // Original exp(-zeta * w0 * t) * (cosh(wd * t) + b * sinh(wd * t)) t = ((1 + b) * exp((-zeta * w0 + wd) * t) + (1 - b) * exp((-zeta * w0 - wd) * t)) / 2; } return 1 - t; } calculateSDFromBD() { // Apple's SwiftUI perceived spring duration implementation https://developer.apple.com/videos/play/wwdc2023/10158/?time=1010 // Equations taken from Kevin Grajeda's article https://www.kvin.me/posts/effortless-ui-spring-animations const pds = globals.timeScale === 1 ? this.pd / K : this.pd; // Mass and velocity should be set to their default values this.m = 1; this.v = 0; // Stiffness = (2π ÷ perceptualDuration)² this.s = pow((2 * PI) / pds, 2); if (this.bn >= 0) { // For bounce ≥ 0 (critically damped to underdamped) // damping = ((1 - bounce) × 4π) ÷ perceptualDuration this.d = ((1 - this.bn) * 4 * PI) / pds; } else { // For bounce < 0 (overdamped) // damping = 4π ÷ (perceptualDuration × (1 + bounce)) // Note: (1 + bounce) is positive since bounce is negative this.d = (4 * PI) / (pds * (1 + this.bn)); } this.s = round(clamp(this.s, minValue, maxSpringParamValue), 3); this.d = round(clamp(this.d, minValue, 300), 3); // Clamping to 300 is needed to prevent insane values in the solver } calculateBDFromSD() { // Calculate perceived duration and bounce from stiffness and damping // Note: We assumes m = 1 and v = 0 for these calculations const pds = (2 * PI) / sqrt(this.s); this.pd = pds * (globals.timeScale === 1 ? K : 1); const zeta = this.d / (2 * sqrt(this.s)); if (zeta <= 1) { // Critically damped to underdamped this.bn = 1 - (this.d * pds) / (4 * PI); } else { // Overdamped this.bn = (4 * PI) / (this.d * pds) - 1; } this.bn = round(clamp(this.bn, -1, 1), 3); this.pd = round(clamp(this.pd, 10 * globals.timeScale, maxSpringParamValue * globals.timeScale), 3); } compute() { const { maxRestSteps, maxIterations, restThreshold, timeStep, m, d, s, v } = this; const w0 = this.w0 = clamp(sqrt(s / m), minValue, K); const bouncedZeta = this.zeta = d / (2 * sqrt(s * m)); // Calculate wd based on damping type if (bouncedZeta < 1) { // Underdamped this.wd = w0 * sqrt(1 - bouncedZeta * bouncedZeta); this.b = (bouncedZeta * w0 + -v) / this.wd; } else if (bouncedZeta === 1) { // Critically damped this.wd = 0; this.b = -v + w0; } else { // Overdamped this.wd = w0 * sqrt(bouncedZeta * bouncedZeta - 1); this.b = (bouncedZeta * w0 + -v) / this.wd; } let solverTime = 0; let restSteps = 0; let iterations = 0; while (restSteps <= maxRestSteps && iterations <= maxIterations) { if (abs(1 - this.solve(solverTime)) < restThreshold) { restSteps++; } else { restSteps = 0; } this.solverDuration = solverTime; solverTime += timeStep; iterations++; } this.settlingDuration = round(this.solverDuration * K, 0) * globals.timeScale; } get bounce() { return this.bn; } set bounce(v) { this.bn = clamp(setValue(v, 1), -1, 1); this.calculateSDFromBD(); this.compute(); } get duration() { return this.pd; } set duration(v) { this.pd = clamp(setValue(v, 1), 10 * globals.timeScale, maxSpringParamValue * globals.timeScale); this.calculateSDFromBD(); this.compute(); } get stiffness() { return this.s; } set stiffness(v) { this.s = clamp(setValue(v, 100), minValue, maxSpringParamValue); this.calculateBDFromSD(); this.compute(); } get damping() { return this.d; } set damping(v) { this.d = clamp(setValue(v, 10), minValue, maxSpringParamValue); this.calculateBDFromSD(); this.compute(); } get mass() { return this.m; } set mass(v) { this.m = clamp(setValue(v, 1), 1, maxSpringParamValue); this.compute(); } get velocity() { return this.v; } set velocity(v) { this.v = clamp(setValue(v, 0), -maxSpringParamValue, maxSpringParamValue); this.compute(); } } /** * @param {SpringParams} [parameters] * @returns {Spring} */ const spring = (parameters) => new Spring(parameters); /** * @deprecated createSpring() is deprecated use spring() instead * * @param {SpringParams} [parameters] * @returns {Spring} */ const createSpring = (parameters) => { console.warn('createSpring() is deprecated use spring() instead'); return new Spring(parameters); }; export { Spring, createSpring, spring };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/easings/steps/index.js
dist/modules/easings/steps/index.js
/** * Anime.js - easings - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { ceil, floor, clamp } from '../../core/helpers.js'; /** * @import { * EasingFunction, * } from '../../types/index.js' */ /** * Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function * Only covers 'end' and 'start' jumpterms * @param {Number} steps * @param {Boolean} [fromStart] * @return {EasingFunction} */ const steps = (steps = 10, fromStart) => { const roundMethod = fromStart ? ceil : floor; return t => roundMethod(clamp(t, 0, 1) * steps) * (1 / steps); }; export { steps };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/utils/index.js
dist/modules/utils/index.js
/** * Anime.js - utils - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { clamp, damp, degToRad, lerp, mapRange, padEnd, padStart, radToDeg, round, roundPad, snap, wrap } from './chainable.js'; export { createSeededRandom, random, randomPick, shuffle } from './random.js'; export { keepTime, sync } from './time.js'; export { get, remove, set } from './target.js'; export { stagger } from './stagger.js'; export { cleanInlineStyles } from '../core/styles.js'; export { registerTargets as $ } from '../core/targets.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/utils/target.js
dist/modules/utils/target.js
/** * Anime.js - utils - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { globals } from '../core/globals.js'; import { valueTypes, minValue, compositionTypes } from '../core/consts.js'; import { isUnd, round } from '../core/helpers.js'; import { registerTargets, parseTargets } from '../core/targets.js'; import { sanitizePropertyName } from '../core/styles.js'; export { cleanInlineStyles } from '../core/styles.js'; import { getTweenType, getOriginalAnimatableValue, decomposeRawValue, decomposedOriginalValue, setValue } from '../core/values.js'; import { convertValueUnit } from '../core/units.js'; import { removeWAAPIAnimation } from '../waapi/composition.js'; import { removeTargetsFromRenderable } from '../animation/composition.js'; import { JSAnimation } from '../animation/animation.js'; /** * @import { * Renderable, * DOMTargetSelector, * JSTargetsParam, * DOMTargetsParam, * TargetsParam, * DOMTarget, * AnimationParams, * TargetsArray, * } from '../types/index.js' */ /** * @import { * WAAPIAnimation * } from '../waapi/waapi.js' */ /** * @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] */ function get(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}`; } } } } /** * @param {TargetsParam} targets * @param {AnimationParams} parameters * @return {JSAnimation} */ const set = (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 {Renderable|WAAPIAnimation} [renderable] * @param {String} [propertyName] * @return {TargetsArray} */ const remove = (targets, renderable, propertyName) => { const targetsArray = parseTargets(targets); for (let i = 0, l = targetsArray.length; i < l; i++) { removeWAAPIAnimation( /** @type {DOMTarget} */(targetsArray[i]), propertyName, renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable), ); } removeTargetsFromRenderable( targetsArray, /** @type {Renderable} */(renderable), propertyName ); return targetsArray; }; export { registerTargets as $, get, remove, set };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/utils/time.js
dist/modules/utils/time.js
/** * Anime.js - utils - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { noop } from '../core/consts.js'; import { globals } from '../core/globals.js'; import { isFnc, isUnd } from '../core/helpers.js'; import { Timer } from '../timer/timer.js'; /** * @import { * Callback, * Tickable, * } from '../types/index.js' */ /** * @param {Callback<Timer>} [callback] * @return {Timer} */ const sync = (callback = noop) => { return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume(); }; /** * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)} */ const keepTime = constructor => { /** @type {Tickable} */ let tracked; return (...args) => { let currentIteration, currentIterationProgress, reversed, alternate; if (tracked) { currentIteration = tracked.currentIteration; currentIterationProgress = tracked.iterationProgress; reversed = tracked.reversed; alternate = tracked._alternate; tracked.revert(); } const cleanup = constructor(...args); if (cleanup && !isFnc(cleanup) && cleanup.revert) tracked = cleanup; if (!isUnd(currentIterationProgress)) { /** @type {Tickable} */(tracked).currentIteration = currentIteration; /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress; } return cleanup || noop; } }; export { keepTime, sync };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/utils/stagger.js
dist/modules/utils/stagger.js
/** * Anime.js - utils - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { unitsExecRgx, emptyString } from '../core/consts.js'; import { isUnd, parseNumber, isFnc, abs, floor, sqrt, round, isArr, isNum, isStr, max } from '../core/helpers.js'; import { parseEase } from '../easings/eases/parser.js'; import { parseTimelinePosition } from '../timeline/position.js'; import { getOriginalAnimatableValue } from '../core/values.js'; import { registerTargets } from '../core/targets.js'; import { shuffle } from './random.js'; /** * @import { * StaggerParams, * StaggerFunction, * } from '../types/index.js' */ /** * @import { * Spring, * } from '../easings/spring/index.js' */ /** * @overload * @param {Number} val * @param {StaggerParams} [params] * @return {StaggerFunction<Number>} */ /** * @overload * @param {String} val * @param {StaggerParams} [params] * @return {StaggerFunction<String>} */ /** * @overload * @param {[Number, Number]} val * @param {StaggerParams} [params] * @return {StaggerFunction<Number>} */ /** * @overload * @param {[String, String]} val * @param {StaggerParams} [params] * @return {StaggerFunction<String>} */ /** * @param {Number|String|[Number, Number]|[String, String]} val The staggered value or range * @param {StaggerParams} [params] The stagger parameters * @return {StaggerFunction<Number|String>} */ const 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 ? parseEase(ease) : null; const grid = params.grid; const axis = params.axis; const customTotal = params.total; const fromFirst = isUnd(from) || from === 0 || from === 'first'; const fromCenter = from === 'center'; const fromLast = from === 'last'; const fromRandom = from === 'random'; const isRange = isArr(val); const useProp = params.use; 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 (target, i, t, tl) => { const [ registeredTarget ] = registerTargets(target); const total = isUnd(customTotal) ? t : customTotal; const customIndex = !isUnd(useProp) ? isFnc(useProp) ? useProp(registeredTarget, i, total) : getOriginalAnimatableValue(registeredTarget, useProp) : false; const staggerIndex = isNum(customIndex) || isStr(customIndex) && isNum(+customIndex) ? +customIndex : i; if (fromCenter) fromIndex = (total - 1) / 2; if (fromLast) fromIndex = total - 1; if (!values.length) { for (let index = 0; index < total; 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)); if (fromRandom) values = shuffle(values); } 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[staggerIndex], 2)) || 0); if (params.modifier) output = params.modifier(output); if (unitMatch) output = `${output}${unitMatch[2]}`; return output; } }; export { stagger };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/utils/number.js
dist/modules/utils/number.js
/** * Anime.js - utils - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { lerp } from '../core/helpers.js'; export { clamp, round, snap } from '../core/helpers.js'; /** * Rounds a number to fixed decimal places * @param {Number|String} v - Value to round * @param {Number} decimalLength - Number of decimal places * @return {String} */ const roundPad = (v, decimalLength) => (+v).toFixed(decimalLength); /** * Pads the start of a value with a string * @param {Number} v - Value to pad * @param {Number} totalLength - Target length * @param {String} padString - String to pad with * @return {String} */ const padStart = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString); /** * Pads the end of a value with a string * @param {Number} v - Value to pad * @param {Number} totalLength - Target length * @param {String} padString - String to pad with * @return {String} */ const padEnd = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString); /** * Wraps a value within a range * @param {Number} v - Value to wrap * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {Number} */ const wrap = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min; /** * Maps a value from one range to another * @param {Number} value - Input value * @param {Number} inLow - Input range minimum * @param {Number} inHigh - Input range maximum * @param {Number} outLow - Output range minimum * @param {Number} outHigh - Output range maximum * @return {Number} */ const mapRange = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow); /** * Converts degrees to radians * @param {Number} degrees - Angle in degrees * @return {Number} */ const degToRad = degrees => degrees * Math.PI / 180; /** * Converts radians to degrees * @param {Number} radians - Angle in radians * @return {Number} */ const radToDeg = radians => radians * 180 / Math.PI; /** * Frame rate independent damped lerp * Based on: https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ * * @param {Number} start - Starting value * @param {Number} end - Target value * @param {Number} deltaTime - Delta time in ms * @param {Number} factor - Interpolation factor in the range [0, 1] * @return {Number} The interpolated value */ const damp = (start, end, deltaTime, factor) => { return !factor ? start : factor === 1 ? end : lerp(start, end, 1 - Math.exp(-factor * deltaTime * .1)); }; export { damp, degToRad, lerp, mapRange, padEnd, padStart, radToDeg, roundPad, wrap };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/utils/random.js
dist/modules/utils/random.js
/** * Anime.js - utils - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ /** * Generate a random number between optional min and max (inclusive) and decimal precision * * @callback RandomNumberGenerator * @param {Number} [min=0] - The minimum value (inclusive) * @param {Number} [max=1] - The maximum value (inclusive) * @param {Number} [decimalLength=0] - Number of decimal places to round to * @return {Number} A random number between min and max */ /** * Generates a random number between min and max (inclusive) with optional decimal precision * * @type {RandomNumberGenerator} */ const random = (min = 0, max = 1, decimalLength = 0) => { const m = 10 ** decimalLength; return Math.floor((Math.random() * (max - min + (1 / m)) + min) * m) / m; }; let _seed = 0; /** * Creates a seeded pseudorandom number generator function * * @param {Number} [seed] - The seed value for the random number generator * @param {Number} [seededMin=0] - The minimum default value (inclusive) of the returned function * @param {Number} [seededMax=1] - The maximum default value (inclusive) of the returned function * @param {Number} [seededDecimalLength=0] - Default number of decimal places to round to of the returned function * @return {RandomNumberGenerator} A function to generate a random number between optional min and max (inclusive) and decimal precision */ const createSeededRandom = (seed, seededMin = 0, seededMax = 1, seededDecimalLength = 0) => { let t = seed === undefined ? _seed++ : seed; return (min = seededMin, max = seededMax, decimalLength = seededDecimalLength) => { t += 0x6D2B79F5; t = Math.imul(t ^ t >>> 15, t | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); const m = 10 ** decimalLength; return Math.floor(((((t ^ t >>> 14) >>> 0) / 4294967296) * (max - min + (1 / m)) + min) * m) / m; } }; /** * Picks a random element from an array or a string * * @template T * @param {String|Array<T>} items - The array or string to pick from * @return {String|T} A random element from the array or character from the string */ const randomPick = items => items[random(0, items.length - 1)]; /** * Shuffles an array in-place using the Fisher-Yates algorithm * Adapted from https://bost.ocks.org/mike/shuffle/ * * @param {Array} items - The array to shuffle (will be modified in-place) * @return {Array} The same array reference, now shuffled */ const 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; }; export { createSeededRandom, random, randomPick, shuffle };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/utils/chainable.js
dist/modules/utils/chainable.js
/** * Anime.js - utils - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { noop } from '../core/consts.js'; import * as number from './number.js'; // Chain-able utilities const numberUtils = number; // Needed to keep the import when bundling const chainables = {}; /** * @callback UtilityFunction * @param {...*} args * @return {Number|String} * * @param {UtilityFunction} fn * @param {Number} [last=0] * @return {function(...(Number|String)): function(Number|String): (Number|String)} */ const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args); /** * @param {Function} fn * @return {function(...(Number|String))} */ const 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 = chainables[prop](...nextArgs); return (/**@type {Number|String} */v) => nextResult(result(v)); }) }); } }; /** * @param {UtilityFunction} fn * @param {String} name * @param {Number} [right] * @return {function(...(Number|String)): UtilityFunction} */ const makeChainable = (name, fn, right = 0) => { const chained = (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args); if (!chainables[name]) chainables[name] = chained; return chained; }; /** * @typedef {Object} ChainablesMap * @property {ChainedClamp} clamp * @property {ChainedRound} round * @property {ChainedSnap} snap * @property {ChainedWrap} wrap * @property {ChainedLerp} lerp * @property {ChainedDamp} damp * @property {ChainedMapRange} mapRange * @property {ChainedRoundPad} roundPad * @property {ChainedPadStart} padStart * @property {ChainedPadEnd} padEnd * @property {ChainedDegToRad} degToRad * @property {ChainedRadToDeg} radToDeg */ /** * @callback ChainedUtilsResult * @param {Number} value - The value to process through the chained operations * @return {Number} The processed result */ /** * @typedef {ChainablesMap & ChainedUtilsResult} ChainableUtil */ // Chainable /** * @callback ChainedRoundPad * @param {Number} decimalLength - Number of decimal places * @return {ChainableUtil} */ const roundPad = /** @type {typeof numberUtils.roundPad & ChainedRoundPad} */(makeChainable('roundPad', numberUtils.roundPad)); /** * @callback ChainedPadStart * @param {Number} totalLength - Target length * @param {String} padString - String to pad with * @return {ChainableUtil} */ const padStart = /** @type {typeof numberUtils.padStart & ChainedPadStart} */(makeChainable('padStart', numberUtils.padStart)); /** * @callback ChainedPadEnd * @param {Number} totalLength - Target length * @param {String} padString - String to pad with * @return {ChainableUtil} */ const padEnd = /** @type {typeof numberUtils.padEnd & ChainedPadEnd} */(makeChainable('padEnd', numberUtils.padEnd)); /** * @callback ChainedWrap * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {ChainableUtil} */ const wrap = /** @type {typeof numberUtils.wrap & ChainedWrap} */(makeChainable('wrap', numberUtils.wrap)); /** * @callback ChainedMapRange * @param {Number} inLow - Input range minimum * @param {Number} inHigh - Input range maximum * @param {Number} outLow - Output range minimum * @param {Number} outHigh - Output range maximum * @return {ChainableUtil} */ const mapRange = /** @type {typeof numberUtils.mapRange & ChainedMapRange} */(makeChainable('mapRange', numberUtils.mapRange)); /** * @callback ChainedDegToRad * @return {ChainableUtil} */ const degToRad = /** @type {typeof numberUtils.degToRad & ChainedDegToRad} */(makeChainable('degToRad', numberUtils.degToRad)); /** * @callback ChainedRadToDeg * @return {ChainableUtil} */ const radToDeg = /** @type {typeof numberUtils.radToDeg & ChainedRadToDeg} */(makeChainable('radToDeg', numberUtils.radToDeg)); /** * @callback ChainedSnap * @param {Number|Array<Number>} increment - Step size or array of snap points * @return {ChainableUtil} */ const snap = /** @type {typeof numberUtils.snap & ChainedSnap} */(makeChainable('snap', numberUtils.snap)); /** * @callback ChainedClamp * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {ChainableUtil} */ const clamp = /** @type {typeof numberUtils.clamp & ChainedClamp} */(makeChainable('clamp', numberUtils.clamp)); /** * @callback ChainedRound * @param {Number} decimalLength - Number of decimal places * @return {ChainableUtil} */ const round = /** @type {typeof numberUtils.round & ChainedRound} */(makeChainable('round', numberUtils.round)); /** * @callback ChainedLerp * @param {Number} start - Starting value * @param {Number} end - Ending value * @return {ChainableUtil} */ const lerp = /** @type {typeof numberUtils.lerp & ChainedLerp} */(makeChainable('lerp', numberUtils.lerp, 1)); /** * @callback ChainedDamp * @param {Number} start - Starting value * @param {Number} end - Target value * @param {Number} deltaTime - Delta time in ms * @return {ChainableUtil} */ const damp = /** @type {typeof numberUtils.damp & ChainedDamp} */(makeChainable('damp', numberUtils.damp, 1)); export { clamp, damp, degToRad, lerp, mapRange, padEnd, padStart, radToDeg, round, roundPad, snap, wrap };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/timer/index.js
dist/modules/timer/index.js
/** * Anime.js - timer - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { Timer, createTimer } from './timer.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/timer/timer.js
dist/modules/timer/timer.js
/** * Anime.js - timer - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { minValue, noop, maxValue, compositionTypes, tickModes } from '../core/consts.js'; import { isFnc, isUnd, now, clampInfinity, clamp, round, forEachChildren, addChild, normalizeTime, floor } from '../core/helpers.js'; import { globals, scope } from '../core/globals.js'; import { setValue } from '../core/values.js'; import { tick } from '../core/render.js'; import { removeTweenSliblings, composeTween, getTweenSiblings } from '../animation/composition.js'; import { Clock } from '../core/clock.js'; import { engine } from '../engine/engine.js'; /** * @import { * Callback, * TimerParams, * Renderable, * Tween, * } from '../types/index.js' */ /** * @import { * ScrollObserver, * } from '../events/scroll.js' */ /** * @import { * Timeline, * } from '../timeline/timeline.js' */ /** * @param {Timer} timer * @return {Timer} */ const resetTimerProperties = timer => { timer.paused = true; timer.began = false; timer.completed = false; return timer; }; /** * @param {Timer} timer * @return {Timer} */ const reviveTimer = timer => { if (!timer._cancelled) return timer; if (timer._hasChildren) { forEachChildren(timer, reviveTimer); } else { forEachChildren(timer, (/** @type {Tween} tween */tween) => { if (tween._composition !== compositionTypes.none) { composeTween(tween, getTweenSiblings(tween.target, tween.property)); } }); } timer._cancelled = 0; return timer; }; let timerId = 0; /** * Base class used to create Timers, Animations and Timelines */ class Timer extends Clock { /** * @param {TimerParams} [parameters] * @param {Timeline} [parent] * @param {Number} [parentPosition] */ constructor(parameters = {}, parent = null, parentPosition = 0) { super(0); const { id, delay, duration, reversed, alternate, loop, loopDelay, autoplay, frameRate, playbackRate, onComplete, onLoop, onPause, onBegin, onBeforeUpdate, onUpdate, } = parameters; if (scope.current) scope.current.register(this); const timerInitTime = parent ? 0 : engine._elapsedTime; const timerDefaults = parent ? parent.defaults : globals.defaults; const timerDelay = /** @type {Number} */(isFnc(delay) || isUnd(delay) ? timerDefaults.delay : +delay); const timerDuration = isFnc(duration) || isUnd(duration) ? Infinity : +duration; const timerLoop = setValue(loop, timerDefaults.loop); const timerLoopDelay = setValue(loopDelay, timerDefaults.loopDelay); const timerIterationCount = timerLoop === true || timerLoop === Infinity || /** @type {Number} */(timerLoop) < 0 ? Infinity : /** @type {Number} */(timerLoop) + 1; let offsetPosition = 0; if (parent) { offsetPosition = parentPosition; } else { // Make sure to tick the engine once if not currently running to get up to date engine._elapsedTime // to avoid big gaps with the following offsetPosition calculation if (!engine.reqId) engine.requestTick(now()); // Make sure to scale the offset position with globals.timeScale to properly handle seconds unit offsetPosition = (engine._elapsedTime - engine._startTime) * globals.timeScale; } // Timer's parameters this.id = !isUnd(id) ? id : ++timerId; /** @type {Timeline} */ this.parent = parent; // Total duration of the timer this.duration = clampInfinity(((timerDuration + timerLoopDelay) * timerIterationCount) - timerLoopDelay) || minValue; /** @type {Boolean} */ this.backwards = false; /** @type {Boolean} */ this.paused = true; /** @type {Boolean} */ this.began = false; /** @type {Boolean} */ this.completed = false; /** @type {Callback<this>} */ this.onBegin = onBegin || timerDefaults.onBegin; /** @type {Callback<this>} */ this.onBeforeUpdate = onBeforeUpdate || timerDefaults.onBeforeUpdate; /** @type {Callback<this>} */ this.onUpdate = onUpdate || timerDefaults.onUpdate; /** @type {Callback<this>} */ this.onLoop = onLoop || timerDefaults.onLoop; /** @type {Callback<this>} */ this.onPause = onPause || timerDefaults.onPause; /** @type {Callback<this>} */ this.onComplete = onComplete || timerDefaults.onComplete; /** @type {Number} */ this.iterationDuration = timerDuration; // Duration of one loop /** @type {Number} */ this.iterationCount = timerIterationCount; // Number of loops /** @type {Boolean|ScrollObserver} */ this._autoplay = parent ? false : setValue(autoplay, timerDefaults.autoplay); /** @type {Number} */ this._offset = offsetPosition; /** @type {Number} */ this._delay = timerDelay; /** @type {Number} */ this._loopDelay = timerLoopDelay; /** @type {Number} */ this._iterationTime = 0; /** @type {Number} */ this._currentIteration = 0; // Current loop index /** @type {Function} */ this._resolve = noop; // Used by .then() /** @type {Boolean} */ this._running = false; /** @type {Number} */ this._reversed = +setValue(reversed, timerDefaults.reversed); /** @type {Number} */ this._reverse = this._reversed; /** @type {Number} */ this._cancelled = 0; /** @type {Boolean} */ this._alternate = setValue(alternate, timerDefaults.alternate); /** @type {Renderable} */ this._prev = null; /** @type {Renderable} */ this._next = null; // Clock's parameters /** @type {Number} */ this._elapsedTime = timerInitTime; /** @type {Number} */ this._startTime = timerInitTime; /** @type {Number} */ this._lastTime = timerInitTime; /** @type {Number} */ this._fps = setValue(frameRate, timerDefaults.frameRate); /** @type {Number} */ this._speed = setValue(playbackRate, timerDefaults.playbackRate); } get cancelled() { return !!this._cancelled; } set cancelled(cancelled) { cancelled ? this.cancel() : this.reset(true).play(); } get currentTime() { return clamp(round(this._currentTime, globals.precision), -this._delay, this.duration); } set currentTime(time) { const paused = this.paused; // Pausing the timer is necessary to avoid time jumps on a running instance this.pause().seek(+time); if (!paused) this.resume(); } get iterationCurrentTime() { return round(this._iterationTime, globals.precision); } set iterationCurrentTime(time) { this.currentTime = (this.iterationDuration * this._currentIteration) + time; } get progress() { return clamp(round(this._currentTime / this.duration, 10), 0, 1); } set progress(progress) { this.currentTime = this.duration * progress; } get iterationProgress() { return clamp(round(this._iterationTime / this.iterationDuration, 10), 0, 1); } set iterationProgress(progress) { const iterationDuration = this.iterationDuration; this.currentTime = (iterationDuration * this._currentIteration) + (iterationDuration * progress); } get currentIteration() { return this._currentIteration; } set currentIteration(iterationCount) { this.currentTime = (this.iterationDuration * clamp(+iterationCount, 0, this.iterationCount - 1)); } get reversed() { return !!this._reversed; } set reversed(reverse) { reverse ? this.reverse() : this.play(); } get speed() { return super.speed; } set speed(playbackRate) { super.speed = playbackRate; this.resetTime(); } /** * @param {Boolean} [softReset] * @return {this} */ reset(softReset = false) { // If cancelled, revive the timer before rendering in order to have propertly composed tweens siblings reviveTimer(this); if (this._reversed && !this._reverse) this.reversed = false; // Rendering before updating the completed flag to prevent skips and to make sure the properties are not overridden // Setting the iterationTime at the end to force the rendering to happend backwards, otherwise calling .reset() on Timelines might not render children in the right order // NOTE: This is only required for Timelines and might be better to move to the Timeline class? this._iterationTime = this.iterationDuration; // Set tickMode to tickModes.FORCE to force rendering tick(this, 0, 1, ~~softReset, tickModes.FORCE); // Reset timer properties after revive / render to make sure the props are not updated again resetTimerProperties(this); // Also reset children properties if (this._hasChildren) { forEachChildren(this, resetTimerProperties); } return this; } /** * @param {Boolean} internalRender * @return {this} */ init(internalRender = false) { this.fps = this._fps; this.speed = this._speed; // Manually calling .init() on timelines should render all children intial state // Forces all children to render once then render to 0 when reseted if (!internalRender && this._hasChildren) { tick(this, this.duration, 1, ~~internalRender, tickModes.FORCE); } this.reset(internalRender); // Make sure to set autoplay to false to child timers so it doesn't attempt to autoplay / link const autoplay = this._autoplay; if (autoplay === true) { this.resume(); } else if (autoplay && !isUnd(/** @type {ScrollObserver} */(autoplay).linked)) { /** @type {ScrollObserver} */(autoplay).link(this); } return this; } /** @return {this} */ resetTime() { const timeScale = 1 / (this._speed * engine._speed); // TODO: See if we can safely use engine._elapsedTime here // if (!engine.reqId) engine.requestTick(now()) // this._startTime = engine._elapsedTime - (this._currentTime + this._delay) * timeScale; this._startTime = now() - (this._currentTime + this._delay) * timeScale; return this; } /** @return {this} */ pause() { if (this.paused) return this; this.paused = true; this.onPause(this); return this; } /** @return {this} */ resume() { if (!this.paused) return this; this.paused = false; // We can safely imediatly render a timer that has no duration and no children if (this.duration <= minValue && !this._hasChildren) { tick(this, minValue, 0, 0, tickModes.FORCE); } else { if (!this._running) { addChild(engine, this); engine._hasChildren = true; this._running = true; } this.resetTime(); // Forces the timer to advance by at least one frame when the next tick occurs this._startTime -= 12; engine.wake(); } return this; } /** @return {this} */ restart() { return this.reset().resume(); } /** * @param {Number} time * @param {Boolean|Number} [muteCallbacks] * @param {Boolean|Number} [internalRender] * @return {this} */ seek(time, muteCallbacks = 0, internalRender = 0) { // Recompose the tween siblings in case the timer has been cancelled reviveTimer(this); // If you seek a completed animation, otherwise the next play will starts at 0 this.completed = false; const isPaused = this.paused; this.paused = true; // timer, time, muteCallbacks, internalRender, tickMode tick(this, time + this._delay, ~~muteCallbacks, ~~internalRender, tickModes.AUTO); return isPaused ? this : this.resume(); } /** @return {this} */ alternate() { const reversed = this._reversed; const count = this.iterationCount; const duration = this.iterationDuration; // Calculate the maximum iterations possible given the iteration duration const iterations = count === Infinity ? floor(maxValue / duration) : count; this._reversed = +(this._alternate && !(iterations % 2) ? reversed : !reversed); if (count === Infinity) { // Handle infinite loops to loop on themself this.iterationProgress = this._reversed ? 1 - this.iterationProgress : this.iterationProgress; } else { this.seek((duration * iterations) - this._currentTime); } this.resetTime(); return this; } /** @return {this} */ play() { if (this._reversed) this.alternate(); return this.resume(); } /** @return {this} */ reverse() { if (!this._reversed) this.alternate(); return this.resume(); } // TODO: Move all the animation / tweens / children related code to Animation / Timeline /** @return {this} */ cancel() { if (this._hasChildren) { forEachChildren(this, (/** @type {Renderable} */child) => child.cancel(), true); } else { forEachChildren(this, removeTweenSliblings); } this._cancelled = 1; // Pausing the timer removes it from the engine return this.pause(); } /** * @param {Number} newDuration * @return {this} */ stretch(newDuration) { const currentDuration = this.duration; const normlizedDuration = normalizeTime(newDuration); if (currentDuration === normlizedDuration) return this; const timeScale = newDuration / currentDuration; const isSetter = newDuration <= minValue; this.duration = isSetter ? minValue : normlizedDuration; this.iterationDuration = isSetter ? minValue : normalizeTime(this.iterationDuration * timeScale); this._offset *= timeScale; this._delay *= timeScale; this._loopDelay *= timeScale; return this; } /** * Cancels the timer by seeking it back to 0 and reverting the attached scroller if necessary * @return {this} */ revert() { tick(this, 0, 1, 0, tickModes.AUTO); const ap = /** @type {ScrollObserver} */(this._autoplay); if (ap && ap.linked && ap.linked === this) ap.revert(); return this.cancel(); } /** * Imediatly completes the timer, cancels it and triggers the onComplete callback * @return {this} */ complete() { return this.seek(this.duration).cancel(); } /** * @typedef {this & {then: null}} ResolvedTimer */ /** * @param {Callback<ResolvedTimer>} [callback] * @return Promise<this> */ then(callback = noop) { const then = this.then; const onResolve = () => { // this.then = null prevents infinite recursion if returned by an async function // https://github.com/juliangarnierorg/anime-beta/issues/26 this.then = null; callback(/** @type {ResolvedTimer} */(this)); this.then = then; this._resolve = noop; }; return new Promise(r => { this._resolve = () => r(onResolve()); // Make sure to resolve imediatly if the timer has already completed if (this.completed) this._resolve(); return this; }); } } /** * @param {TimerParams} [parameters] * @return {Timer} */ const createTimer = parameters => new Timer(parameters, null, 0).init(); export { Timer, createTimer };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/events/index.js
dist/modules/events/index.js
/** * Anime.js - events - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { ScrollObserver, onScroll, scrollContainers } from './scroll.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/events/scroll.js
dist/modules/events/scroll.js
/** * Anime.js - events - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { noop, doc, isDomSymbol, relativeValuesExecRgx, win } from '../core/consts.js'; import { scope, globals } from '../core/globals.js'; import { isUnd, isNum, addChild, forEachChildren, round, isStr, isObj, removeChild, clamp, lerp, isFnc } from '../core/helpers.js'; import { parseTargets } from '../core/targets.js'; import { setValue, getRelativeValue, decomposeRawValue, decomposedOriginalValue } from '../core/values.js'; import { convertValueUnit } from '../core/units.js'; import { Timer } from '../timer/timer.js'; import { get, set } from '../utils/target.js'; import { sync } from '../utils/time.js'; import { none } from '../easings/none.js'; import { parseEase } from '../easings/eases/parser.js'; /** * @import { * TargetsParam, * EasingFunction, * Callback, * EasingParam, * ScrollThresholdValue, * ScrollObserverParams, * Tickable, * ScrollThresholdParam, * ScrollThresholdCallback, * } from '../types/index.js' */ /** * @import { * JSAnimation, * } from '../animation/animation.js' */ /** * @import { * WAAPIAnimation, * } from '../waapi/waapi.js' */ /** * @import { * Timeline, * } from '../timeline/timeline.js' */ /** * @return {Number} */ const getMaxViewHeight = () => { const $el = doc.createElement('div'); doc.body.appendChild($el); $el.style.height = '100lvh'; const height = $el.offsetHeight; doc.body.removeChild($el); return height; }; /** * @template {ScrollThresholdValue|String|Number|Boolean|Function|Object} T * @param {T | ((observer: ScrollObserver) => T)} value * @param {ScrollObserver} scroller * @return {T} */ const parseScrollObserverFunctionParameter = (value, scroller) => value && isFnc(value) ? /** @type {Function} */(value)(scroller) : /** @type {T} */(value); const scrollContainers = new Map(); class ScrollContainer { /** * @param {HTMLElement} $el */ constructor($el) { /** @type {HTMLElement} */ this.element = $el; /** @type {Boolean} */ this.useWin = this.element === doc.body; /** @type {Number} */ this.winWidth = 0; /** @type {Number} */ this.winHeight = 0; /** @type {Number} */ this.width = 0; /** @type {Number} */ this.height = 0; /** @type {Number} */ this.left = 0; /** @type {Number} */ this.top = 0; /** @type {Number} */ this.scale = 1; /** @type {Number} */ this.zIndex = 0; /** @type {Number} */ this.scrollX = 0; /** @type {Number} */ this.scrollY = 0; /** @type {Number} */ this.prevScrollX = 0; /** @type {Number} */ this.prevScrollY = 0; /** @type {Number} */ this.scrollWidth = 0; /** @type {Number} */ this.scrollHeight = 0; /** @type {Number} */ this.velocity = 0; /** @type {Boolean} */ this.backwardX = false; /** @type {Boolean} */ this.backwardY = false; /** @type {Timer} */ this.scrollTicker = new Timer({ autoplay: false, onBegin: () => this.dataTimer.resume(), onUpdate: () => { const backwards = this.backwardX || this.backwardY; forEachChildren(this, (/** @type {ScrollObserver} */child) => child.handleScroll(), backwards); }, onComplete: () => this.dataTimer.pause() }).init(); /** @type {Timer} */ this.dataTimer = new Timer({ autoplay: false, frameRate: 30, onUpdate: (/** @type {Timer} */self) => { const dt = self.deltaTime; const px = this.prevScrollX; const py = this.prevScrollY; const nx = this.scrollX; const ny = this.scrollY; const dx = px - nx; const dy = py - ny; this.prevScrollX = nx; this.prevScrollY = ny; if (dx) this.backwardX = px > nx; if (dy) this.backwardY = py > ny; this.velocity = round(dt > 0 ? Math.sqrt(dx * dx + dy * dy) / dt : 0, 5); } }).init(); /** @type {Timer} */ this.resizeTicker = new Timer({ autoplay: false, duration: 250 * globals.timeScale, onComplete: () => { this.updateWindowBounds(); this.refreshScrollObservers(); this.handleScroll(); } }).init(); /** @type {Timer} */ this.wakeTicker = new Timer({ autoplay: false, duration: 500 * globals.timeScale, onBegin: () => { this.scrollTicker.resume(); }, onComplete: () => { this.scrollTicker.pause(); } }).init(); /** @type {ScrollObserver} */ this._head = null; /** @type {ScrollObserver} */ this._tail = null; this.updateScrollCoords(); this.updateWindowBounds(); this.updateBounds(); this.refreshScrollObservers(); this.handleScroll(); this.resizeObserver = new ResizeObserver(() => this.resizeTicker.restart()); this.resizeObserver.observe(this.element); (this.useWin ? win : this.element).addEventListener('scroll', this, false); } updateScrollCoords() { const useWin = this.useWin; const $el = this.element; this.scrollX = round(useWin ? win.scrollX : $el.scrollLeft, 0); this.scrollY = round(useWin ? win.scrollY : $el.scrollTop, 0); } updateWindowBounds() { this.winWidth = win.innerWidth; this.winHeight = getMaxViewHeight(); } updateBounds() { const style = getComputedStyle(this.element); const $el = this.element; this.scrollWidth = $el.scrollWidth + parseFloat(style.marginLeft) + parseFloat(style.marginRight); this.scrollHeight = $el.scrollHeight + parseFloat(style.marginTop) + parseFloat(style.marginBottom); this.updateWindowBounds(); let width, height; if (this.useWin) { width = this.winWidth; height = this.winHeight; } else { const elRect = $el.getBoundingClientRect(); width = $el.clientWidth; height = $el.clientHeight; this.top = elRect.top; this.left = elRect.left; this.scale = elRect.width ? width / elRect.width : (elRect.height ? height / elRect.height : 1); } this.width = width; this.height = height; } refreshScrollObservers() { forEachChildren(this, (/** @type {ScrollObserver} */child) => { if (child._debug) { child.removeDebug(); } }); this.updateBounds(); forEachChildren(this, (/** @type {ScrollObserver} */child) => { child.refresh(); if (child._debug) { child.debug(); } }); } refresh() { this.updateWindowBounds(); this.updateBounds(); this.refreshScrollObservers(); this.handleScroll(); } handleScroll() { this.updateScrollCoords(); this.wakeTicker.restart(); } /** * @param {Event} e */ handleEvent(e) { switch (e.type) { case 'scroll': this.handleScroll(); break; } } revert() { this.scrollTicker.cancel(); this.dataTimer.cancel(); this.resizeTicker.cancel(); this.wakeTicker.cancel(); this.resizeObserver.disconnect(); (this.useWin ? win : this.element).removeEventListener('scroll', this); scrollContainers.delete(this.element); } } /** * @param {TargetsParam} target * @return {ScrollContainer} */ const registerAndGetScrollContainer = target => { const $el = /** @type {HTMLElement} */(target ? parseTargets(target)[0] || doc.body : doc.body); let scrollContainer = scrollContainers.get($el); if (!scrollContainer) { scrollContainer = new ScrollContainer($el); scrollContainers.set($el, scrollContainer); } return scrollContainer; }; /** * @param {HTMLElement} $el * @param {Number|string} v * @param {Number} size * @param {Number} [under] * @param {Number} [over] * @return {Number} */ const 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 {ScrollThresholdValue} v * @param {Number} size * @param {Number} [under] * @param {Number} [over] * @return {Number} */ const 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 {JSAnimation} linked * @return {HTMLElement} */ const getAnimationDomTarget = linked => { let $linkedTarget; const linkedTargets = linked.targets; for (let i = 0, l = linkedTargets.length; i < l; i++) { const target = linkedTargets[i]; if (target[isDomSymbol]) { $linkedTarget = /** @type {HTMLElement} */(target); break; } } return $linkedTarget; }; let scrollerIndex = 0; const debugColors = ['#FF4B4B','#FF971B','#FFC730','#F9F640','#7AFF5A','#18FF74','#17E09B','#3CFFEC','#05DBE9','#33B3F1','#638CF9','#C563FE','#FF4FCF','#F93F8A']; class ScrollObserver { /** * @param {ScrollObserverParams} parameters */ constructor(parameters = {}) { if (scope.current) scope.current.register(this); const syncMode = setValue(parameters.sync, 'play pause'); const ease = syncMode ? parseEase(/** @type {EasingParam} */(syncMode)) : null; const isLinear = syncMode && (syncMode === 'linear' || syncMode === none); const isEase = syncMode && !(ease === none && !isLinear); const isSmooth = syncMode && (isNum(syncMode) || syncMode === true || isLinear); const isMethods = syncMode && (isStr(syncMode) && !isEase && !isSmooth); const syncMethods = isMethods ? /** @type {String} */(syncMode).split(' ').map( (/** @type {String} */m) => () => { const linked = this.linked; return linked && linked[m] ? linked[m]() : null; } ) : null; const biDirSync = isMethods && syncMethods.length > 2; /** @type {Number} */ this.index = scrollerIndex++; /** @type {String|Number} */ this.id = !isUnd(parameters.id) ? parameters.id : this.index; /** @type {ScrollContainer} */ this.container = registerAndGetScrollContainer(parameters.container); /** @type {HTMLElement} */ this.target = null; /** @type {Tickable|WAAPIAnimation} */ this.linked = null; /** @type {Boolean} */ this.repeat = null; /** @type {Boolean} */ this.horizontal = null; /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */ this.enter = null; /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */ this.leave = null; /** @type {Boolean} */ this.sync = isEase || isSmooth || !!syncMethods; /** @type {EasingFunction} */ this.syncEase = isEase ? ease : null; /** @type {Number} */ this.syncSmooth = isSmooth ? syncMode === true || isLinear ? 1 : /** @type {Number} */(syncMode) : null; /** @type {Callback<ScrollObserver>} */ this.onSyncEnter = syncMethods && !biDirSync && syncMethods[0] ? syncMethods[0] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncLeave = syncMethods && !biDirSync && syncMethods[1] ? syncMethods[1] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncEnterForward = syncMethods && biDirSync && syncMethods[0] ? syncMethods[0] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncLeaveForward = syncMethods && biDirSync && syncMethods[1] ? syncMethods[1] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncEnterBackward = syncMethods && biDirSync && syncMethods[2] ? syncMethods[2] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncLeaveBackward = syncMethods && biDirSync && syncMethods[3] ? syncMethods[3] : noop; /** @type {Callback<ScrollObserver>} */ this.onEnter = parameters.onEnter || noop; /** @type {Callback<ScrollObserver>} */ this.onLeave = parameters.onLeave || noop; /** @type {Callback<ScrollObserver>} */ this.onEnterForward = parameters.onEnterForward || noop; /** @type {Callback<ScrollObserver>} */ this.onLeaveForward = parameters.onLeaveForward || noop; /** @type {Callback<ScrollObserver>} */ this.onEnterBackward = parameters.onEnterBackward || noop; /** @type {Callback<ScrollObserver>} */ this.onLeaveBackward = parameters.onLeaveBackward || noop; /** @type {Callback<ScrollObserver>} */ this.onUpdate = parameters.onUpdate || noop; /** @type {Callback<ScrollObserver>} */ this.onSyncComplete = parameters.onSyncComplete || noop; /** @type {Boolean} */ this.reverted = false; /** @type {Boolean} */ this.ready = false; /** @type {Boolean} */ this.completed = false; /** @type {Boolean} */ this.began = false; /** @type {Boolean} */ this.isInView = false; /** @type {Boolean} */ this.forceEnter = false; /** @type {Boolean} */ this.hasEntered = false; /** @type {Number} */ this.offset = 0; /** @type {Number} */ this.offsetStart = 0; /** @type {Number} */ this.offsetEnd = 0; /** @type {Number} */ this.distance = 0; /** @type {Number} */ this.prevProgress = 0; /** @type {Array} */ this.thresholds = ['start', 'end', 'end', 'start']; /** @type {[Number, Number, Number, Number]} */ this.coords = [0, 0, 0, 0]; /** @type {JSAnimation} */ this.debugStyles = null; /** @type {HTMLElement} */ this.$debug = null; /** @type {ScrollObserverParams} */ this._params = parameters; /** @type {Boolean} */ this._debug = setValue(parameters.debug, false); /** @type {ScrollObserver} */ this._next = null; /** @type {ScrollObserver} */ this._prev = null; addChild(this.container, this); // Wait for the next frame to add to the container in order to handle calls to link() sync(() => { if (this.reverted) return; if (!this.target) { const target = /** @type {HTMLElement} */(parseTargets(parameters.target)[0]); this.target = target || doc.body; this.refresh(); } if (this._debug) this.debug(); }); } /** * @param {Tickable|WAAPIAnimation} linked */ link(linked) { if (linked) { // Make sure to pause the linked object in case it's added later linked.pause(); this.linked = linked; // Forces WAAPI Animation to persist; otherwise, they will stop syncing on finish. if (!isUnd(/** @type {WAAPIAnimation} */(linked))) /** @type {WAAPIAnimation} */(linked).persist = true; // Try to use a target of the linked object if no target parameters specified if (!this._params.target) { /** @type {HTMLElement} */ let $linkedTarget; if (!isUnd(/** @type {JSAnimation} */(linked).targets)) { $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(linked)); } else { forEachChildren(/** @type {Timeline} */(linked), (/** @type {JSAnimation} */child) => { if (child.targets && !$linkedTarget) { $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(child)); } }); } // Fallback to body if no target found this.target = $linkedTarget || doc.body; this.refresh(); } } return this; } get velocity() { return this.container.velocity; } get backward() { return this.horizontal ? this.container.backwardX : this.container.backwardY; } get scroll() { return this.horizontal ? this.container.scrollX : this.container.scrollY; } get progress() { const p = (this.scroll - this.offsetStart) / this.distance; return p === Infinity || isNaN(p) ? 0 : round(clamp(p, 0, 1), 6); } refresh() { // This flag is used to prevent running handleScroll() outside of this.refresh() with values not yet calculated this.ready = true; this.reverted = false; const params = this._params; this.repeat = setValue(parseScrollObserverFunctionParameter(params.repeat, this), true); this.horizontal = setValue(parseScrollObserverFunctionParameter(params.axis, this), 'y') === 'x'; this.enter = setValue(parseScrollObserverFunctionParameter(params.enter, this), 'end start'); this.leave = setValue(parseScrollObserverFunctionParameter(params.leave, this), 'start end'); this.updateBounds(); this.handleScroll(); return this; } removeDebug() { if (this.$debug) { this.$debug.parentNode.removeChild(this.$debug); this.$debug = null; } if (this.debugStyles) { this.debugStyles.revert(); this.$debug = null; } return this; } debug() { this.removeDebug(); const container = this.container; const isHori = this.horizontal; const $existingDebug = container.element.querySelector(':scope > .animejs-onscroll-debug'); const $debug = doc.createElement('div'); const $thresholds = doc.createElement('div'); const $triggers = doc.createElement('div'); const color = debugColors[this.index % debugColors.length]; const useWin = container.useWin; const containerWidth = useWin ? container.winWidth : container.width; const containerHeight = useWin ? container.winHeight : container.height; const scrollWidth = container.scrollWidth; const scrollHeight = container.scrollHeight; const size = this.container.width > 360 ? 320 : 260; const offLeft = isHori ? 0 : 10; const offTop = isHori ? 10 : 0; const half = isHori ? 24 : size / 2; const labelHeight = isHori ? half : 15; const labelWidth = isHori ? 60 : half; const labelSize = isHori ? labelWidth : labelHeight; const repeat = isHori ? 'repeat-x' : 'repeat-y'; /** * @param {Number} v * @return {String} */ const gradientOffset = v => isHori ? '0px '+(v)+'px' : (v)+'px'+' 2px'; /** * @param {String} c * @return {String} */ const lineCSS = (c) => `linear-gradient(${isHori ? 90 : 0}deg, ${c} 2px, transparent 1px)`; /** * @param {String} p * @param {Number} l * @param {Number} t * @param {Number} w * @param {Number} h * @return {String} */ const baseCSS = (p, l, t, w, h) => `position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`; $debug.style.cssText = `${baseCSS('absolute', offLeft, offTop, isHori ? scrollWidth : size, isHori ? size : scrollHeight)} pointer-events: none; z-index: ${this.container.zIndex++}; display: flex; flex-direction: ${isHori ? 'column' : 'row'}; filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75)); `; $thresholds.style.cssText = `${baseCSS('sticky', 0, 0, isHori ? containerWidth : half, isHori ? half : containerHeight)}`; if (!$existingDebug) { $thresholds.style.cssText += `background: ${lineCSS('#FFFF')}${gradientOffset(half-10)} / ${isHori ? '100px 100px' : '100px 100px'} ${repeat}, ${lineCSS('#FFF8')}${gradientOffset(half-10)} / ${isHori ? '10px 10px' : '10px 10px'} ${repeat}; `; } $triggers.style.cssText = `${baseCSS('relative', 0, 0, isHori ? scrollWidth : half, isHori ? half : scrollHeight)}`; if (!$existingDebug) { $triggers.style.cssText += `background: ${lineCSS('#FFFF')}${gradientOffset(0)} / ${isHori ? '100px 10px' : '10px 100px'} ${repeat}, ${lineCSS('#FFF8')}${gradientOffset(0)} / ${isHori ? '10px 0px' : '0px 10px'} ${repeat}; `; } const labels = [' enter: ', ' leave: ']; this.coords.forEach((v, i) => { const isView = i > 1; const value = (isView ? 0 : this.offset) + v; const isTail = i % 2; const isFirst = value < labelSize; const isOver = value > (isView ? isHori ? containerWidth : containerHeight : isHori ? scrollWidth : scrollHeight) - labelSize; const isFlip = (isView ? isTail && !isFirst : !isTail && !isFirst) || isOver; const $label = doc.createElement('div'); const $text = doc.createElement('div'); const dirProp = isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'; const flipOffset = isFlip ? (isHori ? labelWidth : labelHeight) + (!isView ? isHori ? -1 : -2 : isHori ? -1 : isOver ? 0 : -2) : !isView ? isHori ? 1 : 0 : isHori ? 1 : 0; // $text.innerHTML = `${!isView ? '' : labels[isTail] + ' '}${this.id}: ${this.thresholds[i]} ${isView ? '' : labels[isTail]}`; $text.innerHTML = `${this.id}${labels[isTail]}${this.thresholds[i]}`; $label.style.cssText = `${baseCSS('absolute', 0, 0, labelWidth, labelHeight)} display: flex; flex-direction: ${isHori ? 'column' : 'row'}; justify-content: flex-${isView ? 'start' : 'end'}; align-items: flex-${isFlip ? 'end' : 'start'}; border-${dirProp}: 2px ${isTail ? 'solid' : 'solid'} ${color}; `; $text.style.cssText = ` overflow: hidden; max-width: ${(size / 2) - 10}px; height: ${labelHeight}; margin-${isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'}: -2px; padding: 1px; font-family: ui-monospace, monospace; font-size: 10px; letter-spacing: -.025em; line-height: 9px; font-weight: 600; text-align: ${isHori && isFlip || !isHori && !isView ? 'right' : 'left'}; white-space: pre; text-overflow: ellipsis; color: ${isTail ? color : 'rgba(0,0,0,.75)'}; background-color: ${isTail ? 'rgba(0,0,0,.65)' : color}; border: 2px solid ${isTail ? color : 'transparent'}; border-${isHori ? isFlip ? 'top-left' : 'top-right' : isFlip ? 'top-left' : 'bottom-left'}-radius: 5px; border-${isHori ? isFlip ? 'bottom-left' : 'bottom-right' : isFlip ? 'top-right' : 'bottom-right'}-radius: 5px; `; $label.appendChild($text); let position = value - flipOffset + (isHori ? 1 : 0); $label.style[isHori ? 'left' : 'top'] = `${position}px`; // $label.style[isHori ? 'left' : 'top'] = value - flipOffset + (!isFlip && isFirst && !isView ? 1 : isFlip ? 0 : -2) + 'px'; (isView ? $thresholds : $triggers).appendChild($label); }); $debug.appendChild($thresholds); $debug.appendChild($triggers); container.element.appendChild($debug); if (!$existingDebug) $debug.classList.add('animejs-onscroll-debug'); this.$debug = $debug; const containerPosition = get(container.element, 'position'); if (containerPosition === 'static') { this.debugStyles = set(container.element, { position: 'relative '}); } } 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; // let $offsetParent = $el; /** @type {Element} */ if (linked) { linkedTime = linked.currentTime; linked.seek(0, true); } /* Old implementation to get offset and targetSize before fixing https://github.com/juliangarnier/anime/issues/1021 // const isContainerStatic = get(container.element, 'position') === 'static' ? set(container.element, { position: 'relative '}) : false; // while ($el && $el !== container.element && $el !== doc.body) { // const isSticky = get($el, 'position') === 'sticky' ? // set($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; while ($el && $el !== container.element && $el !== doc.body) { const isSticky = get($el, 'position') === 'sticky' ? set($el, { position: 'static' }) : false; $el = $el.parentElement; if (isSticky) { if (!stickys) stickys = []; stickys.push(isSticky); } } const rect = $target.getBoundingClientRect(); const scale = container.scale; const offset = (isHori ? rect.left + container.scrollX - container.left : rect.top + container.scrollY - container.top) * scale; const targetSize = (isHori ? rect.width : rect.height) * scale; 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.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(); } } handleScroll() { if (!this.ready) return; const linked = this.linked; const sync = this.sync; const syncEase = this.syncEase; const syncSmooth = this.syncSmooth; const shouldSeek = linked && (syncEase || syncSmooth); const isHori = this.horizontal; const container = this.container; const scroll = this.scroll; const isBefore = scroll <= this.offsetStart; const isAfter = scroll >= this.offsetEnd; const isInView = !isBefore && !isAfter; const isOnTheEdge = scroll === this.offsetStart || scroll === this.offsetEnd; const forceEnter = !this.hasEntered && isOnTheEdge; const $debug = this._debug && this.$debug; let hasUpdated = false; let syncCompleted = false; let p = this.progress; if (isBefore && this.began) { this.began = false; } if (p > 0 && !this.began) { this.began = true; } if (shouldSeek) { const lp = linked.progress; if (syncSmooth && isNum(syncSmooth)) { if (/** @type {Number} */(syncSmooth) < 1) { const step = 0.0001; const snap = lp < p && p === 1 ? step : lp > p && !p ? -step : 0; p = round(lerp(lp, p, lerp(.01, .2, /** @type {Number} */(syncSmooth))) + snap, 6); } } else if (syncEase) { p = syncEase(p); } hasUpdated = p !== this.prevProgress; syncCompleted = lp === 1; if (hasUpdated && !syncCompleted && (syncSmooth && lp)) { container.wakeTicker.restart(); } } if ($debug) { const sticky = isHori ? container.scrollY : container.scrollX; $debug.style[isHori ? 'top' : 'left'] = sticky + 10 + 'px'; } // Trigger enter callbacks if already in view or when entering the view if ((isInView && !this.isInView) || (forceEnter && !this.forceEnter && !this.hasEntered)) { if (isInView) this.isInView = true; if (!this.forceEnter || !this.hasEntered) { if ($debug && isInView) $debug.style.zIndex = `${this.container.zIndex++}`; this.onSyncEnter(this); this.onEnter(this); if (this.backward) { this.onSyncEnterBackward(this); this.onEnterBackward(this); } else { this.onSyncEnterForward(this); this.onEnterForward(this); } this.hasEntered = true; if (forceEnter) this.forceEnter = true; } else if (isInView) { this.forceEnter = false; } } if (isInView || !isInView && this.isInView) { hasUpdated = true; } if (hasUpdated) { if (shouldSeek) linked.seek(linked.duration * p); this.onUpdate(this); } if (!isInView && this.isInView) { this.isInView = false; this.onSyncLeave(this); this.onLeave(this); if (this.backward) { this.onSyncLeaveBackward(this); this.onLeaveBackward(this); } else { this.onSyncLeaveForward(this); this.onLeaveForward(this); } if (sync && !syncSmooth) { syncCompleted = true; } } if (p >= 1 && this.began && !this.completed && (sync && syncCompleted || !sync)) { if (sync) { this.onSyncComplete(this); } this.completed = true; if ((!this.repeat && !linked) || (!this.repeat && linked && linked.completed)) { this.revert(); } } if (p < 1 && this.completed) { this.completed = false; } this.prevProgress = p; } revert() { if (this.reverted) return; const container = this.container; removeChild(container, this); if (!container._head) { container.revert(); } if (this._debug) { this.removeDebug(); } this.reverted = true; this.ready = false; return this; } } /** * @param {ScrollObserverParams} [parameters={}] * @return {ScrollObserver} */ const onScroll = (parameters = {}) => new ScrollObserver(parameters);
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
true
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/clock.js
dist/modules/core/clock.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { K, maxFps, minValue, tickModes } from './consts.js'; import { round } from './helpers.js'; /** * @import { * Tickable, * Tween, * } from '../types/index.js' */ /* * Base class to control framerate and playback rate. * Inherited by Engine, Timer, Animation and Timeline. */ class Clock { /** @param {Number} [initTime] */ constructor(initTime = 0) { /** @type {Number} */ this.deltaTime = 0; /** @type {Number} */ this._currentTime = initTime; /** @type {Number} */ this._elapsedTime = initTime; /** @type {Number} */ this._startTime = initTime; /** @type {Number} */ this._lastTime = initTime; /** @type {Number} */ this._scheduledTime = 0; /** @type {Number} */ this._frameDuration = round(K / maxFps, 0); /** @type {Number} */ this._fps = maxFps; /** @type {Number} */ this._speed = 1; /** @type {Boolean} */ this._hasChildren = false; /** @type {Tickable|Tween} */ this._head = null; /** @type {Tickable|Tween} */ this._tail = null; } get fps() { return this._fps; } set fps(frameRate) { const previousFrameDuration = this._frameDuration; const fr = +frameRate; const fps = fr < minValue ? minValue : fr; const frameDuration = round(K / fps, 0); this._fps = fps; this._frameDuration = frameDuration; this._scheduledTime += frameDuration - previousFrameDuration; } get speed() { return this._speed; } set speed(playbackRate) { const pbr = +playbackRate; this._speed = pbr < minValue ? minValue : pbr; } /** * @param {Number} time * @return {tickModes} */ requestTick(time) { const scheduledTime = this._scheduledTime; const elapsedTime = this._elapsedTime; this._elapsedTime += (time - elapsedTime); // If the elapsed time is lower than the scheduled time // this means not enough time has passed to hit one frameDuration // so skip that frame if (elapsedTime < scheduledTime) return tickModes.NONE; const frameDuration = this._frameDuration; const frameDelta = elapsedTime - scheduledTime; // Ensures that _scheduledTime progresses in steps of at least 1 frameDuration. // Skips ahead if the actual elapsed time is higher. this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta; return tickModes.AUTO; } /** * @param {Number} time * @return {Number} */ computeDeltaTime(time) { const delta = time - this._lastTime; this.deltaTime = delta; this._lastTime = time; return delta; } } export { Clock };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/consts.js
dist/modules/core/consts.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ // Environments // TODO: Do we need to check if we're running inside a worker ? const isBrowser = typeof window !== 'undefined'; /** @type {Window & {AnimeJS: Array}|null} */ const win = isBrowser ? /** @type {Window & {AnimeJS: Array}} */(/** @type {unknown} */(window)) : null; /** @type {Document|null} */ const doc = isBrowser ? document : null; // Enums /** @enum {Number} */ const tweenTypes = { OBJECT: 0, ATTRIBUTE: 1, CSS: 2, TRANSFORM: 3, CSS_VAR: 4, }; /** @enum {Number} */ const valueTypes = { NUMBER: 0, UNIT: 1, COLOR: 2, COMPLEX: 3, }; /** @enum {Number} */ const tickModes = { NONE: 0, AUTO: 1, FORCE: 2, }; /** @enum {Number} */ const compositionTypes = { replace: 0, none: 1, blend: 2, }; // Cache symbols const isRegisteredTargetSymbol = Symbol(); const isDomSymbol = Symbol(); const isSvgSymbol = Symbol(); const transformsSymbol = Symbol(); const morphPointsSymbol = Symbol(); const proxyTargetSymbol = Symbol(); // Numbers const minValue = 1e-11; const maxValue = 1e12; const K = 1e3; const maxFps = 120; // Strings const emptyString = ''; const cssVarPrefix = 'var('; const shortTransforms = /*#__PURE__*/ (() => { const map = new Map(); map.set('x', 'translateX'); map.set('y', 'translateY'); map.set('z', 'translateZ'); return map; })(); const validTransforms = [ 'translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'matrix', 'matrix3d', 'perspective', ]; const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {}); // Functions /** @return {void} */ const noop = () => {}; // Regex const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i; const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i; const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i; const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i; const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i; // export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g; const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi; // export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i; const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i; const lowerCaseRgx = /([a-z])([A-Z])/g; const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in () const relativeValuesExecRgx = /(\*=|\+=|-=)/; const cssVariableMatchRgx = /var\(\s*(--[\w-]+)(?:\s*,\s*([^)]+))?\s*\)/; export { K, compositionTypes, cssVarPrefix, cssVariableMatchRgx, digitWithExponentRgx, doc, emptyString, hexTestRgx, hslExecRgx, hslaExecRgx, isBrowser, isDomSymbol, isRegisteredTargetSymbol, isSvgSymbol, lowerCaseRgx, maxFps, maxValue, minValue, morphPointsSymbol, noop, proxyTargetSymbol, relativeValuesExecRgx, rgbExecRgx, rgbaExecRgx, shortTransforms, tickModes, transformsExecRgx, transformsFragmentStrings, transformsSymbol, tweenTypes, unitsExecRgx, validTransforms, valueTypes, win };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/colors.js
dist/modules/core/colors.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { rgbExecRgx, rgbaExecRgx, hslExecRgx, hslaExecRgx } from './consts.js'; import { isRgb, isHex, isHsl, isUnd, round } from './helpers.js'; /** * @import { * ColorArray, * } from '../types/index.js' */ /** * RGB / RGBA Color value string -> RGBA values array * @param {String} rgbValue * @return {ColorArray} */ const rgbToRgba = rgbValue => { const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue); const a = !isUnd(rgba[4]) ? +rgba[4] : 1; return [ +rgba[1], +rgba[2], +rgba[3], a ] }; /** * HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array * @param {String} hexValue * @return {ColorArray} */ const hexToRgba = hexValue => { const hexLength = hexValue.length; const isShort = hexLength === 4 || hexLength === 5; return [ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]), +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]), +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]), ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1) ] }; /** * @param {Number} p * @param {Number} q * @param {Number} t * @return {Number} */ const hue2rgb = (p, q, t) => { if (t < 0) t += 1; if (t > 1) t -= 1; return t < 1 / 6 ? p + (q - p) * 6 * t : t < 1 / 2 ? q : t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 : p; }; /** * HSL / HSLA Color value string -> RGBA values array * @param {String} hslValue * @return {ColorArray} */ const hslToRgba = hslValue => { const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue); const h = +hsla[1] / 360; const s = +hsla[2] / 100; const l = +hsla[3] / 100; const a = !isUnd(hsla[4]) ? +hsla[4] : 1; let r, g, b; if (s === 0) { r = g = b = l; } else { const q = l < .5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = round(hue2rgb(p, q, h + 1 / 3) * 255, 0); g = round(hue2rgb(p, q, h) * 255, 0); b = round(hue2rgb(p, q, h - 1 / 3) * 255, 0); } return [r, g, b, a]; }; /** * All in one color converter that converts a color string value into an array of RGBA values * @param {String} colorString * @return {ColorArray} */ const convertColorStringValuesToRgbaArray = colorString => { return isRgb(colorString) ? rgbToRgba(colorString) : isHex(colorString) ? hexToRgba(colorString) : isHsl(colorString) ? hslToRgba(colorString) : [0, 0, 0, 1]; }; export { convertColorStringValuesToRgbaArray };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/transforms.js
dist/modules/core/transforms.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { transformsSymbol, transformsExecRgx } from './consts.js'; import { isUnd, stringStartsWith } from './helpers.js'; /** * @import { * DOMTarget, * } from '../types/index.js' */ /** * @param {DOMTarget} target * @param {String} propName * @param {Object} animationInlineStyles * @return {String} */ const parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } } return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue : stringStartsWith(propName, 'scale') ? '1' : stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px'; }; export { parseInlineTransforms };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/styles.js
dist/modules/core/styles.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { tweenTypes, shortTransforms, isDomSymbol, transformsSymbol, transformsFragmentStrings, emptyString } from './consts.js'; import { forEachChildren, isSvg, toLowerCase, isNil } from './helpers.js'; /** * @import { * JSAnimation, * } from '../animation/animation.js' */ /** * @import { * Target, * DOMTarget, * Renderable, * Tween, * } from '../types/index.js' */ const propertyNamesCache = {}; /** * @param {String} propertyName * @param {Target} target * @param {tweenTypes} tweenType * @return {String} */ const 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; } }; /** * @template {Renderable} T * @param {T} renderable * @return {T} */ const cleanInlineStyles = renderable => { // Allow cleanInlineStyles() to be called on timelines if (renderable._hasChildren) { forEachChildren(renderable, cleanInlineStyles, true); } else { const animation = /** @type {JSAnimation} */(renderable); animation.pause(); forEachChildren(animation, (/** @type {Tween} */tween) => { const tweenProperty = tween.property; const tweenTarget = tween.target; if (tweenTarget[isDomSymbol]) { const targetStyle = /** @type {DOMTarget} */(tweenTarget).style; const originalInlinedValue = tween._inlineValue; const tweenHadNoInlineValue = isNil(originalInlinedValue) || originalInlinedValue === emptyString; if (tween._tweenType === tweenTypes.TRANSFORM) { const cachedTransforms = tweenTarget[transformsSymbol]; if (tweenHadNoInlineValue) { delete cachedTransforms[tweenProperty]; } else { cachedTransforms[tweenProperty] = originalInlinedValue; } if (tween._renderTransforms) { if (!Object.keys(cachedTransforms).length) { targetStyle.removeProperty('transform'); } else { let str = emptyString; for (let key in cachedTransforms) { str += transformsFragmentStrings[key] + cachedTransforms[key] + ') '; } targetStyle.transform = str; } } } else { if (tweenHadNoInlineValue) { targetStyle.removeProperty(toLowerCase(tweenProperty)); } else { targetStyle[tweenProperty] = originalInlinedValue; } } if (animation._tail === tween) { animation.targets.forEach(t => { if (t.getAttribute && t.getAttribute('style') === emptyString) { t.removeAttribute('style'); } }); } } }); } return renderable; }; export { cleanInlineStyles, sanitizePropertyName };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/globals.js
dist/modules/core/globals.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { isBrowser, win, noop, maxFps, K, compositionTypes, doc } from './consts.js'; /** * @import { * DefaultsParams, * DOMTarget, * } from '../types/index.js' * * @import { * Scope, * } from '../scope/index.js' */ /** @type {DefaultsParams} */ const defaults = { id: null, keyframes: null, playbackEase: null, playbackRate: 1, frameRate: maxFps, loop: 0, reversed: false, alternate: false, autoplay: true, persist: false, duration: K, delay: 0, loopDelay: 0, ease: 'out(2)', composition: compositionTypes.replace, modifier: v => v, onBegin: noop, onBeforeUpdate: noop, onUpdate: noop, onLoop: noop, onPause: noop, onComplete: noop, onRender: noop, }; const scope = { /** @type {Scope} */ current: null, /** @type {Document|DOMTarget} */ root: doc, }; const globals = { /** @type {DefaultsParams} */ defaults, /** @type {Number} */ precision: 4, /** @type {Number} equals 1 in ms mode, 0.001 in s mode */ timeScale: 1, /** @type {Number} */ tickThreshold: 200, }; const globalVersions = { version: '4.2.2', engine: null }; if (isBrowser) { if (!win.AnimeJS) win.AnimeJS = []; win.AnimeJS.push(globalVersions); } export { defaults, globalVersions, globals, scope };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/render.js
dist/modules/core/render.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { globals } from './globals.js'; import { minValue, tickModes, valueTypes, compositionTypes, tweenTypes, transformsSymbol, transformsFragmentStrings, emptyString } from './consts.js'; import { forEachChildren, round, now, clamp, lerp } from './helpers.js'; /** * @import { * Tickable, * Renderable, * CallbackArgument, * Tween, * DOMTarget, * } from '../types/index.js' */ /** * @import { * JSAnimation, * } from '../animation/animation.js' */ /** * @import { * Timeline, * } from '../timeline/timeline.js' */ /** * @param {Tickable} tickable * @param {Number} time * @param {Number} muteCallbacks * @param {Number} internalRender * @param {tickModes} tickMode * @return {Number} */ const render = (tickable, time, muteCallbacks, internalRender, tickMode) => { const parent = tickable.parent; const duration = tickable.duration; const completed = tickable.completed; const iterationDuration = tickable.iterationDuration; const iterationCount = tickable.iterationCount; const _currentIteration = tickable._currentIteration; const _loopDelay = tickable._loopDelay; const _reversed = tickable._reversed; const _alternate = tickable._alternate; const _hasChildren = tickable._hasChildren; const tickableDelay = tickable._delay; const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime const tickableEndTime = tickableDelay + iterationDuration; const tickableAbsoluteTime = time - tickableDelay; const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration); const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration); const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime; const isCurrentTimeAboveZero = tickableCurrentTime > 0; const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration; const isSetter = duration <= minValue; const forcedTick = tickMode === tickModes.FORCE; let isOdd = 0; let iterationElapsedTime = tickableAbsoluteTime; // Render checks // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer let hasRendered = 0; // Execute the "expensive" iterations calculations only when necessary if (iterationCount > 1) { // bitwise NOT operator seems to be generally faster than Math.floor() across browsers const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay))); tickable._currentIteration = clamp(currentIteration, 0, iterationCount); // Prevent the iteration count to go above the max iterations when reaching the end of the animation if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--; isOdd = tickable._currentIteration % 2; iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0; } // Checks if exactly one of _reversed and (_alternate && isOdd) is true const isReversed = _reversed ^ (_alternate && isOdd); const _ease = /** @type {Renderable} */(tickable)._ease; let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime; if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0; const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed; tickable._currentTime = tickableAbsoluteTime; tickable._iterationTime = iterationTime; tickable.backwards = isRunningBackwards; if (isCurrentTimeAboveZero && !tickable.began) { tickable.began = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onBegin(/** @type {CallbackArgument} */(tickable)); } } else if (tickableAbsoluteTime <= 0) { tickable.began = false; } // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) { tickable.onLoop(/** @type {CallbackArgument} */(tickable)); } if ( forcedTick || tickMode === tickModes.AUTO && ( time >= tickableDelay && time <= tickableEndTime || // Normal render time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state ) || iterationTime >= tickableEndTime && tickablePrevTime !== duration || iterationTime <= tickableDelay && tickablePrevTime > 0 || time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped ) { if (isCurrentTimeAboveZero) { // Trigger onUpdate callback before rendering tickable.computeDeltaTime(tickablePrevTime); if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable)); } // Start tweens rendering if (!_hasChildren) { // Time has jumped more than globals.tickThreshold so consider this tick manual const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold; const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime; // Only Animation can have tweens, Timer returns undefined let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head); let tweenTarget; let tweenStyle; let tweenTargetTransforms; let tweenTargetTransformsProperties; let tweenTransformsNeedUpdate = 0; while (tween) { const tweenComposition = tween._composition; const tweenCurrentTime = tween._currentTime; const tweenChangeDuration = tween._changeDuration; const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration; const tweenNextRep = tween._nextRep; const tweenPrevRep = tween._prevRep; const tweenHasComposition = tweenComposition !== compositionTypes.none; if ((forcedRender || ( (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) && (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime) )) && (!tweenHasComposition || ( !tween._isOverridden && (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) && (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) && (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay))) )) ) { const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration); const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration); const tweenModifier = tween._modifier; const tweenValueType = tween._valueType; const tweenType = tween._tweenType; const tweenIsObject = tweenType === tweenTypes.OBJECT; const tweenIsNumber = tweenValueType === valueTypes.NUMBER; // Only round the in-between frames values if the final value is a string const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision; // Recompose tween value /** @type {String|Number} */ let value; /** @type {Number} */ let number; if (tweenIsNumber) { value = number = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision ))); } else if (tweenValueType === valueTypes.UNIT) { // Rounding the values speed up string composition number = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision))); value = `${number}${tween._unit}`; } else if (tweenValueType === valueTypes.COLOR) { const fn = tween._fromNumbers; const tn = tween._toNumbers; const r = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[0], tn[0], tweenProgress))), 0, 255), 0); const g = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[1], tn[1], tweenProgress))), 0, 255), 0); const b = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[2], tn[2], tweenProgress))), 0, 255), 0); const a = clamp(/** @type {Number} */(tweenModifier(round(lerp(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1); value = `rgba(${r},${g},${b},${a})`; if (tweenHasComposition) { const ns = tween._numbers; ns[0] = r; ns[1] = g; ns[2] = b; ns[3] = a; } } else if (tweenValueType === valueTypes.COMPLEX) { value = tween._strings[0]; for (let j = 0, l = tween._toNumbers.length; j < l; j++) { const n = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision))); const s = tween._strings[j + 1]; value += `${s ? n + s : n}`; if (tweenHasComposition) { tween._numbers[j] = n; } } } // For additive tweens and Animatables if (tweenHasComposition) { tween._number = number; } if (!internalRender && tweenComposition !== compositionTypes.blend) { const tweenProperty = tween.property; tweenTarget = tween.target; if (tweenIsObject) { tweenTarget[tweenProperty] = value; } else if (tweenType === tweenTypes.ATTRIBUTE) { /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value)); } else { tweenStyle = /** @type {DOMTarget} */(tweenTarget).style; if (tweenType === tweenTypes.TRANSFORM) { if (tweenTarget !== tweenTargetTransforms) { tweenTargetTransforms = tweenTarget; // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage. tweenTargetTransformsProperties = tweenTarget[transformsSymbol]; } tweenTargetTransformsProperties[tweenProperty] = value; tweenTransformsNeedUpdate = 1; } else if (tweenType === tweenTypes.CSS) { tweenStyle[tweenProperty] = value; } else if (tweenType === tweenTypes.CSS_VAR) { tweenStyle.setProperty(tweenProperty,/** @type {String} */(value)); } } if (isCurrentTimeAboveZero) hasRendered = 1; } else { // Used for composing timeline tweens without having to do a real render tween._value = value; } } // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax // to reduce memory usage on string composition if (tweenTransformsNeedUpdate && tween._renderTransforms) { let str = emptyString; for (let key in tweenTargetTransformsProperties) { str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `; } tweenStyle.transform = str; tweenTransformsNeedUpdate = 0; } tween = tween._next; } if (!muteCallbacks && hasRendered) { /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable)); } } if (!muteCallbacks && isCurrentTimeAboveZero) { tickable.onUpdate(/** @type {CallbackArgument} */(tickable)); } } // End tweens rendering // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards if (parent && isSetter) { if (!muteCallbacks && ( // (tickableAbsoluteTime > 0 instead) of (tickableAbsoluteTime >= duration) to prevent floating point precision issues // see: https://github.com/juliangarnier/anime/issues/1088 (parent.began && !isRunningBackwards && tickableAbsoluteTime > 0 && !completed) || (isRunningBackwards && tickableAbsoluteTime <= minValue && completed) )) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable.completed = !isRunningBackwards; } // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) { if (iterationCount === Infinity) { // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer tickable._startTime += tickable.duration; } else if (tickable._currentIteration >= iterationCount - 1) { // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick tickable.paused = true; if (!completed && !_hasChildren) { // If the tickable has children, triggers onComplete() only when all children have completed in the tick function tickable.completed = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable._resolve(/** @type {CallbackArgument} */(tickable)); } } } // Otherwise set the completed flag to false } else { tickable.completed = false; } // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ? return hasRendered; }; /** * @param {Tickable} tickable * @param {Number} time * @param {Number} muteCallbacks * @param {Number} internalRender * @param {Number} tickMode * @return {void} */ const tick = (tickable, time, muteCallbacks, internalRender, tickMode) => { const _currentIteration = tickable._currentIteration; render(tickable, time, muteCallbacks, internalRender, tickMode); if (tickable._hasChildren) { const tl = /** @type {Timeline} */(tickable); const tlIsRunningBackwards = tl.backwards; const tlChildrenTime = internalRender ? time : tl._iterationTime; const tlCildrenTickTime = now(); let tlChildrenHasRendered = 0; let tlChildrenHaveCompleted = true; // If the timeline has looped forward, we need to manually triggers children skipped callbacks if (!internalRender && tl._currentIteration !== _currentIteration) { const tlIterationDuration = tl.iterationDuration; forEachChildren(tl, (/** @type {JSAnimation} */child) => { if (!tlIsRunningBackwards) { // Force an internal render to trigger the callbacks if the child has not completed on loop if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) { render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE); } // Reset their began and completed flags to allow retrigering callbacks on the next iteration child.began = false; child.completed = false; } else { const childDuration = child.duration; const childStartTime = child._offset + child._delay; const childEndTime = childStartTime + childDuration; // Triggers the onComplete callback on reverse for children on the edges of the timeline if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) { child.onComplete(child); } } }); if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl)); } forEachChildren(tl, (/** @type {JSAnimation} */child) => { const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode; tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode); if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false; }, tlIsRunningBackwards); // Renders on timeline are triggered by its children so it needs to be set after rendering the children if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl)); // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end if ((tlChildrenHaveCompleted || tlIsRunningBackwards) && tl._currentTime >= tl.duration) { // Make sure the paused flag is false in case it has been skipped in the render function tl.paused = true; if (!tl.completed) { tl.completed = true; if (!muteCallbacks) { tl.onComplete(/** @type {CallbackArgument} */(tl)); tl._resolve(/** @type {CallbackArgument} */(tl)); } } } } }; export { render, tick };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/targets.js
dist/modules/core/targets.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { scope } from './globals.js'; import { isRegisteredTargetSymbol, isDomSymbol, isSvgSymbol, transformsSymbol, isBrowser } from './consts.js'; import { isSvg, isNil, isArr, isStr } from './helpers.js'; /** * @import { * DOMTarget, * DOMTargetsParam, * JSTargetsArray, * TargetsParam, * JSTargetsParam, * TargetsArray, * DOMTargetsArray, * } from '../types/index.js' */ /** * @param {DOMTargetsParam|TargetsParam} v * @return {NodeList|HTMLCollection} */ function getNodeList(v) { const n = isStr(v) ? scope.root.querySelectorAll(v) : v; if (n instanceof NodeList || n instanceof HTMLCollection) return n; } /** * @overload * @param {DOMTargetsParam} targets * @return {DOMTargetsArray} * * @overload * @param {JSTargetsParam} targets * @return {JSTargetsArray} * * @overload * @param {TargetsParam} targets * @return {TargetsArray} * * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets */ function parseTargets(targets) { if (isNil(targets)) return /** @type {TargetsArray} */([]); if (!isBrowser) return /** @type {JSTargetsArray} */(isArr(targets) && targets.flat(Infinity) || [targets]); if (isArr(targets)) { const flattened = targets.flat(Infinity); /** @type {TargetsArray} */ const parsed = []; for (let i = 0, l = flattened.length; i < l; i++) { const item = flattened[i]; if (!isNil(item)) { const nodeList = getNodeList(item); if (nodeList) { for (let j = 0, jl = nodeList.length; j < jl; j++) { const subItem = nodeList[j]; if (!isNil(subItem)) { let isDuplicate = false; for (let k = 0, kl = parsed.length; k < kl; k++) { if (parsed[k] === subItem) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(subItem); } } } } else { let isDuplicate = false; for (let j = 0, jl = parsed.length; j < jl; j++) { if (parsed[j] === item) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(item); } } } } return parsed; } const nodeList = getNodeList(targets); if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList)); return /** @type {TargetsArray} */([targets]); } /** * @overload * @param {DOMTargetsParam} targets * @return {DOMTargetsArray} * * @overload * @param {JSTargetsParam} targets * @return {JSTargetsArray} * * @overload * @param {TargetsParam} targets * @return {TargetsArray} * * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets */ function registerTargets(targets) { const parsedTargetsArray = parseTargets(targets); const parsedTargetsLength = parsedTargetsArray.length; if (parsedTargetsLength) { for (let i = 0; i < parsedTargetsLength; i++) { const target = parsedTargetsArray[i]; if (!target[isRegisteredTargetSymbol]) { target[isRegisteredTargetSymbol] = true; const isSvgType = isSvg(target); const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType; if (isDom) { target[isDomSymbol] = true; target[isSvgSymbol] = isSvgType; target[transformsSymbol] = {}; } } } } return parsedTargetsArray; } export { getNodeList, parseTargets, registerTargets };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/helpers.js
dist/modules/core/helpers.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { isBrowser, maxValue, minValue, hexTestRgx, lowerCaseRgx } from './consts.js'; import { globals } from './globals.js'; /** * @import { * Target, * DOMTarget, * } from '../types/index.js' */ // Strings /** * @param {String} str * @return {String} */ const toLowerCase = str => str.replace(lowerCaseRgx, '$1-$2').toLowerCase(); /** * Prioritize this method instead of regex when possible * @param {String} str * @param {String} sub * @return {Boolean} */ const stringStartsWith = (str, sub) => str.indexOf(sub) === 0; // Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement. const now = Date.now; // Types checkers const isArr = Array.isArray; /**@param {any} a @return {a is Record<String, any>} */ const isObj = a => a && a.constructor === Object; /**@param {any} a @return {a is Number} */ const isNum = a => typeof a === 'number' && !isNaN(a); /**@param {any} a @return {a is String} */ const isStr = a => typeof a === 'string'; /**@param {any} a @return {a is Function} */ const isFnc = a => typeof a === 'function'; /**@param {any} a @return {a is undefined} */ const isUnd = a => typeof a === 'undefined'; /**@param {any} a @return {a is null | undefined} */ const isNil = a => isUnd(a) || a === null; /**@param {any} a @return {a is SVGElement} */ const isSvg = a => isBrowser && a instanceof SVGElement; /**@param {any} a @return {Boolean} */ const isHex = a => hexTestRgx.test(a); /**@param {any} a @return {Boolean} */ const isRgb = a => stringStartsWith(a, 'rgb'); /**@param {any} a @return {Boolean} */ const isHsl = a => stringStartsWith(a, 'hsl'); /**@param {any} a @return {Boolean} */ const isCol = a => isHex(a) || isRgb(a) || isHsl(a); /**@param {any} a @return {Boolean} */ const isKey = a => !globals.defaults.hasOwnProperty(a); // SVG // Consider the following as CSS animation // CSS opacity animation has better default values (opacity: 1 instead of 0)) // rotate is more commonly intended to be used as a transform const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color']; /** * @param {Target} el * @param {String} propertyName * @return {Boolean} */ const isValidSVGAttribute = (el, propertyName) => { if (svgCssReservedProperties.includes(propertyName)) return false; if (el.getAttribute(propertyName) || propertyName in el) { if (propertyName === 'scale') { // Scale const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode); // Only consider scale as a valid SVG attribute on filter element return elParentNode && elParentNode.tagName === 'filter'; } return true; } }; // Number /** * @param {Number|String} str * @return {Number} */ const parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */(str)) : /** @type {Number} */(str); // Math const pow = Math.pow; const sqrt = Math.sqrt; const sin = Math.sin; const cos = Math.cos; const abs = Math.abs; const exp = Math.exp; const ceil = Math.ceil; const floor = Math.floor; const asin = Math.asin; const max = Math.max; const atan2 = Math.atan2; const PI = Math.PI; const _round = Math.round; /** * Clamps a value between min and max bounds * * @param {Number} v - Value to clamp * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {Number} */ const clamp = (v, min, max) => v < min ? min : v > max ? max : v; const powCache = {}; /** * Rounds a number to specified decimal places * * @param {Number} v - Value to round * @param {Number} decimalLength - Number of decimal places * @return {Number} */ const round = (v, decimalLength) => { if (decimalLength < 0) return v; if (!decimalLength) return _round(v); let p = powCache[decimalLength]; if (!p) p = powCache[decimalLength] = 10 ** decimalLength; return _round(v * p) / p; }; /** * Snaps a value to nearest increment or array value * * @param {Number} v - Value to snap * @param {Number|Array<Number>} increment - Step size or array of snap points * @return {Number} */ const snap = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v; /** * Linear interpolation between two values * * @param {Number} start - Starting value * @param {Number} end - Ending value * @param {Number} factor - Interpolation factor in the range [0, 1] * @return {Number} The interpolated value */ const lerp = (start, end, factor) => start + (end - start) * factor; /** * Replaces infinity with maximum safe value * * @param {Number} v - Value to check * @return {Number} */ const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v; /** * Normalizes time value with minimum threshold * * @param {Number} v - Time value to normalize * @return {Number} */ const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round(v, 11)); // Arrays /** * @template T * @param {T[]} a * @return {T[]} */ const cloneArray = a => isArr(a) ? [ ...a ] : a; // Objects /** * @template T * @template U * @param {T} o1 * @param {U} o2 * @return {T & U} */ const mergeObjects = (o1, o2) => { const merged = /** @type {T & U} */({ ...o1 }); for (let p in o2) { const o1p = /** @type {T & U} */(o1)[p]; merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p; } return merged; }; // Linked lists /** * @param {Object} parent * @param {Function} callback * @param {Boolean} [reverse] * @param {String} [prevProp] * @param {String} [nextProp] * @return {void} */ const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => { let next = parent._head; let adjustedNextProp = nextProp; if (reverse) { next = parent._tail; adjustedNextProp = prevProp; } while (next) { const currentNext = next[adjustedNextProp]; callback(next); next = currentNext; } }; /** * @param {Object} parent * @param {Object} child * @param {String} [prevProp] * @param {String} [nextProp] * @return {void} */ const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => { const prev = child[prevProp]; const next = child[nextProp]; prev ? prev[nextProp] = next : parent._head = next; next ? next[prevProp] = prev : parent._tail = prev; child[prevProp] = null; child[nextProp] = null; }; /** * @param {Object} parent * @param {Object} child * @param {Function} [sortMethod] * @param {String} prevProp * @param {String} nextProp * @return {void} */ const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => { let prev = parent._tail; while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp]; const next = prev ? prev[nextProp] : parent._head; prev ? prev[nextProp] = child : parent._head = child; next ? next[prevProp] = child : parent._tail = child; child[prevProp] = prev; child[nextProp] = next; }; export { PI, _round, abs, addChild, asin, atan2, ceil, clamp, clampInfinity, cloneArray, cos, exp, floor, forEachChildren, isArr, isCol, isFnc, isHex, isHsl, isKey, isNil, isNum, isObj, isRgb, isStr, isSvg, isUnd, isValidSVGAttribute, lerp, max, mergeObjects, normalizeTime, now, parseNumber, pow, removeChild, round, sin, snap, sqrt, stringStartsWith, toLowerCase };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/values.js
dist/modules/core/values.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { tweenTypes, isDomSymbol, isSvgSymbol, validTransforms, shortTransforms, valueTypes, unitsExecRgx, digitWithExponentRgx, proxyTargetSymbol, cssVarPrefix, cssVariableMatchRgx, emptyString } from './consts.js'; import { isUnd, isValidSVGAttribute, stringStartsWith, isCol, isFnc, isStr, cloneArray } from './helpers.js'; import { parseInlineTransforms } from './transforms.js'; import { convertColorStringValuesToRgbaArray } from './colors.js'; /** * @import { * Target, * DOMTarget, * Tween, * TweenPropValue, * TweenDecomposedValue, * } from '../types/index.js' */ /** * @template T, D * @param {T|undefined} targetValue * @param {D} defaultValue * @return {T|D} */ const setValue = (targetValue, defaultValue) => { return isUnd(targetValue) ? defaultValue : targetValue; }; /** * @param {TweenPropValue} value * @param {Target} target * @param {Number} index * @param {Number} total * @param {Object} [store] * @return {any} */ const getFunctionValue = (value, target, index, total, store) => { let func; if (isFnc(value)) { func = () => { const computed = /** @type {Function} */(value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; }; } else if (isStr(value) && stringStartsWith(value, cssVarPrefix)) { func = () => { const match = value.match(cssVariableMatchRgx); const cssVarName = match[1]; const fallbackValue = match[2]; let computed = getComputedStyle(/** @type {HTMLElement} */(target))?.getPropertyValue(cssVarName); // Use fallback if CSS variable is not set or empty if ((!computed || computed.trim() === emptyString) && fallbackValue) { computed = fallbackValue.trim(); } return computed || 0; }; } else { return value; } if (store) store.func = func; return func(); }; /** * @param {Target} target * @param {String} prop * @return {tweenTypes} */ const getTweenType = (target, prop) => { return !target[isDomSymbol] ? tweenTypes.OBJECT : // Handle SVG attributes target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE : // Handle CSS Transform properties differently than CSS to allow individual animations validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM : // CSS variables stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR : // All other CSS properties prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS : // Handle other DOM Attributes prop in target ? tweenTypes.OBJECT : tweenTypes.ATTRIBUTE; }; /** * @param {DOMTarget} target * @param {String} propName * @param {Object} animationInlineStyles * @return {String} */ const getCSSValue = (target, propName, animationInlineStyles) => { const inlineStyles = target.style[propName]; if (inlineStyles && animationInlineStyles) { animationInlineStyles[propName] = inlineStyles; } const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName); return value === 'auto' ? '0' : value; }; /** * @param {Target} target * @param {String} propName * @param {tweenTypes} [tweenType] * @param {Object|void} [animationInlineStyles] * @return {String|Number} */ const getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => { const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName); return type === tweenTypes.OBJECT ? target[propName] || 0 : type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) : type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) : type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() : getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles); }; /** * @param {Number} x * @param {Number} y * @param {String} operator * @return {Number} */ const getRelativeValue = (x, y, operator) => { return operator === '-' ? x - y : operator === '+' ? x + y : x * y; }; /** @return {TweenDecomposedValue} */ const createDecomposedValueTargetObject = () => { return { /** @type {valueTypes} */ t: valueTypes.NUMBER, n: 0, u: null, o: null, d: null, s: null, } }; /** * @param {String|Number} rawValue * @param {TweenDecomposedValue} targetObject * @return {TweenDecomposedValue} */ const decomposeRawValue = (rawValue, targetObject) => { /** @type {valueTypes} */ targetObject.t = valueTypes.NUMBER; targetObject.n = 0; targetObject.u = null; targetObject.o = null; targetObject.d = null; targetObject.s = null; if (!rawValue) return targetObject; const num = +rawValue; if (!isNaN(num)) { // It's a number targetObject.n = num; return targetObject; } else { // let str = /** @type {String} */(rawValue).trim(); let str = /** @type {String} */(rawValue); // Parsing operators (+=, -=, *=) manually is much faster than using regex here if (str[1] === '=') { targetObject.o = str[0]; str = str.slice(2); } // Skip exec regex if the value type is complex or color to avoid long regex backtracking const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str); if (unitMatch) { // Has a number and a unit targetObject.t = valueTypes.UNIT; targetObject.n = +unitMatch[1]; targetObject.u = unitMatch[2]; return targetObject; } else if (targetObject.o) { // Has an operator (+=, -=, *=) targetObject.n = +str; return targetObject; } else if (isCol(str)) { // Is a color targetObject.t = valueTypes.COLOR; targetObject.d = convertColorStringValuesToRgbaArray(str); return targetObject; } else { // Is a more complex string (generally svg coords, calc() or filters CSS values) const matchedNumbers = str.match(digitWithExponentRgx); targetObject.t = valueTypes.COMPLEX; targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : []; targetObject.s = str.split(digitWithExponentRgx) || []; return targetObject; } } }; /** * @param {Tween} tween * @param {TweenDecomposedValue} targetObject * @return {TweenDecomposedValue} */ const decomposeTweenValue = (tween, targetObject) => { targetObject.t = tween._valueType; targetObject.n = tween._toNumber; targetObject.u = tween._unit; targetObject.o = null; targetObject.d = cloneArray(tween._toNumbers); targetObject.s = cloneArray(tween._strings); return targetObject; }; const decomposedOriginalValue = createDecomposedValueTargetObject(); export { createDecomposedValueTargetObject, decomposeRawValue, decomposeTweenValue, decomposedOriginalValue, getFunctionValue, getOriginalAnimatableValue, getRelativeValue, getTweenType, setValue };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/core/units.js
dist/modules/core/units.js
/** * Anime.js - core - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { valueTypes, doc } from './consts.js'; import { isUnd, PI } from './helpers.js'; const angleUnitsMap = { 'deg': 1, 'rad': 180 / PI, 'turn': 360 }; const convertedValuesCache = {}; /** * @import { * DOMTarget, * TweenDecomposedValue, * } from '../types/index.js' */ /** * @param {DOMTarget} el * @param {TweenDecomposedValue} decomposedValue * @param {String} unit * @param {Boolean} [force] * @return {TweenDecomposedValue} */ const 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; }; export { convertValueUnit };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/timeline/timeline.js
dist/modules/timeline/timeline.js
/** * Anime.js - timeline - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { globals } from '../core/globals.js'; import { minValue, compositionTypes, tickModes } from '../core/consts.js'; import { mergeObjects, isObj, isFnc, isUnd, isStr, normalizeTime, forEachChildren, isNum, addChild, clampInfinity } from '../core/helpers.js'; import { setValue } from '../core/values.js'; import { parseTargets } from '../core/targets.js'; import { tick } from '../core/render.js'; import { cleanInlineStyles } from '../core/styles.js'; import { removeTargetsFromRenderable } from '../animation/composition.js'; import { JSAnimation } from '../animation/animation.js'; import { Timer } from '../timer/timer.js'; import { parseEase } from '../easings/eases/parser.js'; import { parseTimelinePosition } from './position.js'; /** * @import { * TargetsParam, * Callback, * Tickable, * TimerParams, * AnimationParams, * Target, * Renderable, * TimelineParams, * DefaultsParams, * TimelinePosition, * StaggerFunction, * } from '../types/index.js' */ /** * @import { * WAAPIAnimation, * } from '../waapi/waapi.js' */ /** * @param {Timeline} tl * @return {Number} */ function getTimelineTotalDuration(tl) { return clampInfinity(((tl.iterationDuration + tl._loopDelay) * tl.iterationCount) - tl._loopDelay) || minValue; } /** * @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] */ 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(true); // 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; } class Timeline extends Timer { /** * @param {TimelineParams} [parameters] */ constructor(parameters = {}) { super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0); /** @type {Number} */ this.duration = 0; // TL duration starts at 0 and grows when adding children /** @type {Record<String, Number>} */ this.labels = {}; const defaultsParams = parameters.defaults; const globalDefaults = globals.defaults; /** @type {DefaultsParams} */ this.defaults = defaultsParams ? mergeObjects(defaultsParams, globalDefaults) : globalDefaults; /** @type {Callback<this>} */ this.onRender = parameters.onRender || globalDefaults.onRender; const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase); this._ease = tlPlaybackEase ? parseEase(tlPlaybackEase) : null; /** @type {Number} */ this.iterationDuration = 0; } /** * @overload * @param {TargetsParam} a1 * @param {AnimationParams} a2 * @param {TimelinePosition|StaggerFunction<Number|String>} [a3] * @return {this} * * @overload * @param {TimerParams} a1 * @param {TimelinePosition} [a2] * @return {this} * * @param {TargetsParam|TimerParams} a1 * @param {TimelinePosition|AnimationParams} a2 * @param {TimelinePosition|StaggerFunction<Number|String>} [a3] */ 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 = 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; /** @type {Number} */ 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, parseTimelinePosition(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,a2), ); } return this.init(true); } } /** * @overload * @param {Tickable} [synced] * @param {TimelinePosition} [position] * @return {this} * * @overload * @param {globalThis.Animation} [synced] * @param {TimelinePosition} [position] * @return {this} * * @overload * @param {WAAPIAnimation} [synced] * @param {TimelinePosition} [position] * @return {this} * * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced] * @param {TimelinePosition} [position] */ 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); } /** * @param {TargetsParam} targets * @param {AnimationParams} parameters * @param {TimelinePosition} [position] * @return {this} */ set(targets, parameters, position) { if (isUnd(parameters)) return this; parameters.duration = minValue; parameters.composition = compositionTypes.replace; return this.add(targets, parameters, position); } /** * @param {Callback<Timer>} callback * @param {TimelinePosition} [position] * @return {this} */ call(callback, position) { if (isUnd(callback) || callback && !isFnc(callback)) return this; return this.add({ duration: 0, onComplete: () => callback(this) }, position); } /** * @param {String} labelName * @param {TimelinePosition} [position] * @return {this} * */ label(labelName, position) { if (isUnd(labelName) || labelName && !isStr(labelName)) return this; this.labels[labelName] = parseTimelinePosition(this, position); return this; } /** * @param {TargetsParam} targets * @param {String} [propertyName] * @return {this} */ remove(targets, propertyName) { removeTargetsFromRenderable(parseTargets(targets), this, propertyName); return this; } /** * @param {Number} newDuration * @return {this} */ stretch(newDuration) { const currentDuration = this.duration; if (currentDuration === normalizeTime(newDuration)) return this; const timeScale = newDuration / currentDuration; const labels = this.labels; forEachChildren(this, (/** @type {JSAnimation} */child) => child.stretch(child.duration * timeScale)); for (let labelName in labels) labels[labelName] *= timeScale; return super.stretch(newDuration); } /** * @return {this} */ refresh() { forEachChildren(this, (/** @type {JSAnimation} */child) => { if (child.refresh) child.refresh(); }); return this; } /** * @return {this} */ revert() { super.revert(); forEachChildren(this, (/** @type {JSAnimation} */child) => child.revert, true); return cleanInlineStyles(this); } /** * @typedef {this & {then: null}} ResolvedTimeline */ /** * @param {Callback<ResolvedTimeline>} [callback] * @return Promise<this> */ then(callback) { return super.then(callback); } } /** * @param {TimelineParams} [parameters] * @return {Timeline} */ const createTimeline = parameters => new Timeline(parameters).init(); export { Timeline, createTimeline };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/timeline/index.js
dist/modules/timeline/index.js
/** * Anime.js - timeline - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { Timeline, createTimeline } from './timeline.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/timeline/position.js
dist/modules/timeline/position.js
/** * Anime.js - timeline - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { relativeValuesExecRgx, minValue } from '../core/consts.js'; import { isUnd, isNum, stringStartsWith, isNil } from '../core/helpers.js'; import { getRelativeValue } from '../core/values.js'; /** * @import { * Tickable, * TimelinePosition, * } from '../types/index.js' */ /** * @import { * Timeline, * } from './timeline.js' */ /** * Timeline's children offsets positions parser * @param {Timeline} timeline * @param {String} timePosition * @return {Number} */ const 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; } }; /** * @param {Timeline} timeline * @param {TimelinePosition} [timePosition] * @return {Number} */ const 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; } }; export { parseTimelinePosition };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/engine/index.js
dist/modules/engine/index.js
/** * Anime.js - engine - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { engine } from './engine.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/engine/engine.js
dist/modules/engine/engine.js
/** * Anime.js - engine - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { globalVersions, defaults, globals } from '../core/globals.js'; import { isBrowser, doc, tickModes, K } from '../core/consts.js'; import { now, removeChild, forEachChildren } from '../core/helpers.js'; import { Clock } from '../core/clock.js'; import { tick } from '../core/render.js'; import { additive } from '../animation/additive.js'; /** * @import { * DefaultsParams, * } from '../types/index.js' */ /** * @import { * Tickable, * } from '../types/index.js' */ const engineTickMethod = /*#__PURE__*/ (() => isBrowser ? requestAnimationFrame : setImmediate)(); const engineCancelMethod = /*#__PURE__*/ (() => isBrowser ? cancelAnimationFrame : clearImmediate)(); class Engine extends Clock { /** @param {Number} [initTime] */ constructor(initTime) { super(initTime); this.useDefaultMainLoop = true; this.pauseOnDocumentHidden = true; /** @type {DefaultsParams} */ this.defaults = defaults; // this.paused = isBrowser && doc.hidden ? true : false; this.paused = true; /** @type {Number|NodeJS.Immediate} */ this.reqId = 0; } update() { const time = this._currentTime = now(); if (this.requestTick(time)) { this.computeDeltaTime(time); const engineSpeed = this._speed; const engineFps = this._fps; let activeTickable = /** @type {Tickable} */(this._head); while (activeTickable) { const nextTickable = activeTickable._next; if (!activeTickable.paused) { tick( activeTickable, (time - activeTickable._startTime) * activeTickable._speed * engineSpeed, 0, // !muteCallbacks 0, // !internalRender activeTickable._fps < engineFps ? activeTickable.requestTick(time) : tickModes.AUTO ); } else { removeChild(this, activeTickable); this._hasChildren = !!this._tail; activeTickable._running = false; if (activeTickable.completed && !activeTickable._cancelled) { activeTickable.cancel(); } } activeTickable = nextTickable; } additive.update(); } } wake() { if (this.useDefaultMainLoop && !this.reqId) { // Imediatly request a tick to update engine._elapsedTime and get accurate offsetPosition calculation in timer.js this.requestTick(now()); this.reqId = engineTickMethod(tickEngine); } return this; } pause() { if (!this.reqId) return; this.paused = true; return killEngine(); } resume() { if (!this.paused) return; this.paused = false; forEachChildren(this, (/** @type {Tickable} */child) => child.resetTime()); return this.wake(); } // Getter and setter for speed get speed() { return this._speed * (globals.timeScale === 1 ? 1 : K); } set speed(playbackRate) { this._speed = playbackRate * globals.timeScale; forEachChildren(this, (/** @type {Tickable} */child) => child.speed = child._speed); } // Getter and setter for timeUnit get timeUnit() { return globals.timeScale === 1 ? 'ms' : 's'; } set timeUnit(unit) { const secondsScale = 0.001; const isSecond = unit === 's'; const newScale = isSecond ? secondsScale : 1; if (globals.timeScale !== newScale) { globals.timeScale = newScale; globals.tickThreshold = 200 * newScale; const scaleFactor = isSecond ? secondsScale : K; /** @type {Number} */ (this.defaults.duration) *= scaleFactor; this._speed *= scaleFactor; } } // Getter and setter for precision get precision() { return globals.precision; } set precision(precision) { globals.precision = precision; } } const engine = /*#__PURE__*/(() => { const engine = new Engine(now()); if (isBrowser) { globalVersions.engine = engine; doc.addEventListener('visibilitychange', () => { if (!engine.pauseOnDocumentHidden) return; doc.hidden ? engine.pause() : engine.resume(); }); } return engine; })(); const tickEngine = () => { if (engine._head) { engine.reqId = engineTickMethod(tickEngine); engine.update(); } else { engine.reqId = 0; } }; const killEngine = () => { engineCancelMethod(/** @type {NodeJS.Immediate & Number} */(engine.reqId)); engine.reqId = 0; return engine; }; export { engine };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/text/index.js
dist/modules/text/index.js
/** * Anime.js - text - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { TextSplitter, split, splitText } from './split.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/text/split.js
dist/modules/text/split.js
/** * Anime.js - text - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { isBrowser, doc } from '../core/consts.js'; import { scope } from '../core/globals.js'; import { isArr, isObj, isFnc, isUnd, isStr, isNum } from '../core/helpers.js'; import { getNodeList } from '../core/targets.js'; import { setValue } from '../core/values.js'; import { keepTime } from '../utils/time.js'; /** * @import { * Tickable, * DOMTarget, * SplitTemplateParams, * SplitFunctionValue, * TextSplitterParams, * } from '../types/index.js' */ const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter; const valueRgx = /\{value\}/g; const indexRgx = /\{i\}/g; const whiteSpaceGroupRgx = /(\s+)/; const whiteSpaceRgx = /^\s+$/; const lineType = 'line'; const wordType = 'word'; const charType = 'char'; const dataLine = `data-line`; /** * @typedef {Object} Segment * @property {String} segment * @property {Boolean} [isWordLike] */ /** * @typedef {Object} Segmenter * @property {function(String): Iterable<Segment>} segment */ /** @type {Segmenter} */ let wordSegmenter = null; /** @type {Segmenter} */ let graphemeSegmenter = null; let $splitTemplate = null; /** * @param {Segment} seg * @return {Boolean} */ const isSegmentWordLike = seg => { return seg.isWordLike || seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later isNum(+seg.segment); // Safari doesn't considers numbers as words }; /** * @param {HTMLElement} $el */ const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true'); /** * @param {DOMTarget} $el * @param {String} type * @return {Array<HTMLElement>} */ const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))]; const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' }; /** * @param {HTMLElement} $el */ const filterEmptyElements = $el => { if (!$el.childElementCount && !$el.textContent.trim()) { const $parent = $el.parentElement; $el.remove(); if ($parent) filterEmptyElements($parent); } }; /** * @param {HTMLElement} $el * @param {Number} lineIndex * @param {Set<HTMLElement>} bin * @returns {Set<HTMLElement>} */ const filterLineElements = ($el, lineIndex, bin) => { const dataLineAttr = $el.getAttribute(dataLine); if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') bin.add($el); let i = $el.childElementCount; while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin); return bin; }; /** * @param {'line'|'word'|'char'} type * @param {SplitTemplateParams} params * @return {String} */ const generateTemplate = (type, params = {}) => { let template = ``; const classString = isStr(params.class) ? ` class="${params.class}"` : ''; const cloneType = setValue(params.clone, false); const wrapType = setValue(params.wrap, false); const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false; if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`; template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`; if (cloneType) { const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0'; const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0'; template += `<span>{value}</span>`; template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`; } else { template += `{value}`; } template += `</span>`; if (wrapType) template += `</span>`; return template; }; /** * @param {String|SplitFunctionValue} htmlTemplate * @param {Array<HTMLElement>} store * @param {Node|HTMLElement} node * @param {DocumentFragment} $parentFragment * @param {'line'|'word'|'char'} type * @param {Boolean} debug * @param {Number} lineIndex * @param {Number} [wordIndex] * @param {Number} [charIndex] * @return {HTMLElement} */ const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => { const isLine = type === lineType; const isChar = type === charType; const className = `_${type}_`; const template = isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate; const displayStyle = isLine ? 'block' : 'inline-block'; $splitTemplate.innerHTML = template .replace(valueRgx, `<i class="${className}"></i>`) .replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`); const $content = $splitTemplate.content; const $highestParent = /** @type {HTMLElement} */($content.firstElementChild); const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent; const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`)); const replacablesLength = $replacables.length; if (replacablesLength) { $highestParent.style.display = displayStyle; $split.style.display = displayStyle; $split.setAttribute(dataLine, `${lineIndex}`); if (!isLine) { $split.setAttribute('data-word', `${wordIndex}`); if (isChar) $split.setAttribute('data-char', `${charIndex}`); } let i = replacablesLength; while (i--) { const $replace = $replacables[i]; const $closestParent = $replace.parentElement; $closestParent.style.display = displayStyle; if (isLine) { $closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML; } else { $closestParent.replaceChild(node.cloneNode(true), $replace); } } store.push($split); $parentFragment.appendChild($content); } else { console.warn(`The expression "{value}" is missing from the provided template.`); } if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`; return $highestParent; }; /** * A class that splits text into words and wraps them in span elements while preserving the original HTML structure. * @class */ class TextSplitter { /** * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target * @param {TextSplitterParams} [parameters] */ constructor(target, parameters = {}) { // Only init segmenters when needed if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : { segment: (text) => { const segments = []; const words = text.split(whiteSpaceGroupRgx); for (let i = 0, l = words.length; i < l; i++) { const segment = words[i]; segments.push({ segment, isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like }); } return segments; } }; if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : { segment: text => [...text].map(char => ({ segment: char })) }; if (!$splitTemplate && isBrowser) $splitTemplate = doc.createElement('template'); if (scope.current) scope.current.register(this); const { words, chars, lines, accessible, includeSpaces, debug } = parameters; const $target = /** @type {HTMLElement} */((target = isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (getNodeList(target) || [])[0]); const lineParams = lines === true ? {} : lines; const wordParams = words === true || isUnd(words) ? {} : words; const charParams = chars === true ? {} : chars; this.debug = setValue(debug, false); this.includeSpaces = setValue(includeSpaces, false); this.accessible = setValue(accessible, true); this.linesOnly = lineParams && (!wordParams && !charParams); /** @type {String|false|SplitFunctionValue} */ this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams; /** @type {String|false|SplitFunctionValue} */ this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams; /** @type {String|false|SplitFunctionValue} */ this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams; this.$target = $target; this.html = $target && $target.innerHTML; this.lines = []; this.words = []; this.chars = []; this.effects = []; this.effectsCleanups = []; this.cache = null; this.ready = false; this.width = 0; this.resizeTimeout = null; const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split(); // Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback this.resizeObserver = new ResizeObserver(() => { // Use a setTimeout instead of a Timer for better tree shaking clearTimeout(this.resizeTimeout); this.resizeTimeout = setTimeout(() => { const currentWidth = /** @type {HTMLElement} */($target).offsetWidth; if (currentWidth === this.width) return; this.width = currentWidth; handleSplit(); }, 150); }); // Only declare the font ready promise when splitting by lines and not alreay split if (this.lineTemplate && !this.ready) { doc.fonts.ready.then(handleSplit); } else { handleSplit(); } $target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.'); } /** * @param {(...args: any[]) => Tickable | (() => void)} effect * @return this */ addEffect(effect) { if (!isFnc(effect)) return console.warn('Effect must return a function.'); const refreshableEffect = keepTime(effect); this.effects.push(refreshableEffect); if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this); return this; } revert() { clearTimeout(this.resizeTimeout); this.lines.length = this.words.length = this.chars.length = 0; this.resizeObserver.disconnect(); // Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process this.effectsCleanups.forEach(cleanup => isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert()); this.$target.innerHTML = this.html; return this; } /** * Recursively processes a node and its children * @param {Node} node */ splitNode(node) { const wordTemplate = this.wordTemplate; const charTemplate = this.charTemplate; const includeSpaces = this.includeSpaces; const debug = this.debug; const nodeType = node.nodeType; if (nodeType === 3) { const nodeText = node.nodeValue; // If the nodeText is only whitespace, leave it as is if (nodeText.trim()) { const tempWords = []; const words = this.words; const chars = this.chars; const wordSegments = wordSegmenter.segment(nodeText); const $wordsFragment = doc.createDocumentFragment(); let prevSeg = null; for (const wordSegment of wordSegments) { const segment = wordSegment.segment; const isWordLike = isSegmentWordLike(wordSegment); // Determine if this segment should be a new word, first segment always becomes a new word if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) { tempWords.push(segment); } else { // Only concatenate if both current and previous are non-word-like and don't contain spaces const lastWordIndex = tempWords.length - 1; const lastWord = tempWords[lastWordIndex]; if (!lastWord.includes(' ') && !segment.includes(' ')) { tempWords[lastWordIndex] += segment; } else { tempWords.push(segment); } } prevSeg = wordSegment; } for (let i = 0, l = tempWords.length; i < l; i++) { const word = tempWords[i]; if (!word.trim()) { // Preserve whitespace only if includeSpaces is false and if the current space is not the first node if (i && includeSpaces) continue; $wordsFragment.appendChild(doc.createTextNode(word)); } else { const nextWord = tempWords[i + 1]; const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim(); const wordToProcess = word; const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null; const $charsFragment = charTemplate ? doc.createDocumentFragment() : doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word); if (charTemplate) { const charSegmentsArray = [...charSegments]; for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) { const charSegment = charSegmentsArray[j]; const isLastChar = j === jl - 1; // If this is the last character and includeSpaces is true with a following space, append the space const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment; const $charNode = doc.createTextNode(charText); processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length); } } if (wordTemplate) { processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length); // Chars elements must be re-parsed in the split() method if both words and chars are parsed } else if (charTemplate) { $wordsFragment.appendChild($charsFragment); } else { $wordsFragment.appendChild(doc.createTextNode(word)); } // Skip the next iteration if we included a space if (hasWordFollowingSpace) i++; } } node.parentNode.replaceChild($wordsFragment, node); } } else if (nodeType === 1) { // Converting to an array is necessary to work around childNodes pottential mutation const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]); for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]); } } /** * @param {Boolean} clearCache * @return {this} */ split(clearCache = false) { const $el = this.$target; const isCached = !!this.cache && !clearCache; const lineTemplate = this.lineTemplate; const wordTemplate = this.wordTemplate; const charTemplate = this.charTemplate; const fontsReady = doc.fonts.status !== 'loading'; const canSplitLines = lineTemplate && fontsReady; this.ready = !lineTemplate || fontsReady; if (canSplitLines || clearCache) { // No need to revert effects animations here since it's already taken care by the refreshable this.effectsCleanups.forEach(cleanup => isFnc(cleanup) && cleanup(this)); } if (!isCached) { if (clearCache) { $el.innerHTML = this.html; this.words.length = this.chars.length = 0; } this.splitNode($el); this.cache = $el.innerHTML; } if (canSplitLines) { if (isCached) $el.innerHTML = this.cache; this.lines.length = 0; if (wordTemplate) this.words = getAllTopLevelElements($el, wordType); } // Always reparse characters after a line reset or if both words and chars are activated if (charTemplate && (canSplitLines || wordTemplate)) { this.chars = getAllTopLevelElements($el, charType); } // Words are used when lines only and prioritized over chars const elementsArray = this.words.length ? this.words : this.chars; let y, linesCount = 0; for (let i = 0, l = elementsArray.length; i < l; i++) { const $el = elementsArray[i]; const { top, height } = $el.getBoundingClientRect(); if (y && top - y > height * .5) linesCount++; $el.setAttribute(dataLine, `${linesCount}`); const nested = $el.querySelectorAll(`[${dataLine}]`); let c = nested.length; while (c--) nested[c].setAttribute(dataLine, `${linesCount}`); y = top; } if (canSplitLines) { const linesFragment = doc.createDocumentFragment(); const parents = new Set(); const clones = []; for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) { const $clone = /** @type {HTMLElement} */($el.cloneNode(true)); filterLineElements($clone, lineIndex, new Set()).forEach($el => { const $parent = $el.parentElement; if ($parent) parents.add($parent); $el.remove(); }); clones.push($clone); } parents.forEach(filterEmptyElements); for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) { processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex); } $el.innerHTML = ''; $el.appendChild(linesFragment); if (wordTemplate) this.words = getAllTopLevelElements($el, wordType); if (charTemplate) this.chars = getAllTopLevelElements($el, charType); } // Remove the word wrappers and clear the words array if lines split only if (this.linesOnly) { const words = this.words; let w = words.length; while (w--) { const $word = words[w]; $word.replaceWith($word.textContent); } words.length = 0; } if (this.accessible && (canSplitLines || !isCached)) { const $accessible = doc.createElement('span'); // Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html) $accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`; // $accessible.setAttribute('tabindex', '-1'); $accessible.innerHTML = this.html; $el.insertBefore($accessible, $el.firstChild); this.lines.forEach(setAriaHidden); this.words.forEach(setAriaHidden); this.chars.forEach(setAriaHidden); } this.width = /** @type {HTMLElement} */($el).offsetWidth; if (canSplitLines || clearCache) { this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this)); } return this; } refresh() { this.split(true); } } /** * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target * @param {TextSplitterParams} [parameters] * @return {TextSplitter} */ const splitText = (target, parameters) => new TextSplitter(target, parameters); /** * @deprecated text.split() is deprecated, import splitText() directly, or text.splitText() * * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target * @param {TextSplitterParams} [parameters] * @return {TextSplitter} */ const split = (target, parameters) => { console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()'); return new TextSplitter(target, parameters); }; export { TextSplitter, split, splitText };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/animation/additive.js
dist/modules/animation/additive.js
/** * Anime.js - animation - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { noop, minValue, valueTypes, tickModes } from '../core/consts.js'; import { cloneArray } from '../core/helpers.js'; import { render } from '../core/render.js'; const additive = { animation: null, update: noop, }; /** * @import { * Tween, * TweenAdditiveLookups, * } from '../types/index.js' */ /** * @typedef AdditiveAnimation * @property {Number} duration * @property {Number} _offset * @property {Number} _delay * @property {Tween} _head * @property {Tween} _tail */ /** * @param {TweenAdditiveLookups} lookups * @return {AdditiveAnimation} */ const addAdditiveAnimation = lookups => { let animation = additive.animation; if (!animation) { animation = { duration: minValue, computeDeltaTime: noop, _offset: 0, _delay: 0, _head: null, _tail: null, }; additive.animation = animation; additive.update = () => { lookups.forEach(propertyAnimation => { for (let propertyName in propertyAnimation) { const tweens = propertyAnimation[propertyName]; const lookupTween = tweens._head; if (lookupTween) { const valueType = lookupTween._valueType; const additiveValues = valueType === valueTypes.COMPLEX || valueType === valueTypes.COLOR ? cloneArray(lookupTween._fromNumbers) : null; let additiveValue = lookupTween._fromNumber; let tween = tweens._tail; while (tween && tween !== lookupTween) { if (additiveValues) { for (let i = 0, l = tween._numbers.length; i < l; i++) additiveValues[i] += tween._numbers[i]; } else { additiveValue += tween._number; } tween = tween._prevAdd; } lookupTween._toNumber = additiveValue; lookupTween._toNumbers = additiveValues; } } }); // TODO: Avoid polymorphism here, idealy the additive animation should be a regular animation with a higher priority in the render loop render(animation, 1, 1, 0, tickModes.FORCE); }; } return animation; }; export { addAdditiveAnimation, additive };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/animation/composition.js
dist/modules/animation/composition.js
/** * Anime.js - animation - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { minValue, compositionTypes, tweenTypes } from '../core/consts.js'; import { forEachChildren, removeChild, isUnd, addChild, round, cloneArray } from '../core/helpers.js'; import { sanitizePropertyName } from '../core/styles.js'; import { engine } from '../engine/engine.js'; import { addAdditiveAnimation, additive } from './additive.js'; /** * @import { * TweenReplaceLookups, * TweenAdditiveLookups, * TweenPropertySiblings, * Tween, * Target, * TargetsArray, * Renderable, * } from '../types/index.js' * * @import { * JSAnimation, * } from '../animation/animation.js' */ const lookups = { /** @type {TweenReplaceLookups} */ _rep: new WeakMap(), /** @type {TweenAdditiveLookups} */ _add: new Map(), }; /** * @param {Target} target * @param {String} property * @param {String} lookup * @return {TweenPropertySiblings} */ const getTweenSiblings = (target, property, lookup = '_rep') => { const lookupMap = lookups[lookup]; let targetLookup = lookupMap.get(target); if (!targetLookup) { targetLookup = {}; lookupMap.set(target, targetLookup); } return targetLookup[property] ? targetLookup[property] : targetLookup[property] = { _head: null, _tail: null, } }; /** * @param {Tween} p * @param {Tween} c * @return {Number|Boolean} */ const addTweenSortMethod = (p, c) => { return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime; }; /** * @param {Tween} tween */ const overrideTween = tween => { tween._isOverlapped = 1; tween._isOverridden = 1; tween._changeDuration = minValue; tween._currentTime = minValue; }; /** * @param {Tween} tween * @param {TweenPropertySiblings} siblings * @return {Tween} */ const composeTween = (tween, siblings) => { const tweenCompositionType = tween._composition; // Handle replaced tweens if (tweenCompositionType === compositionTypes.replace) { const tweenAbsStartTime = tween._absoluteStartTime; addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep'); const prevSibling = tween._prevRep; // Update the previous siblings for composition replace tweens if (prevSibling) { const prevParent = prevSibling.parent; const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration; // Handle looped animations tween if ( // Check if the previous tween is from a different animation tween.parent.id !== prevParent.id && // Check if the animation has loops prevParent.iterationCount> 1 && // Check if _absoluteChangeEndTime of last loop overlaps the current tween prevAbsEndTime + (prevParent.duration - prevParent.iterationDuration) > tweenAbsStartTime ) { // TODO: Find a way to only override the iterations overlapping with the tween overrideTween(prevSibling); let prevPrevSibling = prevSibling._prevRep; // If the tween was part of a set of keyframes, override its siblings while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) { overrideTween(prevPrevSibling); prevPrevSibling = prevPrevSibling._prevRep; } } const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay; if (prevAbsEndTime > absoluteUpdateStartTime) { const prevChangeStartTime = prevSibling._startTime; const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration); // Rounding is necessary here to minimize floating point errors when working in seconds const updatedPrevChangeDuration = round(absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime, 12); prevSibling._changeDuration = updatedPrevChangeDuration; prevSibling._currentTime = updatedPrevChangeDuration; prevSibling._isOverlapped = 1; // Override the previous tween if its new _changeDuration is lower than minValue // TODO: See if it's even neceseeary to test against minValue, checking for 0 might be enough if (updatedPrevChangeDuration < minValue) { overrideTween(prevSibling); } } // Pause (and cancel) the parent if it only contains overlapped tweens let pausePrevParentAnimation = true; forEachChildren(prevParent, (/** @type Tween */t) => { if (!t._isOverlapped) pausePrevParentAnimation = false; }); if (pausePrevParentAnimation) { const prevParentTL = prevParent.parent; if (prevParentTL) { let pausePrevParentTL = true; forEachChildren(prevParentTL, (/** @type JSAnimation */a) => { if (a !== prevParent) { forEachChildren(a, (/** @type Tween */t) => { if (!t._isOverlapped) pausePrevParentTL = false; }); } }); if (pausePrevParentTL) { prevParentTL.cancel(); } } else { prevParent.cancel(); // Previously, calling .cancel() on a timeline child would affect the render order of other children // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop // This is no longer needed since timeline tween composition is now handled separately // Keeping this here for reference // prevParent.completed = true; // prevParent.pause(); } } } // let nextSibling = tween._nextRep; // // All the next siblings are automatically overridden // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // nextSibling = nextSibling._nextRep; // } // } // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // console.log(tween.id, nextSibling.id); // nextSibling = nextSibling._nextRep; // } // } // Handle additive tweens composition } else if (tweenCompositionType === compositionTypes.blend) { const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add'); const additiveAnimation = addAdditiveAnimation(lookups._add); let lookupTween = additiveTweenSiblings._head; if (!lookupTween) { lookupTween = { ...tween }; lookupTween._composition = compositionTypes.replace; lookupTween._updateDuration = minValue; lookupTween._startTime = 0; lookupTween._numbers = cloneArray(tween._fromNumbers); lookupTween._number = 0; lookupTween._next = null; lookupTween._prev = null; addChild(additiveTweenSiblings, lookupTween); addChild(additiveAnimation, lookupTween); } // Convert the values of TO to FROM and set TO to 0 const toNumber = tween._toNumber; tween._fromNumber = lookupTween._fromNumber - toNumber; tween._toNumber = 0; tween._numbers = cloneArray(tween._fromNumbers); tween._number = 0; lookupTween._fromNumber = toNumber; if (tween._toNumbers) { const toNumbers = cloneArray(tween._toNumbers); if (toNumbers) { toNumbers.forEach((value, i) => { tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value; tween._toNumbers[i] = 0; }); } lookupTween._fromNumbers = toNumbers; } addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd'); } return tween; }; /** * @param {Tween} tween * @return {Tween} */ const removeTweenSliblings = tween => { const tweenComposition = tween._composition; if (tweenComposition !== compositionTypes.none) { const tweenTarget = tween.target; const tweenProperty = tween.property; const replaceTweensLookup = lookups._rep; const replaceTargetProps = replaceTweensLookup.get(tweenTarget); const tweenReplaceSiblings = replaceTargetProps[tweenProperty]; removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep'); if (tweenComposition === compositionTypes.blend) { const addTweensLookup = lookups._add; const addTargetProps = addTweensLookup.get(tweenTarget); if (!addTargetProps) return; const additiveTweenSiblings = addTargetProps[tweenProperty]; const additiveAnimation = additive.animation; removeChild(additiveTweenSiblings, tween, '_prevAdd', '_nextAdd'); // If only one tween is left in the additive lookup, it's the tween lookup const lookupTween = additiveTweenSiblings._head; if (lookupTween && lookupTween === additiveTweenSiblings._tail) { removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd'); removeChild(additiveAnimation, lookupTween); let shouldClean = true; for (let prop in addTargetProps) { if (addTargetProps[prop]._head) { shouldClean = false; break; } } if (shouldClean) { addTweensLookup.delete(tweenTarget); } } } } return tween; }; /** * @param {TargetsArray} targetsArray * @param {JSAnimation} animation * @param {String} [propertyName] * @return {Boolean} */ const removeTargetsFromJSAnimation = (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 {Renderable} [renderable] * @param {String} [propertyName] */ const removeTargetsFromRenderable = (targetsArray, renderable, propertyName) => { const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine); let removeMatches; if (parent._hasChildren) { let iterationDuration = 0; forEachChildren(parent, (/** @type {Renderable} */child) => { if (!child._hasChildren) { removeMatches = removeTargetsFromJSAnimation(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) { removeTargetsFromRenderable(targetsArray, 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 = removeTargetsFromJSAnimation( 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(); } }; export { composeTween, getTweenSiblings, overrideTween, removeTargetsFromRenderable, removeTweenSliblings };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/animation/index.js
dist/modules/animation/index.js
/** * Anime.js - animation - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { JSAnimation, animate } from './animation.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/animation/animation.js
dist/modules/animation/animation.js
/** * Anime.js - animation - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { K, compositionTypes, valueTypes, minValue, tweenTypes } from '../core/consts.js'; import { mergeObjects, isUnd, isKey, isObj, round, cloneArray, isNil, addChild, forEachChildren, clampInfinity, normalizeTime, isArr, isNum } from '../core/helpers.js'; import { globals } from '../core/globals.js'; import { registerTargets } from '../core/targets.js'; import { setValue, getTweenType, getFunctionValue, decomposeRawValue, createDecomposedValueTargetObject, getOriginalAnimatableValue, decomposedOriginalValue, getRelativeValue, decomposeTweenValue } from '../core/values.js'; import { sanitizePropertyName, cleanInlineStyles } from '../core/styles.js'; import { convertValueUnit } from '../core/units.js'; import { parseEase } from '../easings/eases/parser.js'; import { Timer } from '../timer/timer.js'; import { getTweenSiblings, overrideTween, composeTween } from './composition.js'; import { additive } from './additive.js'; /** * @import { * Tween, * TweenKeyValue, * TweenParamsOptions, * TweenValues, * DurationKeyframes, * PercentageKeyframes, * AnimationParams, * TweenPropValue, * ArraySyntaxValue, * TargetsParam, * TimerParams, * TweenParamValue, * DOMTarget, * TargetsArray, * Callback, * EasingFunction, * } from '../types/index.js' * * @import { * Timeline, * } from '../timeline/timeline.js' * * @import { * Spring, * } from '../easings/spring/index.js' */ // Defines decomposed values target objects only once and mutate their properties later to avoid GC // TODO: Maybe move the objects creation to values.js and use the decompose function to create the base object const fromTargetObject = createDecomposedValueTargetObject(); const toTargetObject = createDecomposedValueTargetObject(); const inlineStylesStore = {}; const toFunctionStore = { func: null }; const keyframesTargetArray = [null]; const fastSetValuesArray = [null, null]; /** @type {TweenKeyValue} */ const keyObjectTarget = { to: null }; let tweenId = 0; let keyframes; /** @type {TweenParamsOptions & TweenValues} */ let key; /** * @param {DurationKeyframes | PercentageKeyframes} keyframes * @param {AnimationParams} parameters * @return {AnimationParams} */ const generateKeyframes = (keyframes, parameters) => { /** @type {AnimationParams} */ const properties = {}; if (isArr(keyframes)) { const propertyNames = [].concat(.../** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(isKey); for (let i = 0, l = propertyNames.length; i < l; i++) { const propName = propertyNames[i]; const propArray = /** @type {DurationKeyframes} */(keyframes).map(key => { /** @type {TweenKeyValue} */ const newKey = {}; for (let p in key) { const keyValue = /** @type {TweenPropValue} */(key[p]); if (isKey(p)) { if (p === propName) { newKey.to = keyValue; } } else { newKey[p] = keyValue; } } return newKey; }); properties[propName] = /** @type {ArraySyntaxValue} */(propArray); } } else { const totalDuration = /** @type {Number} */(setValue(parameters.duration, globals.defaults.duration)); const keys = Object.keys(keyframes) .map(key => { return {o: parseFloat(key) / 100, p: keyframes[key]} }) .sort((a, b) => a.o - b.o); keys.forEach(key => { const offset = key.o; const prop = key.p; for (let name in prop) { if (isKey(name)) { let propArray = /** @type {Array} */(properties[name]); if (!propArray) propArray = properties[name] = []; const duration = offset * totalDuration; let length = propArray.length; let prevKey = propArray[length - 1]; const keyObj = { to: prop[name] }; let durProgress = 0; for (let i = 0; i < length; i++) { durProgress += propArray[i].duration; } if (length === 1) { keyObj.from = prevKey.to; } if (prop.ease) { keyObj.ease = prop.ease; } keyObj.duration = duration - (length ? durProgress : 0); propArray.push(keyObj); } } return key; }); for (let name in properties) { const propArray = /** @type {Array} */(properties[name]); let prevEase; // let durProgress = 0 for (let i = 0, l = propArray.length; i < l; i++) { const prop = propArray[i]; // Emulate WAPPI easing parameter position const currentEase = prop.ease; prop.ease = prevEase ? prevEase : undefined; prevEase = currentEase; // durProgress += prop.duration; // if (i === l - 1 && durProgress !== totalDuration) { // propArray.push({ from: prop.to, ease: prop.ease, duration: totalDuration - durProgress }) // } } if (!propArray[0].duration) { propArray.shift(); } } } return properties; }; class JSAnimation extends Timer { /** * @param {TargetsParam} targets * @param {AnimationParams} parameters * @param {Timeline} [parent] * @param {Number} [parentPosition] * @param {Boolean} [fastSet=false] * @param {Number} [index=0] * @param {Number} [length=0] */ constructor( targets, parameters, parent, parentPosition, fastSet = false, index = 0, length = 0 ) { super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition); const parsedTargets = registerTargets(targets); const targetsLength = parsedTargets.length; // If the parameters object contains a "keyframes" property, convert all the keyframes values to regular properties const kfParams = /** @type {AnimationParams} */(parameters).keyframes; const params = /** @type {AnimationParams} */(kfParams ? mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters); const { delay, duration, ease, playbackEase, modifier, composition, onRender, } = params; const animDefaults = parent ? parent.defaults : globals.defaults; const animaPlaybackEase = setValue(playbackEase, animDefaults.playbackEase); const animEase = animaPlaybackEase ? parseEase(animaPlaybackEase) : null; const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease); const tEasing = hasSpring ? /** @type {Spring} */(ease).ease : setValue(ease, animEase ? 'linear' : animDefaults.ease); const tDuration = hasSpring ? /** @type {Spring} */(ease).settlingDuration : setValue(duration, animDefaults.duration); const tDelay = setValue(delay, animDefaults.delay); const tModifier = modifier || animDefaults.modifier; // If no composition is defined and the targets length is high (>= 1000) set the composition to 'none' (0) for faster tween creation const tComposition = isUnd(composition) && targetsLength >= K ? compositionTypes.none : !isUnd(composition) ? composition : animDefaults.composition; // const absoluteOffsetTime = this._offset; const absoluteOffsetTime = this._offset + (parent ? parent._offset : 0); // This allows targeting the current animation in the spring onComplete callback if (hasSpring) /** @type {Spring} */(ease).parent = this; let iterationDuration = NaN; let iterationDelay = NaN; let animationAnimationLength = 0; let shouldTriggerRender = 0; for (let targetIndex = 0; targetIndex < targetsLength; targetIndex++) { const target = parsedTargets[targetIndex]; const ti = index || targetIndex; const tl = length || targetsLength; let lastTransformGroupIndex = NaN; let lastTransformGroupLength = NaN; for (let p in params) { if (isKey(p)) { const tweenType = getTweenType(target, p); const propName = sanitizePropertyName(p, target, tweenType); let propValue = params[p]; const isPropValueArray = isArr(propValue); if (fastSet && !isPropValueArray) { fastSetValuesArray[0] = propValue; fastSetValuesArray[1] = propValue; propValue = fastSetValuesArray; } // TODO: Allow nested keyframes inside ObjectValue value (prop: { to: [.5, 1, .75, 2, 3] }) // Normalize property values to valid keyframe syntax: // [x, y] to [{to: [x, y]}] or {to: x} to [{to: x}] or keep keys syntax [{}, {}, {}...] // const keyframes = isArr(propValue) ? propValue.length === 2 && !isObj(propValue[0]) ? [{ to: propValue }] : propValue : [propValue]; if (isPropValueArray) { const arrayLength = /** @type {Array} */(propValue).length; const isNotObjectValue = !isObj(propValue[0]); // Convert [x, y] to [{to: [x, y]}] if (arrayLength === 2 && isNotObjectValue) { keyObjectTarget.to = /** @type {TweenParamValue} */(/** @type {unknown} */(propValue)); keyframesTargetArray[0] = keyObjectTarget; keyframes = keyframesTargetArray; // Convert [x, y, z] to [[x, y], z] } else if (arrayLength > 2 && isNotObjectValue) { keyframes = []; /** @type {Array.<Number>} */(propValue).forEach((v, i) => { if (!i) { fastSetValuesArray[0] = v; } else if (i === 1) { fastSetValuesArray[1] = v; keyframes.push(fastSetValuesArray); } else { keyframes.push(v); } }); } else { keyframes = /** @type {Array.<TweenKeyValue>} */(propValue); } } else { keyframesTargetArray[0] = propValue; keyframes = keyframesTargetArray; } let siblings = null; let prevTween = null; let firstTweenChangeStartTime = NaN; let lastTweenChangeEndTime = 0; let tweenIndex = 0; for (let l = keyframes.length; tweenIndex < l; tweenIndex++) { const keyframe = keyframes[tweenIndex]; if (isObj(keyframe)) { key = keyframe; } else { keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe); key = keyObjectTarget; } toFunctionStore.func = null; const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore); let tweenToValue; // Allows function based values to return an object syntax value ({to: v}) if (isObj(computedToValue) && !isUnd(computedToValue.to)) { key = computedToValue; tweenToValue = computedToValue.to; } else { tweenToValue = computedToValue; } const tweenFromValue = getFunctionValue(key.from, target, ti, tl); const keyEasing = key.ease; const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */(keyEasing).ease); // Easing are treated differently and don't accept function based value to prevent having to pass a function wrapper that returns an other function all the time const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing || tEasing; // Calculate default individual keyframe duration by dividing the tl of keyframes const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).settlingDuration : getFunctionValue(setValue(key.duration, (l > 1 ? getFunctionValue(tDuration, target, ti, tl) / l : tDuration)), target, ti, tl); // Default delay value should only be applied to the first tween const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl); const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl); const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition]; // Modifiers are treated differently and don't accept function based value to prevent having to pass a function wrapper const tweenModifier = key.modifier || tModifier; const hasFromvalue = !isUnd(tweenFromValue); const hasToValue = !isUnd(tweenToValue); const isFromToArray = isArr(tweenToValue); const isFromToValue = isFromToArray || (hasFromvalue && hasToValue); const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay; // Rounding is necessary here to minimize floating point errors when working in seconds const absoluteStartTime = round(absoluteOffsetTime + tweenStartTime, 12); // Force a onRender callback if the animation contains at least one from value and autoplay is set to false if (!shouldTriggerRender && (hasFromvalue || isFromToArray)) shouldTriggerRender = 1; let prevSibling = prevTween; if (tweenComposition !== compositionTypes.none) { if (!siblings) siblings = getTweenSiblings(target, propName); let nextSibling = siblings._head; // Iterate trough all the next siblings until we find a sibling with an equal or inferior start time while (nextSibling && !nextSibling._isOverridden && nextSibling._absoluteStartTime <= absoluteStartTime) { prevSibling = nextSibling; nextSibling = nextSibling._nextRep; // Overrides all the next siblings if the next sibling starts at the same time of after as the new tween start time if (nextSibling && nextSibling._absoluteStartTime >= absoluteStartTime) { while (nextSibling) { overrideTween(nextSibling); // This will ends both the current while loop and the upper one once all the next sibllings have been overriden nextSibling = nextSibling._nextRep; } } } } // Decompose values if (isFromToValue) { decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[0], target, ti, tl) : tweenFromValue, fromTargetObject); decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore) : tweenToValue, toTargetObject); if (fromTargetObject.t === valueTypes.NUMBER) { if (prevSibling) { if (prevSibling._valueType === valueTypes.UNIT) { fromTargetObject.t = valueTypes.UNIT; fromTargetObject.u = prevSibling._unit; } } else { decomposeRawValue( getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore), decomposedOriginalValue ); if (decomposedOriginalValue.t === valueTypes.UNIT) { fromTargetObject.t = valueTypes.UNIT; fromTargetObject.u = decomposedOriginalValue.u; } } } } else { if (hasToValue) { decomposeRawValue(tweenToValue, toTargetObject); } else { if (prevTween) { decomposeTweenValue(prevTween, toTargetObject); } else { // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value : getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore), toTargetObject); } } if (hasFromvalue) { decomposeRawValue(tweenFromValue, fromTargetObject); } else { if (prevTween) { decomposeTweenValue(prevTween, fromTargetObject); } else { decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value : // No need to get and parse the original value if the tween is part of a timeline and has a previous sibling part of the same timeline getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore), fromTargetObject); } } } // Apply operators if (fromTargetObject.o) { fromTargetObject.n = getRelativeValue( !prevSibling ? decomposeRawValue( getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore), decomposedOriginalValue ).n : prevSibling._toNumber, fromTargetObject.n, fromTargetObject.o ); } if (toTargetObject.o) { toTargetObject.n = getRelativeValue(fromTargetObject.n, toTargetObject.n, toTargetObject.o); } // Values omogenisation in cases of type difference between "from" and "to" if (fromTargetObject.t !== toTargetObject.t) { if (fromTargetObject.t === valueTypes.COMPLEX || toTargetObject.t === valueTypes.COMPLEX) { const complexValue = fromTargetObject.t === valueTypes.COMPLEX ? fromTargetObject : toTargetObject; const notComplexValue = fromTargetObject.t === valueTypes.COMPLEX ? toTargetObject : fromTargetObject; notComplexValue.t = valueTypes.COMPLEX; notComplexValue.s = cloneArray(complexValue.s); notComplexValue.d = complexValue.d.map(() => notComplexValue.n); } else if (fromTargetObject.t === valueTypes.UNIT || toTargetObject.t === valueTypes.UNIT) { const unitValue = fromTargetObject.t === valueTypes.UNIT ? fromTargetObject : toTargetObject; const notUnitValue = fromTargetObject.t === valueTypes.UNIT ? toTargetObject : fromTargetObject; notUnitValue.t = valueTypes.UNIT; notUnitValue.u = unitValue.u; } else if (fromTargetObject.t === valueTypes.COLOR || toTargetObject.t === valueTypes.COLOR) { const colorValue = fromTargetObject.t === valueTypes.COLOR ? fromTargetObject : toTargetObject; const notColorValue = fromTargetObject.t === valueTypes.COLOR ? toTargetObject : fromTargetObject; notColorValue.t = valueTypes.COLOR; notColorValue.s = colorValue.s; notColorValue.d = [0, 0, 0, 1]; } } // Unit conversion if (fromTargetObject.u !== toTargetObject.u) { let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject; valueToConvert = convertValueUnit(/** @type {DOMTarget} */(target), valueToConvert, toTargetObject.u ? toTargetObject.u : fromTargetObject.u, false); // TODO: // convertValueUnit(target, to.u ? from : to, to.u ? to.u : from.u); } // Fill in non existing complex values if (toTargetObject.d && fromTargetObject.d && (toTargetObject.d.length !== fromTargetObject.d.length)) { const longestValue = fromTargetObject.d.length > toTargetObject.d.length ? fromTargetObject : toTargetObject; const shortestValue = longestValue === fromTargetObject ? toTargetObject : fromTargetObject; // TODO: Check if n should be used instead of 0 for default complex values shortestValue.d = longestValue.d.map((/** @type {Number} */_, /** @type {Number} */i) => isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]); shortestValue.s = cloneArray(longestValue.s); } // Tween factory // Rounding is necessary here to minimize floating point errors when working in seconds const tweenUpdateDuration = round(+tweenDuration || minValue, 12); // Copy the value of the iniline style if it exist and imediatly nullify it to prevents false positive on other targets let inlineValue = inlineStylesStore[propName]; if (!isNil(inlineValue)) inlineStylesStore[propName] = null; /** @type {Tween} */ const tween = { parent: this, id: tweenId++, property: propName, target: target, _value: null, _func: toFunctionStore.func, _ease: parseEase(tweenEasing), _fromNumbers: cloneArray(fromTargetObject.d), _toNumbers: cloneArray(toTargetObject.d), _strings: cloneArray(toTargetObject.s), _fromNumber: fromTargetObject.n, _toNumber: toTargetObject.n, _numbers: cloneArray(fromTargetObject.d), // For additive tween and animatables _number: fromTargetObject.n, // For additive tween and animatables _unit: toTargetObject.u, _modifier: tweenModifier, _currentTime: 0, _startTime: tweenStartTime, _delay: +tweenDelay, _updateDuration: tweenUpdateDuration, _changeDuration: tweenUpdateDuration, _absoluteStartTime: absoluteStartTime, // NOTE: Investigate bit packing to stores ENUM / BOOL _tweenType: tweenType, _valueType: toTargetObject.t, _composition: tweenComposition, _isOverlapped: 0, _isOverridden: 0, _renderTransforms: 0, _inlineValue: inlineValue, _prevRep: null, // For replaced tween _nextRep: null, // For replaced tween _prevAdd: null, // For additive tween _nextAdd: null, // For additive tween _prev: null, _next: null, }; if (tweenComposition !== compositionTypes.none) { composeTween(tween, siblings); } if (isNaN(firstTweenChangeStartTime)) { firstTweenChangeStartTime = tween._startTime; } // Rounding is necessary here to minimize floating point errors when working in seconds lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12); prevTween = tween; animationAnimationLength++; addChild(this, tween); } // Update animation timings with the added tweens properties if (isNaN(iterationDelay) || firstTweenChangeStartTime < iterationDelay) { iterationDelay = firstTweenChangeStartTime; } if (isNaN(iterationDuration) || lastTweenChangeEndTime > iterationDuration) { iterationDuration = lastTweenChangeEndTime; } // TODO: Find a way to inline tween._renderTransforms = 1 here if (tweenType === tweenTypes.TRANSFORM) { lastTransformGroupIndex = animationAnimationLength - tweenIndex; lastTransformGroupLength = animationAnimationLength; } } } // Set _renderTransforms to last transform property to correctly render the transforms list if (!isNaN(lastTransformGroupIndex)) { let i = 0; forEachChildren(this, (/** @type {Tween} */tween) => { if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) { tween._renderTransforms = 1; if (tween._composition === compositionTypes.blend) { forEachChildren(additive.animation, (/** @type {Tween} */additiveTween) => { if (additiveTween.id === tween.id) { additiveTween._renderTransforms = 1; } }); } } i++; }); } } if (!targetsLength) { console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`); } if (iterationDelay) { forEachChildren(this, (/** @type {Tween} */tween) => { // If (startTime - delay) equals 0, this means the tween is at the begining of the animation so we need to trim the delay too if (!(tween._startTime - tween._delay)) { tween._delay -= iterationDelay; } tween._startTime -= iterationDelay; }); iterationDuration -= iterationDelay; } else { iterationDelay = 0; } // Prevents iterationDuration to be NaN if no valid animatable props have been provided // Prevents _iterationCount to be NaN if no valid animatable props have been provided if (!iterationDuration) { iterationDuration = minValue; this.iterationCount = 0; } /** @type {TargetsArray} */ this.targets = parsedTargets; /** @type {Number} */ this.duration = iterationDuration === minValue ? minValue : clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || minValue; /** @type {Callback<this>} */ this.onRender = onRender || animDefaults.onRender; /** @type {EasingFunction} */ this._ease = animEase; /** @type {Number} */ this._delay = iterationDelay; // NOTE: I'm keeping delay values separated from offsets in timelines because delays can override previous tweens and it could be confusing to debug a timeline with overridden tweens and no associated visible delays. // this._delay = parent ? 0 : iterationDelay; // this._offset += parent ? iterationDelay : 0; /** @type {Number} */ this.iterationDuration = iterationDuration; if (!this._autoplay && shouldTriggerRender) this.onRender(this); } /** * @param {Number} newDuration * @return {this} */ stretch(newDuration) { const currentDuration = this.duration; if (currentDuration === normalizeTime(newDuration)) return this; const timeScale = newDuration / currentDuration; // NOTE: Find a better way to handle the stretch of an animation after stretch = 0 forEachChildren(this, (/** @type {Tween} */tween) => { // Rounding is necessary here to minimize floating point errors tween._updateDuration = normalizeTime(tween._updateDuration * timeScale); tween._changeDuration = normalizeTime(tween._changeDuration * timeScale); tween._currentTime *= timeScale; tween._startTime *= timeScale; tween._absoluteStartTime *= timeScale; }); return super.stretch(newDuration); } /** * @return {this} */ refresh() { forEachChildren(this, (/** @type {Tween} */tween) => { const tweenFunc = tween._func; if (tweenFunc) { const ogValue = getOriginalAnimatableValue(tween.target, tween.property, tween._tweenType); decomposeRawValue(ogValue, decomposedOriginalValue); // TODO: Check for from / to Array based values here, decomposeRawValue(tweenFunc(), toTargetObject); tween._fromNumbers = cloneArray(decomposedOriginalValue.d); tween._fromNumber = decomposedOriginalValue.n; tween._toNumbers = cloneArray(toTargetObject.d); tween._strings = cloneArray(toTargetObject.s); // Make sure to apply relative operators https://github.com/juliangarnier/anime/issues/1025 tween._toNumber = toTargetObject.o ? getRelativeValue(decomposedOriginalValue.n, toTargetObject.n, toTargetObject.o) : toTargetObject.n; } }); // This forces setter animations to render once if (this.duration === minValue) this.restart(); return this; } /** * Cancel the animation and revert all the values affected by this animation to their original state * @return {this} */ revert() { super.revert(); return cleanInlineStyles(this); } /** * @typedef {this & {then: null}} ResolvedJSAnimation */ /** * @param {Callback<ResolvedJSAnimation>} [callback] * @return Promise<this> */ then(callback) { return super.then(callback); } } /** * @param {TargetsParam} targets * @param {AnimationParams} parameters * @return {JSAnimation} */ const animate = (targets, parameters) => new JSAnimation(targets, parameters, null, 0, false).init(); export { JSAnimation, animate };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/waapi/composition.js
dist/modules/waapi/composition.js
/** * Anime.js - waapi - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { removeChild, addChild } from '../core/helpers.js'; /** * @import { * DOMTarget, * } from '../types/index.js' */ /** * @import { * WAAPIAnimation, * } from '../waapi/waapi.js' */ const WAAPIAnimationsLookups = { _head: null, _tail: null, }; /** * @param {DOMTarget} $el * @param {String} [property] * @param {WAAPIAnimation} [parent] * @return {globalThis.Animation} */ const removeWAAPIAnimation = ($el, property, parent) => { let nextLookup = WAAPIAnimationsLookups._head; let anim; while (nextLookup) { const next = nextLookup._next; const matchTarget = nextLookup.$el === $el; const matchProperty = !property || nextLookup.property === property; const matchParent = !parent || nextLookup.parent === parent; if (matchTarget && matchProperty && matchParent) { anim = nextLookup.animation; try { anim.commitStyles(); } catch {} anim.cancel(); removeChild(WAAPIAnimationsLookups, nextLookup); const lookupParent = nextLookup.parent; if (lookupParent) { lookupParent._completed++; if (lookupParent.animations.length === lookupParent._completed) { lookupParent.completed = true; lookupParent.paused = true; if (!lookupParent.muteCallbacks) { lookupParent.onComplete(lookupParent); lookupParent._resolve(lookupParent); } } } } nextLookup = next; } return anim; }; /** * @param {WAAPIAnimation} parent * @param {DOMTarget} $el * @param {String} property * @param {PropertyIndexedKeyframes} keyframes * @param {KeyframeAnimationOptions} params * @retun {globalThis.Animation} */ const addWAAPIAnimation = (parent, $el, property, keyframes, params) => { const animation = $el.animate(keyframes, params); const animTotalDuration = params.delay + (+params.duration * params.iterations); animation.playbackRate = parent._speed; if (parent.paused) animation.pause(); if (parent.duration < animTotalDuration) { parent.duration = animTotalDuration; parent.controlAnimation = animation; } parent.animations.push(animation); removeWAAPIAnimation($el, property); addChild(WAAPIAnimationsLookups, { parent, animation, $el, property, _next: null, _prev: null }); const handleRemove = () => { removeWAAPIAnimation($el, property, parent); }; animation.oncancel = handleRemove; animation.onremove = handleRemove; if (!parent.persist) { animation.onfinish = handleRemove; } return animation; }; export { addWAAPIAnimation, removeWAAPIAnimation };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/waapi/index.js
dist/modules/waapi/index.js
/** * Anime.js - waapi - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { WAAPIAnimation, waapi } from './waapi.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/waapi/waapi.js
dist/modules/waapi/waapi.js
/** * Anime.js - waapi - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { isNil, isUnd, stringStartsWith, isKey, isObj, isArr, toLowerCase, round, isStr, isFnc, isNum } from '../core/helpers.js'; import { scope, globals } from '../core/globals.js'; import { registerTargets } from '../core/targets.js'; import { setValue, getFunctionValue } from '../core/values.js'; import { isBrowser, validTransforms, noop, transformsSymbol, shortTransforms, transformsFragmentStrings, emptyString, K } from '../core/consts.js'; import { none } from '../easings/none.js'; import { parseEaseString } from '../easings/eases/parser.js'; import { addWAAPIAnimation } from './composition.js'; /** * @import { * Callback, * EasingFunction, * EasingParam, * DOMTarget, * DOMTargetsParam, * DOMTargetsArray, * WAAPIAnimationParams, * WAAPITweenOptions, * WAAPIKeyframeValue, * WAAPITweenValue * } from '../types/index.js' */ /** * @import { * Spring, * } from '../easings/spring/index.js' */ /** * @import { * ScrollObserver, * } from '../events/scroll.js' */ /** * Converts an easing function into a valid CSS linear() timing function string * @param {EasingFunction} fn * @param {number} [samples=100] * @returns {string} CSS linear() timing function */ const easingToLinear = (fn, samples = 100) => { const points = []; for (let i = 0; i <= samples; i++) points.push(round(fn(i / samples), 4)); return `linear(${points.join(', ')})`; }; const WAAPIEasesLookups = {}; /** * @param {EasingParam} ease * @return {String} */ const parseWAAPIEasing = (ease) => { let parsedEase = WAAPIEasesLookups[ease]; if (parsedEase) return parsedEase; parsedEase = 'linear'; if (isStr(ease)) { if ( stringStartsWith(ease, 'linear') || stringStartsWith(ease, 'cubic-') || stringStartsWith(ease, 'steps') || stringStartsWith(ease, 'ease') ) { parsedEase = ease; } else if (stringStartsWith(ease, 'cubicB')) { parsedEase = toLowerCase(ease); } else { const parsed = parseEaseString(ease); if (isFnc(parsed)) parsedEase = parsed === none ? 'linear' : easingToLinear(parsed); } // Only cache string based easing name, otherwise function arguments get lost WAAPIEasesLookups[ease] = parsedEase; } else if (isFnc(ease)) { const easing = easingToLinear(ease); if (easing) parsedEase = easing; } else if (/** @type {Spring} */(ease).ease) { parsedEase = easingToLinear(/** @type {Spring} */(ease).ease); } return parsedEase; }; const transformsShorthands = ['x', 'y', 'z']; const commonDefaultPXProperties = [ 'perspective', 'width', 'height', 'margin', 'padding', 'top', 'right', 'bottom', 'left', 'borderWidth', 'fontSize', 'borderRadius', ...transformsShorthands ]; const validIndividualTransforms = /*#__PURE__*/ (() => [...transformsShorthands, ...validTransforms.filter(t => ['X', 'Y', 'Z'].some(axis => t.endsWith(axis)))])(); let transformsPropertiesRegistered = null; /** * @param {String} propName * @param {WAAPIKeyframeValue} value * @param {DOMTarget} $el * @param {Number} i * @param {Number} targetsLength * @return {String} */ const normalizeTweenValue = (propName, value, $el, i, targetsLength) => { // Do not try to compute strings with getFunctionValue otherwise it will convert CSS variables let v = isStr(value) ? value : getFunctionValue(/** @type {any} */(value), $el, i, targetsLength); if (!isNum(v)) return v; if (commonDefaultPXProperties.includes(propName) || stringStartsWith(propName, 'translate')) return `${v}px`; if (stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew')) return `${v}deg`; return `${v}`; }; /** * @param {DOMTarget} $el * @param {String} propName * @param {WAAPIKeyframeValue} from * @param {WAAPIKeyframeValue} to * @param {Number} i * @param {Number} targetsLength * @return {WAAPITweenValue} */ const parseIndividualTweenValue = ($el, propName, from, to, i, targetsLength) => { /** @type {WAAPITweenValue} */ let tweenValue = '0'; const computedTo = !isUnd(to) ? normalizeTweenValue(propName, to, $el, i, targetsLength) : getComputedStyle($el)[propName]; if (!isUnd(from)) { const computedFrom = normalizeTweenValue(propName, from, $el, i, targetsLength); tweenValue = [computedFrom, computedTo]; } else { tweenValue = isArr(to) ? to.map((/** @type {any} */v) => normalizeTweenValue(propName, v, $el, i, targetsLength)) : computedTo; } return tweenValue; }; class WAAPIAnimation { /** * @param {DOMTargetsParam} targets * @param {WAAPIAnimationParams} params */ constructor(targets, params) { if (scope.current) scope.current.register(this); // Skip the registration and fallback to no animation in case CSS.registerProperty is not supported if (isNil(transformsPropertiesRegistered)) { if (isBrowser && (isUnd(CSS) || !Object.hasOwnProperty.call(CSS, 'registerProperty'))) { transformsPropertiesRegistered = false; } else { validTransforms.forEach(t => { const isSkew = stringStartsWith(t, 'skew'); const isScale = stringStartsWith(t, 'scale'); const isRotate = stringStartsWith(t, 'rotate'); const isTranslate = stringStartsWith(t, 'translate'); const isAngle = isRotate || isSkew; const syntax = isAngle ? '<angle>' : isScale ? "<number>" : isTranslate ? "<length-percentage>" : "*"; try { CSS.registerProperty({ name: '--' + t, syntax, inherits: false, initialValue: isTranslate ? '0px' : isAngle ? '0deg' : isScale ? '1' : '0', }); } catch {} }); transformsPropertiesRegistered = true; } } const parsedTargets = registerTargets(targets); const targetsLength = parsedTargets.length; if (!targetsLength) { console.warn(`No target found. Make sure the element you're trying to animate is accessible before creating your animation.`); } const ease = setValue(params.ease, parseWAAPIEasing(globals.defaults.ease)); const spring = /** @type {Spring} */(ease).ease && ease; const autoplay = setValue(params.autoplay, globals.defaults.autoplay); const scroll = autoplay && /** @type {ScrollObserver} */(autoplay).link ? autoplay : false; const alternate = params.alternate && /** @type {Boolean} */(params.alternate) === true; const reversed = params.reversed && /** @type {Boolean} */(params.reversed) === true; const loop = setValue(params.loop, globals.defaults.loop); const iterations = /** @type {Number} */((loop === true || loop === Infinity) ? Infinity : isNum(loop) ? loop + 1 : 1); /** @type {PlaybackDirection} */ const direction = alternate ? reversed ? 'alternate-reverse' : 'alternate' : reversed ? 'reverse' : 'normal'; /** @type {FillMode} */ const fill = 'both'; // We use 'both' here because the animation can be reversed during playback /** @type {String} */ const easing = parseWAAPIEasing(ease); const timeScale = (globals.timeScale === 1 ? 1 : K); /** @type {DOMTargetsArray}] */ this.targets = parsedTargets; /** @type {Array<globalThis.Animation>}] */ this.animations = []; /** @type {globalThis.Animation}] */ this.controlAnimation = null; /** @type {Callback<this>} */ this.onComplete = params.onComplete || /** @type {Callback<WAAPIAnimation>} */(/** @type {unknown} */(globals.defaults.onComplete)); /** @type {Number} */ this.duration = 0; /** @type {Boolean} */ this.muteCallbacks = false; /** @type {Boolean} */ this.completed = false; /** @type {Boolean} */ this.paused = !autoplay || scroll !== false; /** @type {Boolean} */ this.reversed = reversed; /** @type {Boolean} */ this.persist = setValue(params.persist, globals.defaults.persist); /** @type {Boolean|ScrollObserver} */ this.autoplay = autoplay; /** @type {Number} */ this._speed = setValue(params.playbackRate, globals.defaults.playbackRate); /** @type {Function} */ this._resolve = noop; // Used by .then() /** @type {Number} */ this._completed = 0; /** @type {Array.<Object>} */ this._inlineStyles = []; parsedTargets.forEach(($el, i) => { const cachedTransforms = $el[transformsSymbol]; const hasIndividualTransforms = validIndividualTransforms.some(t => params.hasOwnProperty(t)); const elStyle = $el.style; const inlineStyles = this._inlineStyles[i] = {}; /** @type {Number} */ const duration = (spring ? /** @type {Spring} */(spring).settlingDuration : getFunctionValue(setValue(params.duration, globals.defaults.duration), $el, i, targetsLength)) * timeScale; /** @type {Number} */ const delay = getFunctionValue(setValue(params.delay, globals.defaults.delay), $el, i, targetsLength) * timeScale; /** @type {CompositeOperation} */ const composite = /** @type {CompositeOperation} */(setValue(params.composition, 'replace')); for (let name in params) { if (!isKey(name)) continue; /** @type {PropertyIndexedKeyframes} */ const keyframes = {}; /** @type {KeyframeAnimationOptions} */ const tweenParams = { iterations, direction, fill, easing, duration, delay, composite }; const propertyValue = params[name]; const individualTransformProperty = hasIndividualTransforms ? validTransforms.includes(name) ? name : shortTransforms.get(name) : false; const styleName = individualTransformProperty ? 'transform' : name; if (!inlineStyles[styleName]) { inlineStyles[styleName] = elStyle[styleName]; } let parsedPropertyValue; if (isObj(propertyValue)) { const tweenOptions = /** @type {WAAPITweenOptions} */(propertyValue); const tweenOptionsEase = setValue(tweenOptions.ease, ease); const tweenOptionsSpring = /** @type {Spring} */(tweenOptionsEase).ease && tweenOptionsEase; const to = /** @type {WAAPITweenOptions} */(tweenOptions).to; const from = /** @type {WAAPITweenOptions} */(tweenOptions).from; /** @type {Number} */ tweenParams.duration = (tweenOptionsSpring ? /** @type {Spring} */(tweenOptionsSpring).settlingDuration : getFunctionValue(setValue(tweenOptions.duration, duration), $el, i, targetsLength)) * timeScale; /** @type {Number} */ tweenParams.delay = getFunctionValue(setValue(tweenOptions.delay, delay), $el, i, targetsLength) * timeScale; /** @type {CompositeOperation} */ tweenParams.composite = /** @type {CompositeOperation} */(setValue(tweenOptions.composition, composite)); /** @type {String} */ tweenParams.easing = parseWAAPIEasing(tweenOptionsEase); parsedPropertyValue = parseIndividualTweenValue($el, name, from, to, i, targetsLength); if (individualTransformProperty) { keyframes[`--${individualTransformProperty}`] = parsedPropertyValue; cachedTransforms[individualTransformProperty] = parsedPropertyValue; } else { keyframes[name] = parseIndividualTweenValue($el, name, from, to, i, targetsLength); } addWAAPIAnimation(this, $el, name, keyframes, tweenParams); if (!isUnd(from)) { if (!individualTransformProperty) { elStyle[name] = keyframes[name][0]; } else { const key = `--${individualTransformProperty}`; elStyle.setProperty(key, keyframes[key][0]); } } } else { parsedPropertyValue = isArr(propertyValue) ? propertyValue.map((/** @type {any} */v) => normalizeTweenValue(name, v, $el, i, targetsLength)) : normalizeTweenValue(name, /** @type {any} */(propertyValue), $el, i, targetsLength); if (individualTransformProperty) { keyframes[`--${individualTransformProperty}`] = parsedPropertyValue; cachedTransforms[individualTransformProperty] = parsedPropertyValue; } else { keyframes[name] = parsedPropertyValue; } addWAAPIAnimation(this, $el, name, keyframes, tweenParams); } } if (hasIndividualTransforms) { let transforms = emptyString; for (let t in cachedTransforms) { transforms += `${transformsFragmentStrings[t]}var(--${t})) `; } elStyle.transform = transforms; } }); if (scroll) { /** @type {ScrollObserver} */(this.autoplay).link(this); } } /** * @callback forEachCallback * @param {globalThis.Animation} animation */ /** * @param {forEachCallback|String} callback * @return {this} */ forEach(callback) { const cb = isStr(callback) ? (/** @type {globalThis.Animation} */a) => a[callback]() : callback; this.animations.forEach(cb); return this; } get speed() { return this._speed; } set speed(speed) { this._speed = +speed; this.forEach(anim => anim.playbackRate = speed); } get currentTime() { const controlAnimation = this.controlAnimation; const timeScale = globals.timeScale; return this.completed ? this.duration : controlAnimation ? +controlAnimation.currentTime * (timeScale === 1 ? 1 : timeScale) : 0; } set currentTime(time) { const t = time * (globals.timeScale === 1 ? 1 : K); this.forEach(anim => { // Make sure the animation playState is not 'paused' in order to properly trigger an onfinish callback. // The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported. // https://developer.mozilla.org/en-US/docs/Web/API/Animation/finish_event // This is not needed for persisting animations since they never finish. if (!this.persist && t >= this.duration) anim.play(); anim.currentTime = t; }); } get progress() { return this.currentTime / this.duration; } set progress(progress) { this.forEach(anim => anim.currentTime = progress * this.duration || 0); } resume() { if (!this.paused) return this; this.paused = false; // TODO: Store the current time, and seek back to the last position return this.forEach('play'); } pause() { if (this.paused) return this; this.paused = true; return this.forEach('pause'); } alternate() { this.reversed = !this.reversed; this.forEach('reverse'); if (this.paused) this.forEach('pause'); return this; } play() { if (this.reversed) this.alternate(); return this.resume(); } reverse() { if (!this.reversed) this.alternate(); return this.resume(); } /** * @param {Number} time * @param {Boolean} muteCallbacks */ seek(time, muteCallbacks = false) { if (muteCallbacks) this.muteCallbacks = true; if (time < this.duration) this.completed = false; this.currentTime = time; this.muteCallbacks = false; if (this.paused) this.pause(); return this; } restart() { this.completed = false; return this.seek(0, true).resume(); } commitStyles() { return this.forEach('commitStyles'); } complete() { return this.seek(this.duration); } cancel() { this.muteCallbacks = true; // This prevents triggering the onComplete callback and resolving the Promise return this.commitStyles().forEach('cancel'); } revert() { // NOTE: We need a better way to revert the transforms, since right now the entire transform property value is reverted, // This means if you have multiple animations animating different transforms on the same target, // reverting one of them will also override the transform property of the other animations. // A better approach would be to store the original custom property values is they exist instead of the entire transform value, // and update the CSS variables with the orignal value this.cancel().targets.forEach(($el, i) => { const targetStyle = $el.style; const targetInlineStyles = this._inlineStyles[i]; for (let name in targetInlineStyles) { const originalInlinedValue = targetInlineStyles[name]; if (isUnd(originalInlinedValue) || originalInlinedValue === emptyString) { targetStyle.removeProperty(toLowerCase(name)); } else { targetStyle[name] = originalInlinedValue; } } // Remove style attribute if empty if ($el.getAttribute('style') === emptyString) $el.removeAttribute('style'); }); return this; } /** * @typedef {this & {then: null}} ResolvedWAAPIAnimation */ /** * @param {Callback<ResolvedWAAPIAnimation>} [callback] * @return Promise<this> */ then(callback = noop) { const then = this.then; const onResolve = () => { this.then = null; callback(/** @type {ResolvedWAAPIAnimation} */(this)); this.then = then; this._resolve = noop; }; return new Promise(r => { this._resolve = () => r(onResolve()); if (this.completed) this._resolve(); return this; }); } } const waapi = { /** * @param {DOMTargetsParam} targets * @param {WAAPIAnimationParams} params * @return {WAAPIAnimation} */ animate: (targets, params) => new WAAPIAnimation(targets, params), convertEase: easingToLinear }; export { WAAPIAnimation, waapi };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/animatable/index.js
dist/modules/animatable/index.js
/** * Anime.js - animatable - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { Animatable, createAnimatable } from './animatable.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/animatable/animatable.js
dist/modules/animatable/animatable.js
/** * Anime.js - animatable - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { compositionTypes, noop } from '../core/consts.js'; import { scope } from '../core/globals.js'; import { isUnd, isKey, stringStartsWith, isObj, mergeObjects, forEachChildren, isStr, isArr } from '../core/helpers.js'; import { JSAnimation } from '../animation/animation.js'; import { parseEase } from '../easings/eases/parser.js'; /** * @import { * TargetsParam, * AnimatableParams, * AnimationParams, * TweenParamsOptions, * Tween, * AnimatableProperty, * AnimatableObject, * } from '../types/index.js'; */ class Animatable { /** * @param {TargetsParam} targets * @param {AnimatableParams} parameters */ constructor(targets, parameters) { if (scope.current) scope.current.register(this); const beginHandler = () => { if (this.callbacks.completed) this.callbacks.reset(); this.callbacks.play(); }; const pauseHandler = () => { if (this.callbacks.completed) return; let paused = true; for (let name in this.animations) { const anim = this.animations[name]; if (!anim.paused && paused) { paused = false; break; } } if (paused) { this.callbacks.complete(); } }; /** @type {AnimationParams} */ const globalParams = { onBegin: beginHandler, onComplete: pauseHandler, onPause: pauseHandler, }; /** @type {AnimationParams} */ const callbacksAnimationParams = { v: 1, autoplay: false }; const properties = {}; this.targets = []; this.animations = {}; /** @type {JSAnimation|null} */ this.callbacks = null; if (isUnd(targets) || isUnd(parameters)) return; for (let propName in parameters) { const paramValue = parameters[propName]; if (isKey(propName)) { properties[propName] = paramValue; } else if (stringStartsWith(propName, 'on')) { callbacksAnimationParams[propName] = paramValue; } else { globalParams[propName] = paramValue; } } this.callbacks = new JSAnimation({ v: 0 }, callbacksAnimationParams); for (let propName in properties) { const propValue = properties[propName]; const isObjValue = isObj(propValue); /** @type {TweenParamsOptions} */ let propParams = {}; let to = '+=0'; if (isObjValue) { const unit = propValue.unit; if (isStr(unit)) to += unit; } else { propParams.duration = propValue; } propParams[propName] = isObjValue ? mergeObjects({ to }, propValue) : to; const animParams = mergeObjects(globalParams, propParams); animParams.composition = compositionTypes.replace; animParams.autoplay = false; const animation = this.animations[propName] = new JSAnimation(targets, animParams, null, 0, false).init(); if (!this.targets.length) this.targets.push(...animation.targets); /** @type {AnimatableProperty} */ this[propName] = (to, duration, ease) => { const tween = /** @type {Tween} */(animation._head); if (isUnd(to) && tween) { const numbers = tween._numbers; if (numbers && numbers.length) { return numbers; } else { return tween._modifier(tween._number); } } else { forEachChildren(animation, (/** @type {Tween} */tween) => { if (isArr(to)) { for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) { if (!isUnd(tween._numbers[i])) { tween._fromNumbers[i] = /** @type {Number} */(tween._modifier(tween._numbers[i])); tween._toNumbers[i] = to[i]; } } } else { tween._fromNumber = /** @type {Number} */(tween._modifier(tween._number)); tween._toNumber = /** @type {Number} */(to); } if (!isUnd(ease)) tween._ease = parseEase(ease); tween._currentTime = 0; }); if (!isUnd(duration)) animation.stretch(duration); animation.reset(true).resume(); return this; } }; } } revert() { for (let propName in this.animations) { this[propName] = noop; this.animations[propName].revert(); } this.animations = {}; this.targets.length = 0; if (this.callbacks) this.callbacks.revert(); return this; } } /** * @param {TargetsParam} targets * @param {AnimatableParams} parameters * @return {AnimatableObject} */ const createAnimatable = (targets, parameters) => /** @type {AnimatableObject} */ (new Animatable(targets, parameters)); export { Animatable, createAnimatable };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/svg/index.js
dist/modules/svg/index.js
/** * Anime.js - svg - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ export { createMotionPath } from './motionpath.js'; export { createDrawable } from './drawable.js'; export { morphTo } from './morphto.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/svg/morphto.js
dist/modules/svg/morphto.js
/** * Anime.js - svg - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { morphPointsSymbol } from '../core/consts.js'; import { round } from '../core/helpers.js'; import { getPath } from './helpers.js'; /** * @import { * TargetsParam, * FunctionValue * } from '../types/index.js' */ /** * @param {TargetsParam} path2 * @param {Number} [precision] * @return {FunctionValue} */ const morphTo = (path2, precision = .33) => ($path1) => { const tagName1 = ($path1.tagName || '').toLowerCase(); if (!tagName1.match(/^(path|polygon|polyline)$/)) { throw new Error(`Can't morph a <${$path1.tagName}> SVG element. Use <path>, <polygon> or <polyline>.`); } const $path2 = /** @type {SVGGeometryElement} */(getPath(path2)); if (!$path2) { throw new Error("Can't morph to an invalid target. 'path2' must resolve to an existing <path>, <polygon> or <polyline> SVG element."); } const tagName2 = ($path2.tagName || '').toLowerCase(); if (!tagName2.match(/^(path|polygon|polyline)$/)) { throw new Error(`Can't morph a <${$path2.tagName}> SVG element. Use <path>, <polygon> or <polyline>.`); } const isPath = $path1.tagName === 'path'; const separator = isPath ? ' ' : ','; const previousPoints = $path1[morphPointsSymbol]; if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints); let v1 = '', v2 = ''; if (!precision) { v1 = $path1.getAttribute(isPath ? 'd' : 'points'); v2 = $path2.getAttribute(isPath ? 'd' : 'points'); } else { const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength(); const length2 = $path2.getTotalLength(); const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision)); for (let i = 0; i < maxPoints; i++) { const t = i / (maxPoints - 1); const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t); const pointOnPath2 = $path2.getPointAtLength(length2 * t); const prefix = isPath ? (i === 0 ? 'M' : 'L') : ''; v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' '; v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' '; } } $path1[morphPointsSymbol] = v2; return [v1, v2]; }; export { morphTo };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/svg/motionpath.js
dist/modules/svg/motionpath.js
/** * Anime.js - svg - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { isSvgSymbol } from '../core/consts.js'; import { atan2, PI } from '../core/helpers.js'; import { getPath } from './helpers.js'; /** * @import { * TargetsParam, * FunctionValue, * TweenObjectValue, * TweenModifier, * } from '../types/index.js' */ // Motion path animation /** * @param {SVGGeometryElement} $path * @param {Number} totalLength * @param {Number} progress * @param {Number} lookup * @param {Boolean} shouldClamp * @return {DOMPoint} */ const getPathPoint = ($path, totalLength, progress, lookup, shouldClamp) => { const point = progress + lookup; const pointOnPath = shouldClamp ? Math.max(0, Math.min(point, totalLength)) // Clamp between 0 and totalLength : (point % totalLength + totalLength) % totalLength; // Wrap around return $path.getPointAtLength(pointOnPath); }; /** * @param {SVGGeometryElement} $path * @param {String} pathProperty * @param {Number} [offset=0] * @return {FunctionValue} */ const getPathProgess = ($path, pathProperty, offset = 0) => { return $el => { const totalLength = +($path.getTotalLength()); const inSvg = $el[isSvgSymbol]; const ctm = $path.getCTM(); const shouldClamp = offset === 0; /** @type {TweenObjectValue} */ return { from: 0, to: totalLength, /** @type {TweenModifier} */ modifier: progress => { const offsetLength = offset * totalLength; const newProgress = progress + offsetLength; if (pathProperty === 'a') { const p0 = getPathPoint($path, totalLength, newProgress, -1, shouldClamp); const p1 = getPathPoint($path, totalLength, newProgress, 1, shouldClamp); return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI; } else { const p = getPathPoint($path, totalLength, newProgress, 0, shouldClamp); return pathProperty === 'x' ? inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e : inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f } } } } }; /** * @param {TargetsParam} path * @param {Number} [offset=0] */ const createMotionPath = (path, offset = 0) => { const $path = getPath(path); if (!$path) return; return { translateX: getPathProgess($path, 'x', offset), translateY: getPathProgess($path, 'y', offset), rotate: getPathProgess($path, 'a', offset), } }; export { createMotionPath };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/svg/helpers.js
dist/modules/svg/helpers.js
/** * Anime.js - svg - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { isSvg } from '../core/helpers.js'; import { parseTargets } from '../core/targets.js'; /** * @import { * TargetsParam, * } from '../types/index.js' */ /** * @param {TargetsParam} path * @return {SVGGeometryElement|void} */ const getPath = path => { const parsedTargets = parseTargets(path); const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]); if (!$parsedSvg || !isSvg($parsedSvg)) return console.warn(`${path} is not a valid SVGGeometryElement`); return $parsedSvg; }; export { getPath };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/dist/modules/svg/drawable.js
dist/modules/svg/drawable.js
/** * Anime.js - svg - ESM * @version v4.2.2 * @license MIT * @copyright 2025 - Julian Garnier */ import { proxyTargetSymbol, K } from '../core/consts.js'; import { isFnc, sqrt } from '../core/helpers.js'; import { parseTargets } from '../core/targets.js'; /** * @import { * TargetsParam, * DrawableSVGGeometry, * } from '../types/index.js' */ /** * @param {SVGGeometryElement} [$el] * @return {Number} */ const getScaleFactor = $el => { let scaleFactor = 1; if ($el && $el.getCTM) { const ctm = $el.getCTM(); if (ctm) { const scaleX = sqrt(ctm.a * ctm.a + ctm.b * ctm.b); const scaleY = sqrt(ctm.c * ctm.c + ctm.d * ctm.d); scaleFactor = (scaleX + scaleY) / 2; } } return scaleFactor; }; /** * Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality. * @param {SVGGeometryElement} $el - The SVG element to transform into a drawable * @param {number} start - Starting position (0-1) * @param {number} end - Ending position (0-1) * @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality */ const createDrawableProxy = ($el, start, end) => { const pathLength = K; const computedStyles = getComputedStyle($el); const strokeLineCap = computedStyles.strokeLinecap; // @ts-ignore const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null; let currentCap = strokeLineCap; const proxy = new Proxy($el, { get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { return (...args) => { if (args[0] === 'draw') { const value = args[1]; const values = value.split(' '); const v1 = +values[0]; const v2 = +values[1]; // TOTO: Benchmark if performing two slices is more performant than one split // const spaceIndex = value.indexOf(' '); // const v1 = round(+value.slice(0, spaceIndex), precision); // const v2 = round(+value.slice(spaceIndex + 1), precision); const scaleFactor = getScaleFactor($scalled); const os = v1 * -pathLength * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } } }); if ($el.getAttribute('pathLength') !== `${pathLength}`) { $el.setAttribute('pathLength', `${pathLength}`); proxy.setAttribute('draw', `${start} ${end}`); } return /** @type {DrawableSVGGeometry} */(proxy); }; /** * Creates drawable proxies for multiple SVG elements. * @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors * @param {number} [start=0] - Starting position (0-1) * @param {number} [end=0] - Ending position (0-1) * @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality */ const createDrawable = (selector, start = 0, end = 0) => { const els = parseTargets(selector); return els.map($el => createDrawableProxy( /** @type {SVGGeometryElement} */($el), start, end )); }; export { createDrawable };
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/eslint.config.js
eslint.config.js
import globals from "./server/node_modules/globals/index.js" import eslintRecommended from "./server/node_modules/@eslint/js/src/index.js" import eslintConfigPrettier from "./server/node_modules/eslint-config-prettier/index.js" import prettier from "./server/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js" import react from "./server/node_modules/eslint-plugin-react/index.js" import reactRefresh from "./server/node_modules/eslint-plugin-react-refresh/index.js" import reactHooks from "./server/node_modules/eslint-plugin-react-hooks/index.js" import ftFlow from "./server/node_modules/eslint-plugin-ft-flow/dist/index.js" import hermesParser from "./server/node_modules/hermes-eslint/dist/index.js" const reactRecommended = react.configs.recommended const jsxRuntime = react.configs["jsx-runtime"] export default [ eslintRecommended.configs.recommended, eslintConfigPrettier, { ignores: ["**/*.test.js"], languageOptions: { parser: hermesParser, parserOptions: { ecmaFeatures: { jsx: true } }, ecmaVersion: 2020, sourceType: "module", globals: { ...globals.browser, ...globals.es2020, ...globals.node } }, linterOptions: { reportUnusedDisableDirectives: true }, settings: { react: { version: "18.2" } }, plugins: { ftFlow, react, "jsx-runtime": jsxRuntime, "react-hooks": reactHooks, prettier }, rules: { ...reactRecommended.rules, ...reactHooks.configs.recommended.rules, ...ftFlow.recommended, "no-unused-vars": "warn", "no-undef": "warn", "no-empty": "warn", "no-extra-boolean-cast": "warn", "no-prototype-builtins": "off", "prettier/prettier": "warn" } }, { files: ["frontend/src/**/*.js"], plugins: { ftFlow, prettier }, rules: { "prettier/prettier": "warn" } }, { files: [ "server/endpoints/**/*.js", "server/models/**/*.js", "server/swagger/**/*.js", "server/utils/**/*.js", "server/index.js" ], rules: { "no-undef": "warn" } }, { files: ["frontend/src/**/*.jsx"], plugins: { ftFlow, react, "jsx-runtime": jsxRuntime, "react-hooks": reactHooks, "react-refresh": reactRefresh, prettier }, rules: { ...jsxRuntime.rules, "react/prop-types": "off", // FIXME "react-refresh/only-export-components": "warn" } } ]
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/index.js
collector/index.js
process.env.NODE_ENV === "development" ? require("dotenv").config({ path: `.env.${process.env.NODE_ENV}` }) : require("dotenv").config(); require("./utils/logger")(); const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const path = require("path"); const { ACCEPTED_MIMES } = require("./utils/constants"); const { reqBody } = require("./utils/http"); const { processSingleFile } = require("./processSingleFile"); const { processLink, getLinkText } = require("./processLink"); const { wipeCollectorStorage } = require("./utils/files"); const extensions = require("./extensions"); const { processRawText } = require("./processRawText"); const { verifyPayloadIntegrity } = require("./middleware/verifyIntegrity"); const { httpLogger } = require("./middleware/httpLogger"); const app = express(); const FILE_LIMIT = "3GB"; // Only log HTTP requests in development mode and if the ENABLE_HTTP_LOGGER environment variable is set to true if ( process.env.NODE_ENV === "development" && !!process.env.ENABLE_HTTP_LOGGER ) { app.use( httpLogger({ enableTimestamps: !!process.env.ENABLE_HTTP_LOGGER_TIMESTAMPS, }) ); } app.use(cors({ origin: true })); app.use( bodyParser.text({ limit: FILE_LIMIT }), bodyParser.json({ limit: FILE_LIMIT }), bodyParser.urlencoded({ limit: FILE_LIMIT, extended: true, }) ); app.post( "/process", [verifyPayloadIntegrity], async function (request, response) { const { filename, options = {}, metadata = {} } = reqBody(request); try { const targetFilename = path .normalize(filename) .replace(/^(\.\.(\/|\\|$))+/, ""); const { success, reason, documents = [], } = await processSingleFile(targetFilename, options, metadata); response .status(200) .json({ filename: targetFilename, success, reason, documents }); } catch (e) { console.error(e); response.status(200).json({ filename: filename, success: false, reason: "A processing error occurred.", documents: [], }); } return; } ); app.post( "/parse", [verifyPayloadIntegrity], async function (request, response) { const { filename, options = {} } = reqBody(request); try { const targetFilename = path .normalize(filename) .replace(/^(\.\.(\/|\\|$))+/, ""); const { success, reason, documents = [], } = await processSingleFile(targetFilename, { ...options, parseOnly: true, }); response .status(200) .json({ filename: targetFilename, success, reason, documents }); } catch (e) { console.error(e); response.status(200).json({ filename: filename, success: false, reason: "A processing error occurred.", documents: [], }); } return; } ); app.post( "/process-link", [verifyPayloadIntegrity], async function (request, response) { const { link, scraperHeaders = {}, metadata = {} } = reqBody(request); try { const { success, reason, documents = [], } = await processLink(link, scraperHeaders, metadata); response.status(200).json({ url: link, success, reason, documents }); } catch (e) { console.error(e); response.status(200).json({ url: link, success: false, reason: "A processing error occurred.", documents: [], }); } return; } ); app.post( "/util/get-link", [verifyPayloadIntegrity], async function (request, response) { const { link, captureAs = "text" } = reqBody(request); try { const { success, content = null } = await getLinkText(link, captureAs); response.status(200).json({ url: link, success, content }); } catch (e) { console.error(e); response.status(200).json({ url: link, success: false, content: null, }); } return; } ); app.post( "/process-raw-text", [verifyPayloadIntegrity], async function (request, response) { const { textContent, metadata } = reqBody(request); try { const { success, reason, documents = [], } = await processRawText(textContent, metadata); response .status(200) .json({ filename: metadata.title, success, reason, documents }); } catch (e) { console.error(e); response.status(200).json({ filename: metadata?.title || "Unknown-doc.txt", success: false, reason: "A processing error occurred.", documents: [], }); } return; } ); extensions(app); app.get("/accepts", function (_, response) { response.status(200).json(ACCEPTED_MIMES); }); app.all("*", function (_, response) { response.sendStatus(200); }); app .listen(8888, async () => { await wipeCollectorStorage(); console.log(`Document processor app listening on port 8888`); }) .on("error", function (_) { process.once("SIGUSR2", function () { process.kill(process.pid, "SIGUSR2"); }); process.on("SIGINT", function () { process.kill(process.pid, "SIGINT"); }); });
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/index.js
collector/processSingleFile/index.js
const path = require("path"); const fs = require("fs"); const { WATCH_DIRECTORY, SUPPORTED_FILETYPE_CONVERTERS, } = require("../utils/constants"); const { trashFile, isTextType, normalizePath, isWithin, } = require("../utils/files"); const RESERVED_FILES = ["__HOTDIR__.md"]; /** * Process a single file and return the documents * @param {string} targetFilename - The filename to process * @param {Object} options - The options for the file processing * @param {boolean} options.parseOnly - If true, the file will not be saved as a document even when `writeToServerDocuments` is called in the handler. Must be explicitly set to true to use. * @param {Object} metadata - The metadata for the file processing * @returns {Promise<{success: boolean, reason: string, documents: Object[]}>} - The documents from the file processing */ async function processSingleFile(targetFilename, options = {}, metadata = {}) { const fullFilePath = path.resolve( WATCH_DIRECTORY, normalizePath(targetFilename) ); if (!isWithin(path.resolve(WATCH_DIRECTORY), fullFilePath)) return { success: false, reason: "Filename is a not a valid path to process.", documents: [], }; if (RESERVED_FILES.includes(targetFilename)) return { success: false, reason: "Filename is a reserved filename and cannot be processed.", documents: [], }; if (!fs.existsSync(fullFilePath)) return { success: false, reason: "File does not exist in upload directory.", documents: [], }; const fileExtension = path.extname(fullFilePath).toLowerCase(); if (fullFilePath.includes(".") && !fileExtension) { return { success: false, reason: `No file extension found. This file cannot be processed.`, documents: [], }; } let processFileAs = fileExtension; if (!SUPPORTED_FILETYPE_CONVERTERS.hasOwnProperty(fileExtension)) { if (isTextType(fullFilePath)) { console.log( `\x1b[33m[Collector]\x1b[0m The provided filetype of ${fileExtension} does not have a preset and will be processed as .txt.` ); processFileAs = ".txt"; } else { trashFile(fullFilePath); return { success: false, reason: `File extension ${fileExtension} not supported for parsing and cannot be assumed as text file type.`, documents: [], }; } } const FileTypeProcessor = require(SUPPORTED_FILETYPE_CONVERTERS[ processFileAs ]); return await FileTypeProcessor({ fullFilePath, filename: targetFilename, options, metadata, }); } module.exports = { processSingleFile, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asDocx.js
collector/processSingleFile/convert/asDocx.js
const { v4 } = require("uuid"); const { DocxLoader } = require("langchain/document_loaders/fs/docx"); const { createdDate, trashFile, writeToServerDocuments, } = require("../../utils/files"); const { tokenizeString } = require("../../utils/tokenizer"); const { default: slugify } = require("slugify"); async function asDocX({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { const loader = new DocxLoader(fullFilePath); console.log(`-- Working ${filename} --`); let pageContent = []; const docs = await loader.load(); for (const doc of docs) { console.log(`-- Parsing content from docx page --`); if (!doc.pageContent.length) continue; pageContent.push(doc.pageContent); } if (!pageContent.length) { console.error(`Resulting text content was empty for ${filename}.`); trashFile(fullFilePath); return { success: false, reason: `No text content found in ${filename}.`, documents: [], }; } const content = pageContent.join(""); const data = { id: v4(), url: "file://" + fullFilePath, title: metadata.title || filename, docAuthor: metadata.docAuthor || "no author found", description: metadata.description || "No description found.", docSource: metadata.docSource || "docx file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data, filename: `${slugify(filename)}-${data.id}`, options: { parseOnly: options.parseOnly }, }); trashFile(fullFilePath); console.log(`[SUCCESS]: ${filename} converted & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; } module.exports = asDocX;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asImage.js
collector/processSingleFile/convert/asImage.js
const { v4 } = require("uuid"); const { tokenizeString } = require("../../utils/tokenizer"); const { createdDate, trashFile, writeToServerDocuments, } = require("../../utils/files"); const OCRLoader = require("../../utils/OCRLoader"); const { default: slugify } = require("slugify"); async function asImage({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { let content = await new OCRLoader({ targetLanguages: options?.ocr?.langList, }).ocrImage(fullFilePath); if (!content?.length) { console.error(`Resulting text content was empty for ${filename}.`); trashFile(fullFilePath); return { success: false, reason: `No text content found in ${filename}.`, documents: [], }; } console.log(`-- Working ${filename} --`); const data = { id: v4(), url: "file://" + fullFilePath, title: metadata.title || filename, docAuthor: metadata.docAuthor || "Unknown", description: metadata.description || "Unknown", docSource: metadata.docSource || "image file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data, filename: `${slugify(filename)}-${data.id}`, options: { parseOnly: options.parseOnly }, }); trashFile(fullFilePath); console.log(`[SUCCESS]: ${filename} converted & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; } module.exports = asImage;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asMbox.js
collector/processSingleFile/convert/asMbox.js
const { v4 } = require("uuid"); const fs = require("fs"); const { mboxParser } = require("mbox-parser"); const { createdDate, trashFile, writeToServerDocuments, } = require("../../utils/files"); const { tokenizeString } = require("../../utils/tokenizer"); const { default: slugify } = require("slugify"); async function asMbox({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { console.log(`-- Working ${filename} --`); const mails = await mboxParser(fs.createReadStream(fullFilePath)) .then((mails) => mails) .catch((error) => { console.log(`Could not parse mail items`, error); return []; }); if (!mails.length) { console.error(`Resulting mail items was empty for ${filename}.`); trashFile(fullFilePath); return { success: false, reason: `No mail items found in ${filename}.`, documents: [], }; } let item = 1; const documents = []; for (const mail of mails) { if (!mail.hasOwnProperty("text")) continue; const content = mail.text; if (!content) continue; console.log( `-- Working on message "${mail.subject || "Unknown subject"}" --` ); const data = { id: v4(), url: "file://" + fullFilePath, title: metadata.title || (mail?.subject ? slugify(mail?.subject?.replace(".", "")) + ".mbox" : `msg_${item}-${filename}`), docAuthor: metadata.docAuthor || mail?.from?.text, description: metadata.description || "No description found.", docSource: metadata.docSource || "Mbox message file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; item++; const document = writeToServerDocuments({ data, filename: `${slugify(filename)}-${data.id}-msg-${item}`, options: { parseOnly: options.parseOnly }, }); documents.push(document); } trashFile(fullFilePath); console.log( `[SUCCESS]: ${filename} messages converted & ready for embedding.\n` ); return { success: true, reason: null, documents }; } module.exports = asMbox;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asOfficeMime.js
collector/processSingleFile/convert/asOfficeMime.js
const { v4 } = require("uuid"); const officeParser = require("officeparser"); const { createdDate, trashFile, writeToServerDocuments, } = require("../../utils/files"); const { tokenizeString } = require("../../utils/tokenizer"); const { default: slugify } = require("slugify"); async function asOfficeMime({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { console.log(`-- Working ${filename} --`); let content = ""; try { content = await officeParser.parseOfficeAsync(fullFilePath); } catch (error) { console.error(`Could not parse office or office-like file`, error); } if (!content.length) { console.error(`Resulting text content was empty for ${filename}.`); trashFile(fullFilePath); return { success: false, reason: `No text content found in ${filename}.`, documents: [], }; } const data = { id: v4(), url: "file://" + fullFilePath, title: metadata.title || filename, docAuthor: metadata.docAuthor || "no author found", description: metadata.description || "No description found.", docSource: metadata.docSource || "Office file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data, filename: `${slugify(filename)}-${data.id}`, options: { parseOnly: options.parseOnly }, }); trashFile(fullFilePath); console.log(`[SUCCESS]: ${filename} converted & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; } module.exports = asOfficeMime;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asXlsx.js
collector/processSingleFile/convert/asXlsx.js
const { v4 } = require("uuid"); const xlsx = require("node-xlsx").default; const path = require("path"); const fs = require("fs"); const { createdDate, trashFile, writeToServerDocuments, documentsFolder, directUploadsFolder, } = require("../../utils/files"); const { tokenizeString } = require("../../utils/tokenizer"); const { default: slugify } = require("slugify"); function convertToCSV(data) { return data .map((row) => row .map((cell) => { if (cell === null || cell === undefined) return ""; if (typeof cell === "string" && cell.includes(",")) return `"${cell}"`; return cell; }) .join(",") ) .join("\n"); } async function asXlsx({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { const documents = []; const folderName = slugify(`${path.basename(filename)}-${v4().slice(0, 4)}`, { lower: true, trim: true, }); const outFolderPath = options.parseOnly ? path.resolve(directUploadsFolder, folderName) : path.resolve(documentsFolder, folderName); try { const workSheetsFromFile = xlsx.parse(fullFilePath); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); for (const sheet of workSheetsFromFile) { try { const { name, data } = sheet; const content = convertToCSV(data); if (!content?.length) { console.warn(`Sheet "${name}" is empty. Skipping.`); continue; } console.log(`-- Processing sheet: ${name} --`); const sheetData = { id: v4(), url: `file://${path.join(outFolderPath, `${slugify(name)}.csv`)}`, title: metadata.title || `${filename} - Sheet:${name}`, docAuthor: metadata.docAuthor || "Unknown", description: metadata.description || `Spreadsheet data from sheet: ${name}`, docSource: metadata.docSource || "an xlsx file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(/\s+/).length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data: sheetData, filename: `sheet-${slugify(name)}`, destinationOverride: outFolderPath, options: { parseOnly: options.parseOnly }, }); documents.push(document); console.log( `[SUCCESS]: Sheet "${name}" converted & ready for embedding.` ); } catch (err) { console.error(`Error processing sheet "${name}":`, err); continue; } } } catch (err) { console.error("Could not process xlsx file!", err); return { success: false, reason: `Error processing ${filename}: ${err.message}`, documents: [], }; } finally { trashFile(fullFilePath); } if (documents.length === 0) { console.error(`No valid sheets found in ${filename}.`); return { success: false, reason: `No valid sheets found in ${filename}.`, documents: [], }; } console.log( `[SUCCESS]: ${filename} fully processed. Created ${documents.length} document(s).\n` ); return { success: true, reason: null, documents }; } module.exports = asXlsx;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asAudio.js
collector/processSingleFile/convert/asAudio.js
const { v4 } = require("uuid"); const { createdDate, trashFile, writeToServerDocuments, } = require("../../utils/files"); const { tokenizeString } = require("../../utils/tokenizer"); const { default: slugify } = require("slugify"); const { LocalWhisper } = require("../../utils/WhisperProviders/localWhisper"); const { OpenAiWhisper } = require("../../utils/WhisperProviders/OpenAiWhisper"); const WHISPER_PROVIDERS = { openai: OpenAiWhisper, local: LocalWhisper, }; async function asAudio({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { const WhisperProvider = WHISPER_PROVIDERS.hasOwnProperty( options?.whisperProvider ) ? WHISPER_PROVIDERS[options?.whisperProvider] : WHISPER_PROVIDERS.local; console.log(`-- Working ${filename} --`); const whisper = new WhisperProvider({ options }); const { content, error } = await whisper.processFile(fullFilePath, filename); if (!!error) { console.error(`Error encountered for parsing of ${filename}.`); trashFile(fullFilePath); return { success: false, reason: error, documents: [], }; } if (!content?.length) { console.error(`Resulting text content was empty for ${filename}.`); trashFile(fullFilePath); return { success: false, reason: `No text content found in ${filename}.`, documents: [], }; } const data = { id: v4(), url: "file://" + fullFilePath, title: metadata.title || filename, docAuthor: metadata.docAuthor || "no author found", description: metadata.description || "No description found.", docSource: metadata.docSource || "audio file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data, filename: `${slugify(filename)}-${data.id}`, options: { parseOnly: options.parseOnly }, }); trashFile(fullFilePath); console.log( `[SUCCESS]: ${filename} transcribed, converted & ready for embedding.\n` ); return { success: true, reason: null, documents: [document] }; } module.exports = asAudio;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asEPub.js
collector/processSingleFile/convert/asEPub.js
const { v4 } = require("uuid"); const { EPubLoader } = require("langchain/document_loaders/fs/epub"); const { tokenizeString } = require("../../utils/tokenizer"); const { createdDate, trashFile, writeToServerDocuments, } = require("../../utils/files"); const { default: slugify } = require("slugify"); async function asEPub({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { let content = ""; try { const loader = new EPubLoader(fullFilePath, { splitChapters: false }); const docs = await loader.load(); docs.forEach((doc) => (content += doc.pageContent)); } catch (err) { console.error("Could not read epub file!", err); } if (!content?.length) { console.error(`Resulting text content was empty for ${filename}.`); trashFile(fullFilePath); return { success: false, reason: `No text content found in ${filename}.`, documents: [], }; } console.log(`-- Working ${filename} --`); const data = { id: v4(), url: "file://" + fullFilePath, title: metadata.title || filename, docAuthor: metadata.docAuthor || "Unknown", description: metadata.description || "Unknown", docSource: metadata.docSource || "epub file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data, filename: `${slugify(filename)}-${data.id}`, options: { parseOnly: options.parseOnly }, }); trashFile(fullFilePath); console.log(`[SUCCESS]: ${filename} converted & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; } module.exports = asEPub;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asTxt.js
collector/processSingleFile/convert/asTxt.js
const { v4 } = require("uuid"); const fs = require("fs"); const { tokenizeString } = require("../../utils/tokenizer"); const { createdDate, trashFile, writeToServerDocuments, } = require("../../utils/files"); const { default: slugify } = require("slugify"); async function asTxt({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { let content = ""; try { content = fs.readFileSync(fullFilePath, "utf8"); } catch (err) { console.error("Could not read file!", err); } if (!content?.length) { console.error(`Resulting text content was empty for ${filename}.`); trashFile(fullFilePath); return { success: false, reason: `No text content found in ${filename}.`, documents: [], }; } console.log(`-- Working ${filename} --`); const data = { id: v4(), url: "file://" + fullFilePath, title: metadata.title || filename, docAuthor: metadata.docAuthor || "Unknown", description: metadata.description || "Unknown", docSource: metadata.docSource || "a text file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data, filename: `${slugify(filename)}-${data.id}`, options: { parseOnly: options.parseOnly }, }); trashFile(fullFilePath); console.log(`[SUCCESS]: ${filename} converted & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; } module.exports = asTxt;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asPDF/index.js
collector/processSingleFile/convert/asPDF/index.js
const { v4 } = require("uuid"); const { createdDate, trashFile, writeToServerDocuments, } = require("../../../utils/files"); const { tokenizeString } = require("../../../utils/tokenizer"); const { default: slugify } = require("slugify"); const PDFLoader = require("./PDFLoader"); const OCRLoader = require("../../../utils/OCRLoader"); async function asPdf({ fullFilePath = "", filename = "", options = {}, metadata = {}, }) { const pdfLoader = new PDFLoader(fullFilePath, { splitPages: true, }); console.log(`-- Working ${filename} --`); const pageContent = []; let docs = await pdfLoader.load(); if (docs.length === 0) { console.log( `[asPDF] No text content found for ${filename}. Will attempt OCR parse.` ); docs = await new OCRLoader({ targetLanguages: options?.ocr?.langList, }).ocrPDF(fullFilePath); } for (const doc of docs) { console.log( `-- Parsing content from pg ${ doc.metadata?.loc?.pageNumber || "unknown" } --` ); if (!doc.pageContent || !doc.pageContent.length) continue; pageContent.push(doc.pageContent); } if (!pageContent.length) { console.error(`[asPDF] Resulting text content was empty for ${filename}.`); trashFile(fullFilePath); return { success: false, reason: `No text content found in ${filename}.`, documents: [], }; } const content = pageContent.join(""); const data = { id: v4(), url: "file://" + fullFilePath, title: metadata.title || filename, docAuthor: metadata.docAuthor || docs[0]?.metadata?.pdf?.info?.Creator || "no author found", description: metadata.description || docs[0]?.metadata?.pdf?.info?.Title || "No description found.", docSource: metadata.docSource || "pdf file uploaded by the user.", chunkSource: metadata.chunkSource || "", published: createdDate(fullFilePath), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data, filename: `${slugify(filename)}-${data.id}`, options: { parseOnly: options.parseOnly }, }); trashFile(fullFilePath); console.log(`[SUCCESS]: ${filename} converted & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; } module.exports = asPdf;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processSingleFile/convert/asPDF/PDFLoader/index.js
collector/processSingleFile/convert/asPDF/PDFLoader/index.js
const fs = require("fs").promises; class PDFLoader { constructor(filePath, { splitPages = true } = {}) { this.filePath = filePath; this.splitPages = splitPages; } async load() { const buffer = await fs.readFile(this.filePath); const { getDocument, version } = await this.getPdfJS(); const pdf = await getDocument({ data: new Uint8Array(buffer), useWorkerFetch: false, isEvalSupported: false, useSystemFonts: true, }).promise; const meta = await pdf.getMetadata().catch(() => null); const documents = []; for (let i = 1; i <= pdf.numPages; i += 1) { const page = await pdf.getPage(i); const content = await page.getTextContent(); if (content.items.length === 0) { continue; } let lastY; const textItems = []; for (const item of content.items) { if ("str" in item) { if (lastY === item.transform[5] || !lastY) { textItems.push(item.str); } else { textItems.push(`\n${item.str}`); } lastY = item.transform[5]; } } const text = textItems.join(""); documents.push({ pageContent: text.trim(), metadata: { source: this.filePath, pdf: { version, info: meta?.info, metadata: meta?.metadata, totalPages: pdf.numPages, }, loc: { pageNumber: i }, }, }); } if (this.splitPages) { return documents; } if (documents.length === 0) { return []; } return [ { pageContent: documents.map((doc) => doc.pageContent).join("\n\n"), metadata: { source: this.filePath, pdf: { version, info: meta?.info, metadata: meta?.metadata, totalPages: pdf.numPages, }, }, }, ]; } async getPdfJS() { try { const pdfjs = await import("pdf-parse/lib/pdf.js/v1.10.100/build/pdf.js"); return { getDocument: pdfjs.getDocument, version: pdfjs.version }; } catch (e) { console.error(e); throw new Error( "Failed to load pdf-parse. Please install it with eg. `npm install pdf-parse`." ); } } } module.exports = PDFLoader;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/middleware/httpLogger.js
collector/middleware/httpLogger.js
const httpLogger = ({ enableTimestamps = false }) => (req, res, next) => { // Capture the original res.end to log response status const originalEnd = res.end; res.end = function (chunk, encoding) { // Log the request method, status code, and path const statusColor = res.statusCode >= 400 ? "\x1b[31m" : "\x1b[32m"; // Red for errors, green for success console.log( `\x1b[32m[HTTP]\x1b[0m ${statusColor}${res.statusCode}\x1b[0m ${ req.method } -> ${req.path} ${ enableTimestamps ? `@ ${new Date().toLocaleTimeString("en-US", { hour12: true })}` : "" }`.trim() ); // Call the original end method return originalEnd.call(this, chunk, encoding); }; next(); }; module.exports = { httpLogger, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/middleware/verifyIntegrity.js
collector/middleware/verifyIntegrity.js
const { CommunicationKey } = require("../utils/comKey"); const RuntimeSettings = require("../utils/runtimeSettings"); const runtimeSettings = new RuntimeSettings(); function verifyPayloadIntegrity(request, response, next) { const comKey = new CommunicationKey(); if (process.env.NODE_ENV === "development") { comKey.log('verifyPayloadIntegrity is skipped in development.'); runtimeSettings.parseOptionsFromRequest(request); next(); return; } const signature = request.header("X-Integrity"); if (!signature) return response.status(400).json({ msg: 'Failed integrity signature check.' }) const validSignedPayload = comKey.verify(signature, request.body); if (!validSignedPayload) return response.status(400).json({ msg: 'Failed integrity signature check.' }); runtimeSettings.parseOptionsFromRequest(request); next(); } module.exports = { verifyPayloadIntegrity }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/middleware/setDataSigner.js
collector/middleware/setDataSigner.js
const { EncryptionWorker } = require("../utils/EncryptionWorker"); const { CommunicationKey } = require("../utils/comKey"); /** * Express Response Object interface with defined encryptionWorker attached to locals property. * @typedef {import("express").Response & import("express").Response['locals'] & {encryptionWorker: EncryptionWorker} } ResponseWithSigner */ // You can use this middleware to assign the EncryptionWorker to the response locals // property so that if can be used to encrypt/decrypt arbitrary data via response object. // eg: Encrypting API keys in chunk sources. // The way this functions is that the rolling RSA Communication Key is used server-side to private-key encrypt the raw // key of the persistent EncryptionManager credentials. Since EncryptionManager credentials do _not_ roll, we should not send them // even between server<>collector in plaintext because if the user configured the server/collector to be public they could technically // be exposing the key in transit via the X-Payload-Signer header. Even if this risk is minimal we should not do this. // This middleware uses the CommunicationKey public key to first decrypt the base64 representation of the EncryptionManager credentials // and then loads that in to the EncryptionWorker as a buffer so we can use the same credentials across the system. Should we ever break the // collector out into its own service this would still work without SSL/TLS. /** * * @param {import("express").Request} request * @param {import("express").Response} response * @param {import("express").NextFunction} next */ function setDataSigner(request, response, next) { const comKey = new CommunicationKey(); const encryptedPayloadSigner = request.header("X-Payload-Signer"); if (!encryptedPayloadSigner) console.log('Failed to find signed-payload to set encryption worker! Encryption calls will fail.'); const decryptedPayloadSignerKey = comKey.decrypt(encryptedPayloadSigner); const encryptionWorker = new EncryptionWorker(decryptedPayloadSignerKey); response.locals.encryptionWorker = encryptionWorker; next(); } module.exports = { setDataSigner }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/extensions/index.js
collector/extensions/index.js
const { setDataSigner } = require("../middleware/setDataSigner"); const { verifyPayloadIntegrity } = require("../middleware/verifyIntegrity"); const { resolveRepoLoader, resolveRepoLoaderFunction } = require("../utils/extensions/RepoLoader"); const { reqBody } = require("../utils/http"); const { validURL, validateURL } = require("../utils/url"); const RESYNC_METHODS = require("./resync"); const { loadObsidianVault } = require("../utils/extensions/ObsidianVault"); function extensions(app) { if (!app) return; app.post( "/ext/resync-source-document", [verifyPayloadIntegrity, setDataSigner], async function (request, response) { try { const { type, options } = reqBody(request); if (!RESYNC_METHODS.hasOwnProperty(type)) throw new Error(`Type "${type}" is not a valid type to sync.`); return await RESYNC_METHODS[type](options, response); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, reason: e.message || "A processing error occurred.", }); } return; } ) app.post( "/ext/:repo_platform-repo", [verifyPayloadIntegrity, setDataSigner], async function (request, response) { try { const loadRepo = resolveRepoLoaderFunction(request.params.repo_platform); const { success, reason, data } = await loadRepo( reqBody(request), response, ); response.status(200).json({ success, reason, data, }); } catch (e) { console.error(e); response.status(200).json({ success: false, reason: e.message || "A processing error occurred.", data: {}, }); } return; } ); // gets all branches for a specific repo app.post( "/ext/:repo_platform-repo/branches", [verifyPayloadIntegrity], async function (request, response) { try { const RepoLoader = resolveRepoLoader(request.params.repo_platform); const allBranches = await new RepoLoader( reqBody(request) ).getRepoBranches(); response.status(200).json({ success: true, reason: null, data: { branches: allBranches, }, }); } catch (e) { console.error(e); response.status(400).json({ success: false, reason: e.message, data: { branches: [], }, }); } return; } ); app.post( "/ext/youtube-transcript", [verifyPayloadIntegrity], async function (request, response) { try { const { loadYouTubeTranscript } = require("../utils/extensions/YoutubeTranscript"); const { success, reason, data } = await loadYouTubeTranscript( reqBody(request) ); response.status(200).json({ success, reason, data }); } catch (e) { console.error(e); response.status(400).json({ success: false, reason: e.message, data: { title: null, author: null, }, }); } return; } ); app.post( "/ext/website-depth", [verifyPayloadIntegrity], async function (request, response) { try { const websiteDepth = require("../utils/extensions/WebsiteDepth"); const { url, depth = 1, maxLinks = 20 } = reqBody(request); const validatedUrl = validateURL(url); if (!validURL(validatedUrl)) throw new Error("Not a valid URL."); const scrapedData = await websiteDepth(validatedUrl, depth, maxLinks); response.status(200).json({ success: true, data: scrapedData }); } catch (e) { console.error(e); response.status(400).json({ success: false, reason: e.message }); } return; } ); app.post( "/ext/confluence", [verifyPayloadIntegrity, setDataSigner], async function (request, response) { try { const { loadConfluence } = require("../utils/extensions/Confluence"); const { success, reason, data } = await loadConfluence( reqBody(request), response ); response.status(200).json({ success, reason, data }); } catch (e) { console.error(e); response.status(400).json({ success: false, reason: e.message, data: { title: null, author: null, }, }); } return; } ); app.post( "/ext/drupalwiki", [verifyPayloadIntegrity, setDataSigner], async function (request, response) { try { const { loadAndStoreSpaces } = require("../utils/extensions/DrupalWiki"); const { success, reason, data } = await loadAndStoreSpaces( reqBody(request), response ); response.status(200).json({ success, reason, data }); } catch (e) { console.error(e); response.status(400).json({ success: false, reason: e.message, data: { title: null, author: null, }, }); } return; } ); app.post( "/ext/obsidian/vault", [verifyPayloadIntegrity, setDataSigner], async function (request, response) { try { const { files } = reqBody(request); const result = await loadObsidianVault({ files }); response.status(200).json(result); } catch (e) { console.error(e); response.status(400).json({ success: false, reason: e.message, data: null, }); } return; } ); app.post( "/ext/paperless-ngx", [verifyPayloadIntegrity, setDataSigner], async function (request, response) { try { const { loadPaperlessNgx } = require("../utils/extensions/PaperlessNgx"); const result = await loadPaperlessNgx(reqBody(request), response); response.status(200).json(result); } catch (e) { console.error(e); response.status(400).json({ success: false, reason: e.message, data: null, }); } return; } ); } module.exports = extensions;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/extensions/resync/index.js
collector/extensions/resync/index.js
const { getLinkText } = require("../../processLink"); /** * Fetches the content of a raw link. Returns the content as a text string of the link in question. * @param {object} data - metadata from document (eg: link) * @param {import("../../middleware/setDataSigner").ResponseWithSigner} response */ async function resyncLink({ link }, response) { if (!link) throw new Error('Invalid link provided'); try { const { success, content = null } = await getLinkText(link); if (!success) throw new Error(`Failed to sync link content. ${reason}`); response.status(200).json({ success, content }); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } } /** * Fetches the content of a YouTube link. Returns the content as a text string of the video in question. * We offer this as there may be some videos where a transcription could be manually edited after initial scraping * but in general - transcriptions often never change. * @param {object} data - metadata from document (eg: link) * @param {import("../../middleware/setDataSigner").ResponseWithSigner} response */ async function resyncYouTube({ link }, response) { if (!link) throw new Error('Invalid link provided'); try { const { fetchVideoTranscriptContent } = require("../../utils/extensions/YoutubeTranscript"); const { success, reason, content } = await fetchVideoTranscriptContent({ url: link }); if (!success) throw new Error(`Failed to sync YouTube video transcript. ${reason}`); response.status(200).json({ success, content }); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } } /** * Fetches the content of a specific confluence page via its chunkSource. * Returns the content as a text string of the page in question and only that page. * @param {object} data - metadata from document (eg: chunkSource) * @param {import("../../middleware/setDataSigner").ResponseWithSigner} response */ async function resyncConfluence({ chunkSource }, response) { if (!chunkSource) throw new Error('Invalid source property provided'); try { // Confluence data is `payload` encrypted. So we need to expand its // encrypted payload back into query params so we can reFetch the page with same access token/params. const source = response.locals.encryptionWorker.expandPayload(chunkSource); const { fetchConfluencePage } = require("../../utils/extensions/Confluence"); const { success, reason, content } = await fetchConfluencePage({ pageUrl: `https:${source.pathname}`, // need to add back the real protocol baseUrl: source.searchParams.get('baseUrl'), spaceKey: source.searchParams.get('spaceKey'), accessToken: source.searchParams.get('token'), username: source.searchParams.get('username'), cloud: source.searchParams.get('cloud') === 'true', bypassSSL: source.searchParams.get('bypassSSL') === 'true', }); if (!success) throw new Error(`Failed to sync Confluence page content. ${reason}`); response.status(200).json({ success, content }); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } } /** * Fetches the content of a specific confluence page via its chunkSource. * Returns the content as a text string of the page in question and only that page. * @param {object} data - metadata from document (eg: chunkSource) * @param {import("../../middleware/setDataSigner").ResponseWithSigner} response */ async function resyncGithub({ chunkSource }, response) { if (!chunkSource) throw new Error('Invalid source property provided'); try { // Github file data is `payload` encrypted (might contain PAT). So we need to expand its // encrypted payload back into query params so we can reFetch the page with same access token/params. const source = response.locals.encryptionWorker.expandPayload(chunkSource); const { fetchGithubFile } = require("../../utils/extensions/RepoLoader/GithubRepo"); const { success, reason, content } = await fetchGithubFile({ repoUrl: `https:${source.pathname}`, // need to add back the real protocol branch: source.searchParams.get('branch'), accessToken: source.searchParams.get('pat'), sourceFilePath: source.searchParams.get('path'), }); if (!success) throw new Error(`Failed to sync GitHub file content. ${reason}`); response.status(200).json({ success, content }); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } } /** * Fetches the content of a specific DrupalWiki page via its chunkSource. * Returns the content as a text string of the page in question and only that page. * @param {object} data - metadata from document (eg: chunkSource) * @param {import("../../middleware/setDataSigner").ResponseWithSigner} response */ async function resyncDrupalWiki({ chunkSource }, response) { if (!chunkSource) throw new Error('Invalid source property provided'); try { // DrupalWiki data is `payload` encrypted. So we need to expand its // encrypted payload back into query params so we can reFetch the page with same access token/params. const source = response.locals.encryptionWorker.expandPayload(chunkSource); const { loadPage } = require("../../utils/extensions/DrupalWiki"); const { success, reason, content } = await loadPage({ baseUrl: source.searchParams.get('baseUrl'), pageId: source.searchParams.get('pageId'), accessToken: source.searchParams.get('accessToken'), }); if (!success) { console.error(`Failed to sync DrupalWiki page content. ${reason}`); response.status(200).json({ success: false, content: null, }); } else { response.status(200).json({ success, content }); } } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } } /** * Fetches the content of a specific Paperless-ngx document via its chunkSource. * Returns the content as a text string of the document. * @param {object} data - metadata from document (eg: chunkSource) * @param {import("../../middleware/setDataSigner").ResponseWithSigner} response */ async function resyncPaperlessNgx({ chunkSource }, response) { if (!chunkSource) throw new Error('Invalid source property provided'); try { const source = response.locals.encryptionWorker.expandPayload(chunkSource); const { PaperlessNgxLoader } = require("../../utils/extensions/PaperlessNgx/PaperlessNgxLoader"); const loader = new PaperlessNgxLoader({ baseUrl: source.searchParams.get('baseUrl'), apiToken: source.searchParams.get('token'), }); const documentId = source.pathname.split('//')[1]; const content = await loader.fetchDocumentContent(documentId); if (!content) throw new Error('Failed to fetch document content'); response.status(200).json({ success: true, content }); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } } module.exports = { link: resyncLink, youtube: resyncYouTube, confluence: resyncConfluence, github: resyncGithub, drupalwiki: resyncDrupalWiki, "paperless-ngx": resyncPaperlessNgx, }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processLink/index.js
collector/processLink/index.js
const { validURL } = require("../utils/url"); const { scrapeGenericUrl } = require("./convert/generic"); const { validateURL } = require("../utils/url"); /** * Process a link and return the text content. This util will save the link as a document * so it can be used for embedding later. * @param {string} link - The link to process * @param {{[key: string]: string}} scraperHeaders - Custom headers to apply when scraping the link * @param {Object} metadata - Optional metadata to attach to the document * @returns {Promise<{success: boolean, content: string}>} - Response from collector */ async function processLink(link, scraperHeaders = {}, metadata = {}) { const validatedLink = validateURL(link); if (!validURL(validatedLink)) return { success: false, reason: "Not a valid URL." }; return await scrapeGenericUrl({ link: validatedLink, captureAs: "text", scraperHeaders, metadata, saveAsDocument: true, }); } /** * Get the text content of a link - does not save the link as a document * Mostly used in agentic flows/tools calls to get the text content of a link * @param {string} link - The link to get the text content of * @param {('html' | 'text' | 'json')} captureAs - The format to capture the page content as * @returns {Promise<{success: boolean, content: string}>} - Response from collector */ async function getLinkText(link, captureAs = "text") { const validatedLink = validateURL(link); if (!validURL(validatedLink)) return { success: false, reason: "Not a valid URL." }; return await scrapeGenericUrl({ link: validatedLink, captureAs, saveAsDocument: false, }); } module.exports = { processLink, getLinkText, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processLink/helpers/index.js
collector/processLink/helpers/index.js
const path = require("path"); const { validURL } = require("../../utils/url"); const { processSingleFile } = require("../../processSingleFile"); const { downloadURIToFile } = require("../../utils/downloadURIToFile"); const { ACCEPTED_MIMES } = require("../../utils/constants"); const { validYoutubeVideoUrl } = require("../../utils/url"); /** * Get the content type of a resource * - Sends a HEAD request to the URL and returns the Content-Type header with a 5 second timeout * @param {string} url - The URL to get the content type of * @returns {Promise<{success: boolean, reason: string|null, contentType: string|null}>} - The content type of the resource */ async function getContentTypeFromURL(url) { try { if (!url || typeof url !== "string" || !validURL(url)) return { success: false, reason: "Not a valid URL.", contentType: null }; const abortController = new AbortController(); const timeout = setTimeout(() => { abortController.abort(); console.error("Timeout fetching content type for URL:", url.toString()); }, 5_000); const res = await fetch(url, { method: "HEAD", signal: abortController.signal, }).finally(() => clearTimeout(timeout)); if (!res.ok) return { success: false, reason: `HTTP ${res.status}: ${res.statusText}`, contentType: null, }; const contentType = res.headers.get("Content-Type")?.toLowerCase(); const contentTypeWithoutCharset = contentType?.split(";")[0].trim(); if (!contentTypeWithoutCharset) return { success: false, reason: "No Content-Type found.", contentType: null, }; return { success: true, reason: null, contentType: contentTypeWithoutCharset, }; } catch (error) { return { success: false, reason: `Error: ${error.message}`, contentType: null, }; } } /** * Normalize the result object based on the saveAsDocument flag * @param {Object} result - The result object to normalize * @param {boolean} result.success - Whether the result is successful * @param {string|null} result.reason - The reason for the result * @param {Object[]} result.documents - The documents from the result * @param {string|null} result.content - The content of the result * @param {boolean} result.saveAsDocument - Whether to save the content as a document. Default is true * @returns {{success: boolean, reason: string|null, documents: Object[], content: string|null}} - The normalized result object */ function returnResult({ success, reason, documents, content, saveAsDocument = true, } = {}) { if (!saveAsDocument) { return { success, content, }; } else return { success, reason, documents }; } /** * Determine the content type of a link - should be a URL * @param {string} uri - The link to determine the content type of * @returns {Promise<{contentType: string|null, processVia: 'web' | 'file' | 'youtube'}>} - The content type of the link */ async function determineContentType(uri) { let processVia = "web"; // Dont check for content type if it is a YouTube video URL if (validYoutubeVideoUrl(uri)) return { contentType: "text/html", processVia: "youtube" }; return await getContentTypeFromURL(uri) .then((result) => { if (!!result.reason) console.error(result.reason); // If the content type is not text/html or text/plain, and it is in the ACCEPTED_MIMES, // then we can process it as a file if ( !!result.contentType && !["text/html", "text/plain"].includes(result.contentType) && result.contentType in ACCEPTED_MIMES ) processVia = "file"; return { contentType: result.contentType, processVia }; }) .catch((error) => { console.error("Error getting content type from URL", error); return { contentType: null, processVia }; }); } /** * Process a link as a file * @param {string} uri - The link to process as a file * @param {boolean} saveAsDocument - Whether to save the content as a document. Default is true * @returns {Promise<{success: boolean, reason: string|null, documents: Object[], content: string|null, saveAsDocument: boolean}>} - The content of the file */ async function processAsFile({ uri, saveAsDocument = true }) { const fileContentResult = await downloadURIToFile(uri); if (!fileContentResult.success) return returnResult({ success: false, reason: fileContentResult.reason, documents: [], content: null, saveAsDocument, }); const fileFilePath = fileContentResult.fileLocation; const targetFilename = path.basename(fileFilePath); /** * If the saveAsDocument is false, we are only interested in the text content * and can ignore the file as a document by using `parseOnly` in the options. * This will send the file to the Direct Uploads folder instead of the Documents folder. * that will be deleted by the cleanup-orphan-documents job that runs frequently. The trade off * is that since it still is in FS we can debug its output or even potentially reuse it for other purposes. * * TODO: Improve this process via a new option that will instantly delete the file after processing * if we find we dont need this file ever after processing. */ const processSingleFileResult = await processSingleFile(targetFilename, { parseOnly: saveAsDocument === false, }); if (!processSingleFileResult.success) { return returnResult({ success: false, reason: processSingleFileResult.reason, documents: [], content: null, saveAsDocument, }); } // If we intend to return only the text content, return the content from the file // and then delete the file - otherwise it will be saved as a document if (!saveAsDocument) { return returnResult({ success: true, content: processSingleFileResult.documents[0].pageContent, saveAsDocument, }); } return processSingleFileResult; } module.exports = { returnResult, getContentTypeFromURL, determineContentType, processAsFile, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/processLink/convert/generic.js
collector/processLink/convert/generic.js
const { v4 } = require("uuid"); const { PuppeteerWebBaseLoader, } = require("langchain/document_loaders/web/puppeteer"); const { writeToServerDocuments } = require("../../utils/files"); const { tokenizeString } = require("../../utils/tokenizer"); const { default: slugify } = require("slugify"); const { returnResult, determineContentType, processAsFile, } = require("../helpers"); const { loadYouTubeTranscript, } = require("../../utils/extensions/YoutubeTranscript"); const RuntimeSettings = require("../../utils/runtimeSettings"); /** * Scrape a generic URL and return the content in the specified format * @param {Object} config - The configuration object * @param {string} config.link - The URL to scrape * @param {('html' | 'text')} config.captureAs - The format to capture the page content as. Default is 'text' * @param {{[key: string]: string}} config.scraperHeaders - Custom headers to use when making the request * @param {{[key: string]: string}} config.metadata - Metadata to use when creating the document * @param {boolean} config.saveAsDocument - Whether to save the content as a document. Default is true * @returns {Promise<Object>} - The content of the page */ async function scrapeGenericUrl({ link, captureAs = "text", scraperHeaders = {}, metadata = {}, saveAsDocument = true, }) { /** @type {'web' | 'file' | 'youtube'} */ console.log(`-- Working URL ${link} => (captureAs: ${captureAs}) --`); let { contentType, processVia } = await determineContentType(link); console.log(`-- URL determined to be ${contentType} (${processVia}) --`); /** * When the content is a file or a YouTube video, we can use the existing processing functions * These are self-contained and will return the correct response based on the saveAsDocument flag already * so we can return the content immediately. */ if (processVia === "file") return await processAsFile({ uri: link, saveAsDocument }); else if (processVia === "youtube") return await loadYouTubeTranscript( { url: link }, { parseOnly: saveAsDocument === false } ); // Otherwise, assume the content is a webpage and scrape the content from the webpage const content = await getPageContent({ link, captureAs, headers: scraperHeaders, }); if (!content || !content.length) { console.error(`Resulting URL content was empty at ${link}.`); return returnResult({ success: false, reason: `No URL content found at ${link}.`, documents: [], content: null, saveAsDocument, }); } // If the captureAs is text, return the content as a string immediately // so that we dont save the content as a document if (!saveAsDocument) return returnResult({ success: true, content, saveAsDocument, }); // Save the content as a document from the URL const url = new URL(link); const decodedPathname = decodeURIComponent(url.pathname); const filename = `${url.hostname}${decodedPathname.replace(/\//g, "_")}`; const data = { id: v4(), url: "file://" + slugify(filename) + ".html", title: metadata.title || slugify(filename) + ".html", docAuthor: metadata.docAuthor || "no author found", description: metadata.description || "No description found.", docSource: metadata.docSource || "URL link uploaded by the user.", chunkSource: `link://${link}`, published: new Date().toLocaleString(), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments({ data, filename: `url-${slugify(filename)}-${data.id}`, }); console.log(`[SUCCESS]: URL ${link} converted & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; } /** * Validate the headers object * - Keys & Values must be strings and not empty * - Assemble a new object with only the valid keys and values * @param {{[key: string]: string}} headers - The headers object to validate * @returns {{[key: string]: string}} - The validated headers object */ function validatedHeaders(headers = {}) { try { if (Object.keys(headers).length === 0) return {}; let validHeaders = {}; for (const key of Object.keys(headers)) { if (!key?.trim()) continue; if (typeof headers[key] !== "string" || !headers[key]?.trim()) continue; validHeaders[key] = headers[key].trim(); } return validHeaders; } catch (error) { console.error("Error validating headers", error); return {}; } } /** * Get the content of a page * @param {Object} config - The configuration object * @param {string} config.link - The URL to get the content of * @param {('html' | 'text')} config.captureAs - The format to capture the page content as. Default is 'text' * @param {{[key: string]: string}} config.headers - Custom headers to use when making the request * @returns {Promise<string>} - The content of the page */ async function getPageContent({ link, captureAs = "text", headers = {} }) { try { let pageContents = []; const runtimeSettings = new RuntimeSettings(); /** @type {import('puppeteer').PuppeteerLaunchOptions} */ let launchConfig = { headless: "new" }; /* On MacOS 15.1, the headless=new option causes the browser to crash immediately. * It is not clear why this is the case, but it is reproducible. Since AnythinglLM * in production runs in a container, we can disable headless mode to workaround the issue for development purposes. * * This may show a popup window when scraping a page in development mode. * This is expected behavior if seen in development mode on MacOS 15+ */ if ( process.platform === "darwin" && process.env.NODE_ENV === "development" ) { console.log( "Darwin Development Mode: Disabling headless mode to prevent Chromium from crashing." ); launchConfig.headless = "false"; } const loader = new PuppeteerWebBaseLoader(link, { launchOptions: { headless: launchConfig.headless, ignoreHTTPSErrors: true, args: runtimeSettings.get("browserLaunchArgs"), }, gotoOptions: { waitUntil: "networkidle2", }, async evaluate(page, browser) { const result = await page.evaluate((captureAs) => { if (captureAs === "text") return document.body.innerText; if (captureAs === "html") return document.documentElement.innerHTML; return document.body.innerText; }, captureAs); await browser.close(); return result; }, }); // Override scrape method if headers are available let overrideHeaders = validatedHeaders(headers); if (Object.keys(overrideHeaders).length > 0) { loader.scrape = async function () { const { launch } = await PuppeteerWebBaseLoader.imports(); const browser = await launch({ headless: "new", defaultViewport: null, ignoreDefaultArgs: ["--disable-extensions"], ...this.options?.launchOptions, }); const page = await browser.newPage(); await page.setExtraHTTPHeaders(overrideHeaders); await page.goto(this.webPath, { timeout: 180000, waitUntil: "networkidle2", ...this.options?.gotoOptions, }); const bodyHTML = this.options?.evaluate ? await this.options.evaluate(page, browser) : await page.evaluate(() => document.body.innerHTML); await browser.close(); return bodyHTML; }; } const docs = await loader.load(); for (const doc of docs) pageContents.push(doc.pageContent); return pageContents.join(" "); } catch (error) { console.error( "getPageContent failed to be fetched by puppeteer - falling back to fetch!", error ); } try { const pageText = await fetch(link, { method: "GET", headers: { "Content-Type": "text/plain", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36,gzip(gfe)", ...validatedHeaders(headers), }, }).then((res) => res.text()); return pageText; } catch (error) { console.error("getPageContent failed to be fetched by any method.", error); } return null; } module.exports = { scrapeGenericUrl, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/constants.js
collector/utils/constants.js
const WATCH_DIRECTORY = require("path").resolve(__dirname, "../hotdir"); const ACCEPTED_MIMES = { "text/plain": [".txt", ".md", ".org", ".adoc", ".rst"], "text/html": [".html"], "text/csv": [".csv"], "application/json": [".json"], // TODO: Create asDoc.js that works for standard MS Word files. // "application/msword": [".doc"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [ ".docx", ], "application/vnd.openxmlformats-officedocument.presentationml.presentation": [ ".pptx", ], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [ ".xlsx", ], "application/vnd.oasis.opendocument.text": [".odt"], "application/vnd.oasis.opendocument.presentation": [".odp"], "application/pdf": [".pdf"], "application/mbox": [".mbox"], "audio/wav": [".wav"], "audio/mpeg": [".mp3"], "video/mp4": [".mp4"], "video/mpeg": [".mpeg"], "application/epub+zip": [".epub"], "image/png": [".png"], "image/jpeg": [".jpg"], "image/jpg": [".jpg"], "image/webp": [".webp"], }; const SUPPORTED_FILETYPE_CONVERTERS = { ".txt": "./convert/asTxt.js", ".md": "./convert/asTxt.js", ".org": "./convert/asTxt.js", ".adoc": "./convert/asTxt.js", ".rst": "./convert/asTxt.js", ".csv": "./convert/asTxt.js", ".json": "./convert/asTxt.js", ".html": "./convert/asTxt.js", ".pdf": "./convert/asPDF/index.js", ".docx": "./convert/asDocx.js", // TODO: Create asDoc.js that works for standard MS Word files. // ".doc": "./convert/asDoc.js", ".pptx": "./convert/asOfficeMime.js", ".odt": "./convert/asOfficeMime.js", ".odp": "./convert/asOfficeMime.js", ".xlsx": "./convert/asXlsx.js", ".mbox": "./convert/asMbox.js", ".epub": "./convert/asEPub.js", ".mp3": "./convert/asAudio.js", ".wav": "./convert/asAudio.js", ".mp4": "./convert/asAudio.js", ".mpeg": "./convert/asAudio.js", ".png": "./convert/asImage.js", ".jpg": "./convert/asImage.js", ".jpeg": "./convert/asImage.js", ".webp": "./convert/asImage.js", }; module.exports = { SUPPORTED_FILETYPE_CONVERTERS, WATCH_DIRECTORY, ACCEPTED_MIMES, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/OCRLoader/index.js
collector/utils/OCRLoader/index.js
const fs = require("fs"); const os = require("os"); const path = require("path"); const { VALID_LANGUAGE_CODES } = require("./validLangs"); class OCRLoader { /** * The language code(s) to use for the OCR. * @type {string[]} */ language; /** * The cache directory for the OCR. * @type {string} */ cacheDir; /** * The constructor for the OCRLoader. * @param {Object} options - The options for the OCRLoader. * @param {string} options.targetLanguages - The target languages to use for the OCR as a comma separated string. eg: "eng,deu,..." */ constructor({ targetLanguages = "eng" } = {}) { this.language = this.parseLanguages(targetLanguages); this.cacheDir = path.resolve( process.env.STORAGE_DIR ? path.resolve(process.env.STORAGE_DIR, `models`, `tesseract`) : path.resolve(__dirname, `../../../server/storage/models/tesseract`) ); // Ensure the cache directory exists or else Tesseract will persist the cache in the default location. if (!fs.existsSync(this.cacheDir)) fs.mkdirSync(this.cacheDir, { recursive: true }); this.log( `OCRLoader initialized with language support for:`, this.language.map((lang) => VALID_LANGUAGE_CODES[lang]).join(", ") ); } /** * Parses the language code from a provided comma separated string of language codes. * @param {string} language - The language code to parse. * @returns {string[]} The parsed language code. */ parseLanguages(language = null) { try { if (!language || typeof language !== "string") return ["eng"]; const langList = language .split(",") .map((lang) => (lang.trim() !== "" ? lang.trim() : null)) .filter(Boolean) .filter((lang) => VALID_LANGUAGE_CODES.hasOwnProperty(lang)); if (langList.length === 0) return ["eng"]; return langList; } catch (e) { this.log(`Error parsing languages: ${e.message}`, e.stack); return ["eng"]; } } log(text, ...args) { console.log(`\x1b[36m[OCRLoader]\x1b[0m ${text}`, ...args); } /** * Loads a PDF file and returns an array of documents. * This function is reserved to parsing for SCANNED documents - digital documents are not supported in this function * @returns {Promise<{pageContent: string, metadata: object}[]>} An array of documents with page content and metadata. */ async ocrPDF( filePath, { maxExecutionTime = 300_000, batchSize = 10, maxWorkers = null } = {} ) { if ( !filePath || !fs.existsSync(filePath) || !fs.statSync(filePath).isFile() ) { this.log(`File ${filePath} does not exist. Skipping OCR.`); return []; } const documentTitle = path.basename(filePath); this.log(`Starting OCR of ${documentTitle}`); const pdfjs = await import("pdf-parse/lib/pdf.js/v2.0.550/build/pdf.js"); let buffer = fs.readFileSync(filePath); const pdfDocument = await pdfjs.getDocument({ data: buffer }); const documents = []; const meta = await pdfDocument.getMetadata().catch(() => null); const metadata = { source: filePath, pdf: { version: "v2.0.550", info: meta?.info, metadata: meta?.metadata, totalPages: pdfDocument.numPages, }, }; const pdfSharp = new PDFSharp({ validOps: [ pdfjs.OPS.paintJpegXObject, pdfjs.OPS.paintImageXObject, pdfjs.OPS.paintInlineImageXObject, ], }); await pdfSharp.init(); const { createWorker, OEM } = require("tesseract.js"); const BATCH_SIZE = batchSize; const MAX_EXECUTION_TIME = maxExecutionTime; const NUM_WORKERS = maxWorkers ?? Math.min(os.cpus().length, 4); const totalPages = pdfDocument.numPages; const workerPool = await Promise.all( Array(NUM_WORKERS) .fill(0) .map(() => createWorker(this.language, OEM.LSTM_ONLY, { cachePath: this.cacheDir, }) ) ); const startTime = Date.now(); try { this.log("Bootstrapping OCR completed successfully!", { MAX_EXECUTION_TIME_MS: MAX_EXECUTION_TIME, BATCH_SIZE, MAX_CONCURRENT_WORKERS: NUM_WORKERS, TOTAL_PAGES: totalPages, }); const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `OCR job took too long to complete (${ MAX_EXECUTION_TIME / 1000 } seconds)` ) ); }, MAX_EXECUTION_TIME); }); const processPages = async () => { for ( let startPage = 1; startPage <= totalPages; startPage += BATCH_SIZE ) { const endPage = Math.min(startPage + BATCH_SIZE - 1, totalPages); const pageNumbers = Array.from( { length: endPage - startPage + 1 }, (_, i) => startPage + i ); this.log(`Working on pages ${startPage} - ${endPage}`); const pageQueue = [...pageNumbers]; const results = []; const workerPromises = workerPool.map(async (worker, workerIndex) => { while (pageQueue.length > 0) { const pageNum = pageQueue.shift(); this.log( `\x1b[34m[Worker ${ workerIndex + 1 }]\x1b[0m assigned pg${pageNum}` ); const page = await pdfDocument.getPage(pageNum); const imageBuffer = await pdfSharp.pageToBuffer({ page }); if (!imageBuffer) continue; const { data } = await worker.recognize(imageBuffer, {}, "text"); this.log( `✅ \x1b[34m[Worker ${ workerIndex + 1 }]\x1b[0m completed pg${pageNum}` ); results.push({ pageContent: data.text, metadata: { ...metadata, loc: { pageNumber: pageNum }, }, }); } }); await Promise.all(workerPromises); documents.push( ...results.sort( (a, b) => a.metadata.loc.pageNumber - b.metadata.loc.pageNumber ) ); } return documents; }; await Promise.race([timeoutPromise, processPages()]); } catch (e) { this.log(`Error: ${e.message}`, e.stack); } finally { global.Image = undefined; await Promise.all(workerPool.map((worker) => worker.terminate())); } this.log(`Completed OCR of ${documentTitle}!`, { documentsParsed: documents.length, totalPages: totalPages, executionTime: `${((Date.now() - startTime) / 1000).toFixed(2)}s`, }); return documents; } /** * Loads an image file and returns the OCRed text. * @param {string} filePath - The path to the image file. * @param {Object} options - The options for the OCR. * @param {number} options.maxExecutionTime - The maximum execution time of the OCR in milliseconds. * @returns {Promise<string>} The OCRed text. */ async ocrImage(filePath, { maxExecutionTime = 300_000 } = {}) { let content = ""; let worker = null; if ( !filePath || !fs.existsSync(filePath) || !fs.statSync(filePath).isFile() ) { this.log(`File ${filePath} does not exist. Skipping OCR.`); return null; } const documentTitle = path.basename(filePath); try { this.log(`Starting OCR of ${documentTitle}`); const startTime = Date.now(); const { createWorker, OEM } = require("tesseract.js"); worker = await createWorker(this.language, OEM.LSTM_ONLY, { cachePath: this.cacheDir, }); // Race the timeout with the OCR const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `OCR job took too long to complete (${ maxExecutionTime / 1000 } seconds)` ) ); }, maxExecutionTime); }); const processImage = async () => { const { data } = await worker.recognize(filePath, {}, "text"); content = data.text; }; await Promise.race([timeoutPromise, processImage()]); this.log(`Completed OCR of ${documentTitle}!`, { executionTime: `${((Date.now() - startTime) / 1000).toFixed(2)}s`, }); return content; } catch (e) { this.log(`Error: ${e.message}`); return null; } finally { if (!worker) return; await worker.terminate(); } } } /** * Converts a PDF page to a buffer using Sharp. * @param {Object} options - The options for the Sharp PDF page object. * @param {Object} options.page - The PDFJS page proxy object. * @returns {Promise<Buffer>} The buffer of the page. */ class PDFSharp { constructor({ validOps = [] } = {}) { this.sharp = null; this.validOps = validOps; } log(text, ...args) { console.log(`\x1b[36m[PDFSharp]\x1b[0m ${text}`, ...args); } async init() { this.sharp = (await import("sharp")).default; } /** * Converts a PDF page to a buffer. * @param {Object} options - The options for the Sharp PDF page object. * @param {Object} options.page - The PDFJS page proxy object. * @returns {Promise<Buffer>} The buffer of the page. */ async pageToBuffer({ page }) { if (!this.sharp) await this.init(); try { this.log(`Converting page ${page.pageNumber} to image...`); const ops = await page.getOperatorList(); const pageImages = ops.fnArray.length; for (let i = 0; i < pageImages; i++) { try { if (!this.validOps.includes(ops.fnArray[i])) continue; const name = ops.argsArray[i][0]; const img = await page.objs.get(name); const { width, height } = img; const size = img.data.length; const channels = size / width / height; const targetDPI = 70; const targetWidth = Math.floor(width * (targetDPI / 72)); const targetHeight = Math.floor(height * (targetDPI / 72)); const image = this.sharp(img.data, { raw: { width, height, channels }, density: targetDPI, }) .resize({ width: targetWidth, height: targetHeight, fit: "fill", }) .withMetadata({ density: targetDPI, resolution: targetDPI, }) .png(); // For debugging purposes // await image.toFile(path.resolve(__dirname, `../../storage/`, `pg${page.pageNumber}.png`)); return await image.toBuffer(); } catch (error) { this.log(`Iteration error: ${error.message}`, error.stack); continue; } } this.log(`No valid images found on page ${page.pageNumber}`); return null; } catch (error) { this.log(`Error: ${error.message}`, error.stack); return null; } } } module.exports = OCRLoader;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/OCRLoader/validLangs.js
collector/utils/OCRLoader/validLangs.js
/* To get the list of valid language codes - do the following: Open the following URL in your browser: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html Check this element is the proper table tbody with all the codes via console: document.getElementsByTagName('table').item(0).children.item(1) Now, copy the following code and paste it into the console: function parseLangs() { let langs = {}; Array.from(document.getElementsByTagName('table').item(0).children.item(1).children).forEach((el) => { const [codeEl, languageEl, ...rest] = el.children const code = codeEl.innerText.trim() const language = languageEl.innerText.trim() if (!!code && !!language) langs[code] = language }) return langs; } now, run the function: copy(parseLangs()) */ const VALID_LANGUAGE_CODES = { afr: "Afrikaans", amh: "Amharic", ara: "Arabic", asm: "Assamese", aze: "Azerbaijani", aze_cyrl: "Azerbaijani - Cyrilic", bel: "Belarusian", ben: "Bengali", bod: "Tibetan", bos: "Bosnian", bre: "Breton", bul: "Bulgarian", cat: "Catalan; Valencian", ceb: "Cebuano", ces: "Czech", chi_sim: "Chinese - Simplified", chi_tra: "Chinese - Traditional", chr: "Cherokee", cos: "Corsican", cym: "Welsh", dan: "Danish", dan_frak: "Danish - Fraktur (contrib)", deu: "German", deu_frak: "German - Fraktur (contrib)", deu_latf: "German (Fraktur Latin)", dzo: "Dzongkha", ell: "Greek, Modern (1453-)", eng: "English", enm: "English, Middle (1100-1500)", epo: "Esperanto", equ: "Math / equation detection module", est: "Estonian", eus: "Basque", fao: "Faroese", fas: "Persian", fil: "Filipino (old - Tagalog)", fin: "Finnish", fra: "French", frk: "German - Fraktur (now deu_latf)", frm: "French, Middle (ca.1400-1600)", fry: "Western Frisian", gla: "Scottish Gaelic", gle: "Irish", glg: "Galician", grc: "Greek, Ancient (to 1453) (contrib)", guj: "Gujarati", hat: "Haitian; Haitian Creole", heb: "Hebrew", hin: "Hindi", hrv: "Croatian", hun: "Hungarian", hye: "Armenian", iku: "Inuktitut", ind: "Indonesian", isl: "Icelandic", ita: "Italian", ita_old: "Italian - Old", jav: "Javanese", jpn: "Japanese", kan: "Kannada", kat: "Georgian", kat_old: "Georgian - Old", kaz: "Kazakh", khm: "Central Khmer", kir: "Kirghiz; Kyrgyz", kmr: "Kurmanji (Kurdish - Latin Script)", kor: "Korean", kor_vert: "Korean (vertical)", kur: "Kurdish (Arabic Script)", lao: "Lao", lat: "Latin", lav: "Latvian", lit: "Lithuanian", ltz: "Luxembourgish", mal: "Malayalam", mar: "Marathi", mkd: "Macedonian", mlt: "Maltese", mon: "Mongolian", mri: "Maori", msa: "Malay", mya: "Burmese", nep: "Nepali", nld: "Dutch; Flemish", nor: "Norwegian", oci: "Occitan (post 1500)", ori: "Oriya", osd: "Orientation and script detection module", pan: "Panjabi; Punjabi", pol: "Polish", por: "Portuguese", pus: "Pushto; Pashto", que: "Quechua", ron: "Romanian; Moldavian; Moldovan", rus: "Russian", san: "Sanskrit", sin: "Sinhala; Sinhalese", slk: "Slovak", slk_frak: "Slovak - Fraktur (contrib)", slv: "Slovenian", snd: "Sindhi", spa: "Spanish; Castilian", spa_old: "Spanish; Castilian - Old", sqi: "Albanian", srp: "Serbian", srp_latn: "Serbian - Latin", sun: "Sundanese", swa: "Swahili", swe: "Swedish", syr: "Syriac", tam: "Tamil", tat: "Tatar", tel: "Telugu", tgk: "Tajik", tgl: "Tagalog (new - Filipino)", tha: "Thai", tir: "Tigrinya", ton: "Tonga", tur: "Turkish", uig: "Uighur; Uyghur", ukr: "Ukrainian", urd: "Urdu", uzb: "Uzbek", uzb_cyrl: "Uzbek - Cyrilic", vie: "Vietnamese", yid: "Yiddish", yor: "Yoruba", }; module.exports.VALID_LANGUAGE_CODES = VALID_LANGUAGE_CODES;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/logger/index.js
collector/utils/logger/index.js
const winston = require("winston"); class Logger { logger = console; static _instance; constructor() { if (Logger._instance) return Logger._instance; this.logger = process.env.NODE_ENV === "production" ? this.getWinstonLogger() : console; Logger._instance = this; } getWinstonLogger() { const logger = winston.createLogger({ level: "info", defaultMeta: { service: "collector" }, transports: [ new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), winston.format.printf( ({ level, message, service, origin = "" }) => { return `\x1b[36m[${service}]\x1b[0m${ origin ? `\x1b[33m[${origin}]\x1b[0m` : "" } ${level}: ${message}`; } ) ), }), ], }); function formatArgs(args) { return args .map((arg) => { if (arg instanceof Error) { return arg.stack; // If argument is an Error object, return its stack trace } else if (typeof arg === "object") { return JSON.stringify(arg); // Convert objects to JSON string } else { return arg; // Otherwise, return as-is } }) .join(" "); } console.log = function (...args) { logger.info(formatArgs(args)); }; console.error = function (...args) { logger.error(formatArgs(args)); }; console.info = function (...args) { logger.warn(formatArgs(args)); }; return logger; } } /** * Sets and overrides Console methods for logging when called. * This is a singleton method and will not create multiple loggers. * @returns {winston.Logger | console} - instantiated logger interface. */ function setLogger() { return new Logger().logger; } module.exports = setLogger;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/runtimeSettings/index.js
collector/utils/runtimeSettings/index.js
const { reqBody } = require("../http"); /** * Runtime settings are used to configure the collector per-request. * These settings are persisted across requests, but can be overridden per-request. * * The settings are passed in the request body via `options.runtimeSettings` * which is set in the backend #attachOptions function in CollectorApi. * * We do this so that the collector and backend can share the same ENV variables * but only pass the relevant settings to the collector per-request and be able to * access them across the collector via a single instance of RuntimeSettings. * * TODO: We may want to set all options passed from backend to collector here, * but for now - we are only setting the runtime settings specifically for backwards * compatibility with existing CollectorApi usage. */ class RuntimeSettings { static _instance = null; settings = {}; // Any settings here will be persisted across requests // and must be explicitly defined here. settingConfigs = { seenAnyIpWarning: { default: false, validate: (value) => String(value) === "true", }, allowAnyIp: { default: false, // Value must be explicitly "true" or "false" as a string validate: (value) => String(value) === "true", }, browserLaunchArgs: { default: [], validate: (value) => { let args = []; if (Array.isArray(value)) args = value.map((arg) => String(arg.trim())); if (typeof value === "string") args = value.split(",").map((arg) => arg.trim()); return args; }, }, }; constructor() { if (RuntimeSettings._instance) return RuntimeSettings._instance; RuntimeSettings._instance = this; return this; } /** * Parse the runtime settings from the request body options body * see #attachOptions https://github.com/Mintplex-Labs/anything-llm/blob/ebf112007e0d579af3d2b43569db95bdfc59074b/server/utils/collectorApi/index.js#L18 * @param {import('express').Request} request * @returns {void} */ parseOptionsFromRequest(request = {}) { const options = reqBody(request)?.options?.runtimeSettings || {}; for (const [key, value] of Object.entries(options)) { if (!this.settingConfigs.hasOwnProperty(key)) continue; this.set(key, value); } return; } /** * Get a runtime setting * - Will throw an error if the setting requested is not a supported runtime setting key * - Will return the default value if the setting requested is not set at all * @param {string} key * @returns {any} */ get(key) { if (!this.settingConfigs[key]) throw new Error(`Invalid runtime setting: ${key}`); return this.settings.hasOwnProperty(key) ? this.settings[key] : this.settingConfigs[key].default; } /** * Set a runtime setting * - Will throw an error if the setting requested is not a supported runtime setting key * - Will validate the value against the setting's validate function * @param {string} key * @param {any} value * @returns {void} */ set(key, value = null) { if (!this.settingConfigs[key]) throw new Error(`Invalid runtime setting: ${key}`); this.settings[key] = this.settingConfigs[key].validate(value); } } module.exports = RuntimeSettings;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/ObsidianVault/index.js
collector/utils/extensions/ObsidianVault/index.js
const { v4 } = require("uuid"); const { default: slugify } = require("slugify"); const path = require("path"); const fs = require("fs"); const { writeToServerDocuments, sanitizeFileName, documentsFolder, } = require("../../files"); function parseObsidianVaultPath(files = []) { const possiblePaths = new Set(); files.forEach( (file) => file?.path && possiblePaths.add(file.path.split("/")[0]) ); switch (possiblePaths.size) { case 0: return null; case 1: // The user specified a vault properly - so all files are in the same folder. return possiblePaths.values().next().value; default: return null; } } async function loadObsidianVault({ files = [] }) { if (!files || files?.length === 0) return { success: false, error: "No files provided" }; const vaultName = parseObsidianVaultPath(files); const folderUUId = v4().slice(0, 4); const outFolder = vaultName ? slugify(`obsidian-vault-${vaultName}-${folderUUId}`).toLowerCase() : slugify(`obsidian-${folderUUId}`).toLowerCase(); const outFolderPath = path.resolve(documentsFolder, outFolder); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); console.log( `Processing ${files.length} files from Obsidian Vault ${ vaultName ? `"${vaultName}"` : "" }` ); const results = []; for (const file of files) { try { const fullPageContent = file?.content; // If the file has no content or is just whitespace, skip it. if (!fullPageContent || fullPageContent.trim() === "") continue; const data = { id: v4(), url: `obsidian://${file.path}`, title: file.name, docAuthor: "Obsidian Vault", description: file.name, docSource: "Obsidian Vault", chunkSource: `obsidian://${file.path}`, published: new Date().toLocaleString(), wordCount: fullPageContent.split(" ").length, pageContent: fullPageContent, token_count_estimate: fullPageContent.length / 4, // rough estimate }; const targetFileName = sanitizeFileName( `${slugify(file.name)}-${data.id}` ); writeToServerDocuments({ data, filename: targetFileName, destinationOverride: outFolderPath, }); results.push({ file: file.path, status: "success" }); } catch (e) { console.error(`Failed to process ${file.path}:`, e); results.push({ file: file.path, status: "failed", reason: e.message }); } } return { success: true, data: { processed: results.filter((r) => r.status === "success").length, failed: results.filter((r) => r.status === "failed").length, total: files.length, results, destination: path.basename(outFolderPath), }, }; } module.exports = { loadObsidianVault, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/YoutubeTranscript/index.js
collector/utils/extensions/YoutubeTranscript/index.js
const fs = require("fs"); const path = require("path"); const { default: slugify } = require("slugify"); const { v4 } = require("uuid"); const { writeToServerDocuments, sanitizeFileName, documentsFolder, } = require("../../files"); const { tokenizeString } = require("../../tokenizer"); const { YoutubeLoader } = require("./YoutubeLoader"); const { validYoutubeVideoUrl } = require("../../url"); /** * Fetch the transcript content for a YouTube video * @param {string} url - The URL of the YouTube video * @returns {Promise<{success: boolean, reason: string|null, content: string|null, metadata: TranscriptMetadata}>} - The transcript content for the YouTube video */ async function fetchVideoTranscriptContent({ url }) { if (!validYoutubeVideoUrl(url)) { return { success: false, reason: "Invalid URL. Should be youtu.be or youtube.com/watch.", content: null, metadata: {}, }; } console.log(`-- Working YouTube ${url} --`); const loader = YoutubeLoader.createFromUrl(url, { addVideoInfo: true }); const { docs, error } = await loader .load() .then((docs) => ({ docs, error: null })) .catch((e) => ({ docs: [], error: e.message?.split("Error:")?.[1] || e.message, })); if (!docs.length || !!error) { return { success: false, reason: error ?? "No transcript found for that YouTube video.", content: null, metadata: {}, }; } const metadata = docs[0].metadata; const content = docs[0].pageContent; if (!content.length) { return { success: false, reason: "No transcript could be parsed for that YouTube video.", content: null, metadata: {}, }; } return { success: true, reason: null, content, metadata, }; } /** * @typedef {Object} TranscriptMetadata * @property {string} title - The title of the video * @property {string} author - The author of the video * @property {string} description - The description of the video * @property {string} view_count - The view count of the video * @property {string} source - The source of the video (videoId) */ /** * @typedef {Object} TranscriptAsDocument * @property {boolean} success - Whether the transcript was successful * @property {string|null} reason - The reason for the transcript * @property {TranscriptMetadata} metadata - The metadata from the transcript */ /** * @typedef {Object} TranscriptAsContent * @property {boolean} success - Whether the transcript was successful * @property {string|null} reason - The reason for the transcript * @property {string|null} content - The content of the transcript * @property {Object[]} documents - The documents from the transcript * @property {boolean} saveAsDocument - Whether to save the transcript as a document */ /** * Load the transcript content for a YouTube video as well as save it to the server documents * @param {Object} params - The parameters for the YouTube transcript * @param {string} params.url - The URL of the YouTube video * @param {Object} options - The options for the YouTube transcript * @param {boolean} options.parseOnly - Whether to parse the transcript content only or save it to the server documents * @returns {Promise<TranscriptAsDocument | TranscriptAsContent>} - The transcript content for the YouTube video */ async function loadYouTubeTranscript({ url }, options = { parseOnly: false }) { const transcriptResults = await fetchVideoTranscriptContent({ url }); if (!transcriptResults.success) { return { success: false, reason: transcriptResults.reason || "An unknown error occurred during transcription retrieval", documents: [], content: null, saveAsDocument: options.parseOnly, data: {}, }; } const { content, metadata } = transcriptResults; if (options.parseOnly) { return { success: true, reason: null, content: buildTranscriptContentWithMetadata(content, metadata), documents: [], saveAsDocument: options.parseOnly, data: {}, }; } const outFolder = sanitizeFileName( slugify(`${metadata.author} YouTube transcripts`).toLowerCase() ); const outFolderPath = path.resolve(documentsFolder, outFolder); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); const data = { id: v4(), url: url + ".youtube", title: metadata.title || url, docAuthor: metadata.author, description: metadata.description, docSource: url, chunkSource: `youtube://${url}`, published: new Date().toLocaleString(), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; console.log(`[YouTube Loader]: Saving ${metadata.title} to ${outFolder}`); writeToServerDocuments({ data, filename: sanitizeFileName(`${slugify(metadata.title)}-${data.id}`), destinationOverride: outFolderPath, }); return { success: true, reason: null, data: { title: metadata.title, author: metadata.author, destination: outFolder, }, }; } /** * Generate the transcript content and metadata into a single string * * Why? For ephemeral documents where we just want the content, we want to include the metadata as keys in the content * so that the LLM has context about the video, this gives it a better understanding of the video * and allows it to use the metadata in the conversation if relevant. * Examples: * - How many views does <LINK> have? * - Checkout <LINK> and tell me the key points and if it is performing well * - Summarize this video <LINK>? -> description could have links and references * @param {string} content - The content of the transcript * @param {TranscriptMetadata} metadata - The metadata from the transcript * @returns {string} - The concatenated transcript content and metadata */ function buildTranscriptContentWithMetadata(content = "", metadata = {}) { const VALID_METADATA_KEYS = ["title", "author", "description", "view_count"]; if (!content || !metadata || Object.keys(metadata).length === 0) return content; let contentWithMetadata = ""; VALID_METADATA_KEYS.forEach((key) => { if (!metadata[key]) return; contentWithMetadata += `<${key}>${metadata[key]}</${key}>`; }); return `${contentWithMetadata}\nTranscript:\n${content}`; } module.exports = { loadYouTubeTranscript, fetchVideoTranscriptContent, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/YoutubeTranscript/YoutubeLoader/youtube-transcript.js
collector/utils/extensions/YoutubeTranscript/YoutubeLoader/youtube-transcript.js
const { validYoutubeVideoUrl } = require("../../../url"); class YoutubeTranscriptError extends Error { constructor(message) { super(`[YoutubeTranscript] ${message}`); } } /** * Handles fetching and parsing YouTube video transcripts */ class YoutubeTranscript { /** * Encodes a string as a protobuf field * @param {number} fieldNumber - The protobuf field number * @param {string} str - The string to encode * @returns {Buffer} Encoded protobuf field */ static #encodeProtobufString(fieldNumber, str) { const utf8Bytes = Buffer.from(str, "utf8"); const tag = (fieldNumber << 3) | 2; // wire type 2 for string const lengthBytes = this.#encodeVarint(utf8Bytes.length); return Buffer.concat([ Buffer.from([tag]), Buffer.from(lengthBytes), utf8Bytes, ]); } /** * Encodes a number as a protobuf varint * @param {number} value - The number to encode * @returns {number[]} Encoded varint bytes */ static #encodeVarint(value) { const bytes = []; while (value >= 0x80) { bytes.push((value & 0x7f) | 0x80); value >>>= 7; } bytes.push(value); return bytes; } /** * Creates a base64 encoded protobuf message * @param {Object} param - The parameters to encode * @param {string} param.param1 - First parameter * @param {string} param.param2 - Second parameter * @returns {string} Base64 encoded protobuf */ static #getBase64Protobuf({ param1, param2 }) { const field1 = this.#encodeProtobufString(1, param1); const field2 = this.#encodeProtobufString(2, param2); return Buffer.concat([field1, field2]).toString("base64"); } /** * Extracts transcript text from YouTube API response * @param {Object} responseData - The YouTube API response * @returns {string} Combined transcript text */ static #extractTranscriptFromResponse(responseData) { const transcriptRenderer = responseData.actions?.[0]?.updateEngagementPanelAction?.content ?.transcriptRenderer; if (!transcriptRenderer) { throw new Error("No transcript data found in response"); } const segments = transcriptRenderer.content?.transcriptSearchPanelRenderer?.body ?.transcriptSegmentListRenderer?.initialSegments; if (!segments) { throw new Error("Transcript segments not found in response"); } return segments .map((segment) => { const runs = segment.transcriptSegmentRenderer?.snippet?.runs; return runs ? runs.map((run) => run.text).join("") : ""; }) .filter((text) => text) .join(" ") .trim() .replace(/\s+/g, " "); } /** * Calculates a preference score for a caption track to determine the best match * @param {Object} track - The caption track object from YouTube * @param {string} track.languageCode - ISO language code (e.g., 'zh-HK', 'en', 'es') * @param {string} track.kind - Track type ('asr' for auto-generated, "" for human-transcribed) * @param {string[]} preferredLanguages - Array of language codes in preference order (e.g., ['zh-HK', 'en']) * @returns {number} Preference score (lower is better) */ static #calculatePreferenceScore(track, preferredLanguages) { // Language preference: index in preferredLanguages array (0 = most preferred) const languagePreference = preferredLanguages.indexOf(track.languageCode); const languageScore = languagePreference === -1 ? 9999 : languagePreference; // Kind bonus: prefer human-transcribed (undefined) over auto-generated ('asr') const kindBonus = track.kind === "asr" ? 0.5 : 0; return languageScore + kindBonus; } /** * Finds the most suitable caption track based on preferred languages * @param {string} videoBody - The raw HTML response from YouTube * @param {string[]} preferredLanguages - Array of language codes in preference order * @returns {Object|null} The selected caption track or null if none found */ static #findPreferredCaptionTrack(videoBody, preferredLanguages) { const captionsConfigJson = videoBody.match( /"captions":(.*?),"videoDetails":/s ); const captionsConfig = captionsConfigJson?.[1] ? JSON.parse(captionsConfigJson[1]) : null; const captionTracks = captionsConfig ? captionsConfig.playerCaptionsTracklistRenderer.captionTracks : null; if (!captionTracks || captionTracks.length === 0) { return null; } const sortedTracks = [...captionTracks].sort((a, b) => { const scoreA = this.#calculatePreferenceScore(a, preferredLanguages); const scoreB = this.#calculatePreferenceScore(b, preferredLanguages); return scoreA - scoreB; }); return sortedTracks[0]; } /** * Fetches video page content and finds the preferred caption track * @param {string} videoId - YouTube video ID * @param {string[]} preferredLanguages - Array of preferred language codes * @returns {Promise<Object>} The preferred caption track * @throws {YoutubeTranscriptError} If no suitable caption track is found */ static async #getPreferredCaptionTrack(videoId, preferredLanguages) { const videoResponse = await fetch( `https://www.youtube.com/watch?v=${videoId}`, { credentials: "omit" } ); const videoBody = await videoResponse.text(); const preferredCaptionTrack = this.#findPreferredCaptionTrack( videoBody, preferredLanguages ); if (!preferredCaptionTrack) { throw new YoutubeTranscriptError( "No suitable caption track found for the video" ); } return preferredCaptionTrack; } /** * Fetch transcript from YouTube video * @param {string} videoId - Video URL or video identifier * @param {Object} config - Configuration options * @param {string} [config.lang='en'] - Language code (e.g., 'en', 'es', 'fr') * @returns {Promise<string>} Video transcript text */ static async fetchTranscript(videoId, config = {}) { const preferredLanguages = config?.lang ? [config?.lang, "en"] : ["en"]; const identifier = this.retrieveVideoId(videoId); try { const preferredCaptionTrack = await this.#getPreferredCaptionTrack( identifier, preferredLanguages ); const innerProto = this.#getBase64Protobuf({ param1: preferredCaptionTrack.kind || "", param2: preferredCaptionTrack.languageCode, }); const params = this.#getBase64Protobuf({ param1: identifier, param2: innerProto, }); const response = await fetch( "https://www.youtube.com/youtubei/v1/get_transcript", { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36,gzip(gfe)", }, body: JSON.stringify({ context: { client: { clientName: "WEB", clientVersion: "2.20240826.01.00", }, }, params, }), } ); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const responseData = await response.json(); return this.#extractTranscriptFromResponse(responseData); } catch (e) { throw new YoutubeTranscriptError(e.message || e); } } /** * Extract video ID from a YouTube URL or verify an existing ID * @param {string} videoId - Video URL or ID * @returns {string} YouTube video ID */ static retrieveVideoId(videoId) { if (videoId.length === 11) return videoId; // already a valid ID most likely const matchedId = validYoutubeVideoUrl(videoId, true); if (matchedId) return matchedId; throw new YoutubeTranscriptError( "Impossible to retrieve Youtube video ID." ); } } module.exports = { YoutubeTranscript, YoutubeTranscriptError, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/YoutubeTranscript/YoutubeLoader/index.js
collector/utils/extensions/YoutubeTranscript/YoutubeLoader/index.js
const { validYoutubeVideoUrl } = require("../../../url"); /* * This is just a custom implementation of the Langchain JS YouTubeLoader class * as the dependency for YoutubeTranscript is quite fickle and its a rat race to keep it up * and instead of waiting for patches we can just bring this simple script in-house and at least * be able to patch it since its so flaky. When we have more connectors we can kill this because * it will be a pain to maintain over time. */ class YoutubeLoader { #videoId; #language; #addVideoInfo; constructor({ videoId = null, language = null, addVideoInfo = false } = {}) { if (!videoId) throw new Error("Invalid video id!"); this.#videoId = videoId; this.#language = language; this.#addVideoInfo = addVideoInfo; } /** * Extracts the videoId from a YouTube video URL. * @param url The URL of the YouTube video. * @returns The videoId of the YouTube video. */ static getVideoID(url) { const videoId = validYoutubeVideoUrl(url, true); if (videoId) return videoId; throw new Error("Failed to get youtube video id from the url"); } /** * Creates a new instance of the YoutubeLoader class from a YouTube video * URL. * @param url The URL of the YouTube video. * @param config Optional configuration options for the YoutubeLoader instance, excluding the videoId. * @returns A new instance of the YoutubeLoader class. */ static createFromUrl(url, config = {}) { const videoId = YoutubeLoader.getVideoID(url); return new YoutubeLoader({ ...config, videoId }); } /** * Loads the transcript and video metadata from the specified YouTube * video. It uses the youtube-transcript library to fetch the transcript * and the youtubei.js library to fetch the video metadata. * @returns Langchain like doc that is 1 element with PageContent and */ async load() { let transcript; const metadata = { source: this.#videoId, }; try { const fetchTranscript = await import("youtube-transcript-plus").then( (module) => module.fetchTranscript ); const transcriptSegments = await fetchTranscript(this.#videoId, { lang: this.#language, }); if (!transcriptSegments || transcriptSegments.length === 0) throw new Error("Transcription not found"); transcript = this.#convertTranscriptSegmentsToText(transcriptSegments); if (this.#addVideoInfo) { const { Innertube } = require("youtubei.js"); const youtube = await Innertube.create(); const info = (await youtube.getBasicInfo(this.#videoId)).basic_info; metadata.description = info.short_description; metadata.title = info.title; metadata.view_count = info.view_count; metadata.author = info.author; } } catch (e) { throw new Error( `Failed to get YouTube video transcription: ${e?.message}` ); } return [ { pageContent: transcript, metadata, }, ]; } #convertTranscriptSegmentsToText(transcriptSegments) { return transcriptSegments .map((segment) => typeof segment === "string" ? segment : segment.text || "" ) .join(" ") .replace(/\s+/g, " ") .trim(); } } module.exports.YoutubeLoader = YoutubeLoader;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/WebsiteDepth/index.js
collector/utils/extensions/WebsiteDepth/index.js
const { v4 } = require("uuid"); const { PuppeteerWebBaseLoader, } = require("langchain/document_loaders/web/puppeteer"); const { default: slugify } = require("slugify"); const { parse } = require("node-html-parser"); const { writeToServerDocuments } = require("../../files"); const { tokenizeString } = require("../../tokenizer"); const path = require("path"); const fs = require("fs"); async function discoverLinks(startUrl, maxDepth = 1, maxLinks = 20) { const baseUrl = new URL(startUrl); const discoveredLinks = new Set([startUrl]); let queue = [[startUrl, 0]]; // [url, currentDepth] const scrapedUrls = new Set(); for (let currentDepth = 0; currentDepth < maxDepth; currentDepth++) { const levelSize = queue.length; const nextQueue = []; for (let i = 0; i < levelSize && discoveredLinks.size < maxLinks; i++) { const [currentUrl, urlDepth] = queue[i]; if (!scrapedUrls.has(currentUrl)) { scrapedUrls.add(currentUrl); const newLinks = await getPageLinks(currentUrl, baseUrl); for (const link of newLinks) { if (!discoveredLinks.has(link) && discoveredLinks.size < maxLinks) { discoveredLinks.add(link); if (urlDepth + 1 < maxDepth) { nextQueue.push([link, urlDepth + 1]); } } } } } queue = nextQueue; if (queue.length === 0 || discoveredLinks.size >= maxLinks) break; } return Array.from(discoveredLinks); } async function getPageLinks(url, baseUrl) { try { const loader = new PuppeteerWebBaseLoader(url, { launchOptions: { headless: "new" }, gotoOptions: { waitUntil: "networkidle2" }, }); const docs = await loader.load(); const html = docs[0].pageContent; const links = extractLinks(html, baseUrl); return links; } catch (error) { console.error(`Failed to get page links from ${url}.`, error); return []; } } function extractLinks(html, baseUrl) { const root = parse(html); const links = root.querySelectorAll("a"); const extractedLinks = new Set(); for (const link of links) { const href = link.getAttribute("href"); if (href) { const absoluteUrl = new URL(href, baseUrl.href).href; if ( absoluteUrl.startsWith( baseUrl.origin + baseUrl.pathname.split("/").slice(0, -1).join("/") ) ) { extractedLinks.add(absoluteUrl); } } } return Array.from(extractedLinks); } async function bulkScrapePages(links, outFolderPath) { const scrapedData = []; for (let i = 0; i < links.length; i++) { const link = links[i]; console.log(`Scraping ${i + 1}/${links.length}: ${link}`); try { const loader = new PuppeteerWebBaseLoader(link, { launchOptions: { headless: "new" }, gotoOptions: { waitUntil: "networkidle2" }, async evaluate(page, browser) { const result = await page.evaluate(() => document.body.innerText); await browser.close(); return result; }, }); const docs = await loader.load(); const content = docs[0].pageContent; if (!content.length) { console.warn(`Empty content for ${link}. Skipping.`); continue; } const url = new URL(link); const decodedPathname = decodeURIComponent(url.pathname); const filename = `${url.hostname}${decodedPathname.replace(/\//g, "_")}`; const data = { id: v4(), url: "file://" + slugify(filename) + ".html", title: slugify(filename) + ".html", docAuthor: "no author found", description: "No description found.", docSource: "URL link uploaded by the user.", chunkSource: `link://${link}`, published: new Date().toLocaleString(), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; writeToServerDocuments({ data, filename: data.title, destinationOverride: outFolderPath, }); scrapedData.push(data); console.log(`Successfully scraped ${link}.`); } catch (error) { console.error(`Failed to scrape ${link}.`, error); } } return scrapedData; } async function websiteScraper(startUrl, depth = 1, maxLinks = 20) { const websiteName = new URL(startUrl).hostname; const outFolder = slugify( `${slugify(websiteName)}-${v4().slice(0, 4)}` ).toLowerCase(); const outFolderPath = process.env.NODE_ENV === "development" ? path.resolve( __dirname, `../../../../server/storage/documents/${outFolder}` ) : path.resolve(process.env.STORAGE_DIR, `documents/${outFolder}`); console.log("Discovering links..."); const linksToScrape = await discoverLinks(startUrl, depth, maxLinks); console.log(`Found ${linksToScrape.length} links to scrape.`); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); console.log("Starting bulk scraping..."); const scrapedData = await bulkScrapePages(linksToScrape, outFolderPath); console.log(`Scraped ${scrapedData.length} pages.`); return scrapedData; } module.exports = websiteScraper;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/PaperlessNgx/index.js
collector/utils/extensions/PaperlessNgx/index.js
const fs = require("fs"); const path = require("path"); const { default: slugify } = require("slugify"); const { v4 } = require("uuid"); const { writeToServerDocuments, sanitizeFileName, documentsFolder, } = require("../../files"); const { tokenizeString } = require("../../tokenizer"); const { validBaseUrl } = require("../../http"); const PaperlessNgxLoader = require("./PaperlessNgxLoader"); /** * Load documents from a Paperless-ngx instance * @param {object} args - forwarded request body params * @param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker * @returns */ async function loadPaperlessNgx({ baseUrl = null, apiToken = null }, response) { if (!baseUrl || !validBaseUrl(baseUrl)) { return { success: false, reason: "Provided base URL is not a valid URL.", }; } if (!apiToken) { return { success: false, reason: "You need to provide an API token to use the Paperless-ngx connector.", }; } const { origin, hostname } = new URL(baseUrl); console.log(`-- Working Paperless-ngx ${origin} --`); const loader = new PaperlessNgxLoader({ baseUrl: origin, apiToken, }); const { docs, error } = await loader .load() .then((docs) => ({ docs, error: null })) .catch((e) => ({ docs: [], error: e.message?.split("Error:")?.[1] || e.message, })); if (!docs.length || !!error) { return { success: false, reason: error ?? "No parseable documents found in that Paperless-ngx instance.", data: null, }; } const outFolder = slugify( `paperless-${hostname}-${v4().slice(0, 4)}` ).toLowerCase(); const outFolderPath = path.resolve(documentsFolder, outFolder); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); docs.forEach((doc) => { if (!doc.pageContent) return; const data = { id: v4(), url: doc.metadata.url, title: doc.metadata.title, docAuthor: doc.metadata.correspondent || "Unknown", description: `A document from the Paperless-ngx instance at ${origin}`, docSource: `paperless-ngx`, chunkSource: generateChunkSource( { doc, baseUrl: origin, apiToken }, response.locals.encryptionWorker ), published: doc.metadata.created, wordCount: doc.pageContent.split(" ").length, pageContent: doc.pageContent, token_count_estimate: tokenizeString(doc.pageContent), }; console.log( `[Paperless-ngx Loader]: Saving ${doc.metadata.title} to ${outFolder}` ); const fileName = sanitizeFileName( `${slugify(doc.metadata.title)}-${data.id}` ); writeToServerDocuments({ data, filename: fileName, destinationOverride: outFolderPath, }); }); return { success: true, reason: null, data: { files: docs.length, destination: outFolder, }, }; } /** * Generate the full chunkSource for a specific Paperless-ngx document so that we can resync it later. * @param {object} chunkSourceInformation * @param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker * @returns {string} */ function generateChunkSource({ doc, baseUrl, apiToken }, encryptionWorker) { const payload = { baseUrl, token: apiToken, }; return `paperless-ngx://${doc.metadata.id}?payload=${encryptionWorker.encrypt( JSON.stringify(payload) )}`; } module.exports = { loadPaperlessNgx, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/PaperlessNgx/PaperlessNgxLoader/index.js
collector/utils/extensions/PaperlessNgx/PaperlessNgxLoader/index.js
const { htmlToText } = require("html-to-text"); const pdf = require("pdf-parse"); class PaperlessNgxLoader { constructor({ baseUrl, apiToken }) { this.baseUrl = new URL(baseUrl).origin; this.apiToken = apiToken; this.baseHeaders = { Authorization: `Token ${this.apiToken}`, }; } async load() { try { const documents = await this.fetchAllDocuments(); return documents.map((doc) => this.createDocumentFromPage(doc)); } catch (error) { console.error("Error:", error); throw error; } } /** * Fetches all documents from Paperless-ngx * @returns {Promise<{{[key: string]: any, content: string}[]}>} The documents with their content */ async fetchAllDocuments() { try { const documents = []; let nextUrl = `${this.baseUrl}/api/documents/`; let page = 1; while (nextUrl) { console.log(`Fetching documents page ${page} from Paperless-ngx`); try { const data = await fetch(nextUrl, { headers: { "Content-Type": "application/json", ...this.baseHeaders, }, }).then((res) => { if (!res.ok) throw new Error( `Failed to fetch documents from Paperless-ngx: ${res.status}` ); return res.json(); }); const validResults = data.results.filter((doc) => doc?.id); if (!validResults.length) break; documents.push(...validResults); if (data.next === nextUrl) break; nextUrl = data.next || null; page++; } catch (error) { console.error( `Error fetching page ${page} from Paperless-ngx:`, error ); break; } } console.log( `Fetched ${documents.length} documents from Paperless-ngx (Pages: ${ page - 1 })` ); const documentsWithContent = await Promise.all( documents.map(async (doc) => { const content = await this.fetchDocumentContent(doc.id); return { ...doc, content }; }) ); return documentsWithContent.filter((doc) => !!doc.content); } catch (error) { throw new Error( `Failed to fetch documents from Paperless-ngx: ${error.message}` ); } } /** * Fetches the content of a document from Paperless-ngx * @param {string} documentId - The ID of the document to fetch * @returns {Promise<string>} The content of the document */ async fetchDocumentContent(documentId) { try { const response = await fetch( `${this.baseUrl}/api/documents/${documentId}/download/`, { headers: this.baseHeaders, } ); if (!response.ok) throw new Error(`Failed to fetch document content: ${response.status}`); const contentType = response.headers.get("content-type"); switch (contentType) { case "text/plain": return await response.text(); case "application/pdf": const buffer = await response.arrayBuffer(); return await this.parsePdfContent(buffer); default: return await response.text(); } } catch (error) { console.error( `Failed to fetch content for document ${documentId}:`, error ); return ""; } } async parsePdfContent(buffer) { try { const data = await pdf(Buffer.from(buffer)); return data.text; } catch (error) { console.error("Failed to parse PDF content:", error); return ""; } } createDocumentFromPage(doc) { const content = doc.content || ""; const plainTextContent = htmlToText(content, { wordwrap: false, preserveNewlines: true, }); return { pageContent: plainTextContent, metadata: { id: doc.id, title: doc.original_file_name, created: doc.created, modified: doc.modified, added: doc.added, tags: doc.tags, correspondent: doc.correspondent, documentType: doc.document_type, url: `${this.baseUrl}/documents/${doc.id}`, }, }; } } module.exports = PaperlessNgxLoader;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/DrupalWiki/index.js
collector/utils/extensions/DrupalWiki/index.js
/** * Copyright 2024 * * Authors: * - Eugen Mayer (KontextWork) */ const { DrupalWiki } = require("./DrupalWiki"); const { validBaseUrl } = require("../../../utils/http"); async function loadAndStoreSpaces( { baseUrl = null, spaceIds = null, accessToken = null }, response ) { if (!baseUrl) { return { success: false, reason: "Please provide your baseUrl like https://mywiki.drupal-wiki.net.", }; } else if (!validBaseUrl(baseUrl)) { return { success: false, reason: "Provided base URL is not a valid URL.", }; } if (!spaceIds) { return { success: false, reason: "Please provide a list of spaceIds like 21,56,67 you want to extract", }; } if (!accessToken) { return { success: false, reason: "Please provide a REST API-Token.", }; } console.log(`-- Working Drupal Wiki ${baseUrl} for spaceIds: ${spaceIds} --`); const drupalWiki = new DrupalWiki({ baseUrl, accessToken }); const encryptionWorker = response.locals.encryptionWorker; const spaceIdsArr = spaceIds.split(",").map((idStr) => { return Number(idStr.trim()); }); for (const spaceId of spaceIdsArr) { try { await drupalWiki.loadAndStoreAllPagesForSpace(spaceId, encryptionWorker); console.log(`--- Finished space ${spaceId} ---`); } catch (e) { console.error(e); return { success: false, reason: e.message, data: {}, }; } } console.log(`-- Finished all spaces--`); return { success: true, reason: null, data: { spaceIds, destination: drupalWiki.storagePath, }, }; } /** * Gets the page content from a specific Confluence page, not all pages in a workspace. * @returns */ async function loadPage({ baseUrl, pageId, accessToken }) { console.log(`-- Working Drupal Wiki Page ${pageId} of ${baseUrl} --`); const drupalWiki = new DrupalWiki({ baseUrl, accessToken }); try { const page = await drupalWiki.loadPage(pageId); return { success: true, reason: null, content: page.processedBody, }; } catch (e) { return { success: false, reason: `Failed (re)-fetching DrupalWiki page ${pageId} form ${baseUrl}}`, content: null, }; } } module.exports = { loadAndStoreSpaces, loadPage, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/DrupalWiki/DrupalWiki/index.js
collector/utils/extensions/DrupalWiki/DrupalWiki/index.js
/** * Copyright 2024 * * Authors: * - Eugen Mayer (KontextWork) */ const { htmlToText } = require("html-to-text"); const { tokenizeString } = require("../../../tokenizer"); const { sanitizeFileName, writeToServerDocuments, documentsFolder, } = require("../../../files"); const { default: slugify } = require("slugify"); const path = require("path"); const fs = require("fs"); const { processSingleFile } = require("../../../../processSingleFile"); const { WATCH_DIRECTORY, SUPPORTED_FILETYPE_CONVERTERS, } = require("../../../constants"); class Page { /** * * @param {number }id * @param {string }title * @param {string} created * @param {string} type * @param {string} processedBody * @param {string} url * @param {number} spaceId */ constructor({ id, title, created, type, processedBody, url, spaceId }) { this.id = id; this.title = title; this.url = url; this.created = created; this.type = type; this.processedBody = processedBody; this.spaceId = spaceId; } } class DrupalWiki { /** * * @param baseUrl * @param spaceId * @param accessToken */ constructor({ baseUrl, accessToken }) { this.baseUrl = baseUrl; this.accessToken = accessToken; this.storagePath = this.#prepareStoragePath(baseUrl); } /** * Load all pages for the given space, fetching storing each page one by one * to minimize the memory usage * * @param {number} spaceId * @param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker * @returns {Promise<void>} */ async loadAndStoreAllPagesForSpace(spaceId, encryptionWorker) { const pageIndex = await this.#getPageIndexForSpace(spaceId); for (const pageId of pageIndex) { try { const page = await this.loadPage(pageId); // Pages with an empty body will lead to embedding issues / exceptions if (page.processedBody.trim() !== "") { this.#storePage(page, encryptionWorker); await this.#downloadAndProcessAttachments(page.id); } else { console.log(`Skipping page (${page.id}) since it has no content`); } } catch (e) { console.error( `Could not process DrupalWiki page ${pageId} (skipping and continuing): ` ); console.error(e); } } } /** * @param {number} pageId * @returns {Promise<Page>} */ async loadPage(pageId) { return this.#fetchPage(pageId); } /** * Fetches the page ids for the configured space * @param {number} spaceId * @returns{Promise<number[]>} array of pageIds */ async #getPageIndexForSpace(spaceId) { // errors on fetching the pageIndex is fatal, no error handling let hasNext = true; let pageIds = []; let pageNr = 0; do { let { isLast, pageIdsForPage } = await this.#getPagesForSpacePaginated( spaceId, pageNr ); hasNext = !isLast; pageNr++; if (pageIdsForPage.length) { pageIds = pageIds.concat(pageIdsForPage); } } while (hasNext); return pageIds; } /** * * @param {number} pageNr * @param {number} spaceId * @returns {Promise<{isLast,pageIds}>} */ async #getPagesForSpacePaginated(spaceId, pageNr) { /* * { * content: Page[], * last: boolean, * pageable: { * pageNumber: number * } * } */ const data = await this._doFetch( `${this.baseUrl}/api/rest/scope/api/page?size=100&space=${spaceId}&page=${pageNr}` ); const pageIds = data.content.map((page) => { return Number(page.id); }); return { isLast: data.last, pageIdsForPage: pageIds, }; } /** * @param pageId * @returns {Promise<Page>} */ async #fetchPage(pageId) { const data = await this._doFetch( `${this.baseUrl}/api/rest/scope/api/page/${pageId}` ); const url = `${this.baseUrl}/node/${data.id}`; return new Page({ id: data.id, title: data.title, created: data.lastModified, type: data.type, processedBody: this.#processPageBody({ body: data.body, title: data.title, lastModified: data.lastModified, url: url, }), url: url, }); } /** * @param {Page} page * @param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker */ #storePage(page, encryptionWorker) { const { hostname } = new URL(this.baseUrl); // This UUID will ensure that re-importing the same page without any changes will not // show up (deduplication). const targetUUID = `${hostname}.${page.spaceId}.${page.id}.${page.created}`; const wordCount = page.processedBody.split(" ").length; const data = { id: targetUUID, url: `drupalwiki://${page.url}`, title: page.title, docAuthor: this.baseUrl, description: page.title, docSource: `${this.baseUrl} DrupalWiki`, chunkSource: this.#generateChunkSource(page.id, encryptionWorker), published: new Date().toLocaleString(), wordCount: wordCount, pageContent: page.processedBody, token_count_estimate: tokenizeString(page.processedBody), }; const fileName = sanitizeFileName(`${slugify(page.title)}-${data.id}`); console.log( `[DrupalWiki Loader]: Saving page '${page.title}' (${page.id}) to '${this.storagePath}/${fileName}'` ); writeToServerDocuments({ data, filename: fileName, destinationOverride: this.storagePath, }); } /** * Generate the full chunkSource for a specific Confluence page so that we can resync it later. * This data is encrypted into a single `payload` query param so we can replay credentials later * since this was encrypted with the systems persistent password and salt. * @param {number} pageId * @param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker * @returns {string} */ #generateChunkSource(pageId, encryptionWorker) { const payload = { baseUrl: this.baseUrl, pageId: pageId, accessToken: this.accessToken, }; return `drupalwiki://${ this.baseUrl }/node/${pageId}?payload=${encryptionWorker.encrypt( JSON.stringify(payload) )}`; } async _doFetch(url) { const response = await fetch(url, { headers: this.#getHeaders(), }); if (!response.ok) { throw new Error(`Failed to fetch ${url}: ${response.status}`); } return response.json(); } #getHeaders() { return { "Content-Type": "application/json", Accept: "application/json", Authorization: `Bearer ${this.accessToken}`, }; } #prepareStoragePath(baseUrl) { const { hostname } = new URL(baseUrl); const subFolder = slugify(`drupalwiki-${hostname}`).toLowerCase(); const outFolder = path.resolve(documentsFolder, subFolder); if (!fs.existsSync(outFolder)) fs.mkdirSync(outFolder, { recursive: true }); return outFolder; } /** * @param {string} body * @param {string} url * @param {string} title * @param {string} lastModified * @returns {string} * @private */ #processPageBody({ body, url, title, lastModified }) { const textContent = body.trim() !== "" ? body : title; const plainTextContent = htmlToText(textContent, { wordwrap: false, preserveNewlines: true, selectors: [ { selector: "table", format: "dataTable", options: { colSpacing: 3, rowSpacing: 1, uppercaseHeaderCells: true, maxColumnWidth: Infinity, }, }, ], }); const plainBody = plainTextContent.replace(/\n{3,}/g, "\n\n"); return plainBody; } async #downloadAndProcessAttachments(pageId) { try { const data = await this._doFetch( `${this.baseUrl}/api/rest/scope/api/attachment?pageId=${pageId}&size=2000` ); const extensionsList = Object.keys(SUPPORTED_FILETYPE_CONVERTERS); for (const attachment of data.content || data) { const { fileName, id: attachId } = attachment; const lowerName = fileName.toLowerCase(); if (!extensionsList.some((ext) => lowerName.endsWith(ext))) { continue; } const downloadUrl = `${this.baseUrl}/api/rest/scope/api/attachment/${attachId}/download`; const attachmentResponse = await fetch(downloadUrl, { headers: this.#getHeaders(), }); if (!attachmentResponse.ok) { console.log(`Skipping attachment: ${fileName} - Download failed`); continue; } const buffer = await attachmentResponse.arrayBuffer(); const localFilePath = `${WATCH_DIRECTORY}/${fileName}`; require("fs").writeFileSync(localFilePath, Buffer.from(buffer)); await processSingleFile(fileName); } } catch (err) { console.error(`Fetching/processing attachments failed:`, err); } } } module.exports = { DrupalWiki };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/Confluence/index.js
collector/utils/extensions/Confluence/index.js
const fs = require("fs"); const path = require("path"); const { default: slugify } = require("slugify"); const { v4 } = require("uuid"); const { writeToServerDocuments, sanitizeFileName } = require("../../files"); const { tokenizeString } = require("../../tokenizer"); const { ConfluencePagesLoader } = require("./ConfluenceLoader"); /** * Load Confluence documents from a spaceID and Confluence credentials * @param {object} args - forwarded request body params * @param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker * @returns */ async function loadConfluence( { baseUrl = null, spaceKey = null, username = null, accessToken = null, cloud = true, personalAccessToken = null, bypassSSL = false, }, response ) { if (!personalAccessToken && (!username || !accessToken)) { return { success: false, reason: "You need either a personal access token (PAT), or a username and access token to use the Confluence connector.", }; } if (!baseUrl || !validBaseUrl(baseUrl)) { return { success: false, reason: "Provided base URL is not a valid URL.", }; } if (!spaceKey) { return { success: false, reason: "You need to provide a Confluence space key.", }; } const { origin, hostname } = new URL(baseUrl); console.log(`-- Working Confluence ${origin} --`); const loader = new ConfluencePagesLoader({ baseUrl: origin, // Use the origin to avoid issues with subdomains, ports, protocols, etc. spaceKey, username, accessToken, cloud, personalAccessToken, bypassSSL, }); const { docs, error } = await loader .load() .then((docs) => { return { docs, error: null }; }) .catch((e) => { return { docs: [], error: e.message?.split("Error:")?.[1] || e.message, }; }); if (!docs.length || !!error) { return { success: false, reason: error ?? "No pages found for that Confluence space.", }; } const outFolder = slugify( `confluence-${hostname}-${v4().slice(0, 4)}` ).toLowerCase(); const outFolderPath = process.env.NODE_ENV === "development" ? path.resolve( __dirname, `../../../../server/storage/documents/${outFolder}` ) : path.resolve(process.env.STORAGE_DIR, `documents/${outFolder}`); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); docs.forEach((doc) => { if (!doc.pageContent) return; const data = { id: v4(), url: doc.metadata.url + ".page", title: doc.metadata.title || doc.metadata.source, docAuthor: origin, description: doc.metadata.title, docSource: `${origin} Confluence`, chunkSource: generateChunkSource( { doc, baseUrl: origin, spaceKey, accessToken, username, cloud, bypassSSL, }, response.locals.encryptionWorker ), published: new Date().toLocaleString(), wordCount: doc.pageContent.split(" ").length, pageContent: doc.pageContent, token_count_estimate: tokenizeString(doc.pageContent), }; console.log( `[Confluence Loader]: Saving ${doc.metadata.title} to ${outFolder}` ); const fileName = sanitizeFileName( `${slugify(doc.metadata.title)}-${data.id}` ); writeToServerDocuments({ data, filename: fileName, destinationOverride: outFolderPath, }); }); return { success: true, reason: null, data: { spaceKey, destination: outFolder, }, }; } /** * Gets the page content from a specific Confluence page, not all pages in a workspace. * @returns */ async function fetchConfluencePage({ pageUrl, baseUrl, spaceKey, username, accessToken, cloud = true, bypassSSL = false, }) { if (!pageUrl || !baseUrl || !spaceKey || !username || !accessToken) { return { success: false, content: null, reason: "You need either a username and access token, or a personal access token (PAT), to use the Confluence connector.", }; } if (!validBaseUrl(baseUrl)) { return { success: false, content: null, reason: "Provided base URL is not a valid URL.", }; } if (!spaceKey) { return { success: false, content: null, reason: "You need to provide a Confluence space key.", }; } console.log(`-- Working Confluence Page ${pageUrl} --`); const loader = new ConfluencePagesLoader({ baseUrl, // Should be the origin of the baseUrl spaceKey, username, accessToken, cloud, bypassSSL, }); const { docs, error } = await loader .load() .then((docs) => { return { docs, error: null }; }) .catch((e) => { return { docs: [], error: e.message?.split("Error:")?.[1] || e.message, }; }); if (!docs.length || !!error) { return { success: false, reason: error ?? "No pages found for that Confluence space.", content: null, }; } const targetDocument = docs.find( (doc) => doc.pageContent && doc.metadata.url === pageUrl ); if (!targetDocument) { return { success: false, reason: "Target page could not be found in Confluence space.", content: null, }; } return { success: true, reason: null, content: targetDocument.pageContent, }; } /** * Validates if the provided baseUrl is a valid URL at all. * @param {string} baseUrl * @returns {boolean} */ function validBaseUrl(baseUrl) { try { new URL(baseUrl); return true; } catch (e) { return false; } } /** * Generate the full chunkSource for a specific Confluence page so that we can resync it later. * This data is encrypted into a single `payload` query param so we can replay credentials later * since this was encrypted with the systems persistent password and salt. * @param {object} chunkSourceInformation * @param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker * @returns {string} */ function generateChunkSource( { doc, baseUrl, spaceKey, accessToken, username, cloud, bypassSSL }, encryptionWorker ) { const payload = { baseUrl, spaceKey, token: accessToken, username, cloud, bypassSSL, }; return `confluence://${doc.metadata.url}?payload=${encryptionWorker.encrypt( JSON.stringify(payload) )}`; } module.exports = { loadConfluence, fetchConfluencePage, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/Confluence/ConfluenceLoader/index.js
collector/utils/extensions/Confluence/ConfluenceLoader/index.js
/* * This is a custom implementation of the Confluence langchain loader. There was an issue where * code blocks were not being extracted. This is a temporary fix until this issue is resolved.*/ const { htmlToText } = require("html-to-text"); class ConfluencePagesLoader { constructor({ baseUrl, spaceKey, username, accessToken, limit = 25, expand = "body.storage,version", personalAccessToken, cloud = true, bypassSSL = false, }) { this.baseUrl = baseUrl; this.spaceKey = spaceKey; this.username = username; this.accessToken = accessToken; this.limit = limit; this.expand = expand; this.personalAccessToken = personalAccessToken; this.cloud = cloud; this.bypassSSL = bypassSSL; this.log("Initialized Confluence Loader"); if (this.bypassSSL) this.log("!!SSL bypass is enabled!! Use at your own risk!!"); } log(message, ...args) { console.log(`\x1b[36m[Confluence Loader]\x1b[0m ${message}`, ...args); } get authorizationHeader() { if (this.personalAccessToken) { return `Bearer ${this.personalAccessToken}`; } else if (this.username && this.accessToken) { const authToken = Buffer.from( `${this.username}:${this.accessToken}` ).toString("base64"); return `Basic ${authToken}`; } return undefined; } async load(options) { try { const pages = await this.fetchAllPagesInSpace( options?.start, options?.limit ); return pages.map((page) => this.createDocumentFromPage(page)); } catch (error) { this.log("Error:", error); return []; } } async fetchConfluenceData(url) { try { const initialHeaders = { "Content-Type": "application/json", Accept: "application/json", }; const authHeader = this.authorizationHeader; if (authHeader) initialHeaders.Authorization = authHeader; // If SSL bypass is enabled, set the NODE_TLS_REJECT_UNAUTHORIZED environment variable if (this.bypassSSL) process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; const response = await fetch(url, { headers: initialHeaders }); if (!response.ok) { throw new Error( `Failed to fetch ${url} from Confluence: ${response.status}` ); } return await response.json(); } catch (error) { this.log("Error:", error); throw new Error(error.message); } finally { if (this.bypassSSL) process.env.NODE_TLS_REJECT_UNAUTHORIZED = "1"; } } // https://developer.atlassian.com/cloud/confluence/rest/v2/intro/#auth async fetchAllPagesInSpace(start = 0, limit = this.limit) { const url = `${this.baseUrl}${ this.cloud ? "/wiki" : "" }/rest/api/content?spaceKey=${ this.spaceKey }&limit=${limit}&start=${start}&expand=${this.expand}`; const data = await this.fetchConfluenceData(url); if (data.size === 0) { return []; } const nextPageStart = start + data.size; const nextPageResults = await this.fetchAllPagesInSpace( nextPageStart, limit ); return data.results.concat(nextPageResults); } createDocumentFromPage(page) { // Function to extract code blocks const extractCodeBlocks = (content) => { const codeBlockRegex = /<ac:structured-macro ac:name="code"[^>]*>[\s\S]*?<ac:plain-text-body><!\[CDATA\[([\s\S]*?)\]\]><\/ac:plain-text-body>[\s\S]*?<\/ac:structured-macro>/g; const languageRegex = /<ac:parameter ac:name="language">(.*?)<\/ac:parameter>/; return content.replace(codeBlockRegex, (match) => { const language = match.match(languageRegex)?.[1] || ""; const code = match.match( /<ac:plain-text-body><!\[CDATA\[([\s\S]*?)\]\]><\/ac:plain-text-body>/ )?.[1] || ""; return `\n\`\`\`${language}\n${code.trim()}\n\`\`\`\n`; }); }; const contentWithCodeBlocks = extractCodeBlocks(page.body.storage.value); const plainTextContent = htmlToText(contentWithCodeBlocks, { wordwrap: false, preserveNewlines: true, }); const textWithPreservedStructure = plainTextContent.replace( /\n{3,}/g, "\n\n" ); const pageUrl = `${this.baseUrl}/spaces/${this.spaceKey}/pages/${page.id}`; return { pageContent: textWithPreservedStructure, metadata: { id: page.id, status: page.status, title: page.title, type: page.type, url: pageUrl, version: page.version?.number, updated_by: page.version?.by?.displayName, updated_at: page.version?.when, }, }; } } module.exports = { ConfluencePagesLoader };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/RepoLoader/index.js
collector/utils/extensions/RepoLoader/index.js
/** * Dynamically load the correct repository loader from a specific platform * by default will return GitHub. * @param {('github'|'gitlab')} platform * @returns {import("./GithubRepo/RepoLoader")|import("./GitlabRepo/RepoLoader")} the repo loader class for provider */ function resolveRepoLoader(platform = "github") { switch (platform) { case "github": console.log(`Loading GitHub RepoLoader...`); return require("./GithubRepo/RepoLoader"); case "gitlab": console.log(`Loading GitLab RepoLoader...`); return require("./GitlabRepo/RepoLoader"); default: console.log(`Loading GitHub RepoLoader...`); return require("./GithubRepo/RepoLoader"); } } /** * Dynamically load the correct repository loader function from a specific platform * by default will return Github. * @param {('github'|'gitlab')} platform * @returns {import("./GithubRepo")['fetchGithubFile'] | import("./GitlabRepo")['fetchGitlabFile']} the repo loader class for provider */ function resolveRepoLoaderFunction(platform = "github") { switch (platform) { case "github": console.log(`Loading GitHub loader function...`); return require("./GithubRepo").loadGithubRepo; case "gitlab": console.log(`Loading GitLab loader function...`); return require("./GitlabRepo").loadGitlabRepo; default: console.log(`Loading GitHub loader function...`); return require("./GithubRepo").loadGithubRepo; } } module.exports = { resolveRepoLoader, resolveRepoLoaderFunction };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/RepoLoader/GithubRepo/index.js
collector/utils/extensions/RepoLoader/GithubRepo/index.js
const RepoLoader = require("./RepoLoader"); const fs = require("fs"); const path = require("path"); const { default: slugify } = require("slugify"); const { v4 } = require("uuid"); const { writeToServerDocuments } = require("../../../files"); const { tokenizeString } = require("../../../tokenizer"); /** * Load in a GitHub Repo recursively or just the top level if no PAT is provided * @param {object} args - forwarded request body params * @param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker * @returns */ async function loadGithubRepo(args, response) { const repo = new RepoLoader(args); await repo.init(); if (!repo.ready) return { success: false, reason: "Could not prepare GitHub repo for loading! Check URL", }; console.log( `-- Working GitHub ${repo.author}/${repo.project}:${repo.branch} --` ); const docs = await repo.recursiveLoader(); if (!docs.length) { return { success: false, reason: "No files were found for those settings.", }; } console.log(`[GitHub Loader]: Found ${docs.length} source files. Saving...`); const outFolder = slugify( `${repo.author}-${repo.project}-${repo.branch}-${v4().slice(0, 4)}` ).toLowerCase(); const outFolderPath = process.env.NODE_ENV === "development" ? path.resolve( __dirname, `../../../../../server/storage/documents/${outFolder}` ) : path.resolve(process.env.STORAGE_DIR, `documents/${outFolder}`); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); for (const doc of docs) { if (!doc.pageContent) continue; const data = { id: v4(), url: "github://" + doc.metadata.source, title: doc.metadata.source, docAuthor: repo.author, description: "No description found.", docSource: doc.metadata.source, chunkSource: generateChunkSource( repo, doc, response.locals.encryptionWorker ), published: new Date().toLocaleString(), wordCount: doc.pageContent.split(" ").length, pageContent: doc.pageContent, token_count_estimate: tokenizeString(doc.pageContent), }; console.log( `[GitHub Loader]: Saving ${doc.metadata.source} to ${outFolder}` ); writeToServerDocuments({ data, filename: `${slugify(doc.metadata.source)}-${data.id}`, destinationOverride: outFolderPath, }); } return { success: true, reason: null, data: { author: repo.author, repo: repo.project, branch: repo.branch, files: docs.length, destination: outFolder, }, }; } /** * Gets the page content from a specific source file in a give GitHub Repo, not all items in a repo. * @returns */ async function fetchGithubFile({ repoUrl, branch, accessToken = null, sourceFilePath, }) { const repo = new RepoLoader({ repo: repoUrl, branch, accessToken, }); await repo.init(); if (!repo.ready) return { success: false, content: null, reason: "Could not prepare GitHub repo for loading! Check URL or PAT.", }; console.log( `-- Working GitHub ${repo.author}/${repo.project}:${repo.branch} file:${sourceFilePath} --` ); const fileContent = await repo.fetchSingleFile(sourceFilePath); if (!fileContent) { return { success: false, reason: "Target file returned a null content response.", content: null, }; } return { success: true, reason: null, content: fileContent, }; } /** * Generate the full chunkSource for a specific file so that we can resync it later. * This data is encrypted into a single `payload` query param so we can replay credentials later * since this was encrypted with the systems persistent password and salt. * @param {RepoLoader} repo * @param {import("@langchain/core/documents").Document} doc * @param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker * @returns {string} */ function generateChunkSource(repo, doc, encryptionWorker) { const payload = { owner: repo.author, project: repo.project, branch: repo.branch, path: doc.metadata.source, pat: !!repo.accessToken ? repo.accessToken : null, }; return `github://${repo.repo}?payload=${encryptionWorker.encrypt( JSON.stringify(payload) )}`; } module.exports = { loadGithubRepo, fetchGithubFile };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js
collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js
/** * @typedef {Object} RepoLoaderArgs * @property {string} repo - The GitHub repository URL. * @property {string} [branch] - The branch to load from (optional). * @property {string} [accessToken] - GitHub access token for authentication (optional). * @property {string[]} [ignorePaths] - Array of paths to ignore when loading (optional). */ /** * @class * @classdesc Loads and manages GitHub repository content. */ class GitHubRepoLoader { /** * Creates an instance of RepoLoader. * @param {RepoLoaderArgs} [args] - The configuration options. * @returns {GitHubRepoLoader} */ constructor(args = {}) { this.ready = false; this.repo = this.#processRepoUrl(args?.repo); this.branch = args?.branch; this.accessToken = args?.accessToken || null; this.ignorePaths = args?.ignorePaths || []; this.author = null; this.project = null; this.branches = []; } /** * Processes a repository URL to ensure it is in the correct format * - remove the .git suffix if present * - ensure the url is valid * @param {string} repoUrl - The repository URL to process. * @returns {string|null} The processed repository URL, or null if the URL is invalid. */ #processRepoUrl(repoUrl) { if (!repoUrl) return repoUrl; try { const url = new URL(repoUrl); if (url.pathname.endsWith(".git")) url.pathname = url.pathname.slice(0, -4); return url.toString(); } catch (e) { console.error( `[GitHub Loader]: Error processing repository URL ${this.repo}: ${e.message}` ); return repoUrl; } } /** * Validates the GitHub URL format. * - ensure the url is valid * - ensure the hostname is github.com * - ensure the pathname is in the format of github.com/{author}/{project} * - sets the author and project properties of class instance * @returns {boolean} True if the URL is valid, false otherwise. */ #validGithubUrl() { try { const url = new URL(this.repo); // Not a github url at all. if (url.hostname !== "github.com") { console.log( `[GitHub Loader]: Invalid GitHub URL provided! Hostname must be 'github.com'. Got ${url.hostname}` ); return false; } // Assume the url is in the format of github.com/{author}/{project} // Remove the first slash from the pathname so we can split it properly. const [author, project, ..._rest] = url.pathname.slice(1).split("/"); if (!author || !project) { console.log( `[GitHub Loader]: Invalid GitHub URL provided! URL must be in the format of 'github.com/{author}/{project}'. Got ${url.pathname}` ); return false; } this.author = author; this.project = project; return true; } catch (e) { console.log( `[GitHub Loader]: Invalid GitHub URL provided! Error: ${e.message}` ); return false; } } // Ensure the branch provided actually exists // and if it does not or has not been set auto-assign to primary branch. async #validBranch() { await this.getRepoBranches(); if (!!this.branch && this.branches.includes(this.branch)) return; console.log( "[GitHub Loader]: Branch not set! Auto-assigning to a default branch." ); this.branch = this.branches.includes("main") ? "main" : "master"; console.log(`[GitHub Loader]: Branch auto-assigned to ${this.branch}.`); return; } async #validateAccessToken() { if (!this.accessToken) return; const valid = await fetch("https://api.github.com/octocat", { method: "GET", headers: { Authorization: `Bearer ${this.accessToken}`, "X-GitHub-Api-Version": "2022-11-28", }, }) .then((res) => { if (!res.ok) throw new Error(res.statusText); return res.ok; }) .catch((e) => { console.error( "Invalid GitHub Access Token provided! Access token will not be used", e.message ); return false; }); if (!valid) this.accessToken = null; return; } /** * Initializes the RepoLoader instance. * @returns {Promise<RepoLoader>} The initialized RepoLoader instance. */ async init() { if (!this.#validGithubUrl()) return; await this.#validBranch(); await this.#validateAccessToken(); this.ready = true; return this; } /** * Recursively loads the repository content. * @returns {Promise<Array<Object>>} An array of loaded documents. * @throws {Error} If the RepoLoader is not in a ready state. */ async recursiveLoader() { if (!this.ready) throw new Error("[GitHub Loader]: not in ready state!"); const { GithubRepoLoader: LCGithubLoader, } = require("@langchain/community/document_loaders/web/github"); if (this.accessToken) console.log( `[GitHub Loader]: Access token set! Recursive loading enabled!` ); const loader = new LCGithubLoader(this.repo, { branch: this.branch, recursive: !!this.accessToken, // Recursive will hit rate limits. maxConcurrency: 5, unknown: "warn", accessToken: this.accessToken, ignorePaths: this.ignorePaths, verbose: true, }); const docs = await loader.load(); return docs; } // Sort branches to always show either main or master at the top of the result. #branchPrefSort(branches = []) { const preferredSort = ["main", "master"]; return branches.reduce((acc, branch) => { if (preferredSort.includes(branch)) return [branch, ...acc]; return [...acc, branch]; }, []); } /** * Retrieves all branches for the repository. * @returns {Promise<string[]>} An array of branch names. */ async getRepoBranches() { if (!this.#validGithubUrl() || !this.author || !this.project) return []; await this.#validateAccessToken(); // Ensure API access token is valid for pre-flight let page = 0; let polling = true; const branches = []; while (polling) { console.log(`Fetching page ${page} of branches for ${this.project}`); await fetch( `https://api.github.com/repos/${this.author}/${this.project}/branches?per_page=100&page=${page}`, { method: "GET", headers: { ...(this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}), "X-GitHub-Api-Version": "2022-11-28", }, } ) .then((res) => { if (res.ok) return res.json(); throw new Error(`Invalid request to Github API: ${res.statusText}`); }) .then((branchObjects) => { polling = branchObjects.length > 0; branches.push(branchObjects.map((branch) => branch.name)); page++; }) .catch((err) => { polling = false; console.log(`RepoLoader.branches`, err); }); } this.branches = [...new Set(branches.flat())]; return this.#branchPrefSort(this.branches); } /** * Fetches the content of a single file from the repository. * @param {string} sourceFilePath - The path to the file in the repository. * @returns {Promise<string|null>} The content of the file, or null if fetching fails. */ async fetchSingleFile(sourceFilePath) { try { return fetch( `https://api.github.com/repos/${this.author}/${this.project}/contents/${sourceFilePath}?ref=${this.branch}`, { method: "GET", headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", ...(!!this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}), }, } ) .then((res) => { if (res.ok) return res.json(); throw new Error(`Failed to fetch from Github API: ${res.statusText}`); }) .then((json) => { if (json.hasOwnProperty("status") || !json.hasOwnProperty("content")) throw new Error(json?.message || "missing content"); return atob(json.content); }); } catch (e) { console.error(`RepoLoader.fetchSingleFile`, e); return null; } } } module.exports = GitHubRepoLoader;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/collector/utils/extensions/RepoLoader/GitlabRepo/index.js
collector/utils/extensions/RepoLoader/GitlabRepo/index.js
const RepoLoader = require("./RepoLoader"); const fs = require("fs"); const path = require("path"); const { default: slugify } = require("slugify"); const { v4 } = require("uuid"); const { sanitizeFileName, writeToServerDocuments } = require("../../../files"); const { tokenizeString } = require("../../../tokenizer"); /** * Load in a Gitlab Repo recursively or just the top level if no PAT is provided * @param {object} args - forwarded request body params * @param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker * @returns */ async function loadGitlabRepo(args, response) { const repo = new RepoLoader(args); await repo.init(); if (!repo.ready) return { success: false, reason: "Could not prepare Gitlab repo for loading! Check URL", }; console.log( `-- Working GitLab ${repo.author}/${repo.project}:${repo.branch} --` ); const docs = await repo.recursiveLoader(); if (!docs.length) { return { success: false, reason: "No files were found for those settings.", }; } console.log(`[GitLab Loader]: Found ${docs.length} source files. Saving...`); const outFolder = slugify( `${repo.author}-${repo.project}-${repo.branch}-${v4().slice(0, 4)}` ).toLowerCase(); const outFolderPath = process.env.NODE_ENV === "development" ? path.resolve( __dirname, `../../../../../server/storage/documents/${outFolder}` ) : path.resolve(process.env.STORAGE_DIR, `documents/${outFolder}`); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); for (const doc of docs) { if (!doc.metadata || (!doc.pageContent && !doc.issue && !doc.wiki)) continue; let pageContent = null; const data = { id: v4(), url: "gitlab://" + doc.metadata.source, docSource: doc.metadata.source, chunkSource: generateChunkSource( repo, doc, response.locals.encryptionWorker ), published: new Date().toLocaleString(), }; if (doc.pageContent) { pageContent = doc.pageContent; data.title = doc.metadata.source; data.docAuthor = repo.author; data.description = "No description found."; } else if (doc.issue) { pageContent = issueToMarkdown(doc.issue); data.title = `Issue ${doc.issue.iid}: ${doc.issue.title}`; data.docAuthor = doc.issue.author.username; data.description = doc.issue.description; } else if (doc.wiki) { pageContent = doc.wiki.content; data.title = doc.wiki.title; data.docAuthor = repo.author; data.description = doc.wiki.format === "markdown" ? "GitLab Wiki Page (Markdown)" : "GitLab Wiki Page"; } else { continue; } data.wordCount = pageContent.split(" ").length; data.token_count_estimate = tokenizeString(pageContent); data.pageContent = pageContent; console.log( `[GitLab Loader]: Saving ${doc.metadata.source} to ${outFolder}` ); writeToServerDocuments({ data, filename: sanitizeFileName(`${slugify(doc.metadata.source)}-${data.id}`), destinationOverride: outFolderPath, }); } return { success: true, reason: null, data: { author: repo.author, repo: repo.project, projectId: repo.projectId, branch: repo.branch, files: docs.length, destination: outFolder, }, }; } async function fetchGitlabFile({ repoUrl, branch, accessToken = null, sourceFilePath, }) { const repo = new RepoLoader({ repo: repoUrl, branch, accessToken, }); await repo.init(); if (!repo.ready) return { success: false, content: null, reason: "Could not prepare GitLab repo for loading! Check URL or PAT.", }; console.log( `-- Working GitLab ${repo.author}/${repo.project}:${repo.branch} file:${sourceFilePath} --` ); const fileContent = await repo.fetchSingleFile(sourceFilePath); if (!fileContent) { return { success: false, reason: "Target file returned a null content response.", content: null, }; } return { success: true, reason: null, content: fileContent, }; } function generateChunkSource(repo, doc, encryptionWorker) { const payload = { projectId: decodeURIComponent(repo.projectId), branch: repo.branch, path: doc.metadata.source, pat: !!repo.accessToken ? repo.accessToken : null, }; return `gitlab://${repo.repo}?payload=${encryptionWorker.encrypt( JSON.stringify(payload) )}`; } function issueToMarkdown(issue) { const metadata = {}; const userFields = ["author", "assignees", "closed_by"]; const userToUsername = ({ username }) => username; for (const userField of userFields) { if (issue[userField]) { if (Array.isArray(issue[userField])) { metadata[userField] = issue[userField].map(userToUsername); } else { metadata[userField] = userToUsername(issue[userField]); } } } const singleValueFields = [ "web_url", "state", "created_at", "updated_at", "closed_at", "due_date", "type", "merge_request_count", "upvotes", "downvotes", "labels", "has_tasks", "task_status", "confidential", "severity", ]; for (const singleValueField of singleValueFields) { metadata[singleValueField] = issue[singleValueField]; } if (issue.milestone) { metadata.milestone = `${issue.milestone.title} (${issue.milestone.id})`; } if (issue.time_stats) { const timeFields = ["time_estimate", "total_time_spent"]; for (const timeField of timeFields) { const fieldName = `human_${timeField}`; if (issue?.time_stats[fieldName]) { metadata[timeField] = issue.time_stats[fieldName]; } } } const metadataString = Object.entries(metadata) .map(([name, value]) => { if (!value || value?.length < 1) { return null; } let result = `- ${name.replace("_", " ")}:`; if (!Array.isArray(value)) { result += ` ${value}`; } else { result += "\n" + value.map((s) => ` - ${s}`).join("\n"); } return result; }) .filter((item) => item != null) .join("\n"); let markdown = `# ${issue.title} (${issue.iid}) ${issue.description} ## Metadata ${metadataString}`; if (issue.discussions.length > 0) { markdown += ` ## Activity ${issue.discussions.join("\n\n")} `; } return markdown; } module.exports = { loadGitlabRepo, fetchGitlabFile };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false