Initial commit xmarticaims
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var registry = require('./registry.cjs');
|
||||
|
||||
|
||||
|
||||
exports.registerAdapter = registry.registerAdapter;
|
||||
@@ -0,0 +1 @@
|
||||
export { registerAdapter } from "./registry.js";
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
export { registerAdapter } from './registry.js';
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Anime.js adapter API. Each library or class group that wants to extend `animate()` and `utils.set()` calls `registerAdapter()` to create its own `Adapter`. The returned `Adapter` exposes `registerTargetAdapter(detect)` for per-class detection and `registerPropertyResolver(fn)` for global Color / Vector / pattern-based fallbacks.
|
||||
*
|
||||
* import { registerAdapter } from 'animejs/adapters';
|
||||
*
|
||||
* const myAdapter = registerAdapter();
|
||||
* const widget = myAdapter.registerTargetAdapter((t) => t instanceof MyWidget);
|
||||
* widget.registerProperty('value',
|
||||
* (t) => t.getValue(),
|
||||
* (target, value) => target.setValue(value),
|
||||
* );
|
||||
*
|
||||
* For scalar tweens, `value` is the interpolated number. For color and complex tweens it is `undefined`; read `tween._numbers` instead. `gate(target)` scopes the prop to a subset of matching targets.
|
||||
*
|
||||
* Resolution order: every Adapter's target adapters in registration order (first match wins) then every Adapter's property resolvers (first non-null wins) then engine direct property path.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef TargetAdapterEntry
|
||||
* @property {(t: any) => any} get
|
||||
* @property {(target: any, value: number, tween: any) => void} set
|
||||
* @property {(t: any) => boolean} [gate]
|
||||
*/
|
||||
|
||||
const alwaysTrue = () => true;
|
||||
|
||||
class TargetAdapter {
|
||||
/**
|
||||
* @param {(t: any) => boolean} detect
|
||||
*/
|
||||
constructor(detect) {
|
||||
this.detect = detect;
|
||||
/** @type {Record<string, TargetAdapterEntry>} */
|
||||
this.props = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a property the adapter handles. `setter` receives `(target, value, tween)`. For color and complex tweens `value` is `undefined`, read `tween._numbers` instead. `gate(target)` scopes the prop to a subset of matching targets.
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {(t: any) => any} getter
|
||||
* @param {(target: any, value: number, tween: any) => void} setter
|
||||
* @param {(t: any) => boolean} [gate]
|
||||
*/
|
||||
registerProperty(name, getter, setter, gate) {
|
||||
this.props[name] = {
|
||||
get: getter,
|
||||
set: setter,
|
||||
gate: gate || alwaysTrue,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class Adapter {
|
||||
/**
|
||||
* @param {((t: any) => boolean) | null} [detect]
|
||||
* Optional gate. When provided, every lookup against this Adapter's target adapters and resolvers is skipped if `detect(target)` returns falsy. Lets the Adapter as a whole short-circuit on unrelated targets.
|
||||
*/
|
||||
constructor(detect) {
|
||||
/** @type {((t: any) => boolean) | null} */
|
||||
this.detect = detect || null;
|
||||
/** @type {TargetAdapter[]} */
|
||||
this.targetAdapters = [];
|
||||
/** @type {((target: any, name: string) => TargetAdapterEntry | null)[]} */
|
||||
this.propertyResolvers = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and registers a `TargetAdapter` scoped to this Adapter.
|
||||
*
|
||||
* @param {(t: any) => boolean} detect
|
||||
* @return {TargetAdapter}
|
||||
*/
|
||||
registerTargetAdapter(detect) {
|
||||
const ta = new TargetAdapter(detect);
|
||||
this.targetAdapters.push(ta);
|
||||
return ta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a property resolver scoped to this Adapter. Resolvers are functions invoked at tween creation when no target adapter has claimed the name; the function returns an entry for names it handles or `null` to defer. Use for runtime-matched patterns (Color / Vector axis detection, name-prefix conventions, etc.).
|
||||
*
|
||||
* @param {(target: any, name: string) => TargetAdapterEntry | null} resolver
|
||||
*/
|
||||
registerPropertyResolver(resolver) {
|
||||
if (this.propertyResolvers.indexOf(resolver) === -1) this.propertyResolvers.push(resolver);
|
||||
}
|
||||
}
|
||||
|
||||
const adapters = /** @type {Adapter[]} */([]);
|
||||
|
||||
/**
|
||||
* Creates and registers an Adapter. Each library extending `animate()` calls this once and uses the returned Adapter to wire up its target adapters and property resolvers. The optional `detect` short-circuits all lookups against the Adapter when the target is unrelated.
|
||||
*
|
||||
* @param {(t: any) => boolean} [detect]
|
||||
* @return {Adapter}
|
||||
*/
|
||||
function registerAdapter(detect) {
|
||||
const a = new Adapter(detect);
|
||||
adapters.push(a);
|
||||
return a;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal resolution. Tries every Adapter's target adapters first (in registration order, first match wins), then every Adapter's property resolvers.
|
||||
*
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @return {TargetAdapterEntry | null}
|
||||
*/
|
||||
function resolveAdapterEntry(target, name) {
|
||||
if (!target) return null;
|
||||
const al = adapters.length;
|
||||
outer: for (let i = 0; i < al; i++) {
|
||||
const a = adapters[i];
|
||||
if (a.detect && !a.detect(target)) continue;
|
||||
const tas = a.targetAdapters;
|
||||
for (let j = 0, m = tas.length; j < m; j++) {
|
||||
const ta = tas[j];
|
||||
if (ta.detect(target)) {
|
||||
const entry = ta.props[name];
|
||||
if (entry && (!entry.gate || entry.gate(target))) return entry;
|
||||
break outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < al; i++) {
|
||||
const a = adapters[i];
|
||||
if (a.detect && !a.detect(target)) continue;
|
||||
const rs = a.propertyResolvers;
|
||||
for (let j = 0, m = rs.length; j < m; j++) {
|
||||
const entry = rs[j](target, name);
|
||||
if (entry) return entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
exports.registerAdapter = registerAdapter;
|
||||
exports.resolveAdapterEntry = resolveAdapterEntry;
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Creates and registers an Adapter. Each library extending `animate()` calls this once and uses the returned Adapter to wire up its target adapters and property resolvers. The optional `detect` short-circuits all lookups against the Adapter when the target is unrelated.
|
||||
*
|
||||
* @param {(t: any) => boolean} [detect]
|
||||
* @return {Adapter}
|
||||
*/
|
||||
export function registerAdapter(detect?: (t: any) => boolean): Adapter;
|
||||
/**
|
||||
* Internal resolution. Tries every Adapter's target adapters first (in registration order, first match wins), then every Adapter's property resolvers.
|
||||
*
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @return {TargetAdapterEntry | null}
|
||||
*/
|
||||
export function resolveAdapterEntry(target: any, name: string): TargetAdapterEntry | null;
|
||||
export type TargetAdapterEntry = {
|
||||
get: (t: any) => any;
|
||||
set: (target: any, value: number, tween: any) => void;
|
||||
gate?: (t: any) => boolean;
|
||||
};
|
||||
declare class Adapter {
|
||||
/**
|
||||
* @param {((t: any) => boolean) | null} [detect]
|
||||
* Optional gate. When provided, every lookup against this Adapter's target adapters and resolvers is skipped if `detect(target)` returns falsy. Lets the Adapter as a whole short-circuit on unrelated targets.
|
||||
*/
|
||||
constructor(detect?: ((t: any) => boolean) | null);
|
||||
/** @type {((t: any) => boolean) | null} */
|
||||
detect: ((t: any) => boolean) | null;
|
||||
/** @type {TargetAdapter[]} */
|
||||
targetAdapters: TargetAdapter[];
|
||||
/** @type {((target: any, name: string) => TargetAdapterEntry | null)[]} */
|
||||
propertyResolvers: ((target: any, name: string) => TargetAdapterEntry | null)[];
|
||||
/**
|
||||
* Creates and registers a `TargetAdapter` scoped to this Adapter.
|
||||
*
|
||||
* @param {(t: any) => boolean} detect
|
||||
* @return {TargetAdapter}
|
||||
*/
|
||||
registerTargetAdapter(detect: (t: any) => boolean): TargetAdapter;
|
||||
/**
|
||||
* Registers a property resolver scoped to this Adapter. Resolvers are functions invoked at tween creation when no target adapter has claimed the name; the function returns an entry for names it handles or `null` to defer. Use for runtime-matched patterns (Color / Vector axis detection, name-prefix conventions, etc.).
|
||||
*
|
||||
* @param {(target: any, name: string) => TargetAdapterEntry | null} resolver
|
||||
*/
|
||||
registerPropertyResolver(resolver: (target: any, name: string) => TargetAdapterEntry | null): void;
|
||||
}
|
||||
declare class TargetAdapter {
|
||||
/**
|
||||
* @param {(t: any) => boolean} detect
|
||||
*/
|
||||
constructor(detect: (t: any) => boolean);
|
||||
detect: (t: any) => boolean;
|
||||
/** @type {Record<string, TargetAdapterEntry>} */
|
||||
props: Record<string, TargetAdapterEntry>;
|
||||
/**
|
||||
* Registers a property the adapter handles. `setter` receives `(target, value, tween)`. For color and complex tweens `value` is `undefined`, read `tween._numbers` instead. `gate(target)` scopes the prop to a subset of matching targets.
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {(t: any) => any} getter
|
||||
* @param {(target: any, value: number, tween: any) => void} setter
|
||||
* @param {(t: any) => boolean} [gate]
|
||||
*/
|
||||
registerProperty(name: string, getter: (t: any) => any, setter: (target: any, value: number, tween: any) => void, gate?: (t: any) => boolean): void;
|
||||
}
|
||||
export {};
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
/**
|
||||
* Anime.js adapter API. Each library or class group that wants to extend `animate()` and `utils.set()` calls `registerAdapter()` to create its own `Adapter`. The returned `Adapter` exposes `registerTargetAdapter(detect)` for per-class detection and `registerPropertyResolver(fn)` for global Color / Vector / pattern-based fallbacks.
|
||||
*
|
||||
* import { registerAdapter } from 'animejs/adapters';
|
||||
*
|
||||
* const myAdapter = registerAdapter();
|
||||
* const widget = myAdapter.registerTargetAdapter((t) => t instanceof MyWidget);
|
||||
* widget.registerProperty('value',
|
||||
* (t) => t.getValue(),
|
||||
* (target, value) => target.setValue(value),
|
||||
* );
|
||||
*
|
||||
* For scalar tweens, `value` is the interpolated number. For color and complex tweens it is `undefined`; read `tween._numbers` instead. `gate(target)` scopes the prop to a subset of matching targets.
|
||||
*
|
||||
* Resolution order: every Adapter's target adapters in registration order (first match wins) then every Adapter's property resolvers (first non-null wins) then engine direct property path.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef TargetAdapterEntry
|
||||
* @property {(t: any) => any} get
|
||||
* @property {(target: any, value: number, tween: any) => void} set
|
||||
* @property {(t: any) => boolean} [gate]
|
||||
*/
|
||||
|
||||
const alwaysTrue = () => true;
|
||||
|
||||
class TargetAdapter {
|
||||
/**
|
||||
* @param {(t: any) => boolean} detect
|
||||
*/
|
||||
constructor(detect) {
|
||||
this.detect = detect;
|
||||
/** @type {Record<string, TargetAdapterEntry>} */
|
||||
this.props = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a property the adapter handles. `setter` receives `(target, value, tween)`. For color and complex tweens `value` is `undefined`, read `tween._numbers` instead. `gate(target)` scopes the prop to a subset of matching targets.
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {(t: any) => any} getter
|
||||
* @param {(target: any, value: number, tween: any) => void} setter
|
||||
* @param {(t: any) => boolean} [gate]
|
||||
*/
|
||||
registerProperty(name, getter, setter, gate) {
|
||||
this.props[name] = {
|
||||
get: getter,
|
||||
set: setter,
|
||||
gate: gate || alwaysTrue,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class Adapter {
|
||||
/**
|
||||
* @param {((t: any) => boolean) | null} [detect]
|
||||
* Optional gate. When provided, every lookup against this Adapter's target adapters and resolvers is skipped if `detect(target)` returns falsy. Lets the Adapter as a whole short-circuit on unrelated targets.
|
||||
*/
|
||||
constructor(detect) {
|
||||
/** @type {((t: any) => boolean) | null} */
|
||||
this.detect = detect || null;
|
||||
/** @type {TargetAdapter[]} */
|
||||
this.targetAdapters = [];
|
||||
/** @type {((target: any, name: string) => TargetAdapterEntry | null)[]} */
|
||||
this.propertyResolvers = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and registers a `TargetAdapter` scoped to this Adapter.
|
||||
*
|
||||
* @param {(t: any) => boolean} detect
|
||||
* @return {TargetAdapter}
|
||||
*/
|
||||
registerTargetAdapter(detect) {
|
||||
const ta = new TargetAdapter(detect);
|
||||
this.targetAdapters.push(ta);
|
||||
return ta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a property resolver scoped to this Adapter. Resolvers are functions invoked at tween creation when no target adapter has claimed the name; the function returns an entry for names it handles or `null` to defer. Use for runtime-matched patterns (Color / Vector axis detection, name-prefix conventions, etc.).
|
||||
*
|
||||
* @param {(target: any, name: string) => TargetAdapterEntry | null} resolver
|
||||
*/
|
||||
registerPropertyResolver(resolver) {
|
||||
if (this.propertyResolvers.indexOf(resolver) === -1) this.propertyResolvers.push(resolver);
|
||||
}
|
||||
}
|
||||
|
||||
const adapters = /** @type {Adapter[]} */([]);
|
||||
|
||||
/**
|
||||
* Creates and registers an Adapter. Each library extending `animate()` calls this once and uses the returned Adapter to wire up its target adapters and property resolvers. The optional `detect` short-circuits all lookups against the Adapter when the target is unrelated.
|
||||
*
|
||||
* @param {(t: any) => boolean} [detect]
|
||||
* @return {Adapter}
|
||||
*/
|
||||
function registerAdapter(detect) {
|
||||
const a = new Adapter(detect);
|
||||
adapters.push(a);
|
||||
return a;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal resolution. Tries every Adapter's target adapters first (in registration order, first match wins), then every Adapter's property resolvers.
|
||||
*
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @return {TargetAdapterEntry | null}
|
||||
*/
|
||||
function resolveAdapterEntry(target, name) {
|
||||
if (!target) return null;
|
||||
const al = adapters.length;
|
||||
outer: for (let i = 0; i < al; i++) {
|
||||
const a = adapters[i];
|
||||
if (a.detect && !a.detect(target)) continue;
|
||||
const tas = a.targetAdapters;
|
||||
for (let j = 0, m = tas.length; j < m; j++) {
|
||||
const ta = tas[j];
|
||||
if (ta.detect(target)) {
|
||||
const entry = ta.props[name];
|
||||
if (entry && (!entry.gate || entry.gate(target))) return entry;
|
||||
break outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < al; i++) {
|
||||
const a = adapters[i];
|
||||
if (a.detect && !a.detect(target)) continue;
|
||||
const rs = a.propertyResolvers;
|
||||
for (let j = 0, m = rs.length; j < m; j++) {
|
||||
const entry = rs[j](target, name);
|
||||
if (entry) return entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export { registerAdapter, resolveAdapterEntry };
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var registry = require('../registry.cjs');
|
||||
|
||||
// Duck-typed gate for three.js targets, used as threeAdapter's Adapter-level detect.
|
||||
// Early-rejects DOM nodes via nodeType so the OR chain only runs on non-DOM objects.
|
||||
// Includes the isAnimejsInstanceProxy marker set in instance.js for per-instance wrappers.
|
||||
const isThreeTarget = (t) => !!(
|
||||
t && !t.nodeType && (
|
||||
t.isObject3D || t.isMaterial || t.isTexture ||
|
||||
t.isFog || t.isFogExp2 || t.isUniformNode ||
|
||||
t.isColor || t.isVector2 || t.isVector3 || t.isVector4 ||
|
||||
t.isAnimejsInstanceProxy
|
||||
)
|
||||
);
|
||||
|
||||
const threeAdapter = registry.registerAdapter(isThreeTarget);
|
||||
|
||||
exports.threeAdapter = threeAdapter;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
export const threeAdapter: {
|
||||
detect: (t: any) => boolean;
|
||||
targetAdapters: {
|
||||
detect: (t: any) => boolean;
|
||||
props: Record<string, import("../registry.js").TargetAdapterEntry>;
|
||||
registerProperty(name: string, getter: (t: any) => any, setter: (target: any, value: number, tween: any) => void, gate?: (t: any) => boolean): void;
|
||||
}[];
|
||||
propertyResolvers: ((target: any, name: string) => import("../registry.js").TargetAdapterEntry | null)[];
|
||||
registerTargetAdapter(detect: (t: any) => boolean): {
|
||||
detect: (t: any) => boolean;
|
||||
props: Record<string, import("../registry.js").TargetAdapterEntry>;
|
||||
registerProperty(name: string, getter: (t: any) => any, setter: (target: any, value: number, tween: any) => void, gate?: (t: any) => boolean): void;
|
||||
};
|
||||
registerPropertyResolver(resolver: (target: any, name: string) => TargetAdapterEntry | null): void;
|
||||
};
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { registerAdapter } from '../registry.js';
|
||||
|
||||
// Duck-typed gate for three.js targets, used as threeAdapter's Adapter-level detect.
|
||||
// Early-rejects DOM nodes via nodeType so the OR chain only runs on non-DOM objects.
|
||||
// Includes the isAnimejsInstanceProxy marker set in instance.js for per-instance wrappers.
|
||||
const isThreeTarget = (t) => !!(
|
||||
t && !t.nodeType && (
|
||||
t.isObject3D || t.isMaterial || t.isTexture ||
|
||||
t.isFog || t.isFogExp2 || t.isUniformNode ||
|
||||
t.isColor || t.isVector2 || t.isVector3 || t.isVector4 ||
|
||||
t.isAnimejsInstanceProxy
|
||||
)
|
||||
);
|
||||
|
||||
const threeAdapter = registerAdapter(isThreeTarget);
|
||||
|
||||
export { threeAdapter };
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var three = require('three');
|
||||
var number = require('../../utils/number.cjs');
|
||||
|
||||
/**
|
||||
* Generic read/write helpers for the three.js bindings. Each operates on a target (or target array) and walks to the leaf via a path tag - direct (`target[name]`), uniform (`target.uniforms[name].value`), or TSL node (`target[name].value`). Adapter and resolver files pass the matching `PATH_*` constant; the JIT specializes each call site so the branch in `leafAt` / `writeLeafScalar` constant-folds.
|
||||
*/
|
||||
|
||||
|
||||
const COLOR_NORM = 1 / 255;
|
||||
|
||||
const AXIS_MAP = /** @type {Record<string, 'x' | 'y' | 'z' | 'w'>} */({ X: 'x', Y: 'y', Z: 'z', W: 'w' });
|
||||
|
||||
const PATH_DIRECT = 0;
|
||||
const PATH_UNIFORM = 1;
|
||||
const PATH_NODE = 2;
|
||||
|
||||
const KIND_COLOR = 0;
|
||||
const KIND_SCALAR = 1;
|
||||
const KIND_VECTOR = 2;
|
||||
|
||||
// Reuse one mutable descriptor across calls, callers must consume immediately since the next call mutates it.
|
||||
const desc = { kind: 0, path: 0, base: '', axis: /** @type {'x' | 'y' | 'z' | 'w'} */('x') };
|
||||
|
||||
/**
|
||||
* Patches a column-major `Matrix4.elements` array in place with CSS-style `skewX(α)` / `skewY(β)`, the 3D extension `skewZ(γ)` (shears z by x), and a `transform-origin` shift.
|
||||
*
|
||||
* @param {number[]} e
|
||||
* @param {number} skewX
|
||||
* @param {number} skewY
|
||||
* @param {number} skewZ
|
||||
* @param {number} ox
|
||||
* @param {number} oy
|
||||
* @param {number} oz
|
||||
*/
|
||||
function applySkewOrigin(e, skewX, skewY, skewZ, ox, oy, oz) {
|
||||
if (skewX !== 0) {
|
||||
const t = Math.tan(number.degToRad(skewX));
|
||||
e[4] += e[0] * t;
|
||||
e[5] += e[1] * t;
|
||||
e[6] += e[2] * t;
|
||||
}
|
||||
if (skewY !== 0) {
|
||||
const t = Math.tan(number.degToRad(skewY));
|
||||
e[0] += e[4] * t;
|
||||
e[1] += e[5] * t;
|
||||
e[2] += e[6] * t;
|
||||
}
|
||||
if (skewZ !== 0) {
|
||||
const t = Math.tan(number.degToRad(skewZ));
|
||||
e[0] += e[8] * t;
|
||||
e[1] += e[9] * t;
|
||||
e[2] += e[10] * t;
|
||||
}
|
||||
if (ox !== 0 || oy !== 0 || oz !== 0) {
|
||||
e[12] += ox - (e[0] * ox + e[4] * oy + e[8] * oz);
|
||||
e[13] += oy - (e[1] * ox + e[5] * oy + e[9] * oz);
|
||||
e[14] += oz - (e[2] * ox + e[6] * oy + e[10] * oz);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} c
|
||||
* @return {String | null}
|
||||
*/
|
||||
function readColorHex(c) {
|
||||
return c ? `#${c.getHexString(three.SRGBColorSpace)}` : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` when `v` is a `Vector2/3/4` instance whose dimension covers `axis`. `Quaternion` and plain `{x,y,z,w}`-shaped objects are intentionally rejected.
|
||||
*
|
||||
* @param {any} v
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @return {boolean}
|
||||
*/
|
||||
function isVectorWith(v, axis) {
|
||||
if (!v) return false;
|
||||
if (axis === 'x' || axis === 'y') return !!(v.isVector2 || v.isVector3 || v.isVector4);
|
||||
if (axis === 'z') return !!(v.isVector3 || v.isVector4);
|
||||
return !!v.isVector4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classifies `target[name]` and returns a descriptor `{ kind, path, base, axis }` (or `null`). Used by the resolver entries in `resolvers.js` and by the `Object3D` adapter to build the matching access pattern for any three.js target (Object3D, Material, Texture, Fog, UniformNode).
|
||||
*
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @return {{ kind: number, path: number, base: string, axis: 'x' | 'y' | 'z' | 'w' } | null}
|
||||
*/
|
||||
function classifyTargetProp(target, name) {
|
||||
const value = target[name];
|
||||
if (value !== undefined) {
|
||||
if (value && value.isColor) {
|
||||
desc.kind = KIND_COLOR; desc.path = PATH_DIRECT;
|
||||
return desc;
|
||||
}
|
||||
if (value && value.isUniformNode) {
|
||||
// Route TSL slot writes through node value, booleans share the scalar entry.
|
||||
const v = value.value;
|
||||
if (v && v.isColor) {
|
||||
desc.kind = KIND_COLOR; desc.path = PATH_NODE;
|
||||
return desc;
|
||||
}
|
||||
if (typeof v === 'number' || typeof v === 'boolean') {
|
||||
desc.kind = KIND_SCALAR; desc.path = PATH_NODE;
|
||||
return desc;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (typeof value === 'number' || typeof value === 'boolean') {
|
||||
desc.kind = KIND_SCALAR; desc.path = PATH_DIRECT;
|
||||
return desc;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const uniforms = target.uniforms;
|
||||
const u = uniforms && uniforms[name];
|
||||
if (u) {
|
||||
const uv = u.value;
|
||||
if (uv && uv.isColor) {
|
||||
desc.kind = KIND_COLOR; desc.path = PATH_UNIFORM;
|
||||
return desc;
|
||||
}
|
||||
if (typeof uv === 'number') {
|
||||
desc.kind = KIND_SCALAR; desc.path = PATH_UNIFORM;
|
||||
return desc;
|
||||
}
|
||||
}
|
||||
// Decompose vector axis for names like posX, uOffsetY, uVec4W, colorNodeX.
|
||||
const axis = AXIS_MAP[name[name.length - 1]];
|
||||
if (axis) {
|
||||
const base = name.slice(0, -1);
|
||||
if (isVectorWith(target[base], axis)) {
|
||||
desc.kind = KIND_VECTOR; desc.path = PATH_DIRECT; desc.base = base; desc.axis = axis;
|
||||
return desc;
|
||||
}
|
||||
const baseSlot = target[base];
|
||||
if (baseSlot && baseSlot.isUniformNode && isVectorWith(baseSlot.value, axis)) {
|
||||
desc.kind = KIND_VECTOR; desc.path = PATH_NODE; desc.base = base; desc.axis = axis;
|
||||
return desc;
|
||||
}
|
||||
const ub = uniforms && uniforms[base];
|
||||
if (ub && isVectorWith(ub.value, axis)) {
|
||||
desc.kind = KIND_VECTOR; desc.path = PATH_UNIFORM; desc.base = base; desc.axis = axis;
|
||||
return desc;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function leafAt(target, name, path) {
|
||||
if (path === PATH_DIRECT) return target[name];
|
||||
if (path === PATH_UNIFORM) {
|
||||
const u = target.uniforms;
|
||||
const e = u && u[name];
|
||||
return e ? e.value : null;
|
||||
}
|
||||
const n = target[name];
|
||||
return n ? n.value : null;
|
||||
}
|
||||
|
||||
function writeLeafScalar(target, name, v, path) {
|
||||
if (path === PATH_DIRECT) { target[name] = v; return; }
|
||||
if (path === PATH_UNIFORM) {
|
||||
const u = target.uniforms;
|
||||
const e = u && u[name];
|
||||
if (e) e.value = v;
|
||||
return;
|
||||
}
|
||||
const n = target[name];
|
||||
if (n) n.value = v;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} path
|
||||
* @param {number} [defaultValue]
|
||||
* @return {number}
|
||||
*/
|
||||
function readScalar(target, name, path, defaultValue) {
|
||||
if (defaultValue === undefined) defaultValue = 0;
|
||||
if (!target) return defaultValue;
|
||||
const first = Array.isArray(target) ? target[0] : target;
|
||||
if (!first) return defaultValue;
|
||||
const v = leafAt(first, name, path);
|
||||
return v === undefined || v === null ? defaultValue : v;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} v
|
||||
* @param {number} path
|
||||
*/
|
||||
function writeScalar(target, name, v, path) {
|
||||
if (!target) return;
|
||||
if (Array.isArray(target)) {
|
||||
for (let i = 0, l = target.length; i < l; i++) writeLeafScalar(target[i], name, v, path);
|
||||
} else {
|
||||
writeLeafScalar(target, name, v, path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} path
|
||||
* @return {String | null}
|
||||
*/
|
||||
function readColorAt(target, name, path) {
|
||||
if (!target) return null;
|
||||
const first = Array.isArray(target) ? target[0] : target;
|
||||
return readColorHex(first ? leafAt(first, name, path) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {Array.<Number>} ns
|
||||
* @param {number} path
|
||||
*/
|
||||
function writeColorAt(target, name, ns, path) {
|
||||
if (!target) return;
|
||||
const r = ns[0] * COLOR_NORM;
|
||||
const g = ns[1] * COLOR_NORM;
|
||||
const b = ns[2] * COLOR_NORM;
|
||||
if (Array.isArray(target)) {
|
||||
for (let i = 0, l = target.length; i < l; i++) {
|
||||
const c = leafAt(target[i], name, path);
|
||||
if (c) c.setRGB(r, g, b, three.SRGBColorSpace);
|
||||
}
|
||||
} else {
|
||||
const c = leafAt(target, name, path);
|
||||
if (c) c.setRGB(r, g, b, three.SRGBColorSpace);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} base
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @param {number} path
|
||||
* @return {number}
|
||||
*/
|
||||
function readVectorAt(target, base, axis, path) {
|
||||
if (!target) return 0;
|
||||
const first = Array.isArray(target) ? target[0] : target;
|
||||
const vec = first ? leafAt(first, base, path) : null;
|
||||
return vec ? vec[axis] : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} base
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @param {number} v
|
||||
* @param {number} path
|
||||
*/
|
||||
function writeVectorAt(target, base, axis, v, path) {
|
||||
if (!target) return;
|
||||
if (Array.isArray(target)) {
|
||||
for (let i = 0, l = target.length; i < l; i++) {
|
||||
const vec = leafAt(target[i], base, path);
|
||||
if (vec) vec[axis] = v;
|
||||
}
|
||||
} else {
|
||||
const vec = leafAt(target, base, path);
|
||||
if (vec) vec[axis] = v;
|
||||
}
|
||||
}
|
||||
|
||||
exports.AXIS_MAP = AXIS_MAP;
|
||||
exports.COLOR_NORM = COLOR_NORM;
|
||||
exports.KIND_COLOR = KIND_COLOR;
|
||||
exports.KIND_SCALAR = KIND_SCALAR;
|
||||
exports.KIND_VECTOR = KIND_VECTOR;
|
||||
exports.PATH_DIRECT = PATH_DIRECT;
|
||||
exports.applySkewOrigin = applySkewOrigin;
|
||||
exports.classifyTargetProp = classifyTargetProp;
|
||||
exports.isVectorWith = isVectorWith;
|
||||
exports.readColorAt = readColorAt;
|
||||
exports.readColorHex = readColorHex;
|
||||
exports.readScalar = readScalar;
|
||||
exports.readVectorAt = readVectorAt;
|
||||
exports.writeColorAt = writeColorAt;
|
||||
exports.writeScalar = writeScalar;
|
||||
exports.writeVectorAt = writeVectorAt;
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Patches a column-major `Matrix4.elements` array in place with CSS-style `skewX(α)` / `skewY(β)`, the 3D extension `skewZ(γ)` (shears z by x), and a `transform-origin` shift.
|
||||
*
|
||||
* @param {number[]} e
|
||||
* @param {number} skewX
|
||||
* @param {number} skewY
|
||||
* @param {number} skewZ
|
||||
* @param {number} ox
|
||||
* @param {number} oy
|
||||
* @param {number} oz
|
||||
*/
|
||||
export function applySkewOrigin(e: number[], skewX: number, skewY: number, skewZ: number, ox: number, oy: number, oz: number): void;
|
||||
/**
|
||||
* @param {any} c
|
||||
* @return {String | null}
|
||||
*/
|
||||
export function readColorHex(c: any): string | null;
|
||||
/**
|
||||
* Returns `true` when `v` is a `Vector2/3/4` instance whose dimension covers `axis`. `Quaternion` and plain `{x,y,z,w}`-shaped objects are intentionally rejected.
|
||||
*
|
||||
* @param {any} v
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @return {boolean}
|
||||
*/
|
||||
export function isVectorWith(v: any, axis: "x" | "y" | "z" | "w"): boolean;
|
||||
/**
|
||||
* Classifies `target[name]` and returns a descriptor `{ kind, path, base, axis }` (or `null`). Used by the resolver entries in `resolvers.js` and by the `Object3D` adapter to build the matching access pattern for any three.js target (Object3D, Material, Texture, Fog, UniformNode).
|
||||
*
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @return {{ kind: number, path: number, base: string, axis: 'x' | 'y' | 'z' | 'w' } | null}
|
||||
*/
|
||||
export function classifyTargetProp(target: any, name: string): {
|
||||
kind: number;
|
||||
path: number;
|
||||
base: string;
|
||||
axis: "x" | "y" | "z" | "w";
|
||||
} | null;
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} path
|
||||
* @param {number} [defaultValue]
|
||||
* @return {number}
|
||||
*/
|
||||
export function readScalar(target: any, name: string, path: number, defaultValue?: number): number;
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} v
|
||||
* @param {number} path
|
||||
*/
|
||||
export function writeScalar(target: any, name: string, v: number, path: number): void;
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} path
|
||||
* @return {String | null}
|
||||
*/
|
||||
export function readColorAt(target: any, name: string, path: number): string | null;
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {Array.<Number>} ns
|
||||
* @param {number} path
|
||||
*/
|
||||
export function writeColorAt(target: any, name: string, ns: Array<number>, path: number): void;
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} base
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @param {number} path
|
||||
* @return {number}
|
||||
*/
|
||||
export function readVectorAt(target: any, base: string, axis: "x" | "y" | "z" | "w", path: number): number;
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} base
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @param {number} v
|
||||
* @param {number} path
|
||||
*/
|
||||
export function writeVectorAt(target: any, base: string, axis: "x" | "y" | "z" | "w", v: number, path: number): void;
|
||||
export const COLOR_NORM: number;
|
||||
export const AXIS_MAP: Record<string, "x" | "y" | "z" | "w">;
|
||||
export const PATH_DIRECT: 0;
|
||||
export const KIND_COLOR: 0;
|
||||
export const KIND_SCALAR: 1;
|
||||
export const KIND_VECTOR: 2;
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { SRGBColorSpace } from 'three';
|
||||
import { degToRad } from '../../utils/number.js';
|
||||
|
||||
/**
|
||||
* Generic read/write helpers for the three.js bindings. Each operates on a target (or target array) and walks to the leaf via a path tag - direct (`target[name]`), uniform (`target.uniforms[name].value`), or TSL node (`target[name].value`). Adapter and resolver files pass the matching `PATH_*` constant; the JIT specializes each call site so the branch in `leafAt` / `writeLeafScalar` constant-folds.
|
||||
*/
|
||||
|
||||
|
||||
const COLOR_NORM = 1 / 255;
|
||||
|
||||
const AXIS_MAP = /** @type {Record<string, 'x' | 'y' | 'z' | 'w'>} */({ X: 'x', Y: 'y', Z: 'z', W: 'w' });
|
||||
|
||||
const PATH_DIRECT = 0;
|
||||
const PATH_UNIFORM = 1;
|
||||
const PATH_NODE = 2;
|
||||
|
||||
const KIND_COLOR = 0;
|
||||
const KIND_SCALAR = 1;
|
||||
const KIND_VECTOR = 2;
|
||||
|
||||
// Reuse one mutable descriptor across calls, callers must consume immediately since the next call mutates it.
|
||||
const desc = { kind: 0, path: 0, base: '', axis: /** @type {'x' | 'y' | 'z' | 'w'} */('x') };
|
||||
|
||||
/**
|
||||
* Patches a column-major `Matrix4.elements` array in place with CSS-style `skewX(α)` / `skewY(β)`, the 3D extension `skewZ(γ)` (shears z by x), and a `transform-origin` shift.
|
||||
*
|
||||
* @param {number[]} e
|
||||
* @param {number} skewX
|
||||
* @param {number} skewY
|
||||
* @param {number} skewZ
|
||||
* @param {number} ox
|
||||
* @param {number} oy
|
||||
* @param {number} oz
|
||||
*/
|
||||
function applySkewOrigin(e, skewX, skewY, skewZ, ox, oy, oz) {
|
||||
if (skewX !== 0) {
|
||||
const t = Math.tan(degToRad(skewX));
|
||||
e[4] += e[0] * t;
|
||||
e[5] += e[1] * t;
|
||||
e[6] += e[2] * t;
|
||||
}
|
||||
if (skewY !== 0) {
|
||||
const t = Math.tan(degToRad(skewY));
|
||||
e[0] += e[4] * t;
|
||||
e[1] += e[5] * t;
|
||||
e[2] += e[6] * t;
|
||||
}
|
||||
if (skewZ !== 0) {
|
||||
const t = Math.tan(degToRad(skewZ));
|
||||
e[0] += e[8] * t;
|
||||
e[1] += e[9] * t;
|
||||
e[2] += e[10] * t;
|
||||
}
|
||||
if (ox !== 0 || oy !== 0 || oz !== 0) {
|
||||
e[12] += ox - (e[0] * ox + e[4] * oy + e[8] * oz);
|
||||
e[13] += oy - (e[1] * ox + e[5] * oy + e[9] * oz);
|
||||
e[14] += oz - (e[2] * ox + e[6] * oy + e[10] * oz);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} c
|
||||
* @return {String | null}
|
||||
*/
|
||||
function readColorHex(c) {
|
||||
return c ? `#${c.getHexString(SRGBColorSpace)}` : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` when `v` is a `Vector2/3/4` instance whose dimension covers `axis`. `Quaternion` and plain `{x,y,z,w}`-shaped objects are intentionally rejected.
|
||||
*
|
||||
* @param {any} v
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @return {boolean}
|
||||
*/
|
||||
function isVectorWith(v, axis) {
|
||||
if (!v) return false;
|
||||
if (axis === 'x' || axis === 'y') return !!(v.isVector2 || v.isVector3 || v.isVector4);
|
||||
if (axis === 'z') return !!(v.isVector3 || v.isVector4);
|
||||
return !!v.isVector4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classifies `target[name]` and returns a descriptor `{ kind, path, base, axis }` (or `null`). Used by the resolver entries in `resolvers.js` and by the `Object3D` adapter to build the matching access pattern for any three.js target (Object3D, Material, Texture, Fog, UniformNode).
|
||||
*
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @return {{ kind: number, path: number, base: string, axis: 'x' | 'y' | 'z' | 'w' } | null}
|
||||
*/
|
||||
function classifyTargetProp(target, name) {
|
||||
const value = target[name];
|
||||
if (value !== undefined) {
|
||||
if (value && value.isColor) {
|
||||
desc.kind = KIND_COLOR; desc.path = PATH_DIRECT;
|
||||
return desc;
|
||||
}
|
||||
if (value && value.isUniformNode) {
|
||||
// Route TSL slot writes through node value, booleans share the scalar entry.
|
||||
const v = value.value;
|
||||
if (v && v.isColor) {
|
||||
desc.kind = KIND_COLOR; desc.path = PATH_NODE;
|
||||
return desc;
|
||||
}
|
||||
if (typeof v === 'number' || typeof v === 'boolean') {
|
||||
desc.kind = KIND_SCALAR; desc.path = PATH_NODE;
|
||||
return desc;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (typeof value === 'number' || typeof value === 'boolean') {
|
||||
desc.kind = KIND_SCALAR; desc.path = PATH_DIRECT;
|
||||
return desc;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const uniforms = target.uniforms;
|
||||
const u = uniforms && uniforms[name];
|
||||
if (u) {
|
||||
const uv = u.value;
|
||||
if (uv && uv.isColor) {
|
||||
desc.kind = KIND_COLOR; desc.path = PATH_UNIFORM;
|
||||
return desc;
|
||||
}
|
||||
if (typeof uv === 'number') {
|
||||
desc.kind = KIND_SCALAR; desc.path = PATH_UNIFORM;
|
||||
return desc;
|
||||
}
|
||||
}
|
||||
// Decompose vector axis for names like posX, uOffsetY, uVec4W, colorNodeX.
|
||||
const axis = AXIS_MAP[name[name.length - 1]];
|
||||
if (axis) {
|
||||
const base = name.slice(0, -1);
|
||||
if (isVectorWith(target[base], axis)) {
|
||||
desc.kind = KIND_VECTOR; desc.path = PATH_DIRECT; desc.base = base; desc.axis = axis;
|
||||
return desc;
|
||||
}
|
||||
const baseSlot = target[base];
|
||||
if (baseSlot && baseSlot.isUniformNode && isVectorWith(baseSlot.value, axis)) {
|
||||
desc.kind = KIND_VECTOR; desc.path = PATH_NODE; desc.base = base; desc.axis = axis;
|
||||
return desc;
|
||||
}
|
||||
const ub = uniforms && uniforms[base];
|
||||
if (ub && isVectorWith(ub.value, axis)) {
|
||||
desc.kind = KIND_VECTOR; desc.path = PATH_UNIFORM; desc.base = base; desc.axis = axis;
|
||||
return desc;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function leafAt(target, name, path) {
|
||||
if (path === PATH_DIRECT) return target[name];
|
||||
if (path === PATH_UNIFORM) {
|
||||
const u = target.uniforms;
|
||||
const e = u && u[name];
|
||||
return e ? e.value : null;
|
||||
}
|
||||
const n = target[name];
|
||||
return n ? n.value : null;
|
||||
}
|
||||
|
||||
function writeLeafScalar(target, name, v, path) {
|
||||
if (path === PATH_DIRECT) { target[name] = v; return; }
|
||||
if (path === PATH_UNIFORM) {
|
||||
const u = target.uniforms;
|
||||
const e = u && u[name];
|
||||
if (e) e.value = v;
|
||||
return;
|
||||
}
|
||||
const n = target[name];
|
||||
if (n) n.value = v;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} path
|
||||
* @param {number} [defaultValue]
|
||||
* @return {number}
|
||||
*/
|
||||
function readScalar(target, name, path, defaultValue) {
|
||||
if (defaultValue === undefined) defaultValue = 0;
|
||||
if (!target) return defaultValue;
|
||||
const first = Array.isArray(target) ? target[0] : target;
|
||||
if (!first) return defaultValue;
|
||||
const v = leafAt(first, name, path);
|
||||
return v === undefined || v === null ? defaultValue : v;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} v
|
||||
* @param {number} path
|
||||
*/
|
||||
function writeScalar(target, name, v, path) {
|
||||
if (!target) return;
|
||||
if (Array.isArray(target)) {
|
||||
for (let i = 0, l = target.length; i < l; i++) writeLeafScalar(target[i], name, v, path);
|
||||
} else {
|
||||
writeLeafScalar(target, name, v, path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {number} path
|
||||
* @return {String | null}
|
||||
*/
|
||||
function readColorAt(target, name, path) {
|
||||
if (!target) return null;
|
||||
const first = Array.isArray(target) ? target[0] : target;
|
||||
return readColorHex(first ? leafAt(first, name, path) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} name
|
||||
* @param {Array.<Number>} ns
|
||||
* @param {number} path
|
||||
*/
|
||||
function writeColorAt(target, name, ns, path) {
|
||||
if (!target) return;
|
||||
const r = ns[0] * COLOR_NORM;
|
||||
const g = ns[1] * COLOR_NORM;
|
||||
const b = ns[2] * COLOR_NORM;
|
||||
if (Array.isArray(target)) {
|
||||
for (let i = 0, l = target.length; i < l; i++) {
|
||||
const c = leafAt(target[i], name, path);
|
||||
if (c) c.setRGB(r, g, b, SRGBColorSpace);
|
||||
}
|
||||
} else {
|
||||
const c = leafAt(target, name, path);
|
||||
if (c) c.setRGB(r, g, b, SRGBColorSpace);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} base
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @param {number} path
|
||||
* @return {number}
|
||||
*/
|
||||
function readVectorAt(target, base, axis, path) {
|
||||
if (!target) return 0;
|
||||
const first = Array.isArray(target) ? target[0] : target;
|
||||
const vec = first ? leafAt(first, base, path) : null;
|
||||
return vec ? vec[axis] : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} target
|
||||
* @param {string} base
|
||||
* @param {'x' | 'y' | 'z' | 'w'} axis
|
||||
* @param {number} v
|
||||
* @param {number} path
|
||||
*/
|
||||
function writeVectorAt(target, base, axis, v, path) {
|
||||
if (!target) return;
|
||||
if (Array.isArray(target)) {
|
||||
for (let i = 0, l = target.length; i < l; i++) {
|
||||
const vec = leafAt(target[i], base, path);
|
||||
if (vec) vec[axis] = v;
|
||||
}
|
||||
} else {
|
||||
const vec = leafAt(target, base, path);
|
||||
if (vec) vec[axis] = v;
|
||||
}
|
||||
}
|
||||
|
||||
export { AXIS_MAP, COLOR_NORM, KIND_COLOR, KIND_SCALAR, KIND_VECTOR, PATH_DIRECT, applySkewOrigin, classifyTargetProp, isVectorWith, readColorAt, readColorHex, readScalar, readVectorAt, writeColorAt, writeScalar, writeVectorAt };
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var adapter = require('./adapter.cjs');
|
||||
require('./resolvers.cjs');
|
||||
require('./uniform.cjs');
|
||||
require('./object3d.cjs');
|
||||
var instance = require('./instance.cjs');
|
||||
|
||||
|
||||
|
||||
exports.threeAdapter = adapter.threeAdapter;
|
||||
exports.commitChanges = instance.commitChanges;
|
||||
exports.getInstances = instance.getInstances;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export { threeAdapter } from "./adapter.js";
|
||||
export { getInstances, commitChanges } from "./instance.js";
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
export { threeAdapter } from './adapter.js';
|
||||
import './resolvers.js';
|
||||
import './uniform.js';
|
||||
import './object3d.js';
|
||||
export { commitChanges, getInstances } from './instance.js';
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var three = require('three');
|
||||
var number = require('../../utils/number.cjs');
|
||||
var adapter = require('./adapter.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
|
||||
const hasSkewOrigin = (t) => !!(t._skewX || t._skewY || t._skewZ || t._originX || t._originY || t._originZ);
|
||||
|
||||
/**
|
||||
* @import { Object3D, InstancedMesh } from 'three'
|
||||
*
|
||||
* @typedef {InstancedMesh | BatchedMesh} InstanceParent
|
||||
*/
|
||||
|
||||
const DIRTY_POS = 1;
|
||||
const DIRTY_ROT = 2;
|
||||
const DIRTY_SCALE = 4;
|
||||
const DIRTY_SKEW = 8;
|
||||
|
||||
/** @type {WeakMap<InstanceParent, InstanceBinding>} */
|
||||
const bindings = new WeakMap();
|
||||
|
||||
/**
|
||||
* Per-mesh state for `InstancedMesh` / `BatchedMesh` animations. Holds the instance array, the dirty queue, and the chained `onBeforeRender` closure.
|
||||
*/
|
||||
class InstanceBinding {
|
||||
|
||||
/** @param {InstanceParent} mesh */
|
||||
constructor(mesh) {
|
||||
this.mesh = mesh;
|
||||
this.hasInstanceMatrix = 'instanceMatrix' in mesh;
|
||||
/** @type {(Instance | null)[]} */
|
||||
this.instances = [];
|
||||
/** @type {Instance[]} */
|
||||
this.dirtyList = [];
|
||||
/** @type {Object3D['onBeforeRender'] | null} */
|
||||
this.userOnBeforeRender = mesh.onBeforeRender || null;
|
||||
this.chainedHandler = makeChainedHandler(this);
|
||||
Object.defineProperty(mesh, 'onBeforeRender', {
|
||||
configurable: true,
|
||||
get: () => this.chainedHandler,
|
||||
set: (fn) => { this.userOnBeforeRender = fn; },
|
||||
});
|
||||
}
|
||||
|
||||
flush() {
|
||||
const list = this.dirtyList;
|
||||
if (list.length === 0) return;
|
||||
for (let i = 0, l = list.length; i < l; i++) list[i]._flush();
|
||||
if (this.hasInstanceMatrix) /** @type {InstancedMesh} */(this.mesh).instanceMatrix.needsUpdate = true;
|
||||
list.length = 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @return {Object3D['onBeforeRender']}
|
||||
*/
|
||||
function makeChainedHandler(binding) {
|
||||
return function (renderer, scene, camera, geometry, material, group) {
|
||||
binding.flush();
|
||||
const u = binding.userOnBeforeRender;
|
||||
if (u) u.call(binding.mesh, renderer, scene, camera, geometry, material, group);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-instance adapter for `InstancedMesh` or `BatchedMesh`. Returned by `getInstances(mesh)`. Exposes the same flat properties as the mesh adapter, applied to a single instance id. Writes are coalesced and flushed before each render via `onBeforeRender`; call `commitChanges(mesh)` if you need to read `mesh.instanceMatrix` between a tick and a render.
|
||||
*
|
||||
* Caveats:
|
||||
* - `opacity` writes the parent's shared material, every instance is affected.
|
||||
* - `visible` is backed by `BatchedMesh.setVisibleAt`. On `InstancedMesh` it is a no-op, use `scale = 0` to hide an instance.
|
||||
*/
|
||||
class Instance {
|
||||
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @param {number} id
|
||||
*/
|
||||
constructor(binding, id) {
|
||||
this.isAnimejsInstanceProxy = true;
|
||||
this.parent = binding.mesh;
|
||||
this.id = id;
|
||||
this._position = new three.Vector3();
|
||||
this._rotation = new three.Euler(0, 0, 0, 'XYZ');
|
||||
this._scale = new three.Vector3(1, 1, 1);
|
||||
this._matrix = new three.Matrix4();
|
||||
this._quat = new three.Quaternion();
|
||||
// Pre-allocate _color so the hidden class stays stable, set color mutates it in place rather than re-binding the field.
|
||||
this._color = new three.Color();
|
||||
this._dirty = 0;
|
||||
// Skew in degrees and transform-origin in object-space.
|
||||
// applySkewOrigin computes Math.tan inline per non-zero axis, so we only carry the user-facing angle here.
|
||||
this._skewX = 0;
|
||||
this._skewY = 0;
|
||||
this._skewZ = 0;
|
||||
this._originX = 0;
|
||||
this._originY = 0;
|
||||
this._originZ = 0;
|
||||
// Skip the position-only fast path in _flush whenever any skew or origin is non-zero, since both modify the matrix beyond pure translation.
|
||||
this._hasSkewOrigin = false;
|
||||
// Cache the binding dirty queue once so per-frame setters skip a property hop.
|
||||
/** @type {Instance[]} */
|
||||
this._dirtyList = binding.dirtyList;
|
||||
// Cache parent capability flags once so per-frame setters skip prototype-chain in checks.
|
||||
const parent = binding.mesh;
|
||||
this._hasSetColor = 'setColorAt' in parent;
|
||||
this._hasSetVisible = 'setVisibleAt' in parent;
|
||||
this._hasGetVisible = 'getVisibleAt' in parent;
|
||||
|
||||
parent.getMatrixAt(id, this._matrix);
|
||||
if (this._matrix.elements[15] === 0) this._matrix.identity();
|
||||
this._matrix.decompose(this._position, this._quat, this._scale);
|
||||
this._rotation.setFromQuaternion(this._quat, 'XYZ');
|
||||
|
||||
if ('getColorAt' in parent && 'instanceColor' in parent && parent.instanceColor) {
|
||||
parent.getColorAt(id, this._color);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} flag
|
||||
*/
|
||||
_markDirty(flag) {
|
||||
// Enqueue once per frame, later flags only OR into _dirty without re-pushing to the queue.
|
||||
if (this._dirty === 0) this._dirtyList.push(this);
|
||||
this._dirty |= flag;
|
||||
}
|
||||
|
||||
_flush() {
|
||||
const d = this._dirty;
|
||||
if (!d) return;
|
||||
const m = this._matrix;
|
||||
const p = this._position;
|
||||
if (d === DIRTY_POS && !this._hasSkewOrigin) {
|
||||
const e = m.elements;
|
||||
e[12] = p.x; e[13] = p.y; e[14] = p.z;
|
||||
} else {
|
||||
const q = this._quat;
|
||||
if (d & DIRTY_ROT) q.setFromEuler(this._rotation);
|
||||
m.compose(p, q, this._scale);
|
||||
if (this._hasSkewOrigin) {
|
||||
helpers.applySkewOrigin(m.elements, this._skewX, this._skewY, this._skewZ, this._originX, this._originY, this._originZ);
|
||||
}
|
||||
}
|
||||
this.parent.setMatrixAt(this.id, m);
|
||||
this._dirty = 0;
|
||||
}
|
||||
|
||||
get x() { return this._position.x; }
|
||||
set x(v) { this._position.x = v; this._markDirty(DIRTY_POS); }
|
||||
|
||||
get y() { return this._position.y; }
|
||||
set y(v) { this._position.y = v; this._markDirty(DIRTY_POS); }
|
||||
|
||||
get z() { return this._position.z; }
|
||||
set z(v) { this._position.z = v; this._markDirty(DIRTY_POS); }
|
||||
|
||||
get rotateX() { return number.radToDeg(this._rotation.x); }
|
||||
set rotateX(v) { this._rotation.x = number.degToRad(v); this._markDirty(DIRTY_ROT); }
|
||||
|
||||
get rotateY() { return number.radToDeg(this._rotation.y); }
|
||||
set rotateY(v) { this._rotation.y = number.degToRad(v); this._markDirty(DIRTY_ROT); }
|
||||
|
||||
get rotateZ() { return number.radToDeg(this._rotation.z); }
|
||||
set rotateZ(v) { this._rotation.z = number.degToRad(v); this._markDirty(DIRTY_ROT); }
|
||||
|
||||
get scaleX() { return this._scale.x; }
|
||||
set scaleX(v) { this._scale.x = v; this._markDirty(DIRTY_SCALE); }
|
||||
|
||||
get scaleY() { return this._scale.y; }
|
||||
set scaleY(v) { this._scale.y = v; this._markDirty(DIRTY_SCALE); }
|
||||
|
||||
get scaleZ() { return this._scale.z; }
|
||||
set scaleZ(v) { this._scale.z = v; this._markDirty(DIRTY_SCALE); }
|
||||
|
||||
get scale() { return this._scale.x; }
|
||||
set scale(v) {
|
||||
const s = this._scale;
|
||||
s.x = v; s.y = v; s.z = v;
|
||||
this._markDirty(DIRTY_SCALE);
|
||||
}
|
||||
|
||||
get skewX() { return this._skewX; }
|
||||
set skewX(v) {
|
||||
this._skewX = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get skewY() { return this._skewY; }
|
||||
set skewY(v) {
|
||||
this._skewY = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get skewZ() { return this._skewZ; }
|
||||
set skewZ(v) {
|
||||
this._skewZ = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get transformOriginX() { return this._originX; }
|
||||
set transformOriginX(v) {
|
||||
this._originX = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get transformOriginY() { return this._originY; }
|
||||
set transformOriginY(v) {
|
||||
this._originY = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get transformOriginZ() { return this._originZ; }
|
||||
set transformOriginZ(v) {
|
||||
this._originZ = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get opacity() {
|
||||
return helpers.readScalar(/** @type {any} */(this.parent).material, 'opacity', helpers.PATH_DIRECT, 1);
|
||||
}
|
||||
/** @param {number} v */
|
||||
set opacity(v) {
|
||||
helpers.writeScalar(/** @type {any} */(this.parent).material, 'opacity', v, helpers.PATH_DIRECT);
|
||||
}
|
||||
|
||||
get visible() {
|
||||
return this._hasGetVisible ? /** @type {any} */(this.parent).getVisibleAt(this.id) : true;
|
||||
}
|
||||
/** @param {boolean} v */
|
||||
set visible(v) {
|
||||
if (this._hasSetVisible) /** @type {any} */(this.parent).setVisibleAt(this.id, v);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes pending matrix writes for every dirty instance of `mesh`.
|
||||
* Called automatically before each render. Call it yourself if you read
|
||||
* `mesh.instanceMatrix` between an animation tick and the next render.
|
||||
*
|
||||
* @param {InstanceParent} mesh
|
||||
*/
|
||||
function commitChanges(mesh) {
|
||||
const binding = bindings.get(mesh);
|
||||
if (binding) binding.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of per-instance adapters for `mesh`. Index by id, deleted slots on `BatchedMesh` are `null`. Pass the array (or a slice / a single element) to `animate()`.
|
||||
*
|
||||
* animate(getInstances(mesh), { x: 100, delay: stagger(5) });
|
||||
* animate(getInstances(mesh)[42], { scale: 2 });
|
||||
*
|
||||
* The same array reference is preserved across `mesh.count` / `addInstance` / `deleteInstance` calls. Entries are pushed, nulled, or truncated in place. Animations bound to an outdated reference keep tweening their original adapters.
|
||||
*
|
||||
* `mesh.onBeforeRender` is replaced with an accessor that flushes
|
||||
* pending instance writes before each render and forwards to your
|
||||
* handler. Assigning your own `mesh.onBeforeRender = fn` keeps the
|
||||
* auto-flush, but reading `mesh.onBeforeRender` afterwards returns the
|
||||
* chained dispatcher rather than `fn` itself, so identity checks
|
||||
* (`mesh.onBeforeRender === fn`) will not match.
|
||||
*
|
||||
* @param {InstanceParent} mesh
|
||||
* @return {(Instance | null)[]}
|
||||
*/
|
||||
function getInstances(mesh) {
|
||||
let binding = bindings.get(mesh);
|
||||
if (!binding) {
|
||||
binding = new InstanceBinding(mesh);
|
||||
bindings.set(mesh, binding);
|
||||
}
|
||||
if (mesh instanceof three.BatchedMesh) {
|
||||
return refreshBatched(binding);
|
||||
}
|
||||
return refreshInstanced(binding);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @return {(Instance | null)[]}
|
||||
*/
|
||||
function refreshInstanced(binding) {
|
||||
const mesh = /** @type {InstancedMesh} */(binding.mesh);
|
||||
const count = mesh.count;
|
||||
const arr = binding.instances;
|
||||
if (arr.length === 0 && count > 0) {
|
||||
arr.length = count;
|
||||
for (let i = 0; i < count; i++) arr[i] = new Instance(binding, i);
|
||||
return arr;
|
||||
}
|
||||
if (arr.length < count) {
|
||||
for (let i = arr.length; i < count; i++) arr.push(new Instance(binding, i));
|
||||
} else if (arr.length > count) {
|
||||
arr.length = count;
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @return {(Instance | null)[]}
|
||||
*/
|
||||
function refreshBatched(binding) {
|
||||
const mesh = /** @type {BatchedMesh} */(binding.mesh);
|
||||
const arr = binding.instances;
|
||||
// Read three internal _instanceInfo to skip slots marked inactive by deleteInstance.
|
||||
// Iterate the full slot count, not instanceCount, since deleted slots leave gaps but live ids past them must still be visited.
|
||||
const instanceInfo = /** @type {{ _instanceInfo?: { active: boolean }[] }} */(mesh)._instanceInfo ?? [];
|
||||
const len = instanceInfo.length;
|
||||
if (arr.length < len) arr.length = len;
|
||||
for (let i = 0; i < len; i++) {
|
||||
const info = instanceInfo[i];
|
||||
const inactive = info && info.active === false;
|
||||
if (inactive) {
|
||||
arr[i] = null;
|
||||
} else if (!arr[i]) {
|
||||
arr[i] = new Instance(binding, i);
|
||||
}
|
||||
}
|
||||
if (arr.length > len) arr.length = len;
|
||||
return arr;
|
||||
}
|
||||
|
||||
const instanceAdapter = adapter.threeAdapter.registerTargetAdapter((t) => t instanceof Instance);
|
||||
instanceAdapter.registerProperty('color',
|
||||
(t) => helpers.readColorHex(t._color),
|
||||
(t, _, tw) => {
|
||||
if (!t._hasSetColor) return;
|
||||
const ns = tw._numbers;
|
||||
t._color.setRGB(ns[0] * helpers.COLOR_NORM, ns[1] * helpers.COLOR_NORM, ns[2] * helpers.COLOR_NORM, three.SRGBColorSpace);
|
||||
const p = /** @type {any} */(t.parent);
|
||||
p.setColorAt(t.id, t._color);
|
||||
if (p.instanceColor) p.instanceColor.needsUpdate = true;
|
||||
},
|
||||
);
|
||||
// Shorthand 3-token string x y z routed via the engine COMPLEX path.
|
||||
// The setter reads tween _numbers for the per-frame lerped triplet.
|
||||
instanceAdapter.registerProperty('transformOrigin',
|
||||
(t) => `${t._originX} ${t._originY} ${t._originZ}`,
|
||||
(t, _, tw) => {
|
||||
const ns = tw._numbers;
|
||||
t._originX = ns[0];
|
||||
t._originY = ns[1];
|
||||
t._originZ = ns[2];
|
||||
t._hasSkewOrigin = hasSkewOrigin(t);
|
||||
t._markDirty(DIRTY_SKEW);
|
||||
},
|
||||
);
|
||||
|
||||
exports.commitChanges = commitChanges;
|
||||
exports.getInstances = getInstances;
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Flushes pending matrix writes for every dirty instance of `mesh`.
|
||||
* Called automatically before each render. Call it yourself if you read
|
||||
* `mesh.instanceMatrix` between an animation tick and the next render.
|
||||
*
|
||||
* @param {InstanceParent} mesh
|
||||
*/
|
||||
export function commitChanges(mesh: InstanceParent): void;
|
||||
/**
|
||||
* Returns an array of per-instance adapters for `mesh`. Index by id, deleted slots on `BatchedMesh` are `null`. Pass the array (or a slice / a single element) to `animate()`.
|
||||
*
|
||||
* animate(getInstances(mesh), { x: 100, delay: stagger(5) });
|
||||
* animate(getInstances(mesh)[42], { scale: 2 });
|
||||
*
|
||||
* The same array reference is preserved across `mesh.count` / `addInstance` / `deleteInstance` calls. Entries are pushed, nulled, or truncated in place. Animations bound to an outdated reference keep tweening their original adapters.
|
||||
*
|
||||
* `mesh.onBeforeRender` is replaced with an accessor that flushes
|
||||
* pending instance writes before each render and forwards to your
|
||||
* handler. Assigning your own `mesh.onBeforeRender = fn` keeps the
|
||||
* auto-flush, but reading `mesh.onBeforeRender` afterwards returns the
|
||||
* chained dispatcher rather than `fn` itself, so identity checks
|
||||
* (`mesh.onBeforeRender === fn`) will not match.
|
||||
*
|
||||
* @param {InstanceParent} mesh
|
||||
* @return {(Instance | null)[]}
|
||||
*/
|
||||
export function getInstances(mesh: InstanceParent): (Instance | null)[];
|
||||
export type InstanceParent = InstancedMesh | BatchedMesh;
|
||||
/**
|
||||
* Per-instance adapter for `InstancedMesh` or `BatchedMesh`. Returned by `getInstances(mesh)`. Exposes the same flat properties as the mesh adapter, applied to a single instance id. Writes are coalesced and flushed before each render via `onBeforeRender`; call `commitChanges(mesh)` if you need to read `mesh.instanceMatrix` between a tick and a render.
|
||||
*
|
||||
* Caveats:
|
||||
* - `opacity` writes the parent's shared material, every instance is affected.
|
||||
* - `visible` is backed by `BatchedMesh.setVisibleAt`. On `InstancedMesh` it is a no-op, use `scale = 0` to hide an instance.
|
||||
*/
|
||||
declare class Instance {
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @param {number} id
|
||||
*/
|
||||
constructor(binding: InstanceBinding, id: number);
|
||||
isAnimejsInstanceProxy: boolean;
|
||||
parent: InstanceParent;
|
||||
id: number;
|
||||
_position: Vector3;
|
||||
_rotation: Euler;
|
||||
_scale: Vector3;
|
||||
_matrix: Matrix4;
|
||||
_quat: Quaternion;
|
||||
_color: Color;
|
||||
_dirty: number;
|
||||
_skewX: number;
|
||||
_skewY: number;
|
||||
_skewZ: number;
|
||||
_originX: number;
|
||||
_originY: number;
|
||||
_originZ: number;
|
||||
_hasSkewOrigin: boolean;
|
||||
/** @type {Instance[]} */
|
||||
_dirtyList: Instance[];
|
||||
_hasSetColor: boolean;
|
||||
_hasSetVisible: boolean;
|
||||
_hasGetVisible: boolean;
|
||||
/**
|
||||
* @param {number} flag
|
||||
*/
|
||||
_markDirty(flag: number): void;
|
||||
_flush(): void;
|
||||
set x(v: number);
|
||||
get x(): number;
|
||||
set y(v: number);
|
||||
get y(): number;
|
||||
set z(v: number);
|
||||
get z(): number;
|
||||
set rotateX(v: number);
|
||||
get rotateX(): number;
|
||||
set rotateY(v: number);
|
||||
get rotateY(): number;
|
||||
set rotateZ(v: number);
|
||||
get rotateZ(): number;
|
||||
set scaleX(v: number);
|
||||
get scaleX(): number;
|
||||
set scaleY(v: number);
|
||||
get scaleY(): number;
|
||||
set scaleZ(v: number);
|
||||
get scaleZ(): number;
|
||||
set scale(v: number);
|
||||
get scale(): number;
|
||||
set skewX(v: number);
|
||||
get skewX(): number;
|
||||
set skewY(v: number);
|
||||
get skewY(): number;
|
||||
set skewZ(v: number);
|
||||
get skewZ(): number;
|
||||
set transformOriginX(v: number);
|
||||
get transformOriginX(): number;
|
||||
set transformOriginY(v: number);
|
||||
get transformOriginY(): number;
|
||||
set transformOriginZ(v: number);
|
||||
get transformOriginZ(): number;
|
||||
/** @param {number} v */
|
||||
set opacity(v: number);
|
||||
get opacity(): number;
|
||||
/** @param {boolean} v */
|
||||
set visible(v: boolean);
|
||||
get visible(): boolean;
|
||||
}
|
||||
import type { InstancedMesh } from 'three';
|
||||
import { BatchedMesh } from 'three';
|
||||
import { Vector3 } from 'three';
|
||||
import { Euler } from 'three';
|
||||
import { Matrix4 } from 'three';
|
||||
import { Quaternion } from 'three';
|
||||
import { Color } from 'three';
|
||||
/**
|
||||
* Per-mesh state for `InstancedMesh` / `BatchedMesh` animations. Holds the instance array, the dirty queue, and the chained `onBeforeRender` closure.
|
||||
*/
|
||||
declare class InstanceBinding {
|
||||
/** @param {InstanceParent} mesh */
|
||||
constructor(mesh: InstanceParent);
|
||||
mesh: InstanceParent;
|
||||
hasInstanceMatrix: boolean;
|
||||
/** @type {(Instance | null)[]} */
|
||||
instances: (Instance | null)[];
|
||||
/** @type {Instance[]} */
|
||||
dirtyList: Instance[];
|
||||
/** @type {Object3D['onBeforeRender'] | null} */
|
||||
userOnBeforeRender: Object3D["onBeforeRender"] | null;
|
||||
chainedHandler: (renderer: import("three").WebGLRenderer, scene: import("three").Scene, camera: import("three").Camera, geometry: import("three").BufferGeometry, material: import("three").Material, group: import("three").Group) => void;
|
||||
flush(): void;
|
||||
}
|
||||
import type { Object3D } from 'three';
|
||||
export {};
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { SRGBColorSpace, Vector3, Euler, Matrix4, Quaternion, Color, BatchedMesh } from 'three';
|
||||
import { radToDeg, degToRad } from '../../utils/number.js';
|
||||
import { threeAdapter } from './adapter.js';
|
||||
import { readColorHex, COLOR_NORM, applySkewOrigin, readScalar, PATH_DIRECT, writeScalar } from './helpers.js';
|
||||
|
||||
const hasSkewOrigin = (t) => !!(t._skewX || t._skewY || t._skewZ || t._originX || t._originY || t._originZ);
|
||||
|
||||
/**
|
||||
* @import { Object3D, InstancedMesh } from 'three'
|
||||
*
|
||||
* @typedef {InstancedMesh | BatchedMesh} InstanceParent
|
||||
*/
|
||||
|
||||
const DIRTY_POS = 1;
|
||||
const DIRTY_ROT = 2;
|
||||
const DIRTY_SCALE = 4;
|
||||
const DIRTY_SKEW = 8;
|
||||
|
||||
/** @type {WeakMap<InstanceParent, InstanceBinding>} */
|
||||
const bindings = new WeakMap();
|
||||
|
||||
/**
|
||||
* Per-mesh state for `InstancedMesh` / `BatchedMesh` animations. Holds the instance array, the dirty queue, and the chained `onBeforeRender` closure.
|
||||
*/
|
||||
class InstanceBinding {
|
||||
|
||||
/** @param {InstanceParent} mesh */
|
||||
constructor(mesh) {
|
||||
this.mesh = mesh;
|
||||
this.hasInstanceMatrix = 'instanceMatrix' in mesh;
|
||||
/** @type {(Instance | null)[]} */
|
||||
this.instances = [];
|
||||
/** @type {Instance[]} */
|
||||
this.dirtyList = [];
|
||||
/** @type {Object3D['onBeforeRender'] | null} */
|
||||
this.userOnBeforeRender = mesh.onBeforeRender || null;
|
||||
this.chainedHandler = makeChainedHandler(this);
|
||||
Object.defineProperty(mesh, 'onBeforeRender', {
|
||||
configurable: true,
|
||||
get: () => this.chainedHandler,
|
||||
set: (fn) => { this.userOnBeforeRender = fn; },
|
||||
});
|
||||
}
|
||||
|
||||
flush() {
|
||||
const list = this.dirtyList;
|
||||
if (list.length === 0) return;
|
||||
for (let i = 0, l = list.length; i < l; i++) list[i]._flush();
|
||||
if (this.hasInstanceMatrix) /** @type {InstancedMesh} */(this.mesh).instanceMatrix.needsUpdate = true;
|
||||
list.length = 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @return {Object3D['onBeforeRender']}
|
||||
*/
|
||||
function makeChainedHandler(binding) {
|
||||
return function (renderer, scene, camera, geometry, material, group) {
|
||||
binding.flush();
|
||||
const u = binding.userOnBeforeRender;
|
||||
if (u) u.call(binding.mesh, renderer, scene, camera, geometry, material, group);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-instance adapter for `InstancedMesh` or `BatchedMesh`. Returned by `getInstances(mesh)`. Exposes the same flat properties as the mesh adapter, applied to a single instance id. Writes are coalesced and flushed before each render via `onBeforeRender`; call `commitChanges(mesh)` if you need to read `mesh.instanceMatrix` between a tick and a render.
|
||||
*
|
||||
* Caveats:
|
||||
* - `opacity` writes the parent's shared material, every instance is affected.
|
||||
* - `visible` is backed by `BatchedMesh.setVisibleAt`. On `InstancedMesh` it is a no-op, use `scale = 0` to hide an instance.
|
||||
*/
|
||||
class Instance {
|
||||
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @param {number} id
|
||||
*/
|
||||
constructor(binding, id) {
|
||||
this.isAnimejsInstanceProxy = true;
|
||||
this.parent = binding.mesh;
|
||||
this.id = id;
|
||||
this._position = new Vector3();
|
||||
this._rotation = new Euler(0, 0, 0, 'XYZ');
|
||||
this._scale = new Vector3(1, 1, 1);
|
||||
this._matrix = new Matrix4();
|
||||
this._quat = new Quaternion();
|
||||
// Pre-allocate _color so the hidden class stays stable, set color mutates it in place rather than re-binding the field.
|
||||
this._color = new Color();
|
||||
this._dirty = 0;
|
||||
// Skew in degrees and transform-origin in object-space.
|
||||
// applySkewOrigin computes Math.tan inline per non-zero axis, so we only carry the user-facing angle here.
|
||||
this._skewX = 0;
|
||||
this._skewY = 0;
|
||||
this._skewZ = 0;
|
||||
this._originX = 0;
|
||||
this._originY = 0;
|
||||
this._originZ = 0;
|
||||
// Skip the position-only fast path in _flush whenever any skew or origin is non-zero, since both modify the matrix beyond pure translation.
|
||||
this._hasSkewOrigin = false;
|
||||
// Cache the binding dirty queue once so per-frame setters skip a property hop.
|
||||
/** @type {Instance[]} */
|
||||
this._dirtyList = binding.dirtyList;
|
||||
// Cache parent capability flags once so per-frame setters skip prototype-chain in checks.
|
||||
const parent = binding.mesh;
|
||||
this._hasSetColor = 'setColorAt' in parent;
|
||||
this._hasSetVisible = 'setVisibleAt' in parent;
|
||||
this._hasGetVisible = 'getVisibleAt' in parent;
|
||||
|
||||
parent.getMatrixAt(id, this._matrix);
|
||||
if (this._matrix.elements[15] === 0) this._matrix.identity();
|
||||
this._matrix.decompose(this._position, this._quat, this._scale);
|
||||
this._rotation.setFromQuaternion(this._quat, 'XYZ');
|
||||
|
||||
if ('getColorAt' in parent && 'instanceColor' in parent && parent.instanceColor) {
|
||||
parent.getColorAt(id, this._color);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} flag
|
||||
*/
|
||||
_markDirty(flag) {
|
||||
// Enqueue once per frame, later flags only OR into _dirty without re-pushing to the queue.
|
||||
if (this._dirty === 0) this._dirtyList.push(this);
|
||||
this._dirty |= flag;
|
||||
}
|
||||
|
||||
_flush() {
|
||||
const d = this._dirty;
|
||||
if (!d) return;
|
||||
const m = this._matrix;
|
||||
const p = this._position;
|
||||
if (d === DIRTY_POS && !this._hasSkewOrigin) {
|
||||
const e = m.elements;
|
||||
e[12] = p.x; e[13] = p.y; e[14] = p.z;
|
||||
} else {
|
||||
const q = this._quat;
|
||||
if (d & DIRTY_ROT) q.setFromEuler(this._rotation);
|
||||
m.compose(p, q, this._scale);
|
||||
if (this._hasSkewOrigin) {
|
||||
applySkewOrigin(m.elements, this._skewX, this._skewY, this._skewZ, this._originX, this._originY, this._originZ);
|
||||
}
|
||||
}
|
||||
this.parent.setMatrixAt(this.id, m);
|
||||
this._dirty = 0;
|
||||
}
|
||||
|
||||
get x() { return this._position.x; }
|
||||
set x(v) { this._position.x = v; this._markDirty(DIRTY_POS); }
|
||||
|
||||
get y() { return this._position.y; }
|
||||
set y(v) { this._position.y = v; this._markDirty(DIRTY_POS); }
|
||||
|
||||
get z() { return this._position.z; }
|
||||
set z(v) { this._position.z = v; this._markDirty(DIRTY_POS); }
|
||||
|
||||
get rotateX() { return radToDeg(this._rotation.x); }
|
||||
set rotateX(v) { this._rotation.x = degToRad(v); this._markDirty(DIRTY_ROT); }
|
||||
|
||||
get rotateY() { return radToDeg(this._rotation.y); }
|
||||
set rotateY(v) { this._rotation.y = degToRad(v); this._markDirty(DIRTY_ROT); }
|
||||
|
||||
get rotateZ() { return radToDeg(this._rotation.z); }
|
||||
set rotateZ(v) { this._rotation.z = degToRad(v); this._markDirty(DIRTY_ROT); }
|
||||
|
||||
get scaleX() { return this._scale.x; }
|
||||
set scaleX(v) { this._scale.x = v; this._markDirty(DIRTY_SCALE); }
|
||||
|
||||
get scaleY() { return this._scale.y; }
|
||||
set scaleY(v) { this._scale.y = v; this._markDirty(DIRTY_SCALE); }
|
||||
|
||||
get scaleZ() { return this._scale.z; }
|
||||
set scaleZ(v) { this._scale.z = v; this._markDirty(DIRTY_SCALE); }
|
||||
|
||||
get scale() { return this._scale.x; }
|
||||
set scale(v) {
|
||||
const s = this._scale;
|
||||
s.x = v; s.y = v; s.z = v;
|
||||
this._markDirty(DIRTY_SCALE);
|
||||
}
|
||||
|
||||
get skewX() { return this._skewX; }
|
||||
set skewX(v) {
|
||||
this._skewX = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get skewY() { return this._skewY; }
|
||||
set skewY(v) {
|
||||
this._skewY = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get skewZ() { return this._skewZ; }
|
||||
set skewZ(v) {
|
||||
this._skewZ = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get transformOriginX() { return this._originX; }
|
||||
set transformOriginX(v) {
|
||||
this._originX = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get transformOriginY() { return this._originY; }
|
||||
set transformOriginY(v) {
|
||||
this._originY = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get transformOriginZ() { return this._originZ; }
|
||||
set transformOriginZ(v) {
|
||||
this._originZ = v;
|
||||
this._hasSkewOrigin = hasSkewOrigin(this);
|
||||
this._markDirty(DIRTY_SKEW);
|
||||
}
|
||||
|
||||
get opacity() {
|
||||
return readScalar(/** @type {any} */(this.parent).material, 'opacity', PATH_DIRECT, 1);
|
||||
}
|
||||
/** @param {number} v */
|
||||
set opacity(v) {
|
||||
writeScalar(/** @type {any} */(this.parent).material, 'opacity', v, PATH_DIRECT);
|
||||
}
|
||||
|
||||
get visible() {
|
||||
return this._hasGetVisible ? /** @type {any} */(this.parent).getVisibleAt(this.id) : true;
|
||||
}
|
||||
/** @param {boolean} v */
|
||||
set visible(v) {
|
||||
if (this._hasSetVisible) /** @type {any} */(this.parent).setVisibleAt(this.id, v);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes pending matrix writes for every dirty instance of `mesh`.
|
||||
* Called automatically before each render. Call it yourself if you read
|
||||
* `mesh.instanceMatrix` between an animation tick and the next render.
|
||||
*
|
||||
* @param {InstanceParent} mesh
|
||||
*/
|
||||
function commitChanges(mesh) {
|
||||
const binding = bindings.get(mesh);
|
||||
if (binding) binding.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of per-instance adapters for `mesh`. Index by id, deleted slots on `BatchedMesh` are `null`. Pass the array (or a slice / a single element) to `animate()`.
|
||||
*
|
||||
* animate(getInstances(mesh), { x: 100, delay: stagger(5) });
|
||||
* animate(getInstances(mesh)[42], { scale: 2 });
|
||||
*
|
||||
* The same array reference is preserved across `mesh.count` / `addInstance` / `deleteInstance` calls. Entries are pushed, nulled, or truncated in place. Animations bound to an outdated reference keep tweening their original adapters.
|
||||
*
|
||||
* `mesh.onBeforeRender` is replaced with an accessor that flushes
|
||||
* pending instance writes before each render and forwards to your
|
||||
* handler. Assigning your own `mesh.onBeforeRender = fn` keeps the
|
||||
* auto-flush, but reading `mesh.onBeforeRender` afterwards returns the
|
||||
* chained dispatcher rather than `fn` itself, so identity checks
|
||||
* (`mesh.onBeforeRender === fn`) will not match.
|
||||
*
|
||||
* @param {InstanceParent} mesh
|
||||
* @return {(Instance | null)[]}
|
||||
*/
|
||||
function getInstances(mesh) {
|
||||
let binding = bindings.get(mesh);
|
||||
if (!binding) {
|
||||
binding = new InstanceBinding(mesh);
|
||||
bindings.set(mesh, binding);
|
||||
}
|
||||
if (mesh instanceof BatchedMesh) {
|
||||
return refreshBatched(binding);
|
||||
}
|
||||
return refreshInstanced(binding);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @return {(Instance | null)[]}
|
||||
*/
|
||||
function refreshInstanced(binding) {
|
||||
const mesh = /** @type {InstancedMesh} */(binding.mesh);
|
||||
const count = mesh.count;
|
||||
const arr = binding.instances;
|
||||
if (arr.length === 0 && count > 0) {
|
||||
arr.length = count;
|
||||
for (let i = 0; i < count; i++) arr[i] = new Instance(binding, i);
|
||||
return arr;
|
||||
}
|
||||
if (arr.length < count) {
|
||||
for (let i = arr.length; i < count; i++) arr.push(new Instance(binding, i));
|
||||
} else if (arr.length > count) {
|
||||
arr.length = count;
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {InstanceBinding} binding
|
||||
* @return {(Instance | null)[]}
|
||||
*/
|
||||
function refreshBatched(binding) {
|
||||
const mesh = /** @type {BatchedMesh} */(binding.mesh);
|
||||
const arr = binding.instances;
|
||||
// Read three internal _instanceInfo to skip slots marked inactive by deleteInstance.
|
||||
// Iterate the full slot count, not instanceCount, since deleted slots leave gaps but live ids past them must still be visited.
|
||||
const instanceInfo = /** @type {{ _instanceInfo?: { active: boolean }[] }} */(mesh)._instanceInfo ?? [];
|
||||
const len = instanceInfo.length;
|
||||
if (arr.length < len) arr.length = len;
|
||||
for (let i = 0; i < len; i++) {
|
||||
const info = instanceInfo[i];
|
||||
const inactive = info && info.active === false;
|
||||
if (inactive) {
|
||||
arr[i] = null;
|
||||
} else if (!arr[i]) {
|
||||
arr[i] = new Instance(binding, i);
|
||||
}
|
||||
}
|
||||
if (arr.length > len) arr.length = len;
|
||||
return arr;
|
||||
}
|
||||
|
||||
const instanceAdapter = threeAdapter.registerTargetAdapter((t) => t instanceof Instance);
|
||||
instanceAdapter.registerProperty('color',
|
||||
(t) => readColorHex(t._color),
|
||||
(t, _, tw) => {
|
||||
if (!t._hasSetColor) return;
|
||||
const ns = tw._numbers;
|
||||
t._color.setRGB(ns[0] * COLOR_NORM, ns[1] * COLOR_NORM, ns[2] * COLOR_NORM, SRGBColorSpace);
|
||||
const p = /** @type {any} */(t.parent);
|
||||
p.setColorAt(t.id, t._color);
|
||||
if (p.instanceColor) p.instanceColor.needsUpdate = true;
|
||||
},
|
||||
);
|
||||
// Shorthand 3-token string x y z routed via the engine COMPLEX path.
|
||||
// The setter reads tween _numbers for the per-frame lerped triplet.
|
||||
instanceAdapter.registerProperty('transformOrigin',
|
||||
(t) => `${t._originX} ${t._originY} ${t._originZ}`,
|
||||
(t, _, tw) => {
|
||||
const ns = tw._numbers;
|
||||
t._originX = ns[0];
|
||||
t._originY = ns[1];
|
||||
t._originZ = ns[2];
|
||||
t._hasSkewOrigin = hasSkewOrigin(t);
|
||||
t._markDirty(DIRTY_SKEW);
|
||||
},
|
||||
);
|
||||
|
||||
export { commitChanges, getInstances };
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var three = require('three');
|
||||
var number = require('../../utils/number.cjs');
|
||||
var adapter = require('./adapter.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
|
||||
/**
|
||||
* `Object3D` adapter. Maps flat properties (position, rotation, scale, opacity, color, visible, light / audio / camera specifics) onto the matching three.js fields, and auto-detects material props (direct / uniform / TSL `UniformNode`) on the target's `material` at tween creation.
|
||||
*/
|
||||
|
||||
|
||||
const colorTarget = (t) => t.isLight ? t : t.material;
|
||||
|
||||
// Per-mesh skew and transformOrigin state, stored under a private symbol so we add one hidden property instead of polluting the Object3D surface with seven underscored fields.
|
||||
const skewSymbol = Symbol('animejs.skewOrigin');
|
||||
|
||||
// Fallback opacity storage for Object3D targets without a material such as Groups or CSS2DObjects.
|
||||
// Without it reads always return the default 1, so reverse-direction tweens between two non-default values collapse to a no-op delta and the visibility flip never fires on the way back.
|
||||
const opacitySymbol = Symbol('animejs.opacity');
|
||||
|
||||
/**
|
||||
* Sets `o.visible` based on opacity and current scale. If `opacity` is omitted, reads it from `o.material` (defaults to `1` when no material is present).
|
||||
*
|
||||
* @param {Object3D & { material?: import('three').Material | import('three').Material[] }} o
|
||||
* @param {number} [opacity]
|
||||
*/
|
||||
function setVisibility(o, opacity) {
|
||||
if (opacity === undefined) {
|
||||
if (o.material) {
|
||||
opacity = helpers.readScalar(o.material, 'opacity', helpers.PATH_DIRECT, 1);
|
||||
} else {
|
||||
const v = o[opacitySymbol];
|
||||
opacity = v === undefined ? 1 : v;
|
||||
}
|
||||
}
|
||||
const s = o.scale;
|
||||
o.visible = !!(opacity && s.x && s.y && s.z);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs a per-mesh `updateMatrix` override on first skew / transformOrigin write. The override calls the original three.js compose, then patches the result with `applySkewOrigin` whenever any axis is non-zero. Idempotent.
|
||||
*
|
||||
* @param {any} mesh
|
||||
* @return {{ skewX: number, skewY: number, skewZ: number, originX: number, originY: number, originZ: number }}
|
||||
*/
|
||||
function installSkewMatrix(mesh) {
|
||||
let s = mesh[skewSymbol];
|
||||
if (s) return s;
|
||||
s = mesh[skewSymbol] = { skewX: 0, skewY: 0, skewZ: 0, originX: 0, originY: 0, originZ: 0 };
|
||||
const original = mesh.updateMatrix;
|
||||
mesh.updateMatrix = function () {
|
||||
original.call(this);
|
||||
const st = this[skewSymbol];
|
||||
if (st.skewX !== 0 || st.skewY !== 0 || st.skewZ !== 0 || st.originX !== 0 || st.originY !== 0 || st.originZ !== 0) {
|
||||
helpers.applySkewOrigin(this.matrix.elements, st.skewX, st.skewY, st.skewZ, st.originX, st.originY, st.originZ);
|
||||
}
|
||||
};
|
||||
return s;
|
||||
}
|
||||
|
||||
const threeObject3D = adapter.threeAdapter.registerTargetAdapter((t) => t instanceof three.Object3D);
|
||||
|
||||
// Position
|
||||
threeObject3D.registerProperty('x', (t) => t.position.x, (t, v) => { t.position.x = v; });
|
||||
threeObject3D.registerProperty('y', (t) => t.position.y, (t, v) => { t.position.y = v; });
|
||||
threeObject3D.registerProperty('z', (t) => t.position.z, (t, v) => { t.position.z = v; });
|
||||
|
||||
// Rotation in degrees
|
||||
threeObject3D.registerProperty('rotateX', (t) => number.radToDeg(t.rotation.x), (t, v) => { t.rotation.x = number.degToRad(v); });
|
||||
threeObject3D.registerProperty('rotateY', (t) => number.radToDeg(t.rotation.y), (t, v) => { t.rotation.y = number.degToRad(v); });
|
||||
threeObject3D.registerProperty('rotateZ', (t) => number.radToDeg(t.rotation.z), (t, v) => { t.rotation.z = number.degToRad(v); });
|
||||
|
||||
// Scale per-axis and uniform
|
||||
threeObject3D.registerProperty('scaleX', (t) => t.scale.x, (t, v) => { t.scale.x = v; setVisibility(t); });
|
||||
threeObject3D.registerProperty('scaleY', (t) => t.scale.y, (t, v) => { t.scale.y = v; setVisibility(t); });
|
||||
threeObject3D.registerProperty('scaleZ', (t) => t.scale.z, (t, v) => { t.scale.z = v; setVisibility(t); });
|
||||
threeObject3D.registerProperty('scale',
|
||||
(t) => t.scale.x,
|
||||
(t, v) => {
|
||||
t.scale.x = v; t.scale.y = v; t.scale.z = v;
|
||||
setVisibility(t);
|
||||
},
|
||||
);
|
||||
|
||||
// Material
|
||||
threeObject3D.registerProperty('visible', (t) => t.visible, (t, v) => { t.visible = !!v; });
|
||||
threeObject3D.registerProperty('opacity',
|
||||
(t) => {
|
||||
if (t.material) return helpers.readScalar(t.material, 'opacity', helpers.PATH_DIRECT, 1);
|
||||
const v = t[opacitySymbol];
|
||||
return v === undefined ? 1 : v;
|
||||
},
|
||||
(t, v) => {
|
||||
if (t.material) helpers.writeScalar(t.material, 'opacity', v, helpers.PATH_DIRECT);
|
||||
else t[opacitySymbol] = v;
|
||||
setVisibility(t, v);
|
||||
},
|
||||
(t) => !t.isLight,
|
||||
);
|
||||
threeObject3D.registerProperty('color',
|
||||
(t) => helpers.readColorAt(colorTarget(t), 'color', helpers.PATH_DIRECT),
|
||||
(t, _, tw) => helpers.writeColorAt(colorTarget(t), 'color', tw._numbers, helpers.PATH_DIRECT),
|
||||
);
|
||||
|
||||
// HemisphereLight
|
||||
threeObject3D.registerProperty('groundColor',
|
||||
(t) => helpers.readColorAt(t, 'groundColor', helpers.PATH_DIRECT),
|
||||
(t, _, tw) => helpers.writeColorAt(t, 'groundColor', tw._numbers, helpers.PATH_DIRECT),
|
||||
(t) => !!t.groundColor,
|
||||
);
|
||||
|
||||
// Scene background, lazily initializes scene background to a Color on first write so the user does not have to set one upfront.
|
||||
threeObject3D.registerProperty('background',
|
||||
(t) => {
|
||||
const bg = /** @type {any} */(t).background;
|
||||
return bg && bg.isColor ? helpers.readColorHex(bg) : '#000000';
|
||||
},
|
||||
(t, _, tw) => {
|
||||
const scene = /** @type {any} */(t);
|
||||
let bg = scene.background;
|
||||
if (!bg || !bg.isColor) {
|
||||
bg = new three.Color();
|
||||
scene.background = bg;
|
||||
}
|
||||
const ns = tw._numbers;
|
||||
bg.setRGB(ns[0] * helpers.COLOR_NORM, ns[1] * helpers.COLOR_NORM, ns[2] * helpers.COLOR_NORM, three.SRGBColorSpace);
|
||||
},
|
||||
(t) => !!t.isScene,
|
||||
);
|
||||
|
||||
// Method-bridged props for Audio and PerspectiveCamera focalLength, read via getXxx and write via setXxx.
|
||||
const registerMethodProp = (apiName, getter, setter, gate) => {
|
||||
threeObject3D.registerProperty(apiName,
|
||||
(t) => t[getter](),
|
||||
(t, v) => { t[setter](v); },
|
||||
(t) => !!t[gate],
|
||||
);
|
||||
};
|
||||
registerMethodProp('volume', 'getVolume', 'setVolume', 'setVolume');
|
||||
// PositionalAudio
|
||||
registerMethodProp('refDistance', 'getRefDistance', 'setRefDistance', 'setRefDistance');
|
||||
registerMethodProp('rolloffFactor', 'getRolloffFactor', 'setRolloffFactor', 'setRefDistance');
|
||||
registerMethodProp('maxDistance', 'getMaxDistance', 'setMaxDistance', 'setRefDistance');
|
||||
// PerspectiveCamera
|
||||
registerMethodProp('focalLength', 'getFocalLength', 'setFocalLength', 'setFocalLength');
|
||||
|
||||
// Camera projection-update props, setter writes the value then calls updateProjectionMatrix.
|
||||
const registerCameraProp = (apiName, gate) => {
|
||||
threeObject3D.registerProperty(apiName,
|
||||
(t) => t[apiName],
|
||||
(t, v) => { t[apiName] = v; t.updateProjectionMatrix(); },
|
||||
gate,
|
||||
);
|
||||
};
|
||||
const isPersp = (t) => !!t.isPerspectiveCamera;
|
||||
const isOrtho = (t) => !!t.isOrthographicCamera;
|
||||
registerCameraProp('fov', isPersp);
|
||||
registerCameraProp('aspect', isPersp);
|
||||
registerCameraProp('left', isOrtho);
|
||||
registerCameraProp('right', isOrtho);
|
||||
registerCameraProp('top', isOrtho);
|
||||
registerCameraProp('bottom', isOrtho);
|
||||
|
||||
// Skew in degrees and transform-origin in object-space.
|
||||
// Patches mesh updateMatrix on first write so the standard PRS compose is followed by an in-place skew and origin shift.
|
||||
// Reads default to 0 for meshes that have never been written.
|
||||
/**
|
||||
* @param {String} apiName
|
||||
* @param {String} key
|
||||
*/
|
||||
const registerSkewProp = (apiName, key) => {
|
||||
threeObject3D.registerProperty(apiName,
|
||||
(t) => { const s = /** @type {any} */(t)[skewSymbol]; return s ? s[key] : 0; },
|
||||
(t, v) => { installSkewMatrix(t)[key] = v; },
|
||||
);
|
||||
};
|
||||
registerSkewProp('skewX', 'skewX');
|
||||
registerSkewProp('skewY', 'skewY');
|
||||
registerSkewProp('skewZ', 'skewZ');
|
||||
registerSkewProp('transformOriginX', 'originX');
|
||||
registerSkewProp('transformOriginY', 'originY');
|
||||
registerSkewProp('transformOriginZ', 'originZ');
|
||||
|
||||
// Shorthand 3-token string x y z or 2-string from-to array routed via the engine COMPLEX path.
|
||||
// The setter reads tween _numbers for the per-frame lerped triplet.
|
||||
threeObject3D.registerProperty('transformOrigin',
|
||||
(t) => {
|
||||
const s = /** @type {any} */(t)[skewSymbol];
|
||||
return s ? `${s.originX} ${s.originY} ${s.originZ}` : '0 0 0';
|
||||
},
|
||||
(t, _, tw) => {
|
||||
const s = installSkewMatrix(t);
|
||||
const ns = tw._numbers;
|
||||
s.originX = ns[0];
|
||||
s.originY = ns[1];
|
||||
s.originZ = ns[2];
|
||||
},
|
||||
);
|
||||
|
||||
// Shared by both camera types.
|
||||
const isCamera = (t) => !!t.isPerspectiveCamera || !!t.isOrthographicCamera;
|
||||
registerCameraProp('near', isCamera);
|
||||
registerCameraProp('far', isCamera);
|
||||
registerCameraProp('zoom', isCamera);
|
||||
|
||||
// Auto-detection for material props on meshes and direct Vector / Color fields on the target is provided by the shared resolvers in resolvers.js.
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { Object3D, Color, SRGBColorSpace } from 'three';
|
||||
import { radToDeg, degToRad } from '../../utils/number.js';
|
||||
import { threeAdapter } from './adapter.js';
|
||||
import { readScalar, PATH_DIRECT, writeScalar, readColorAt, writeColorAt, readColorHex, COLOR_NORM, applySkewOrigin } from './helpers.js';
|
||||
|
||||
/**
|
||||
* `Object3D` adapter. Maps flat properties (position, rotation, scale, opacity, color, visible, light / audio / camera specifics) onto the matching three.js fields, and auto-detects material props (direct / uniform / TSL `UniformNode`) on the target's `material` at tween creation.
|
||||
*/
|
||||
|
||||
|
||||
const colorTarget = (t) => t.isLight ? t : t.material;
|
||||
|
||||
// Per-mesh skew and transformOrigin state, stored under a private symbol so we add one hidden property instead of polluting the Object3D surface with seven underscored fields.
|
||||
const skewSymbol = Symbol('animejs.skewOrigin');
|
||||
|
||||
// Fallback opacity storage for Object3D targets without a material such as Groups or CSS2DObjects.
|
||||
// Without it reads always return the default 1, so reverse-direction tweens between two non-default values collapse to a no-op delta and the visibility flip never fires on the way back.
|
||||
const opacitySymbol = Symbol('animejs.opacity');
|
||||
|
||||
/**
|
||||
* Sets `o.visible` based on opacity and current scale. If `opacity` is omitted, reads it from `o.material` (defaults to `1` when no material is present).
|
||||
*
|
||||
* @param {Object3D & { material?: import('three').Material | import('three').Material[] }} o
|
||||
* @param {number} [opacity]
|
||||
*/
|
||||
function setVisibility(o, opacity) {
|
||||
if (opacity === undefined) {
|
||||
if (o.material) {
|
||||
opacity = readScalar(o.material, 'opacity', PATH_DIRECT, 1);
|
||||
} else {
|
||||
const v = o[opacitySymbol];
|
||||
opacity = v === undefined ? 1 : v;
|
||||
}
|
||||
}
|
||||
const s = o.scale;
|
||||
o.visible = !!(opacity && s.x && s.y && s.z);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs a per-mesh `updateMatrix` override on first skew / transformOrigin write. The override calls the original three.js compose, then patches the result with `applySkewOrigin` whenever any axis is non-zero. Idempotent.
|
||||
*
|
||||
* @param {any} mesh
|
||||
* @return {{ skewX: number, skewY: number, skewZ: number, originX: number, originY: number, originZ: number }}
|
||||
*/
|
||||
function installSkewMatrix(mesh) {
|
||||
let s = mesh[skewSymbol];
|
||||
if (s) return s;
|
||||
s = mesh[skewSymbol] = { skewX: 0, skewY: 0, skewZ: 0, originX: 0, originY: 0, originZ: 0 };
|
||||
const original = mesh.updateMatrix;
|
||||
mesh.updateMatrix = function () {
|
||||
original.call(this);
|
||||
const st = this[skewSymbol];
|
||||
if (st.skewX !== 0 || st.skewY !== 0 || st.skewZ !== 0 || st.originX !== 0 || st.originY !== 0 || st.originZ !== 0) {
|
||||
applySkewOrigin(this.matrix.elements, st.skewX, st.skewY, st.skewZ, st.originX, st.originY, st.originZ);
|
||||
}
|
||||
};
|
||||
return s;
|
||||
}
|
||||
|
||||
const threeObject3D = threeAdapter.registerTargetAdapter((t) => t instanceof Object3D);
|
||||
|
||||
// Position
|
||||
threeObject3D.registerProperty('x', (t) => t.position.x, (t, v) => { t.position.x = v; });
|
||||
threeObject3D.registerProperty('y', (t) => t.position.y, (t, v) => { t.position.y = v; });
|
||||
threeObject3D.registerProperty('z', (t) => t.position.z, (t, v) => { t.position.z = v; });
|
||||
|
||||
// Rotation in degrees
|
||||
threeObject3D.registerProperty('rotateX', (t) => radToDeg(t.rotation.x), (t, v) => { t.rotation.x = degToRad(v); });
|
||||
threeObject3D.registerProperty('rotateY', (t) => radToDeg(t.rotation.y), (t, v) => { t.rotation.y = degToRad(v); });
|
||||
threeObject3D.registerProperty('rotateZ', (t) => radToDeg(t.rotation.z), (t, v) => { t.rotation.z = degToRad(v); });
|
||||
|
||||
// Scale per-axis and uniform
|
||||
threeObject3D.registerProperty('scaleX', (t) => t.scale.x, (t, v) => { t.scale.x = v; setVisibility(t); });
|
||||
threeObject3D.registerProperty('scaleY', (t) => t.scale.y, (t, v) => { t.scale.y = v; setVisibility(t); });
|
||||
threeObject3D.registerProperty('scaleZ', (t) => t.scale.z, (t, v) => { t.scale.z = v; setVisibility(t); });
|
||||
threeObject3D.registerProperty('scale',
|
||||
(t) => t.scale.x,
|
||||
(t, v) => {
|
||||
t.scale.x = v; t.scale.y = v; t.scale.z = v;
|
||||
setVisibility(t);
|
||||
},
|
||||
);
|
||||
|
||||
// Material
|
||||
threeObject3D.registerProperty('visible', (t) => t.visible, (t, v) => { t.visible = !!v; });
|
||||
threeObject3D.registerProperty('opacity',
|
||||
(t) => {
|
||||
if (t.material) return readScalar(t.material, 'opacity', PATH_DIRECT, 1);
|
||||
const v = t[opacitySymbol];
|
||||
return v === undefined ? 1 : v;
|
||||
},
|
||||
(t, v) => {
|
||||
if (t.material) writeScalar(t.material, 'opacity', v, PATH_DIRECT);
|
||||
else t[opacitySymbol] = v;
|
||||
setVisibility(t, v);
|
||||
},
|
||||
(t) => !t.isLight,
|
||||
);
|
||||
threeObject3D.registerProperty('color',
|
||||
(t) => readColorAt(colorTarget(t), 'color', PATH_DIRECT),
|
||||
(t, _, tw) => writeColorAt(colorTarget(t), 'color', tw._numbers, PATH_DIRECT),
|
||||
);
|
||||
|
||||
// HemisphereLight
|
||||
threeObject3D.registerProperty('groundColor',
|
||||
(t) => readColorAt(t, 'groundColor', PATH_DIRECT),
|
||||
(t, _, tw) => writeColorAt(t, 'groundColor', tw._numbers, PATH_DIRECT),
|
||||
(t) => !!t.groundColor,
|
||||
);
|
||||
|
||||
// Scene background, lazily initializes scene background to a Color on first write so the user does not have to set one upfront.
|
||||
threeObject3D.registerProperty('background',
|
||||
(t) => {
|
||||
const bg = /** @type {any} */(t).background;
|
||||
return bg && bg.isColor ? readColorHex(bg) : '#000000';
|
||||
},
|
||||
(t, _, tw) => {
|
||||
const scene = /** @type {any} */(t);
|
||||
let bg = scene.background;
|
||||
if (!bg || !bg.isColor) {
|
||||
bg = new Color();
|
||||
scene.background = bg;
|
||||
}
|
||||
const ns = tw._numbers;
|
||||
bg.setRGB(ns[0] * COLOR_NORM, ns[1] * COLOR_NORM, ns[2] * COLOR_NORM, SRGBColorSpace);
|
||||
},
|
||||
(t) => !!t.isScene,
|
||||
);
|
||||
|
||||
// Method-bridged props for Audio and PerspectiveCamera focalLength, read via getXxx and write via setXxx.
|
||||
const registerMethodProp = (apiName, getter, setter, gate) => {
|
||||
threeObject3D.registerProperty(apiName,
|
||||
(t) => t[getter](),
|
||||
(t, v) => { t[setter](v); },
|
||||
(t) => !!t[gate],
|
||||
);
|
||||
};
|
||||
registerMethodProp('volume', 'getVolume', 'setVolume', 'setVolume');
|
||||
// PositionalAudio
|
||||
registerMethodProp('refDistance', 'getRefDistance', 'setRefDistance', 'setRefDistance');
|
||||
registerMethodProp('rolloffFactor', 'getRolloffFactor', 'setRolloffFactor', 'setRefDistance');
|
||||
registerMethodProp('maxDistance', 'getMaxDistance', 'setMaxDistance', 'setRefDistance');
|
||||
// PerspectiveCamera
|
||||
registerMethodProp('focalLength', 'getFocalLength', 'setFocalLength', 'setFocalLength');
|
||||
|
||||
// Camera projection-update props, setter writes the value then calls updateProjectionMatrix.
|
||||
const registerCameraProp = (apiName, gate) => {
|
||||
threeObject3D.registerProperty(apiName,
|
||||
(t) => t[apiName],
|
||||
(t, v) => { t[apiName] = v; t.updateProjectionMatrix(); },
|
||||
gate,
|
||||
);
|
||||
};
|
||||
const isPersp = (t) => !!t.isPerspectiveCamera;
|
||||
const isOrtho = (t) => !!t.isOrthographicCamera;
|
||||
registerCameraProp('fov', isPersp);
|
||||
registerCameraProp('aspect', isPersp);
|
||||
registerCameraProp('left', isOrtho);
|
||||
registerCameraProp('right', isOrtho);
|
||||
registerCameraProp('top', isOrtho);
|
||||
registerCameraProp('bottom', isOrtho);
|
||||
|
||||
// Skew in degrees and transform-origin in object-space.
|
||||
// Patches mesh updateMatrix on first write so the standard PRS compose is followed by an in-place skew and origin shift.
|
||||
// Reads default to 0 for meshes that have never been written.
|
||||
/**
|
||||
* @param {String} apiName
|
||||
* @param {String} key
|
||||
*/
|
||||
const registerSkewProp = (apiName, key) => {
|
||||
threeObject3D.registerProperty(apiName,
|
||||
(t) => { const s = /** @type {any} */(t)[skewSymbol]; return s ? s[key] : 0; },
|
||||
(t, v) => { installSkewMatrix(t)[key] = v; },
|
||||
);
|
||||
};
|
||||
registerSkewProp('skewX', 'skewX');
|
||||
registerSkewProp('skewY', 'skewY');
|
||||
registerSkewProp('skewZ', 'skewZ');
|
||||
registerSkewProp('transformOriginX', 'originX');
|
||||
registerSkewProp('transformOriginY', 'originY');
|
||||
registerSkewProp('transformOriginZ', 'originZ');
|
||||
|
||||
// Shorthand 3-token string x y z or 2-string from-to array routed via the engine COMPLEX path.
|
||||
// The setter reads tween _numbers for the per-frame lerped triplet.
|
||||
threeObject3D.registerProperty('transformOrigin',
|
||||
(t) => {
|
||||
const s = /** @type {any} */(t)[skewSymbol];
|
||||
return s ? `${s.originX} ${s.originY} ${s.originZ}` : '0 0 0';
|
||||
},
|
||||
(t, _, tw) => {
|
||||
const s = installSkewMatrix(t);
|
||||
const ns = tw._numbers;
|
||||
s.originX = ns[0];
|
||||
s.originY = ns[1];
|
||||
s.originZ = ns[2];
|
||||
},
|
||||
);
|
||||
|
||||
// Shared by both camera types.
|
||||
const isCamera = (t) => !!t.isPerspectiveCamera || !!t.isOrthographicCamera;
|
||||
registerCameraProp('near', isCamera);
|
||||
registerCameraProp('far', isCamera);
|
||||
registerCameraProp('zoom', isCamera);
|
||||
|
||||
// Auto-detection for material props on meshes and direct Vector / Color fields on the target is provided by the shared resolvers in resolvers.js.
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var adapter = require('./adapter.cjs');
|
||||
var number = require('../../utils/number.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
|
||||
/**
|
||||
* Global property resolvers for three.js targets. Auto-detect `Color`-typed properties, `Vector2/3/4` axis components, shader uniforms, and TSL `UniformNode` slots on any three.js object. For mesh-like targets, a second resolver walks to `target.material` and runs the same detection there.
|
||||
*/
|
||||
|
||||
|
||||
const identity = (t) => t;
|
||||
const getMaterial = (t) => t.material;
|
||||
|
||||
const directColorCache = [{}, {}, {}];
|
||||
const directScalarCache = [{}, {}, {}];
|
||||
const directVectorCache = [{}, {}, {}];
|
||||
|
||||
const materialColorCache = [{}, {}, {}];
|
||||
const materialScalarCache = [{}, {}, {}];
|
||||
const materialVectorCache = [{}, {}, {}];
|
||||
|
||||
const buildEntry = (name, d, getHost, colorCaches, scalarCaches, vectorCaches) => {
|
||||
const path = d.path;
|
||||
if (d.kind === helpers.KIND_COLOR) {
|
||||
const cache = colorCaches[path];
|
||||
return cache[name] || (cache[name] = {
|
||||
get: (t) => helpers.readColorAt(getHost(t), name, path),
|
||||
set: (t, _, tw) => helpers.writeColorAt(getHost(t), name, tw._numbers, path),
|
||||
});
|
||||
}
|
||||
if (d.kind === helpers.KIND_SCALAR) {
|
||||
const cache = scalarCaches[path];
|
||||
return cache[name] || (cache[name] = {
|
||||
get: (t) => helpers.readScalar(getHost(t), name, path),
|
||||
set: (t, v) => helpers.writeScalar(getHost(t), name, v, path),
|
||||
});
|
||||
}
|
||||
// KIND_VECTOR
|
||||
const base = d.base;
|
||||
const axis = d.axis;
|
||||
const cache = vectorCaches[path];
|
||||
return cache[name] || (cache[name] = {
|
||||
get: (t) => helpers.readVectorAt(getHost(t), base, axis, path),
|
||||
set: (t, v) => helpers.writeVectorAt(getHost(t), base, axis, v, path),
|
||||
});
|
||||
};
|
||||
|
||||
// Detect direct Color, Vector axis, uniforms, and UniformNode slots on the target.
|
||||
// Numeric or boolean direct fields fall through to the engine OBJECT path.
|
||||
adapter.threeAdapter.registerPropertyResolver((target, name) => {
|
||||
const d = helpers.classifyTargetProp(target, name);
|
||||
if (!d) return null;
|
||||
if (d.kind === helpers.KIND_SCALAR && d.path === helpers.PATH_DIRECT) return null;
|
||||
return buildEntry(name, d, identity, directColorCache, directScalarCache, directVectorCache);
|
||||
});
|
||||
|
||||
// Walk to target.material for meshes and other Object3D subclasses with a material field.
|
||||
// Skip when the target already exposes the name directly so a mesh-level mapping wins.
|
||||
adapter.threeAdapter.registerPropertyResolver((target, name) => {
|
||||
if (target[name] !== undefined) return null;
|
||||
const m = target.material;
|
||||
if (!m) return null;
|
||||
const first = Array.isArray(m) ? m[0] : m;
|
||||
if (!first) return null;
|
||||
const d = helpers.classifyTargetProp(first, name);
|
||||
if (!d) return null;
|
||||
return buildEntry(name, d, getMaterial, materialColorCache, materialScalarCache, materialVectorCache);
|
||||
});
|
||||
|
||||
// Convert angle-named scalar fields between degrees and radians so users animate in degrees on any three.js target.
|
||||
// Object3D Euler rotation is excluded because Euler is not a number, the rotateX/Y/Z mappings handle it.
|
||||
const ANGLE_NAMES = { rotation: 1, angle: 1 };
|
||||
const angleEntries = {};
|
||||
adapter.threeAdapter.registerPropertyResolver((target, name) => {
|
||||
if (!ANGLE_NAMES[name]) return null;
|
||||
if (typeof target[name] !== 'number') return null;
|
||||
return angleEntries[name] || (angleEntries[name] = {
|
||||
get: (t) => number.radToDeg(t[name]),
|
||||
set: (t, v) => { t[name] = number.degToRad(v); },
|
||||
});
|
||||
});
|
||||
|
||||
// Decompose Euler-typed angle fields to axis components in degrees, like rotationX, rotationY, rotationZ when rotation is an Euler.
|
||||
// Object3D mappings win because static adapter props beat resolvers, so this only catches non-Object3D targets with an Euler rotation field.
|
||||
const eulerAxisEntries = {};
|
||||
adapter.threeAdapter.registerPropertyResolver((target, name) => {
|
||||
const axis = helpers.AXIS_MAP[name[name.length - 1]];
|
||||
if (!axis) return null;
|
||||
const base = name.slice(0, -1);
|
||||
if (!ANGLE_NAMES[base]) return null;
|
||||
const v = target[base];
|
||||
if (!v || !v.isEuler) return null;
|
||||
return eulerAxisEntries[name] || (eulerAxisEntries[name] = {
|
||||
get: (t) => number.radToDeg(t[base][axis]),
|
||||
set: (t, v) => { t[base][axis] = number.degToRad(v); },
|
||||
});
|
||||
});
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { threeAdapter } from './adapter.js';
|
||||
import { radToDeg, degToRad } from '../../utils/number.js';
|
||||
import { classifyTargetProp, KIND_SCALAR, PATH_DIRECT, AXIS_MAP, KIND_COLOR, writeColorAt, readColorAt, writeScalar, readScalar, writeVectorAt, readVectorAt } from './helpers.js';
|
||||
|
||||
/**
|
||||
* Global property resolvers for three.js targets. Auto-detect `Color`-typed properties, `Vector2/3/4` axis components, shader uniforms, and TSL `UniformNode` slots on any three.js object. For mesh-like targets, a second resolver walks to `target.material` and runs the same detection there.
|
||||
*/
|
||||
|
||||
|
||||
const identity = (t) => t;
|
||||
const getMaterial = (t) => t.material;
|
||||
|
||||
const directColorCache = [{}, {}, {}];
|
||||
const directScalarCache = [{}, {}, {}];
|
||||
const directVectorCache = [{}, {}, {}];
|
||||
|
||||
const materialColorCache = [{}, {}, {}];
|
||||
const materialScalarCache = [{}, {}, {}];
|
||||
const materialVectorCache = [{}, {}, {}];
|
||||
|
||||
const buildEntry = (name, d, getHost, colorCaches, scalarCaches, vectorCaches) => {
|
||||
const path = d.path;
|
||||
if (d.kind === KIND_COLOR) {
|
||||
const cache = colorCaches[path];
|
||||
return cache[name] || (cache[name] = {
|
||||
get: (t) => readColorAt(getHost(t), name, path),
|
||||
set: (t, _, tw) => writeColorAt(getHost(t), name, tw._numbers, path),
|
||||
});
|
||||
}
|
||||
if (d.kind === KIND_SCALAR) {
|
||||
const cache = scalarCaches[path];
|
||||
return cache[name] || (cache[name] = {
|
||||
get: (t) => readScalar(getHost(t), name, path),
|
||||
set: (t, v) => writeScalar(getHost(t), name, v, path),
|
||||
});
|
||||
}
|
||||
// KIND_VECTOR
|
||||
const base = d.base;
|
||||
const axis = d.axis;
|
||||
const cache = vectorCaches[path];
|
||||
return cache[name] || (cache[name] = {
|
||||
get: (t) => readVectorAt(getHost(t), base, axis, path),
|
||||
set: (t, v) => writeVectorAt(getHost(t), base, axis, v, path),
|
||||
});
|
||||
};
|
||||
|
||||
// Detect direct Color, Vector axis, uniforms, and UniformNode slots on the target.
|
||||
// Numeric or boolean direct fields fall through to the engine OBJECT path.
|
||||
threeAdapter.registerPropertyResolver((target, name) => {
|
||||
const d = classifyTargetProp(target, name);
|
||||
if (!d) return null;
|
||||
if (d.kind === KIND_SCALAR && d.path === PATH_DIRECT) return null;
|
||||
return buildEntry(name, d, identity, directColorCache, directScalarCache, directVectorCache);
|
||||
});
|
||||
|
||||
// Walk to target.material for meshes and other Object3D subclasses with a material field.
|
||||
// Skip when the target already exposes the name directly so a mesh-level mapping wins.
|
||||
threeAdapter.registerPropertyResolver((target, name) => {
|
||||
if (target[name] !== undefined) return null;
|
||||
const m = target.material;
|
||||
if (!m) return null;
|
||||
const first = Array.isArray(m) ? m[0] : m;
|
||||
if (!first) return null;
|
||||
const d = classifyTargetProp(first, name);
|
||||
if (!d) return null;
|
||||
return buildEntry(name, d, getMaterial, materialColorCache, materialScalarCache, materialVectorCache);
|
||||
});
|
||||
|
||||
// Convert angle-named scalar fields between degrees and radians so users animate in degrees on any three.js target.
|
||||
// Object3D Euler rotation is excluded because Euler is not a number, the rotateX/Y/Z mappings handle it.
|
||||
const ANGLE_NAMES = { rotation: 1, angle: 1 };
|
||||
const angleEntries = {};
|
||||
threeAdapter.registerPropertyResolver((target, name) => {
|
||||
if (!ANGLE_NAMES[name]) return null;
|
||||
if (typeof target[name] !== 'number') return null;
|
||||
return angleEntries[name] || (angleEntries[name] = {
|
||||
get: (t) => radToDeg(t[name]),
|
||||
set: (t, v) => { t[name] = degToRad(v); },
|
||||
});
|
||||
});
|
||||
|
||||
// Decompose Euler-typed angle fields to axis components in degrees, like rotationX, rotationY, rotationZ when rotation is an Euler.
|
||||
// Object3D mappings win because static adapter props beat resolvers, so this only catches non-Object3D targets with an Euler rotation field.
|
||||
const eulerAxisEntries = {};
|
||||
threeAdapter.registerPropertyResolver((target, name) => {
|
||||
const axis = AXIS_MAP[name[name.length - 1]];
|
||||
if (!axis) return null;
|
||||
const base = name.slice(0, -1);
|
||||
if (!ANGLE_NAMES[base]) return null;
|
||||
const v = target[base];
|
||||
if (!v || !v.isEuler) return null;
|
||||
return eulerAxisEntries[name] || (eulerAxisEntries[name] = {
|
||||
get: (t) => radToDeg(t[base][axis]),
|
||||
set: (t, v) => { t[base][axis] = degToRad(v); },
|
||||
});
|
||||
});
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Anime.js - adapters - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var three = require('three');
|
||||
var adapter = require('./adapter.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
|
||||
/**
|
||||
* Bare `UniformNode` adapter. Auto-detects `UniformNode` instances and exposes their `.value` for animation. Scalars and booleans animate via `value`, `Color` uniforms via `color`, and `Vector2/3/4` uniforms via `x` / `y` / `z` / `w` axes.
|
||||
*
|
||||
* import 'animejs/bindings/three';
|
||||
* import { uniform } from 'three/tsl';
|
||||
* animate(uniform(0), { value: 1 });
|
||||
* animate(uniform(new Color()), { color: '#0f0' });
|
||||
* animate(uniform(new Vector3()), { x: 1, y: 0.5 });
|
||||
*
|
||||
* `UniformNode` slots assigned to `NodeMaterial` (`material.colorNode`, `material.offsetNode`, ...) are auto-detected by the shared resolvers in `resolvers.js`. Non-uniform nodes (`mix`, `add`, computed expressions), `Matrix3/4` and `Texture` valued uniforms, and `UniformArrayNode` / `BufferNode` are out of scope and fall through to the engine's direct property path.
|
||||
*/
|
||||
|
||||
|
||||
const uniformNode = adapter.threeAdapter.registerTargetAdapter((t) => !!(t && t.isUniformNode));
|
||||
|
||||
// Scalar and bool uniforms animate via the engine OBJECT fallthrough on value, no adapter prop needed since the engine writes uniform value natively.
|
||||
uniformNode.registerProperty('color',
|
||||
(t) => helpers.readColorHex(t.value),
|
||||
(t, _, tw) => {
|
||||
const ns = tw._numbers;
|
||||
t.value.setRGB(ns[0] * helpers.COLOR_NORM, ns[1] * helpers.COLOR_NORM, ns[2] * helpers.COLOR_NORM, three.SRGBColorSpace);
|
||||
},
|
||||
(t) => !!(t.value && t.value.isColor),
|
||||
);
|
||||
uniformNode.registerProperty('x', (t) => t.value.x, (t, v) => { t.value.x = v; }, (t) => helpers.isVectorWith(t.value, 'x'));
|
||||
uniformNode.registerProperty('y', (t) => t.value.y, (t, v) => { t.value.y = v; }, (t) => helpers.isVectorWith(t.value, 'y'));
|
||||
uniformNode.registerProperty('z', (t) => t.value.z, (t, v) => { t.value.z = v; }, (t) => helpers.isVectorWith(t.value, 'z'));
|
||||
uniformNode.registerProperty('w', (t) => t.value.w, (t, v) => { t.value.w = v; }, (t) => helpers.isVectorWith(t.value, 'w'));
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Anime.js - adapters - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { SRGBColorSpace } from 'three';
|
||||
import { threeAdapter } from './adapter.js';
|
||||
import { readColorHex, COLOR_NORM, isVectorWith } from './helpers.js';
|
||||
|
||||
/**
|
||||
* Bare `UniformNode` adapter. Auto-detects `UniformNode` instances and exposes their `.value` for animation. Scalars and booleans animate via `value`, `Color` uniforms via `color`, and `Vector2/3/4` uniforms via `x` / `y` / `z` / `w` axes.
|
||||
*
|
||||
* import 'animejs/bindings/three';
|
||||
* import { uniform } from 'three/tsl';
|
||||
* animate(uniform(0), { value: 1 });
|
||||
* animate(uniform(new Color()), { color: '#0f0' });
|
||||
* animate(uniform(new Vector3()), { x: 1, y: 0.5 });
|
||||
*
|
||||
* `UniformNode` slots assigned to `NodeMaterial` (`material.colorNode`, `material.offsetNode`, ...) are auto-detected by the shared resolvers in `resolvers.js`. Non-uniform nodes (`mix`, `add`, computed expressions), `Matrix3/4` and `Texture` valued uniforms, and `UniformArrayNode` / `BufferNode` are out of scope and fall through to the engine's direct property path.
|
||||
*/
|
||||
|
||||
|
||||
const uniformNode = threeAdapter.registerTargetAdapter((t) => !!(t && t.isUniformNode));
|
||||
|
||||
// Scalar and bool uniforms animate via the engine OBJECT fallthrough on value, no adapter prop needed since the engine writes uniform value natively.
|
||||
uniformNode.registerProperty('color',
|
||||
(t) => readColorHex(t.value),
|
||||
(t, _, tw) => {
|
||||
const ns = tw._numbers;
|
||||
t.value.setRGB(ns[0] * COLOR_NORM, ns[1] * COLOR_NORM, ns[2] * COLOR_NORM, SRGBColorSpace);
|
||||
},
|
||||
(t) => !!(t.value && t.value.isColor),
|
||||
);
|
||||
uniformNode.registerProperty('x', (t) => t.value.x, (t, v) => { t.value.x = v; }, (t) => isVectorWith(t.value, 'x'));
|
||||
uniformNode.registerProperty('y', (t) => t.value.y, (t, v) => { t.value.y = v; }, (t) => isVectorWith(t.value, 'y'));
|
||||
uniformNode.registerProperty('z', (t) => t.value.z, (t, v) => { t.value.z = v; }, (t) => isVectorWith(t.value, 'z'));
|
||||
uniformNode.registerProperty('w', (t) => t.value.w, (t, v) => { t.value.w = v; }, (t) => isVectorWith(t.value, 'w'));
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Anime.js - animatable - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('../core/consts.cjs');
|
||||
var globals = require('../core/globals.cjs');
|
||||
var helpers = require('../core/helpers.cjs');
|
||||
var animation = require('../animation/animation.cjs');
|
||||
var parser = require('../easings/eases/parser.cjs');
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* TargetsParam,
|
||||
* AnimatableParams,
|
||||
* AnimationParams,
|
||||
* TweenParamsOptions,
|
||||
* Tween,
|
||||
* AnimatableProperty,
|
||||
* AnimatableObject,
|
||||
* } from '../types/index.js';
|
||||
*/
|
||||
|
||||
class Animatable {
|
||||
/**
|
||||
* @param {TargetsParam} targets
|
||||
* @param {AnimatableParams} parameters
|
||||
*/
|
||||
constructor(targets, parameters) {
|
||||
if (globals.scope.current) globals.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 = [];
|
||||
/** @type {Record<String, JSAnimation>} */
|
||||
this.animations = {};
|
||||
/** @type {JSAnimation|null} */
|
||||
this.callbacks = null;
|
||||
if (helpers.isUnd(targets) || helpers.isUnd(parameters)) return;
|
||||
for (let propName in parameters) {
|
||||
const paramValue = parameters[propName];
|
||||
if (helpers.isKey(propName)) {
|
||||
properties[propName] = paramValue;
|
||||
} else if (helpers.stringStartsWith(propName, 'on')) {
|
||||
callbacksAnimationParams[propName] = paramValue;
|
||||
} else {
|
||||
globalParams[propName] = paramValue;
|
||||
}
|
||||
}
|
||||
this.callbacks = new animation.JSAnimation({ v: 0 }, callbacksAnimationParams);
|
||||
for (let propName in properties) {
|
||||
const propValue = properties[propName];
|
||||
const isObjValue = helpers.isObj(propValue);
|
||||
/** @type {TweenParamsOptions} */
|
||||
let propParams = {};
|
||||
let to = '+=0';
|
||||
if (isObjValue) {
|
||||
const unit = propValue.unit;
|
||||
if (helpers.isStr(unit)) to += unit;
|
||||
} else {
|
||||
propParams.duration = propValue;
|
||||
}
|
||||
propParams[propName] = isObjValue ? helpers.mergeObjects({ to }, propValue) : to;
|
||||
const animParams = helpers.mergeObjects(globalParams, propParams);
|
||||
animParams.composition = consts.compositionTypes.replace;
|
||||
animParams.autoplay = false;
|
||||
const animation$1 = this.animations[propName] = new animation.JSAnimation(targets, animParams, null, 0, false).init();
|
||||
if (!this.targets.length) this.targets.push(...animation$1.targets);
|
||||
/** @type {AnimatableProperty} */
|
||||
this[propName] = (to, duration, ease) => {
|
||||
const tween = /** @type {Tween} */(animation$1._head);
|
||||
if (helpers.isUnd(to) && tween) {
|
||||
const numbers = tween._numbers;
|
||||
if (numbers && numbers.length) {
|
||||
return numbers;
|
||||
} else {
|
||||
return tween._modifier(tween._number);
|
||||
}
|
||||
} else {
|
||||
helpers.forEachChildren(animation$1, (/** @type {Tween} */tween) => {
|
||||
if (helpers.isArr(to)) {
|
||||
for (let i = 0, l = /** @type {Array} */(to).length; i < l; i++) {
|
||||
if (!helpers.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 (!helpers.isUnd(ease)) tween._ease = parser.parseEase(ease);
|
||||
tween._currentTime = 0;
|
||||
});
|
||||
if (!helpers.isUnd(duration)) animation$1.stretch(duration);
|
||||
animation$1.reset(true).resume();
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
revert() {
|
||||
for (let propName in this.animations) {
|
||||
this[propName] = consts.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));
|
||||
|
||||
exports.Animatable = Animatable;
|
||||
exports.createAnimatable = createAnimatable;
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* @import {
|
||||
* TargetsParam,
|
||||
* AnimatableParams,
|
||||
* AnimationParams,
|
||||
* TweenParamsOptions,
|
||||
* Tween,
|
||||
* AnimatableProperty,
|
||||
* AnimatableObject,
|
||||
* } from '../types/index.js';
|
||||
*/
|
||||
export class Animatable {
|
||||
/**
|
||||
* @param {TargetsParam} targets
|
||||
* @param {AnimatableParams} parameters
|
||||
*/
|
||||
constructor(targets: TargetsParam, parameters: AnimatableParams);
|
||||
targets: (HTMLElement | SVGElement | import("../types/index.js").JSTarget)[];
|
||||
/** @type {Record<String, JSAnimation>} */
|
||||
animations: Record<string, JSAnimation>;
|
||||
/** @type {JSAnimation|null} */
|
||||
callbacks: JSAnimation | null;
|
||||
revert(): this;
|
||||
}
|
||||
export function createAnimatable(targets: TargetsParam, parameters: AnimatableParams): AnimatableObject;
|
||||
import { JSAnimation } from '../animation/animation.js';
|
||||
import type { TargetsParam } from '../types/index.js';
|
||||
import type { AnimatableParams } from '../types/index.js';
|
||||
import type { AnimatableObject } from '../types/index.js';
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Anime.js - animatable - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { compositionTypes, noop } from '../core/consts.js';
|
||||
import { scope } from '../core/globals.js';
|
||||
import { isUnd, isKey, stringStartsWith, isObj, mergeObjects, forEachChildren, isArr, isStr } 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 = [];
|
||||
/** @type {Record<String, JSAnimation>} */
|
||||
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 };
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Anime.js - animatable - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var animatable = require('./animatable.cjs');
|
||||
|
||||
|
||||
|
||||
exports.Animatable = animatable.Animatable;
|
||||
exports.createAnimatable = animatable.createAnimatable;
|
||||
+1
@@ -0,0 +1 @@
|
||||
export * from "./animatable.js";
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Anime.js - animatable - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
export { Animatable, createAnimatable } from './animatable.js';
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Anime.js - animation - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('../core/consts.cjs');
|
||||
var helpers = require('../core/helpers.cjs');
|
||||
var render = require('../core/render.cjs');
|
||||
|
||||
const additive = {
|
||||
animation: null,
|
||||
update: consts.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: consts.minValue,
|
||||
computeDeltaTime: consts.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 === consts.valueTypes.COMPLEX || valueType === consts.valueTypes.COLOR ? helpers.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.render(animation, 1, 1, 0, consts.tickModes.FORCE);
|
||||
};
|
||||
}
|
||||
return animation;
|
||||
};
|
||||
|
||||
exports.addAdditiveAnimation = addAdditiveAnimation;
|
||||
exports.additive = additive;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
export namespace additive {
|
||||
export let animation: any;
|
||||
export { noop as update };
|
||||
}
|
||||
export function addAdditiveAnimation(lookups: TweenAdditiveLookups): AdditiveAnimation;
|
||||
export type AdditiveAnimation = {
|
||||
duration: number;
|
||||
_offset: number;
|
||||
_delay: number;
|
||||
_head: Tween;
|
||||
_tail: Tween;
|
||||
};
|
||||
import { noop } from '../core/consts.js';
|
||||
import type { TweenAdditiveLookups } from '../types/index.js';
|
||||
import type { Tween } from '../types/index.js';
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Anime.js - animation - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - 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 };
|
||||
+746
@@ -0,0 +1,746 @@
|
||||
/**
|
||||
* Anime.js - animation - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('../core/consts.cjs');
|
||||
var helpers = require('../core/helpers.cjs');
|
||||
var globals = require('../core/globals.cjs');
|
||||
var targets = require('../core/targets.cjs');
|
||||
var registry = require('../adapters/registry.cjs');
|
||||
var values = require('../core/values.cjs');
|
||||
var styles = require('../core/styles.cjs');
|
||||
var units = require('../core/units.cjs');
|
||||
var parser = require('../easings/eases/parser.cjs');
|
||||
var timer = require('../timer/timer.cjs');
|
||||
var composition = require('./composition.cjs');
|
||||
var additive = require('./additive.cjs');
|
||||
|
||||
/**
|
||||
* @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 = values.createDecomposedValueTargetObject();
|
||||
const toTargetObject = values.createDecomposedValueTargetObject();
|
||||
const inlineStylesStore = {};
|
||||
const toFunctionStore = { func: null };
|
||||
const fromFunctionStore = { func: null };
|
||||
const keyframesTargetArray = [null];
|
||||
const fastSetValuesArray = [null, null];
|
||||
/** @type {TweenKeyValue} */
|
||||
const keyObjectTarget = { to: null };
|
||||
|
||||
let tweenId = 0;
|
||||
let JSAnimationId = 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 (helpers.isArr(keyframes)) {
|
||||
const propertyNames = [].concat(.../** @type {DurationKeyframes} */(keyframes).map(key => Object.keys(key))).filter(helpers.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 (helpers.isKey(p)) {
|
||||
if (p === propName) {
|
||||
newKey.to = keyValue;
|
||||
}
|
||||
} else {
|
||||
newKey[p] = keyValue;
|
||||
}
|
||||
}
|
||||
return newKey;
|
||||
});
|
||||
properties[propName] = /** @type {ArraySyntaxValue} */(propArray);
|
||||
}
|
||||
|
||||
} else {
|
||||
const totalDuration = /** @type {Number} */(values.setValue(parameters.duration, globals.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 (helpers.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.Timer {
|
||||
/**
|
||||
* @param {TargetsParam} targets
|
||||
* @param {AnimationParams} parameters
|
||||
* @param {Timeline} [parent]
|
||||
* @param {Number} [parentPosition]
|
||||
* @param {Boolean} [fastSet=false]
|
||||
* @param {Number} [index=0]
|
||||
* @param {TargetsArray} [allTargets]
|
||||
*/
|
||||
constructor(
|
||||
targets$1,
|
||||
parameters,
|
||||
parent,
|
||||
parentPosition,
|
||||
fastSet = false,
|
||||
index = 0,
|
||||
allTargets
|
||||
) {
|
||||
|
||||
super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
|
||||
|
||||
/** @type {Tween} */
|
||||
this._head;
|
||||
/** @type {Tween} */
|
||||
this._tail;
|
||||
|
||||
++JSAnimationId;
|
||||
|
||||
const parsedTargets = targets.registerTargets(targets$1);
|
||||
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 ? helpers.mergeObjects(generateKeyframes(/** @type {DurationKeyframes} */(kfParams), parameters), parameters) : parameters);
|
||||
|
||||
const {
|
||||
id,
|
||||
delay,
|
||||
duration,
|
||||
ease,
|
||||
playbackEase,
|
||||
modifier,
|
||||
composition: composition$1,
|
||||
onRender,
|
||||
} = params;
|
||||
|
||||
const animDefaults = parent ? parent.defaults : globals.globals.defaults;
|
||||
const animEase = values.setValue(ease, animDefaults.ease);
|
||||
const animPlaybackEase = values.setValue(playbackEase, animDefaults.playbackEase);
|
||||
const parsedAnimPlaybackEase = animPlaybackEase ? parser.parseEase(animPlaybackEase) : null;
|
||||
const hasSpring = !helpers.isUnd(/** @type {Spring} */(animEase).ease);
|
||||
const tEasing = hasSpring ? /** @type {Spring} */(animEase).ease : values.setValue(ease, parsedAnimPlaybackEase ? 'linear' : animDefaults.ease);
|
||||
const tDuration = hasSpring ? /** @type {Spring} */(animEase).settlingDuration : values.setValue(duration, animDefaults.duration);
|
||||
const tDelay = values.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 = helpers.isUnd(composition$1) && targetsLength >= consts.K ? consts.compositionTypes.none : !helpers.isUnd(composition$1) ? composition$1 : 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} */(animEase).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 = allTargets || parsedTargets;
|
||||
|
||||
let lastTransformGroupIndex = NaN;
|
||||
let lastTransformGroupLength = NaN;
|
||||
|
||||
for (let p in params) {
|
||||
|
||||
if (helpers.isKey(p)) {
|
||||
|
||||
const tweenType = values.getTweenType(target, p);
|
||||
const adapterProp = registry.resolveAdapterEntry(target, p);
|
||||
|
||||
const propName = styles.sanitizePropertyName(p, target, tweenType);
|
||||
|
||||
let propValue = params[p];
|
||||
|
||||
const isPropValueArray = helpers.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 = !helpers.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 (helpers.isObj(keyframe)) {
|
||||
key = keyframe;
|
||||
} else {
|
||||
keyObjectTarget.to = /** @type {TweenParamValue} */(keyframe);
|
||||
key = keyObjectTarget;
|
||||
}
|
||||
|
||||
toFunctionStore.func = null;
|
||||
fromFunctionStore.func = null;
|
||||
|
||||
const computedComposition = values.getFunctionValue(values.setValue(key.composition, tComposition), target, ti, tl, null, null);
|
||||
const tweenComposition = helpers.isNum(computedComposition) ? computedComposition : consts.compositionTypes[computedComposition];
|
||||
if (!siblings && tweenComposition !== consts.compositionTypes.none) siblings = composition.getTweenSiblings(target, propName);
|
||||
// Timelines pass the last sibling tween if it belongs to the same timeline
|
||||
// Standalone animations only pass prevTween when the property has multiple keyframes
|
||||
const tailTween = siblings ? siblings._tail : null;
|
||||
const prevSiblingTween = parent && tailTween && tailTween.parent.parent === parent ? tailTween : prevTween;
|
||||
const computedToValue = values.getFunctionValue(key.to, target, ti, tl, toFunctionStore, prevSiblingTween);
|
||||
|
||||
let tweenToValue;
|
||||
// Allows function based values to return an object syntax value ({to: v})
|
||||
if (helpers.isObj(computedToValue) && !helpers.isUnd(computedToValue.to)) {
|
||||
key = computedToValue;
|
||||
tweenToValue = computedToValue.to;
|
||||
} else {
|
||||
tweenToValue = computedToValue;
|
||||
}
|
||||
const tweenFromValue = values.getFunctionValue(key.from, target, ti, tl, fromFunctionStore, prevSiblingTween);
|
||||
const easeToParse = key.ease || tEasing;
|
||||
|
||||
const easeFunctionResult = values.getFunctionValue(easeToParse, target, ti, tl, null, prevSiblingTween);
|
||||
const keyEasing = helpers.isFnc(easeFunctionResult) || helpers.isStr(easeFunctionResult) ? easeFunctionResult : easeToParse;
|
||||
|
||||
const hasSpring = !helpers.isUnd(keyEasing) && !helpers.isUnd(/** @type {Spring} */(keyEasing).ease);
|
||||
const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing;
|
||||
// Calculate default individual keyframe duration by dividing the tl of keyframes
|
||||
const tweenDuration = hasSpring ? /** @type {Spring} */(keyEasing).settlingDuration : values.getFunctionValue(values.setValue(key.duration, (l > 1 ? values.getFunctionValue(tDuration, target, ti, tl, null, prevSiblingTween) / l : tDuration)), target, ti, tl, null, prevSiblingTween);
|
||||
// Default delay value should only be applied to the first tween
|
||||
const tweenDelay = values.getFunctionValue(values.setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl, null, prevSiblingTween);
|
||||
// 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 = !helpers.isUnd(tweenFromValue);
|
||||
const hasToValue = !helpers.isUnd(tweenToValue);
|
||||
const isFromToArray = helpers.isArr(tweenToValue);
|
||||
const isFromToValue = isFromToArray || (hasFromvalue && hasToValue);
|
||||
// Capture the update-start in local time, the previous sibling's end for keyframes after the first, zero for the first keyframe. Used to derive a precision-matched _absoluteUpdateStartTime below.
|
||||
const tweenUpdateStartLocal = prevTween ? lastTweenChangeEndTime : 0;
|
||||
const tweenStartTime = prevTween ? lastTweenChangeEndTime + tweenDelay : tweenDelay;
|
||||
// Rounding is necessary here to minimize floating point errors when working in seconds
|
||||
const absoluteStartTime = helpers.round(absoluteOffsetTime + tweenStartTime, 12);
|
||||
// Match the rounding pattern of prevSibling._absoluteEndTime so the composition overlap check compares cleanly when keyframes touch at a boundary.
|
||||
const absoluteUpdateStartTime = helpers.round(absoluteOffsetTime + tweenUpdateStartLocal, 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 !== consts.compositionTypes.none) {
|
||||
let nextSibling = siblings._head;
|
||||
// Walk prior siblings up to the new tween, skipping overridden ones so the chain resolves to the latest live value instead of stopping at the first override.
|
||||
while (nextSibling && nextSibling._absoluteStartTime <= absoluteStartTime) {
|
||||
if (!nextSibling._isOverridden) 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) {
|
||||
composition.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) {
|
||||
values.decomposeRawValue(isFromToArray ? values.getFunctionValue(tweenToValue[0], target, ti, tl, fromFunctionStore, prevSiblingTween) : tweenFromValue, fromTargetObject);
|
||||
values.decomposeRawValue(isFromToArray ? values.getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore, prevSiblingTween) : tweenToValue, toTargetObject);
|
||||
// Needed to force an inline style registration
|
||||
const originalValue = values.getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore);
|
||||
if (fromTargetObject.t === consts.valueTypes.NUMBER) {
|
||||
if (prevSibling) {
|
||||
if (prevSibling._valueType === consts.valueTypes.UNIT) {
|
||||
fromTargetObject.t = consts.valueTypes.UNIT;
|
||||
fromTargetObject.u = prevSibling._unit;
|
||||
}
|
||||
} else {
|
||||
values.decomposeRawValue(
|
||||
originalValue,
|
||||
values.decomposedOriginalValue
|
||||
);
|
||||
if (values.decomposedOriginalValue.t === consts.valueTypes.UNIT) {
|
||||
fromTargetObject.t = consts.valueTypes.UNIT;
|
||||
fromTargetObject.u = values.decomposedOriginalValue.u;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (hasToValue) {
|
||||
values.decomposeRawValue(tweenToValue, toTargetObject);
|
||||
} else {
|
||||
if (prevTween) {
|
||||
values.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
|
||||
values.decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
|
||||
values.getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore), toTargetObject);
|
||||
}
|
||||
}
|
||||
if (hasFromvalue) {
|
||||
values.decomposeRawValue(tweenFromValue, fromTargetObject);
|
||||
} else {
|
||||
if (prevTween) {
|
||||
values.decomposeTweenValue(prevTween, fromTargetObject);
|
||||
} 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
|
||||
values.decomposeRawValue(parent && prevSibling && prevSibling.parent.parent === parent ? prevSibling._value :
|
||||
values.getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore), fromTargetObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply operators
|
||||
if (fromTargetObject.o) {
|
||||
fromTargetObject.n = values.getRelativeValue(
|
||||
!prevSibling ? values.decomposeRawValue(
|
||||
values.getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore),
|
||||
values.decomposedOriginalValue
|
||||
).n : prevSibling._toNumber,
|
||||
fromTargetObject.n,
|
||||
fromTargetObject.o
|
||||
);
|
||||
}
|
||||
|
||||
if (toTargetObject.o) {
|
||||
toTargetObject.n = values.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 === consts.valueTypes.COMPLEX || toTargetObject.t === consts.valueTypes.COMPLEX) {
|
||||
const complexValue = fromTargetObject.t === consts.valueTypes.COMPLEX ? fromTargetObject : toTargetObject;
|
||||
const notComplexValue = fromTargetObject.t === consts.valueTypes.COMPLEX ? toTargetObject : fromTargetObject;
|
||||
notComplexValue.t = consts.valueTypes.COMPLEX;
|
||||
notComplexValue.s = helpers.cloneArray(complexValue.s);
|
||||
notComplexValue.d = complexValue.d.map(() => notComplexValue.n);
|
||||
} else if (fromTargetObject.t === consts.valueTypes.UNIT || toTargetObject.t === consts.valueTypes.UNIT) {
|
||||
const unitValue = fromTargetObject.t === consts.valueTypes.UNIT ? fromTargetObject : toTargetObject;
|
||||
const notUnitValue = fromTargetObject.t === consts.valueTypes.UNIT ? toTargetObject : fromTargetObject;
|
||||
notUnitValue.t = consts.valueTypes.UNIT;
|
||||
notUnitValue.u = unitValue.u;
|
||||
} else if (fromTargetObject.t === consts.valueTypes.COLOR || toTargetObject.t === consts.valueTypes.COLOR) {
|
||||
const colorValue = fromTargetObject.t === consts.valueTypes.COLOR ? fromTargetObject : toTargetObject;
|
||||
const notColorValue = fromTargetObject.t === consts.valueTypes.COLOR ? toTargetObject : fromTargetObject;
|
||||
notColorValue.t = consts.valueTypes.COLOR;
|
||||
notColorValue.d = colorValue.d.map(() => 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Unit conversion
|
||||
if (fromTargetObject.u !== toTargetObject.u) {
|
||||
let valueToConvert = toTargetObject.u ? fromTargetObject : toTargetObject;
|
||||
valueToConvert = units.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) => helpers.isUnd(shortestValue.d[i]) ? 0 : shortestValue.d[i]);
|
||||
shortestValue.s = helpers.cloneArray(longestValue.s);
|
||||
}
|
||||
|
||||
// Tween factory
|
||||
|
||||
// Rounding is necessary here to minimize floating point errors when working in seconds
|
||||
const tweenUpdateDuration = helpers.round(+tweenDuration || consts.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 (!helpers.isNil(inlineValue)) inlineStylesStore[propName] = null;
|
||||
|
||||
// Resolve the adapter setter once so render skips the lookup per frame.
|
||||
const tweenSetter = adapterProp ? adapterProp.set : null;
|
||||
|
||||
// Rounding is necessary here to minimize floating point errors when working in seconds
|
||||
lastTweenChangeEndTime = helpers.round(tweenStartTime + tweenUpdateDuration, 12);
|
||||
|
||||
const fromD = fromTargetObject.d;
|
||||
const toD = toTargetObject.d;
|
||||
const toS = toTargetObject.s;
|
||||
|
||||
/** @type {Tween} */
|
||||
const tween = {
|
||||
parent: this,
|
||||
id: tweenId++,
|
||||
property: propName,
|
||||
target: target,
|
||||
_value: null,
|
||||
_toFunc: toFunctionStore.func,
|
||||
_fromFunc: fromFunctionStore.func,
|
||||
_ease: parser.parseEase(tweenEasing),
|
||||
_fromNumbers: fromD ? helpers.cloneArray(fromD) : consts.emptyArray,
|
||||
_toNumbers: toD ? helpers.cloneArray(toD) : consts.emptyArray,
|
||||
_strings: toS ? helpers.cloneArray(toS) : consts.emptyArray,
|
||||
_fromNumber: fromTargetObject.n,
|
||||
_toNumber: toTargetObject.n,
|
||||
_numbers: fromD ? helpers.cloneArray(fromD) : consts.emptyArray, // 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,
|
||||
_absoluteUpdateStartTime: absoluteUpdateStartTime,
|
||||
_absoluteEndTime: helpers.round(absoluteOffsetTime + lastTweenChangeEndTime, 12),
|
||||
_hasFromValue: hasFromvalue || isFromToArray ? 1 : 0,
|
||||
// NOTE: Investigate bit packing to stores ENUM / BOOL
|
||||
_tweenType: tweenType,
|
||||
_setter: tweenSetter,
|
||||
_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 !== consts.compositionTypes.none) {
|
||||
composition.composeTween(tween, siblings);
|
||||
}
|
||||
|
||||
// Pre-compute the tween end value for function-based value chaining (ie morphTo / scrambleText in keyframe arrays and timelines)
|
||||
const vt = tween._valueType;
|
||||
if (vt === consts.valueTypes.COMPLEX) {
|
||||
tween._value = values.composeComplexValue(tween, 1, -1);
|
||||
} else if (vt === consts.valueTypes.UNIT) {
|
||||
tween._value = `${tweenModifier(tween._toNumber)}${tween._unit}`;
|
||||
} else if (vt === consts.valueTypes.COLOR) {
|
||||
const d = toTargetObject.d;
|
||||
tween._value = `rgba(${helpers.round(d[0], 0)},${helpers.round(d[1], 0)},${helpers.round(d[2], 0)},${d[3]})`;
|
||||
} else {
|
||||
tween._value = tweenModifier(tween._toNumber);
|
||||
}
|
||||
|
||||
if (isNaN(firstTweenChangeStartTime)) {
|
||||
firstTweenChangeStartTime = tween._startTime;
|
||||
}
|
||||
|
||||
prevTween = tween;
|
||||
animationAnimationLength++;
|
||||
|
||||
helpers.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 === consts.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;
|
||||
helpers.forEachChildren(this, (/** @type {Tween} */tween) => {
|
||||
if (i >= lastTransformGroupIndex && i < lastTransformGroupLength) {
|
||||
tween._renderTransforms = 1;
|
||||
if (tween._composition === consts.compositionTypes.blend) {
|
||||
helpers.forEachChildren(additive.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) {
|
||||
helpers.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 = consts.minValue;
|
||||
this.iterationCount = 0;
|
||||
}
|
||||
/** @type {TargetsArray} */
|
||||
this.targets = parsedTargets;
|
||||
/** @type {String|Number} */
|
||||
this.id = !helpers.isUnd(id) ? id : JSAnimationId;
|
||||
/** @type {Number} */
|
||||
this.duration = iterationDuration === consts.minValue ? consts.minValue : helpers.clampInfinity(((iterationDuration + this._loopDelay) * this.iterationCount) - this._loopDelay) || consts.minValue;
|
||||
/** @type {Callback<this>} */
|
||||
this.onRender = onRender || animDefaults.onRender;
|
||||
/** @type {EasingFunction} */
|
||||
this._ease = parsedAnimPlaybackEase;
|
||||
/** @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 === helpers.normalizeTime(newDuration)) return this;
|
||||
const timeScale = newDuration / currentDuration;
|
||||
// NOTE: Find a better way to handle the stretch of an animation after stretch = 0
|
||||
helpers.forEachChildren(this, (/** @type {Tween} */tween) => {
|
||||
// Rounding is necessary here to minimize floating point errors
|
||||
tween._updateDuration = helpers.normalizeTime(tween._updateDuration * timeScale);
|
||||
tween._changeDuration = helpers.normalizeTime(tween._changeDuration * timeScale);
|
||||
tween._currentTime *= timeScale;
|
||||
tween._delay *= timeScale;
|
||||
tween._startTime *= timeScale;
|
||||
tween._absoluteStartTime *= timeScale;
|
||||
tween._absoluteUpdateStartTime *= timeScale;
|
||||
tween._absoluteEndTime *= timeScale;
|
||||
});
|
||||
return super.stretch(newDuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {this}
|
||||
*/
|
||||
refresh() {
|
||||
helpers.forEachChildren(this, (/** @type {Tween} */tween) => {
|
||||
const toFunc = tween._toFunc;
|
||||
const fromFunc = tween._fromFunc;
|
||||
if (toFunc || fromFunc) {
|
||||
if (fromFunc) {
|
||||
values.decomposeRawValue(fromFunc(), fromTargetObject);
|
||||
if (fromTargetObject.u !== tween._unit && tween.target[consts.isDomSymbol]) {
|
||||
units.convertValueUnit(/** @type {DOMTarget} */(tween.target), fromTargetObject, tween._unit, true);
|
||||
}
|
||||
tween._fromNumbers = helpers.cloneArray(fromTargetObject.d);
|
||||
tween._fromNumber = fromTargetObject.n;
|
||||
} else if (toFunc) {
|
||||
// When only toFunc exists, get from value from target
|
||||
values.decomposeRawValue(values.getOriginalAnimatableValue(tween.target, tween.property, tween._tweenType), values.decomposedOriginalValue);
|
||||
tween._fromNumbers = helpers.cloneArray(values.decomposedOriginalValue.d);
|
||||
tween._fromNumber = values.decomposedOriginalValue.n;
|
||||
}
|
||||
if (toFunc) {
|
||||
values.decomposeRawValue(toFunc(), toTargetObject);
|
||||
tween._toNumbers = helpers.cloneArray(toTargetObject.d);
|
||||
tween._strings = helpers.cloneArray(toTargetObject.s);
|
||||
// Make sure to apply relative operators https://github.com/juliangarnier/anime/issues/1025
|
||||
tween._toNumber = toTargetObject.o ? values.getRelativeValue(tween._fromNumber, toTargetObject.n, toTargetObject.o) : toTargetObject.n;
|
||||
}
|
||||
}
|
||||
});
|
||||
// This forces setter animations to render once
|
||||
if (this.duration === consts.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 styles.revertValues(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) => {
|
||||
if (globals.globals.editor) {
|
||||
return globals.globals.editor.addAnimation(targets, parameters);
|
||||
} else {
|
||||
return new JSAnimation(targets, parameters, null, 0, false).init();
|
||||
}
|
||||
};
|
||||
|
||||
exports.JSAnimation = JSAnimation;
|
||||
exports.animate = animate;
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
export 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 {TargetsArray} [allTargets]
|
||||
*/
|
||||
constructor(targets: TargetsParam, parameters: AnimationParams, parent?: Timeline, parentPosition?: number, fastSet?: boolean, index?: number, allTargets?: TargetsArray);
|
||||
/** @type {Tween} */
|
||||
_head: Tween;
|
||||
/** @type {Tween} */
|
||||
_tail: Tween;
|
||||
/** @type {TargetsArray} */
|
||||
targets: TargetsArray;
|
||||
/** @type {Callback<this>} */
|
||||
onRender: Callback<this>;
|
||||
/** @type {EasingFunction} */
|
||||
_ease: EasingFunction;
|
||||
/**
|
||||
* @param {Number} newDuration
|
||||
* @return {this}
|
||||
*/
|
||||
stretch(newDuration: number): this;
|
||||
/**
|
||||
* @return {this}
|
||||
*/
|
||||
refresh(): this;
|
||||
/**
|
||||
* Cancel the animation and revert all the values affected by this animation to their original state
|
||||
* @return {this}
|
||||
*/
|
||||
revert(): this;
|
||||
/**
|
||||
* @typedef {this & {then: null}} ResolvedJSAnimation
|
||||
*/
|
||||
/**
|
||||
* @param {Callback<ResolvedJSAnimation>} [callback]
|
||||
* @return Promise<this>
|
||||
*/
|
||||
then(callback?: Callback<this & {
|
||||
then: null;
|
||||
}>): Promise<any>;
|
||||
}
|
||||
export function animate(targets: TargetsParam, parameters: AnimationParams): JSAnimation;
|
||||
import { Timer } from '../timer/timer.js';
|
||||
import type { Tween } from '../types/index.js';
|
||||
import type { TargetsArray } from '../types/index.js';
|
||||
import type { Callback } from '../types/index.js';
|
||||
import type { EasingFunction } from '../types/index.js';
|
||||
import type { TargetsParam } from '../types/index.js';
|
||||
import type { AnimationParams } from '../types/index.js';
|
||||
import type { Timeline } from '../timeline/timeline.js';
|
||||
+743
@@ -0,0 +1,743 @@
|
||||
/**
|
||||
* Anime.js - animation - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { K, compositionTypes, valueTypes, emptyArray, minValue, isDomSymbol, tweenTypes } from '../core/consts.js';
|
||||
import { mergeObjects, isUnd, isKey, isObj, cloneArray, isNil, round, addChild, forEachChildren, clampInfinity, normalizeTime, isArr, isNum, isFnc, isStr } from '../core/helpers.js';
|
||||
import { globals } from '../core/globals.js';
|
||||
import { registerTargets } from '../core/targets.js';
|
||||
import { resolveAdapterEntry } from '../adapters/registry.js';
|
||||
import { setValue, getTweenType, getFunctionValue, decomposeRawValue, getOriginalAnimatableValue, createDecomposedValueTargetObject, decomposedOriginalValue, getRelativeValue, composeComplexValue, decomposeTweenValue } from '../core/values.js';
|
||||
import { sanitizePropertyName, revertValues } 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 fromFunctionStore = { func: null };
|
||||
const keyframesTargetArray = [null];
|
||||
const fastSetValuesArray = [null, null];
|
||||
/** @type {TweenKeyValue} */
|
||||
const keyObjectTarget = { to: null };
|
||||
|
||||
let tweenId = 0;
|
||||
let JSAnimationId = 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 {TargetsArray} [allTargets]
|
||||
*/
|
||||
constructor(
|
||||
targets,
|
||||
parameters,
|
||||
parent,
|
||||
parentPosition,
|
||||
fastSet = false,
|
||||
index = 0,
|
||||
allTargets
|
||||
) {
|
||||
|
||||
super(/** @type {TimerParams & AnimationParams} */(parameters), parent, parentPosition);
|
||||
|
||||
/** @type {Tween} */
|
||||
this._head;
|
||||
/** @type {Tween} */
|
||||
this._tail;
|
||||
|
||||
++JSAnimationId;
|
||||
|
||||
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 {
|
||||
id,
|
||||
delay,
|
||||
duration,
|
||||
ease,
|
||||
playbackEase,
|
||||
modifier,
|
||||
composition,
|
||||
onRender,
|
||||
} = params;
|
||||
|
||||
const animDefaults = parent ? parent.defaults : globals.defaults;
|
||||
const animEase = setValue(ease, animDefaults.ease);
|
||||
const animPlaybackEase = setValue(playbackEase, animDefaults.playbackEase);
|
||||
const parsedAnimPlaybackEase = animPlaybackEase ? parseEase(animPlaybackEase) : null;
|
||||
const hasSpring = !isUnd(/** @type {Spring} */(animEase).ease);
|
||||
const tEasing = hasSpring ? /** @type {Spring} */(animEase).ease : setValue(ease, parsedAnimPlaybackEase ? 'linear' : animDefaults.ease);
|
||||
const tDuration = hasSpring ? /** @type {Spring} */(animEase).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} */(animEase).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 = allTargets || parsedTargets;
|
||||
|
||||
let lastTransformGroupIndex = NaN;
|
||||
let lastTransformGroupLength = NaN;
|
||||
|
||||
for (let p in params) {
|
||||
|
||||
if (isKey(p)) {
|
||||
|
||||
const tweenType = getTweenType(target, p);
|
||||
const adapterProp = resolveAdapterEntry(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;
|
||||
fromFunctionStore.func = null;
|
||||
|
||||
const computedComposition = getFunctionValue(setValue(key.composition, tComposition), target, ti, tl, null, null);
|
||||
const tweenComposition = isNum(computedComposition) ? computedComposition : compositionTypes[computedComposition];
|
||||
if (!siblings && tweenComposition !== compositionTypes.none) siblings = getTweenSiblings(target, propName);
|
||||
// Timelines pass the last sibling tween if it belongs to the same timeline
|
||||
// Standalone animations only pass prevTween when the property has multiple keyframes
|
||||
const tailTween = siblings ? siblings._tail : null;
|
||||
const prevSiblingTween = parent && tailTween && tailTween.parent.parent === parent ? tailTween : prevTween;
|
||||
const computedToValue = getFunctionValue(key.to, target, ti, tl, toFunctionStore, prevSiblingTween);
|
||||
|
||||
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, fromFunctionStore, prevSiblingTween);
|
||||
const easeToParse = key.ease || tEasing;
|
||||
|
||||
const easeFunctionResult = getFunctionValue(easeToParse, target, ti, tl, null, prevSiblingTween);
|
||||
const keyEasing = isFnc(easeFunctionResult) || isStr(easeFunctionResult) ? easeFunctionResult : easeToParse;
|
||||
|
||||
const hasSpring = !isUnd(keyEasing) && !isUnd(/** @type {Spring} */(keyEasing).ease);
|
||||
const tweenEasing = hasSpring ? /** @type {Spring} */(keyEasing).ease : keyEasing;
|
||||
// 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, null, prevSiblingTween) / l : tDuration)), target, ti, tl, null, prevSiblingTween);
|
||||
// Default delay value should only be applied to the first tween
|
||||
const tweenDelay = getFunctionValue(setValue(key.delay, (!tweenIndex ? tDelay : 0)), target, ti, tl, null, prevSiblingTween);
|
||||
// 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);
|
||||
// Capture the update-start in local time, the previous sibling's end for keyframes after the first, zero for the first keyframe. Used to derive a precision-matched _absoluteUpdateStartTime below.
|
||||
const tweenUpdateStartLocal = prevTween ? lastTweenChangeEndTime : 0;
|
||||
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);
|
||||
// Match the rounding pattern of prevSibling._absoluteEndTime so the composition overlap check compares cleanly when keyframes touch at a boundary.
|
||||
const absoluteUpdateStartTime = round(absoluteOffsetTime + tweenUpdateStartLocal, 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) {
|
||||
let nextSibling = siblings._head;
|
||||
// Walk prior siblings up to the new tween, skipping overridden ones so the chain resolves to the latest live value instead of stopping at the first override.
|
||||
while (nextSibling && nextSibling._absoluteStartTime <= absoluteStartTime) {
|
||||
if (!nextSibling._isOverridden) 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, fromFunctionStore, prevSiblingTween) : tweenFromValue, fromTargetObject);
|
||||
decomposeRawValue(isFromToArray ? getFunctionValue(tweenToValue[1], target, ti, tl, toFunctionStore, prevSiblingTween) : tweenToValue, toTargetObject);
|
||||
// Needed to force an inline style registration
|
||||
const originalValue = getOriginalAnimatableValue(target, propName, tweenType, inlineStylesStore);
|
||||
if (fromTargetObject.t === valueTypes.NUMBER) {
|
||||
if (prevSibling) {
|
||||
if (prevSibling._valueType === valueTypes.UNIT) {
|
||||
fromTargetObject.t = valueTypes.UNIT;
|
||||
fromTargetObject.u = prevSibling._unit;
|
||||
}
|
||||
} else {
|
||||
decomposeRawValue(
|
||||
originalValue,
|
||||
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 {
|
||||
// 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), 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.d = colorValue.d.map(() => 0);
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
// Resolve the adapter setter once so render skips the lookup per frame.
|
||||
const tweenSetter = adapterProp ? adapterProp.set : null;
|
||||
|
||||
// Rounding is necessary here to minimize floating point errors when working in seconds
|
||||
lastTweenChangeEndTime = round(tweenStartTime + tweenUpdateDuration, 12);
|
||||
|
||||
const fromD = fromTargetObject.d;
|
||||
const toD = toTargetObject.d;
|
||||
const toS = toTargetObject.s;
|
||||
|
||||
/** @type {Tween} */
|
||||
const tween = {
|
||||
parent: this,
|
||||
id: tweenId++,
|
||||
property: propName,
|
||||
target: target,
|
||||
_value: null,
|
||||
_toFunc: toFunctionStore.func,
|
||||
_fromFunc: fromFunctionStore.func,
|
||||
_ease: parseEase(tweenEasing),
|
||||
_fromNumbers: fromD ? cloneArray(fromD) : emptyArray,
|
||||
_toNumbers: toD ? cloneArray(toD) : emptyArray,
|
||||
_strings: toS ? cloneArray(toS) : emptyArray,
|
||||
_fromNumber: fromTargetObject.n,
|
||||
_toNumber: toTargetObject.n,
|
||||
_numbers: fromD ? cloneArray(fromD) : emptyArray, // 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,
|
||||
_absoluteUpdateStartTime: absoluteUpdateStartTime,
|
||||
_absoluteEndTime: round(absoluteOffsetTime + lastTweenChangeEndTime, 12),
|
||||
_hasFromValue: hasFromvalue || isFromToArray ? 1 : 0,
|
||||
// NOTE: Investigate bit packing to stores ENUM / BOOL
|
||||
_tweenType: tweenType,
|
||||
_setter: tweenSetter,
|
||||
_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);
|
||||
}
|
||||
|
||||
// Pre-compute the tween end value for function-based value chaining (ie morphTo / scrambleText in keyframe arrays and timelines)
|
||||
const vt = tween._valueType;
|
||||
if (vt === valueTypes.COMPLEX) {
|
||||
tween._value = composeComplexValue(tween, 1, -1);
|
||||
} else if (vt === valueTypes.UNIT) {
|
||||
tween._value = `${tweenModifier(tween._toNumber)}${tween._unit}`;
|
||||
} else if (vt === valueTypes.COLOR) {
|
||||
const d = toTargetObject.d;
|
||||
tween._value = `rgba(${round(d[0], 0)},${round(d[1], 0)},${round(d[2], 0)},${d[3]})`;
|
||||
} else {
|
||||
tween._value = tweenModifier(tween._toNumber);
|
||||
}
|
||||
|
||||
if (isNaN(firstTweenChangeStartTime)) {
|
||||
firstTweenChangeStartTime = tween._startTime;
|
||||
}
|
||||
|
||||
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 {String|Number} */
|
||||
this.id = !isUnd(id) ? id : JSAnimationId;
|
||||
/** @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 = parsedAnimPlaybackEase;
|
||||
/** @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._delay *= timeScale;
|
||||
tween._startTime *= timeScale;
|
||||
tween._absoluteStartTime *= timeScale;
|
||||
tween._absoluteUpdateStartTime *= timeScale;
|
||||
tween._absoluteEndTime *= timeScale;
|
||||
});
|
||||
return super.stretch(newDuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {this}
|
||||
*/
|
||||
refresh() {
|
||||
forEachChildren(this, (/** @type {Tween} */tween) => {
|
||||
const toFunc = tween._toFunc;
|
||||
const fromFunc = tween._fromFunc;
|
||||
if (toFunc || fromFunc) {
|
||||
if (fromFunc) {
|
||||
decomposeRawValue(fromFunc(), fromTargetObject);
|
||||
if (fromTargetObject.u !== tween._unit && tween.target[isDomSymbol]) {
|
||||
convertValueUnit(/** @type {DOMTarget} */(tween.target), fromTargetObject, tween._unit, true);
|
||||
}
|
||||
tween._fromNumbers = cloneArray(fromTargetObject.d);
|
||||
tween._fromNumber = fromTargetObject.n;
|
||||
} else if (toFunc) {
|
||||
// When only toFunc exists, get from value from target
|
||||
decomposeRawValue(getOriginalAnimatableValue(tween.target, tween.property, tween._tweenType), decomposedOriginalValue);
|
||||
tween._fromNumbers = cloneArray(decomposedOriginalValue.d);
|
||||
tween._fromNumber = decomposedOriginalValue.n;
|
||||
}
|
||||
if (toFunc) {
|
||||
decomposeRawValue(toFunc(), toTargetObject);
|
||||
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(tween._fromNumber, 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 revertValues(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) => {
|
||||
if (globals.editor) {
|
||||
return globals.editor.addAnimation(targets, parameters);
|
||||
} else {
|
||||
return new JSAnimation(targets, parameters, null, 0, false).init();
|
||||
}
|
||||
};
|
||||
|
||||
export { JSAnimation, animate };
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
/**
|
||||
* Anime.js - animation - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('../core/consts.cjs');
|
||||
var helpers = require('../core/helpers.cjs');
|
||||
var styles = require('../core/styles.cjs');
|
||||
var engine = require('../engine/engine.cjs');
|
||||
var additive = require('./additive.cjs');
|
||||
|
||||
/**
|
||||
* @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 = consts.minValue;
|
||||
tween._currentTime = consts.minValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Tween} tween
|
||||
* @param {TweenPropertySiblings} siblings
|
||||
* @return {Tween}
|
||||
*/
|
||||
const composeTween = (tween, siblings) => {
|
||||
|
||||
const tweenCompositionType = tween._composition;
|
||||
|
||||
// Handle replaced tweens
|
||||
|
||||
if (tweenCompositionType === consts.compositionTypes.replace) {
|
||||
|
||||
const tweenAbsStartTime = tween._absoluteStartTime;
|
||||
|
||||
helpers.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._absoluteEndTime;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Read the precision-matched update-start instead of subtracting tween._delay live so sequential keyframes touching at a boundary don't trigger a phantom overlap from float drift.
|
||||
const absoluteUpdateStartTime = tween._absoluteUpdateStartTime;
|
||||
|
||||
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 = helpers.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 < consts.minValue) {
|
||||
overrideTween(prevSibling);
|
||||
}
|
||||
}
|
||||
|
||||
// Skip the cancel cascade when both tweens share the same parent timeline, a timeline cannot replace itself.
|
||||
const tweenParentTL = tween.parent.parent;
|
||||
if (!tweenParentTL || tweenParentTL !== prevParent.parent) {
|
||||
|
||||
let pausePrevParentAnimation = true;
|
||||
|
||||
helpers.forEachChildren(prevParent, (/** @type Tween */t) => {
|
||||
if (!t._isOverlapped) pausePrevParentAnimation = false;
|
||||
});
|
||||
|
||||
if (pausePrevParentAnimation) {
|
||||
const prevParentTL = prevParent.parent;
|
||||
if (prevParentTL) {
|
||||
let pausePrevParentTL = true;
|
||||
helpers.forEachChildren(prevParentTL, (/** @type JSAnimation */a) => {
|
||||
if (a !== prevParent) {
|
||||
helpers.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 === consts.compositionTypes.blend) {
|
||||
|
||||
const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add');
|
||||
const additiveAnimation = additive.addAdditiveAnimation(lookups._add);
|
||||
|
||||
let lookupTween = additiveTweenSiblings._head;
|
||||
|
||||
if (!lookupTween) {
|
||||
lookupTween = { ...tween };
|
||||
lookupTween._composition = consts.compositionTypes.replace;
|
||||
lookupTween._updateDuration = consts.minValue;
|
||||
lookupTween._startTime = 0;
|
||||
lookupTween._numbers = helpers.cloneArray(tween._fromNumbers);
|
||||
lookupTween._number = 0;
|
||||
lookupTween._next = null;
|
||||
lookupTween._prev = null;
|
||||
helpers.addChild(additiveTweenSiblings, lookupTween);
|
||||
helpers.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 = helpers.cloneArray(tween._fromNumbers);
|
||||
tween._number = 0;
|
||||
lookupTween._fromNumber = toNumber;
|
||||
|
||||
if (tween._toNumbers.length) {
|
||||
const toNumbers = helpers.cloneArray(tween._toNumbers);
|
||||
toNumbers.forEach((value, i) => {
|
||||
tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value;
|
||||
tween._toNumbers[i] = 0;
|
||||
});
|
||||
lookupTween._fromNumbers = toNumbers;
|
||||
}
|
||||
|
||||
helpers.addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd');
|
||||
|
||||
}
|
||||
|
||||
return tween;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Tween} tween
|
||||
* @return {Tween}
|
||||
*/
|
||||
const removeTweenSliblings = tween => {
|
||||
const tweenComposition = tween._composition;
|
||||
if (tweenComposition !== consts.compositionTypes.none) {
|
||||
const tweenTarget = tween.target;
|
||||
const tweenProperty = tween.property;
|
||||
const replaceTweensLookup = lookups._rep;
|
||||
const replaceTargetProps = replaceTweensLookup.get(tweenTarget);
|
||||
const tweenReplaceSiblings = replaceTargetProps[tweenProperty];
|
||||
helpers.removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep');
|
||||
if (tweenComposition === consts.compositionTypes.blend) {
|
||||
const addTweensLookup = lookups._add;
|
||||
const addTargetProps = addTweensLookup.get(tweenTarget);
|
||||
if (!addTargetProps) return;
|
||||
const additiveTweenSiblings = addTargetProps[tweenProperty];
|
||||
const additiveAnimation = additive.additive.animation;
|
||||
helpers.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) {
|
||||
helpers.removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd');
|
||||
helpers.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;
|
||||
helpers.forEachChildren(animation, (/**@type {Tween} */tween) => {
|
||||
const tweenTarget = tween.target;
|
||||
if (targetsArray.includes(tweenTarget)) {
|
||||
const tweenName = tween.property;
|
||||
const tweenType = tween._tweenType;
|
||||
const normalizePropName = styles.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 === consts.tweenTypes.TRANSFORM &&
|
||||
tween._prev &&
|
||||
tween._prev._tweenType === consts.tweenTypes.TRANSFORM
|
||||
) {
|
||||
tween._prev._renderTransforms = 1;
|
||||
}
|
||||
// Removes the tween from the selected animation
|
||||
helpers.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.engine);
|
||||
let removeMatches;
|
||||
if (parent._hasChildren) {
|
||||
let iterationDuration = 0;
|
||||
helpers.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();
|
||||
helpers.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 (!helpers.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();
|
||||
}
|
||||
};
|
||||
|
||||
exports.composeTween = composeTween;
|
||||
exports.getTweenSiblings = getTweenSiblings;
|
||||
exports.overrideTween = overrideTween;
|
||||
exports.removeTargetsFromRenderable = removeTargetsFromRenderable;
|
||||
exports.removeTweenSliblings = removeTweenSliblings;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
export function getTweenSiblings(target: Target, property: string, lookup?: string): TweenPropertySiblings;
|
||||
export function overrideTween(tween: Tween): void;
|
||||
export function composeTween(tween: Tween, siblings: TweenPropertySiblings): Tween;
|
||||
export function removeTweenSliblings(tween: Tween): Tween;
|
||||
export function removeTargetsFromRenderable(targetsArray: TargetsArray, renderable?: Renderable, propertyName?: string): void;
|
||||
import type { Target } from '../types/index.js';
|
||||
import type { TweenPropertySiblings } from '../types/index.js';
|
||||
import type { Tween } from '../types/index.js';
|
||||
import type { TargetsArray } from '../types/index.js';
|
||||
import type { Renderable } from '../types/index.js';
|
||||
+380
@@ -0,0 +1,380 @@
|
||||
/**
|
||||
* Anime.js - animation - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { compositionTypes, minValue, 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 { additive, addAdditiveAnimation } 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._absoluteEndTime;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Read the precision-matched update-start instead of subtracting tween._delay live so sequential keyframes touching at a boundary don't trigger a phantom overlap from float drift.
|
||||
const absoluteUpdateStartTime = tween._absoluteUpdateStartTime;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// Skip the cancel cascade when both tweens share the same parent timeline, a timeline cannot replace itself.
|
||||
const tweenParentTL = tween.parent.parent;
|
||||
if (!tweenParentTL || tweenParentTL !== prevParent.parent) {
|
||||
|
||||
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.length) {
|
||||
const toNumbers = cloneArray(tween._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 };
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Anime.js - animation - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var animation = require('./animation.cjs');
|
||||
|
||||
|
||||
|
||||
exports.JSAnimation = animation.JSAnimation;
|
||||
exports.animate = animation.animate;
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./animation.js";
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Anime.js - animation - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
export { JSAnimation, animate } from './animation.js';
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('./consts.cjs');
|
||||
var globals = require('./globals.cjs');
|
||||
|
||||
/**
|
||||
* @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._lastTickTime = initTime;
|
||||
/** @type {Number} */
|
||||
this._startTime = initTime;
|
||||
/** @type {Number} */
|
||||
this._lastTime = initTime;
|
||||
/** @type {Number} */
|
||||
this._frameDuration = consts.K / consts.maxFps;
|
||||
/** @type {Number} */
|
||||
this._fps = consts.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 fr = +frameRate;
|
||||
const fps = fr < consts.minValue ? consts.minValue : fr;
|
||||
const frameDuration = consts.K / fps;
|
||||
if (fps > globals.defaults.frameRate) globals.defaults.frameRate = fps;
|
||||
this._fps = fps;
|
||||
this._frameDuration = frameDuration;
|
||||
}
|
||||
|
||||
get speed() {
|
||||
return this._speed;
|
||||
}
|
||||
|
||||
set speed(playbackRate) {
|
||||
const pbr = +playbackRate;
|
||||
this._speed = pbr < consts.minValue ? consts.minValue : pbr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Number} time
|
||||
* @return {tickModes}
|
||||
*/
|
||||
requestTick(time) {
|
||||
const frameDuration = this._frameDuration;
|
||||
const elapsed = time - this._lastTickTime;
|
||||
const scaled = frameDuration * .25;
|
||||
const tolerance = scaled < 4 ? scaled : 4;
|
||||
// Tolerance prevents dropping frames that arrive a bit early due to RAF jitter
|
||||
// typically <= ~25% of frame duration and capped at 4ms so it doesn't dominate at high fps.
|
||||
// e.g. at 60fps (frameDuration=16.667ms) a frame arriving after 15ms:
|
||||
// - without tolerance: 15 < 16.667 -> skip
|
||||
// - with tolerance: 15 + 4 >= 16.667 -> tick
|
||||
if (elapsed + tolerance < frameDuration) return consts.tickModes.NONE;
|
||||
this._lastTickTime = elapsed >= frameDuration ? time - (elapsed % frameDuration) : time;
|
||||
return consts.tickModes.AUTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Number} time
|
||||
* @return {Number}
|
||||
*/
|
||||
computeDeltaTime(time) {
|
||||
const delta = time - this._lastTime;
|
||||
this.deltaTime = delta;
|
||||
this._lastTime = time;
|
||||
return delta;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
exports.Clock = Clock;
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* @import {
|
||||
* Tickable,
|
||||
* Tween,
|
||||
* } from '../types/index.js'
|
||||
*/
|
||||
export class Clock {
|
||||
/** @param {Number} [initTime] */
|
||||
constructor(initTime?: number);
|
||||
/** @type {Number} */
|
||||
deltaTime: number;
|
||||
/** @type {Number} */
|
||||
_currentTime: number;
|
||||
/** @type {Number} */
|
||||
_lastTickTime: number;
|
||||
/** @type {Number} */
|
||||
_startTime: number;
|
||||
/** @type {Number} */
|
||||
_lastTime: number;
|
||||
/** @type {Number} */
|
||||
_frameDuration: number;
|
||||
/** @type {Number} */
|
||||
_fps: number;
|
||||
/** @type {Number} */
|
||||
_speed: number;
|
||||
/** @type {Boolean} */
|
||||
_hasChildren: boolean;
|
||||
/** @type {Tickable|Tween} */
|
||||
_head: Tickable | Tween;
|
||||
/** @type {Tickable|Tween} */
|
||||
_tail: Tickable | Tween;
|
||||
set fps(frameRate: number);
|
||||
get fps(): number;
|
||||
set speed(playbackRate: number);
|
||||
get speed(): number;
|
||||
/**
|
||||
* @param {Number} time
|
||||
* @return {tickModes}
|
||||
*/
|
||||
requestTick(time: number): tickModes;
|
||||
/**
|
||||
* @param {Number} time
|
||||
* @return {Number}
|
||||
*/
|
||||
computeDeltaTime(time: number): number;
|
||||
}
|
||||
import type { Tickable } from '../types/index.js';
|
||||
import type { Tween } from '../types/index.js';
|
||||
import { tickModes } from './consts.js';
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { K, maxFps, minValue, tickModes } from './consts.js';
|
||||
import { defaults } from './globals.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._lastTickTime = initTime;
|
||||
/** @type {Number} */
|
||||
this._startTime = initTime;
|
||||
/** @type {Number} */
|
||||
this._lastTime = initTime;
|
||||
/** @type {Number} */
|
||||
this._frameDuration = K / maxFps;
|
||||
/** @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 fr = +frameRate;
|
||||
const fps = fr < minValue ? minValue : fr;
|
||||
const frameDuration = K / fps;
|
||||
if (fps > defaults.frameRate) defaults.frameRate = fps;
|
||||
this._fps = fps;
|
||||
this._frameDuration = frameDuration;
|
||||
}
|
||||
|
||||
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 frameDuration = this._frameDuration;
|
||||
const elapsed = time - this._lastTickTime;
|
||||
const scaled = frameDuration * .25;
|
||||
const tolerance = scaled < 4 ? scaled : 4;
|
||||
// Tolerance prevents dropping frames that arrive a bit early due to RAF jitter
|
||||
// typically <= ~25% of frame duration and capped at 4ms so it doesn't dominate at high fps.
|
||||
// e.g. at 60fps (frameDuration=16.667ms) a frame arriving after 15ms:
|
||||
// - without tolerance: 15 < 16.667 -> skip
|
||||
// - with tolerance: 15 + 4 >= 16.667 -> tick
|
||||
if (elapsed + tolerance < frameDuration) return tickModes.NONE;
|
||||
this._lastTickTime = elapsed >= frameDuration ? time - (elapsed % frameDuration) : time;
|
||||
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 };
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('./consts.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* ColorArray,
|
||||
* } from '../types/index.js'
|
||||
*/
|
||||
|
||||
/**
|
||||
* RGB / RGBA Color value string -> RGBA values array
|
||||
* @param {String} rgbValue
|
||||
* @return {ColorArray}
|
||||
*/
|
||||
const rgbToRgba = rgbValue => {
|
||||
const rgba = consts.rgbExecRgx.exec(rgbValue) || consts.rgbaExecRgx.exec(rgbValue);
|
||||
const a = !helpers.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 = consts.hslExecRgx.exec(hslValue) || consts.hslaExecRgx.exec(hslValue);
|
||||
const h = +hsla[1] / 360;
|
||||
const s = +hsla[2] / 100;
|
||||
const l = +hsla[3] / 100;
|
||||
const a = !helpers.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 = helpers.round(hue2rgb(p, q, h + 1 / 3) * 255, 0);
|
||||
g = helpers.round(hue2rgb(p, q, h) * 255, 0);
|
||||
b = helpers.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 helpers.isRgb(colorString) ? rgbToRgba(colorString) :
|
||||
helpers.isHex(colorString) ? hexToRgba(colorString) :
|
||||
helpers.isHsl(colorString) ? hslToRgba(colorString) :
|
||||
[0, 0, 0, 1];
|
||||
};
|
||||
|
||||
exports.convertColorStringValuesToRgbaArray = convertColorStringValuesToRgbaArray;
|
||||
@@ -0,0 +1,2 @@
|
||||
export function convertColorStringValuesToRgbaArray(colorString: string): ColorArray;
|
||||
import type { ColorArray } from '../types/index.js';
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - 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 };
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
// Environments
|
||||
|
||||
// TODO: Do we need to check if we're running inside a worker ?
|
||||
const isBrowser = typeof window !== 'undefined';
|
||||
|
||||
/** @typedef {Window & {AnimeJS: Array}|null} AnimeJSWindow
|
||||
|
||||
/** @type {AnimeJSWindow} */
|
||||
const win = isBrowser ? /** @type {AnimeJSWindow} */(/** @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 proxyTargetSymbol = Symbol();
|
||||
|
||||
// Numbers
|
||||
|
||||
const minValue = 1e-11;
|
||||
const maxValue = 1e12;
|
||||
const K = 1e3;
|
||||
const maxFps = 240;
|
||||
|
||||
// Strings
|
||||
|
||||
const emptyString = '';
|
||||
const cssVarPrefix = 'var(';
|
||||
|
||||
// Arrays
|
||||
|
||||
// Shared sentinel for tween slots that don't hold array data. Never mutated, only read; COMPLEX and COLOR tweens always replace the slot before writing.
|
||||
const emptyArray = [];
|
||||
|
||||
const shortTransforms = /*#__PURE__*/ (() => {
|
||||
const map = new Map();
|
||||
map.set('x', 'translateX');
|
||||
map.set('y', 'translateY');
|
||||
map.set('z', 'translateZ');
|
||||
return map;
|
||||
})();
|
||||
|
||||
const validTransforms = [
|
||||
'perspective',
|
||||
'translateX',
|
||||
'translateY',
|
||||
'translateZ',
|
||||
'rotate',
|
||||
'rotateX',
|
||||
'rotateY',
|
||||
'rotateZ',
|
||||
'scale',
|
||||
'scaleX',
|
||||
'scaleY',
|
||||
'scaleZ',
|
||||
'skew',
|
||||
'skewX',
|
||||
'skewY',
|
||||
];
|
||||
|
||||
const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {});
|
||||
|
||||
// Functions
|
||||
|
||||
/** @return {void} */
|
||||
const noop = () => {};
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {T} v
|
||||
* @return {T}
|
||||
*/
|
||||
const noopModifier = v => v;
|
||||
|
||||
// Regex
|
||||
|
||||
const validRgbHslRgx = /\)\s*[-.\d]/;
|
||||
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 relativeValuesExecRgx = /(\*=|\+=|-=)/;
|
||||
const cssVariableMatchRgx = /var\(\s*(--[\w-]+)(?:\s*,\s*([^)]+))?\s*\)/;
|
||||
|
||||
exports.K = K;
|
||||
exports.compositionTypes = compositionTypes;
|
||||
exports.cssVarPrefix = cssVarPrefix;
|
||||
exports.cssVariableMatchRgx = cssVariableMatchRgx;
|
||||
exports.digitWithExponentRgx = digitWithExponentRgx;
|
||||
exports.doc = doc;
|
||||
exports.emptyArray = emptyArray;
|
||||
exports.emptyString = emptyString;
|
||||
exports.hexTestRgx = hexTestRgx;
|
||||
exports.hslExecRgx = hslExecRgx;
|
||||
exports.hslaExecRgx = hslaExecRgx;
|
||||
exports.isBrowser = isBrowser;
|
||||
exports.isDomSymbol = isDomSymbol;
|
||||
exports.isRegisteredTargetSymbol = isRegisteredTargetSymbol;
|
||||
exports.isSvgSymbol = isSvgSymbol;
|
||||
exports.lowerCaseRgx = lowerCaseRgx;
|
||||
exports.maxFps = maxFps;
|
||||
exports.maxValue = maxValue;
|
||||
exports.minValue = minValue;
|
||||
exports.noop = noop;
|
||||
exports.noopModifier = noopModifier;
|
||||
exports.proxyTargetSymbol = proxyTargetSymbol;
|
||||
exports.relativeValuesExecRgx = relativeValuesExecRgx;
|
||||
exports.rgbExecRgx = rgbExecRgx;
|
||||
exports.rgbaExecRgx = rgbaExecRgx;
|
||||
exports.shortTransforms = shortTransforms;
|
||||
exports.tickModes = tickModes;
|
||||
exports.transformsFragmentStrings = transformsFragmentStrings;
|
||||
exports.transformsSymbol = transformsSymbol;
|
||||
exports.tweenTypes = tweenTypes;
|
||||
exports.unitsExecRgx = unitsExecRgx;
|
||||
exports.validRgbHslRgx = validRgbHslRgx;
|
||||
exports.validTransforms = validTransforms;
|
||||
exports.valueTypes = valueTypes;
|
||||
exports.win = win;
|
||||
@@ -0,0 +1,68 @@
|
||||
export const isBrowser: boolean;
|
||||
/** @typedef {Window & {AnimeJS: Array}|null} AnimeJSWindow
|
||||
|
||||
/** @type {AnimeJSWindow} */
|
||||
export const win: AnimeJSWindow;
|
||||
/** @type {Document|null} */
|
||||
export const doc: Document | null;
|
||||
export type tweenTypes = number;
|
||||
export namespace tweenTypes {
|
||||
let OBJECT: number;
|
||||
let ATTRIBUTE: number;
|
||||
let CSS: number;
|
||||
let TRANSFORM: number;
|
||||
let CSS_VAR: number;
|
||||
}
|
||||
export type valueTypes = number;
|
||||
export namespace valueTypes {
|
||||
let NUMBER: number;
|
||||
let UNIT: number;
|
||||
let COLOR: number;
|
||||
let COMPLEX: number;
|
||||
}
|
||||
export type tickModes = number;
|
||||
export namespace tickModes {
|
||||
let NONE: number;
|
||||
let AUTO: number;
|
||||
let FORCE: number;
|
||||
}
|
||||
export type compositionTypes = number;
|
||||
export namespace compositionTypes {
|
||||
let replace: number;
|
||||
let none: number;
|
||||
let blend: number;
|
||||
}
|
||||
export const isRegisteredTargetSymbol: unique symbol;
|
||||
export const isDomSymbol: unique symbol;
|
||||
export const isSvgSymbol: unique symbol;
|
||||
export const transformsSymbol: unique symbol;
|
||||
export const proxyTargetSymbol: unique symbol;
|
||||
export const minValue: 1e-11;
|
||||
export const maxValue: 1000000000000;
|
||||
export const K: 1000;
|
||||
export const maxFps: 240;
|
||||
export const emptyString: "";
|
||||
export const cssVarPrefix: "var(";
|
||||
export const emptyArray: any[];
|
||||
export const shortTransforms: Map<any, any>;
|
||||
export const validTransforms: string[];
|
||||
export const transformsFragmentStrings: {};
|
||||
export function noop(): void;
|
||||
export function noopModifier<T>(v: T): T;
|
||||
export const validRgbHslRgx: RegExp;
|
||||
export const hexTestRgx: RegExp;
|
||||
export const rgbExecRgx: RegExp;
|
||||
export const rgbaExecRgx: RegExp;
|
||||
export const hslExecRgx: RegExp;
|
||||
export const hslaExecRgx: RegExp;
|
||||
export const digitWithExponentRgx: RegExp;
|
||||
export const unitsExecRgx: RegExp;
|
||||
export const lowerCaseRgx: RegExp;
|
||||
export const relativeValuesExecRgx: RegExp;
|
||||
export const cssVariableMatchRgx: RegExp;
|
||||
/**
|
||||
* /**
|
||||
*/
|
||||
export type AnimeJSWindow = (Window & {
|
||||
AnimeJS: any[];
|
||||
}) | null;
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
// Environments
|
||||
|
||||
// TODO: Do we need to check if we're running inside a worker ?
|
||||
const isBrowser = typeof window !== 'undefined';
|
||||
|
||||
/** @typedef {Window & {AnimeJS: Array}|null} AnimeJSWindow
|
||||
|
||||
/** @type {AnimeJSWindow} */
|
||||
const win = isBrowser ? /** @type {AnimeJSWindow} */(/** @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 proxyTargetSymbol = Symbol();
|
||||
|
||||
// Numbers
|
||||
|
||||
const minValue = 1e-11;
|
||||
const maxValue = 1e12;
|
||||
const K = 1e3;
|
||||
const maxFps = 240;
|
||||
|
||||
// Strings
|
||||
|
||||
const emptyString = '';
|
||||
const cssVarPrefix = 'var(';
|
||||
|
||||
// Arrays
|
||||
|
||||
// Shared sentinel for tween slots that don't hold array data. Never mutated, only read; COMPLEX and COLOR tweens always replace the slot before writing.
|
||||
const emptyArray = [];
|
||||
|
||||
const shortTransforms = /*#__PURE__*/ (() => {
|
||||
const map = new Map();
|
||||
map.set('x', 'translateX');
|
||||
map.set('y', 'translateY');
|
||||
map.set('z', 'translateZ');
|
||||
return map;
|
||||
})();
|
||||
|
||||
const validTransforms = [
|
||||
'perspective',
|
||||
'translateX',
|
||||
'translateY',
|
||||
'translateZ',
|
||||
'rotate',
|
||||
'rotateX',
|
||||
'rotateY',
|
||||
'rotateZ',
|
||||
'scale',
|
||||
'scaleX',
|
||||
'scaleY',
|
||||
'scaleZ',
|
||||
'skew',
|
||||
'skewX',
|
||||
'skewY',
|
||||
];
|
||||
|
||||
const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {});
|
||||
|
||||
// Functions
|
||||
|
||||
/** @return {void} */
|
||||
const noop = () => {};
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {T} v
|
||||
* @return {T}
|
||||
*/
|
||||
const noopModifier = v => v;
|
||||
|
||||
// Regex
|
||||
|
||||
const validRgbHslRgx = /\)\s*[-.\d]/;
|
||||
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 relativeValuesExecRgx = /(\*=|\+=|-=)/;
|
||||
const cssVariableMatchRgx = /var\(\s*(--[\w-]+)(?:\s*,\s*([^)]+))?\s*\)/;
|
||||
|
||||
export { K, compositionTypes, cssVarPrefix, cssVariableMatchRgx, digitWithExponentRgx, doc, emptyArray, emptyString, hexTestRgx, hslExecRgx, hslaExecRgx, isBrowser, isDomSymbol, isRegisteredTargetSymbol, isSvgSymbol, lowerCaseRgx, maxFps, maxValue, minValue, noop, noopModifier, proxyTargetSymbol, relativeValuesExecRgx, rgbExecRgx, rgbaExecRgx, shortTransforms, tickModes, transformsFragmentStrings, transformsSymbol, tweenTypes, unitsExecRgx, validRgbHslRgx, validTransforms, valueTypes, win };
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('./consts.cjs');
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* DefaultsParams,
|
||||
* DOMTarget,
|
||||
* } from '../types/index.js'
|
||||
*
|
||||
* @import {
|
||||
* Scope,
|
||||
* } from '../scope/index.js'
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} EditorGlobals
|
||||
* @property {boolean} showPanel
|
||||
* @property {Function} addAnimation
|
||||
* @property {Function} addSet
|
||||
* @property {Function} addTimeline
|
||||
* @property {Function} addTimelineChild
|
||||
* @property {Function} addTimelineLabel
|
||||
* @property {Function} addTimelineCall
|
||||
* @property {Function} addTimelineSync
|
||||
* @property {Function} resolveStagger
|
||||
* @property {Object|null} _head
|
||||
* @property {Object|null} _tail
|
||||
*/
|
||||
|
||||
/** @type {DefaultsParams} */
|
||||
const defaults = {
|
||||
id: null,
|
||||
keyframes: null,
|
||||
playbackEase: null,
|
||||
playbackRate: 1,
|
||||
frameRate: consts.maxFps,
|
||||
loop: 0,
|
||||
reversed: false,
|
||||
alternate: false,
|
||||
autoplay: true,
|
||||
persist: false,
|
||||
duration: consts.K,
|
||||
delay: 0,
|
||||
loopDelay: 0,
|
||||
ease: 'out(2)',
|
||||
composition: consts.compositionTypes.replace,
|
||||
modifier: consts.noopModifier,
|
||||
onBegin: consts.noop,
|
||||
onBeforeUpdate: consts.noop,
|
||||
onUpdate: consts.noop,
|
||||
onLoop: consts.noop,
|
||||
onPause: consts.noop,
|
||||
onComplete: consts.noop,
|
||||
onRender: consts.noop,
|
||||
};
|
||||
|
||||
const scope = {
|
||||
/** @type {Scope} */
|
||||
current: null,
|
||||
/** @type {Document|DOMTarget} */
|
||||
root: consts.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,
|
||||
/** @type {EditorGlobals|null} */
|
||||
editor: null,
|
||||
};
|
||||
|
||||
const globalVersions = { version: '4.5.0', engine: null };
|
||||
|
||||
if (consts.isBrowser) {
|
||||
if (!consts.win.AnimeJS) consts.win.AnimeJS = [];
|
||||
consts.win.AnimeJS.push(globalVersions);
|
||||
}
|
||||
|
||||
exports.defaults = defaults;
|
||||
exports.globalVersions = globalVersions;
|
||||
exports.globals = globals;
|
||||
exports.scope = scope;
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @import {
|
||||
* DefaultsParams,
|
||||
* DOMTarget,
|
||||
* } from '../types/index.js'
|
||||
*
|
||||
* @import {
|
||||
* Scope,
|
||||
* } from '../scope/index.js'
|
||||
*/
|
||||
/**
|
||||
* @typedef {Object} EditorGlobals
|
||||
* @property {boolean} showPanel
|
||||
* @property {Function} addAnimation
|
||||
* @property {Function} addSet
|
||||
* @property {Function} addTimeline
|
||||
* @property {Function} addTimelineChild
|
||||
* @property {Function} addTimelineLabel
|
||||
* @property {Function} addTimelineCall
|
||||
* @property {Function} addTimelineSync
|
||||
* @property {Function} resolveStagger
|
||||
* @property {Object|null} _head
|
||||
* @property {Object|null} _tail
|
||||
*/
|
||||
/** @type {DefaultsParams} */
|
||||
export const defaults: DefaultsParams;
|
||||
export namespace scope {
|
||||
export let current: Scope;
|
||||
export { doc as root };
|
||||
}
|
||||
export namespace globals {
|
||||
export { defaults };
|
||||
export let precision: number;
|
||||
export let timeScale: number;
|
||||
export let tickThreshold: number;
|
||||
export let editor: EditorGlobals | null;
|
||||
}
|
||||
export namespace globalVersions {
|
||||
let version: string;
|
||||
let engine: any;
|
||||
}
|
||||
export type EditorGlobals = {
|
||||
showPanel: boolean;
|
||||
addAnimation: Function;
|
||||
addSet: Function;
|
||||
addTimeline: Function;
|
||||
addTimelineChild: Function;
|
||||
addTimelineLabel: Function;
|
||||
addTimelineCall: Function;
|
||||
addTimelineSync: Function;
|
||||
resolveStagger: Function;
|
||||
_head: any | null;
|
||||
_tail: any | null;
|
||||
};
|
||||
import type { DefaultsParams } from '../types/index.js';
|
||||
import type { Scope } from '../scope/index.js';
|
||||
import { doc } from './consts.js';
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { isBrowser, win, noop, noopModifier, compositionTypes, K, maxFps, doc } from './consts.js';
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* DefaultsParams,
|
||||
* DOMTarget,
|
||||
* } from '../types/index.js'
|
||||
*
|
||||
* @import {
|
||||
* Scope,
|
||||
* } from '../scope/index.js'
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} EditorGlobals
|
||||
* @property {boolean} showPanel
|
||||
* @property {Function} addAnimation
|
||||
* @property {Function} addSet
|
||||
* @property {Function} addTimeline
|
||||
* @property {Function} addTimelineChild
|
||||
* @property {Function} addTimelineLabel
|
||||
* @property {Function} addTimelineCall
|
||||
* @property {Function} addTimelineSync
|
||||
* @property {Function} resolveStagger
|
||||
* @property {Object|null} _head
|
||||
* @property {Object|null} _tail
|
||||
*/
|
||||
|
||||
/** @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: noopModifier,
|
||||
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,
|
||||
/** @type {EditorGlobals|null} */
|
||||
editor: null,
|
||||
};
|
||||
|
||||
const globalVersions = { version: '4.5.0', engine: null };
|
||||
|
||||
if (isBrowser) {
|
||||
if (!win.AnimeJS) win.AnimeJS = [];
|
||||
win.AnimeJS.push(globalVersions);
|
||||
}
|
||||
|
||||
export { defaults, globalVersions, globals, scope };
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('./consts.cjs');
|
||||
var globals = require('./globals.cjs');
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* Target,
|
||||
* DOMTarget,
|
||||
* } from '../types/index.js'
|
||||
*/
|
||||
|
||||
// Strings
|
||||
|
||||
/**
|
||||
* @param {String} str
|
||||
* @return {String}
|
||||
*/
|
||||
const toLowerCase = str => str.replace(consts.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 => consts.isBrowser && a instanceof SVGElement;
|
||||
/**@param {any} a @return {Boolean} */
|
||||
const isHex = a => consts.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} */ // Make sure boxShadow syntax like 'rgb(255, 0, 0) 0px 0px 6px 0px' is not a valid color type
|
||||
const isCol = a => isHex(a) || ((isRgb(a) || isHsl(a)) && (a[a.length - 1] === ')' || !consts.validRgbHslRgx.test(a)));
|
||||
/**@param {any} a @return {Boolean} */
|
||||
const isKey = a => !globals.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;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
const p = 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) => factor === 1 ? end : factor === 0 ? start : start + (end - start) * factor;
|
||||
|
||||
/**
|
||||
* Replaces infinity with maximum safe value
|
||||
*
|
||||
* @param {Number} v - Value to check
|
||||
* @return {Number}
|
||||
*/
|
||||
const clampInfinity = v => v === Infinity ? consts.maxValue : v === -Infinity ? -consts.maxValue : v;
|
||||
|
||||
/**
|
||||
* Normalizes time value with minimum threshold
|
||||
*
|
||||
* @param {Number} v - Time value to normalize
|
||||
* @return {Number}
|
||||
*/
|
||||
const normalizeTime = v => v <= consts.minValue ? consts.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;
|
||||
};
|
||||
|
||||
exports.PI = PI;
|
||||
exports._round = _round;
|
||||
exports.abs = abs;
|
||||
exports.addChild = addChild;
|
||||
exports.asin = asin;
|
||||
exports.atan2 = atan2;
|
||||
exports.ceil = ceil;
|
||||
exports.clamp = clamp;
|
||||
exports.clampInfinity = clampInfinity;
|
||||
exports.cloneArray = cloneArray;
|
||||
exports.cos = cos;
|
||||
exports.exp = exp;
|
||||
exports.floor = floor;
|
||||
exports.forEachChildren = forEachChildren;
|
||||
exports.isArr = isArr;
|
||||
exports.isCol = isCol;
|
||||
exports.isFnc = isFnc;
|
||||
exports.isHex = isHex;
|
||||
exports.isHsl = isHsl;
|
||||
exports.isKey = isKey;
|
||||
exports.isNil = isNil;
|
||||
exports.isNum = isNum;
|
||||
exports.isObj = isObj;
|
||||
exports.isRgb = isRgb;
|
||||
exports.isStr = isStr;
|
||||
exports.isSvg = isSvg;
|
||||
exports.isUnd = isUnd;
|
||||
exports.isValidSVGAttribute = isValidSVGAttribute;
|
||||
exports.lerp = lerp;
|
||||
exports.max = max;
|
||||
exports.mergeObjects = mergeObjects;
|
||||
exports.normalizeTime = normalizeTime;
|
||||
exports.now = now;
|
||||
exports.parseNumber = parseNumber;
|
||||
exports.pow = pow;
|
||||
exports.removeChild = removeChild;
|
||||
exports.round = round;
|
||||
exports.sin = sin;
|
||||
exports.snap = snap;
|
||||
exports.sqrt = sqrt;
|
||||
exports.stringStartsWith = stringStartsWith;
|
||||
exports.toLowerCase = toLowerCase;
|
||||
@@ -0,0 +1,43 @@
|
||||
export function toLowerCase(str: string): string;
|
||||
export function stringStartsWith(str: string, sub: string): boolean;
|
||||
export const now: () => number;
|
||||
export const isArr: (arg: any) => arg is any[];
|
||||
export function isObj(a: any): a is Record<string, any>;
|
||||
export function isNum(a: any): a is number;
|
||||
export function isStr(a: any): a is string;
|
||||
export function isFnc(a: any): a is Function;
|
||||
export function isUnd(a: any): a is undefined;
|
||||
export function isNil(a: any): a is null | undefined;
|
||||
export function isSvg(a: any): a is SVGElement;
|
||||
export function isHex(a: any): boolean;
|
||||
export function isRgb(a: any): boolean;
|
||||
export function isHsl(a: any): boolean;
|
||||
export function isCol(a: any): boolean;
|
||||
export function isKey(a: any): boolean;
|
||||
export function isValidSVGAttribute(el: Target, propertyName: string): boolean;
|
||||
export function parseNumber(str: number | string): number;
|
||||
export const pow: (x: number, y: number) => number;
|
||||
export const sqrt: (x: number) => number;
|
||||
export const sin: (x: number) => number;
|
||||
export const cos: (x: number) => number;
|
||||
export const abs: (x: number) => number;
|
||||
export const exp: (x: number) => number;
|
||||
export const ceil: (x: number) => number;
|
||||
export const floor: (x: number) => number;
|
||||
export const asin: (x: number) => number;
|
||||
export const max: (...values: number[]) => number;
|
||||
export const atan2: (y: number, x: number) => number;
|
||||
export const PI: number;
|
||||
export const _round: (x: number) => number;
|
||||
export function clamp(v: number, min: number, max: number): number;
|
||||
export function round(v: number, decimalLength: number): number;
|
||||
export function snap(v: number, increment: number | Array<number>): number;
|
||||
export function lerp(start: number, end: number, factor: number): number;
|
||||
export function clampInfinity(v: number): number;
|
||||
export function normalizeTime(v: number): number;
|
||||
export function cloneArray<T>(a: T[]): T[];
|
||||
export function mergeObjects<T, U>(o1: T, o2: U): T & U;
|
||||
export function forEachChildren(parent: any, callback: Function, reverse?: boolean, prevProp?: string, nextProp?: string): void;
|
||||
export function removeChild(parent: any, child: any, prevProp?: string, nextProp?: string): void;
|
||||
export function addChild(parent: any, child: any, sortMethod?: Function, prevProp?: string, nextProp?: string): void;
|
||||
import type { Target } from '../types/index.js';
|
||||
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { isBrowser, maxValue, minValue, hexTestRgx, lowerCaseRgx, validRgbHslRgx } 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} */ // Make sure boxShadow syntax like 'rgb(255, 0, 0) 0px 0px 6px 0px' is not a valid color type
|
||||
const isCol = a => isHex(a) || ((isRgb(a) || isHsl(a)) && (a[a.length - 1] === ')' || !validRgbHslRgx.test(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;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
const p = 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) => factor === 1 ? end : factor === 0 ? start : 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 };
|
||||
@@ -0,0 +1,414 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var globals = require('./globals.cjs');
|
||||
var consts = require('./consts.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
var transforms = require('./transforms.cjs');
|
||||
var values = require('./values.cjs');
|
||||
|
||||
/**
|
||||
* @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 = helpers.clamp(tickablePrevAbsoluteTime, -tickableDelay, duration);
|
||||
const tickableCurrentTime = helpers.clamp(tickableAbsoluteTime, -tickableDelay, duration);
|
||||
const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime;
|
||||
const isCurrentTimeAboveZero = tickableCurrentTime > 0;
|
||||
const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration;
|
||||
const isSetter = duration <= consts.minValue;
|
||||
const forcedTick = tickMode === consts.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 period = iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay);
|
||||
const currentIteration = ~~(tickableCurrentTime / period);
|
||||
tickable._currentIteration = helpers.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;
|
||||
// Derive elapsed from the same `~~` truncation that gave currentIteration. Using `% period` here can disagree with `~~(/period)` under float drift at iteration boundaries and write the wrong end of the tween for one frame.
|
||||
iterationElapsedTime = tickableCurrentTime - currentIteration * period || 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 === consts.tickModes.AUTO && (
|
||||
// Timeline children render from their offset instead of their delay so the gap left by a truncated sibling is covered on seek.
|
||||
time >= (parent && tickableDelay > 0 ? 0 : 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 is per-iteration, compared to the delay to catch a backward seek into a looped iteration's delay region. Exclude the final settled end, where iterationTime clamps to duration and would falsely match the delay region when the delay exceeds the duration.
|
||||
iterationTime <= tickableDelay && tickablePrevTime > 0 && !isCurrentTimeEqualOrAboveDuration ||
|
||||
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.globals.tickThreshold;
|
||||
// Round to match the precision of tween._absoluteStartTime so equal-time boundary checks compare cleanly without floating point drift from the unrounded _offset.
|
||||
const absoluteTime = helpers.round(tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime, 12);
|
||||
|
||||
// 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 !== consts.compositionTypes.none;
|
||||
// The previous sibling stops writing at its truncated end, so this tween takes over the hold from that point.
|
||||
const tweenPrevRepEndTime = tweenPrevRep ? tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration : 0;
|
||||
const tweenPrevRepIsCrossParent = tweenPrevRep && tweenPrevRep.parent !== tween.parent;
|
||||
// Same parent keyframes take over at their own start, end plus delay equals the next start by construction.
|
||||
// Cross parent siblings take over at their update start.
|
||||
// Negative delay siblings take over at their own start instead.
|
||||
const tweenNextRepTakeover = !tweenNextRep || tweenNextRep._isOverridden ? tweenAbsEndTime :
|
||||
tweenNextRep.parent === tween.parent ? tweenAbsEndTime + tweenNextRep._delay :
|
||||
tweenNextRep._absoluteStartTime < tweenNextRep._absoluteUpdateStartTime ? tweenNextRep._absoluteStartTime : tweenNextRep._absoluteUpdateStartTime;
|
||||
|
||||
if ((forcedRender || (
|
||||
// Tail keyframes always re-evaluate the gate so an earlier keyframe cannot leave the target stale by writing past its own range after a backward seek.
|
||||
(tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenNextRepTakeover ||
|
||||
(tweenPrevRep && !tweenPrevRepIsCrossParent && (!tweenNextRep || tweenNextRep.parent !== tween.parent))) &&
|
||||
// A cross parent tween re-renders its from value from the previous sibling truncated end so the handoff gap holds.
|
||||
// A keyframe re-renders its from revert while the next keyframe time is stale so a backward jump over its range cannot leave the next value in place.
|
||||
(tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime ||
|
||||
(tweenPrevRepIsCrossParent && !tween._hasFromValue && !tweenPrevRep._isOverridden && absoluteTime >= tweenPrevRepEndTime) ||
|
||||
(tweenNextRep && !tweenNextRep._isOverridden && tweenNextRep.parent === tween.parent && tweenNextRep._currentTime !== 0 && iterationTime < tweenNextRep._startTime))
|
||||
)) &&
|
||||
// Non-first keyframes wait until the iteration reaches their own start before rendering, so the previous keyframe can handle the from-revert when scrubbed backward past this tween's range.
|
||||
(!tweenPrevRep || tweenPrevRepIsCrossParent || iterationTime >= tween._startTime) &&
|
||||
(!tweenHasComposition || (
|
||||
!tween._isOverridden &&
|
||||
(!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) &&
|
||||
// The next sibling owns the value past its takeover point, so yielding there keeps writes single owner in both directions.
|
||||
(!tweenNextRep || tweenNextRep._isOverridden || absoluteTime <= tweenNextRepTakeover) &&
|
||||
// The previous sibling owns the value up to its truncated end.
|
||||
// Cross parent tweens take over the hold from that point, explicit from values wait for their own start.
|
||||
(!tweenPrevRep || (tweenPrevRep._isOverridden || (!tweenPrevRepIsCrossParent ?
|
||||
absoluteTime >= tweenPrevRepEndTime + tween._delay :
|
||||
absoluteTime >= tween._absoluteStartTime || (!tween._hasFromValue && absoluteTime >= tweenPrevRepEndTime))))
|
||||
))
|
||||
) {
|
||||
|
||||
const tweenNewTime = tween._currentTime = helpers.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 === consts.tweenTypes.OBJECT;
|
||||
const tweenIsNumber = tweenValueType === consts.valueTypes.NUMBER;
|
||||
// Only round the in-between frames values if the final value is a string. Object targets consume raw numbers, so rounding is dead work there.
|
||||
const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.globals.precision;
|
||||
|
||||
// Recompose tween value
|
||||
/** @type {String|Number} */
|
||||
let value;
|
||||
/** @type {Number} */
|
||||
let number;
|
||||
|
||||
if (tweenIsNumber) {
|
||||
value = number = /** @type {Number} */(tweenModifier(helpers.round(helpers.lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision )));
|
||||
} else if (tweenValueType === consts.valueTypes.UNIT) {
|
||||
// Rounding the values speed up string composition
|
||||
number = /** @type {Number} */(tweenModifier(helpers.round(helpers.lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision)));
|
||||
value = `${number}${tween._unit}`;
|
||||
} else if (tweenValueType === consts.valueTypes.COLOR) {
|
||||
const ns = tween._numbers;
|
||||
const fn = tween._fromNumbers;
|
||||
const tn = tween._toNumbers;
|
||||
const omt = 1 - tweenProgress;
|
||||
const fr = fn[0], fg = fn[1], fb = fn[2];
|
||||
const tr = tn[0], tg = tn[1], tb = tn[2];
|
||||
// RGB channels lerp in pseudo-linear space (square inputs, sqrt result) to approximate gamma-correct blending.
|
||||
// See https://developer.nvidia.com/gpugems/gpugems3/part-iv-image-effects/chapter-24-importance-being-linear.
|
||||
ns[0] = /** @type {Number} */(tweenModifier(Math.sqrt(fr * fr * omt + tr * tr * tweenProgress)));
|
||||
ns[1] = /** @type {Number} */(tweenModifier(Math.sqrt(fg * fg * omt + tg * tg * tweenProgress)));
|
||||
ns[2] = /** @type {Number} */(tweenModifier(Math.sqrt(fb * fb * omt + tb * tb * tweenProgress)));
|
||||
ns[3] = /** @type {Number} */(tweenModifier(helpers.lerp(fn[3], tn[3], tweenProgress)));
|
||||
// The rgba string is built only for the dispatch path or the internalRender composition tick (setters handles the color comp)
|
||||
if (!tween._setter || internalRender) {
|
||||
value = `rgba(${helpers.round(ns[0], 0)},${helpers.round(ns[1], 0)},${helpers.round(ns[2], 0)},${ns[3]})`;
|
||||
}
|
||||
} else if (tweenValueType === consts.valueTypes.COMPLEX) {
|
||||
value = values.composeComplexValue(tween, tweenProgress, tweenPrecision);
|
||||
}
|
||||
|
||||
// For additive tweens and Animatables
|
||||
if (tweenHasComposition) {
|
||||
tween._number = number;
|
||||
}
|
||||
|
||||
if (!internalRender && tweenComposition !== consts.compositionTypes.blend) {
|
||||
|
||||
const tweenProperty = tween.property;
|
||||
tweenTarget = tween.target;
|
||||
|
||||
if (tween._setter) {
|
||||
tween._setter(tweenTarget, number, tween);
|
||||
} else if (tweenIsObject) {
|
||||
tweenTarget[tweenProperty] = value;
|
||||
} else if (tweenType === consts.tweenTypes.ATTRIBUTE) {
|
||||
/** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value));
|
||||
} else {
|
||||
tweenStyle = /** @type {DOMTarget} */(tweenTarget).style;
|
||||
if (tweenType === consts.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[consts.transformsSymbol];
|
||||
}
|
||||
tweenTargetTransformsProperties[tweenProperty] = value;
|
||||
tweenTransformsNeedUpdate = 1;
|
||||
} else if (tweenType === consts.tweenTypes.CSS) {
|
||||
tweenStyle[tweenProperty] = value;
|
||||
} else if (tweenType === consts.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;
|
||||
}
|
||||
|
||||
} else if (tweenCurrentTime && tweenPrevRep && !tweenPrevRepIsCrossParent && iterationTime < tween._startTime) {
|
||||
// Mark the keyframe as reverted when the playhead moves before its start, the previous keyframe owns the from revert and writes it once.
|
||||
tween._currentTime = 0;
|
||||
}
|
||||
|
||||
if (tweenTransformsNeedUpdate && tween._renderTransforms) {
|
||||
tweenStyle.transform = transforms.buildTransformString(tweenTargetTransformsProperties);
|
||||
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 <= consts.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 = helpers.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;
|
||||
helpers.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, consts.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 <= consts.minValue && (!childStartTime || childEndTime === tlIterationDuration)) {
|
||||
child.onComplete(child);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl));
|
||||
}
|
||||
|
||||
helpers.forEachChildren(tl, (/** @type {JSAnimation} */child) => {
|
||||
const childTime = helpers.round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds
|
||||
// Skip past-end siblings on backward iteration so their progress=1 to-values don't render last and overwrite the active sibling's write. Compare against _delay + duration so children with a normalized delay are not skipped while still inside their active range.
|
||||
if (tlIsRunningBackwards && childTime > child._delay + child.duration) return;
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.render = render;
|
||||
exports.tick = tick;
|
||||
@@ -0,0 +1,4 @@
|
||||
export function render(tickable: Tickable, time: number, muteCallbacks: number, internalRender: number, tickMode: tickModes): number;
|
||||
export function tick(tickable: Tickable, time: number, muteCallbacks: number, internalRender: number, tickMode: number): void;
|
||||
import type { Tickable } from '../types/index.js';
|
||||
import { tickModes } from './consts.js';
|
||||
@@ -0,0 +1,411 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { globals } from './globals.js';
|
||||
import { minValue, tickModes, valueTypes, compositionTypes, tweenTypes, transformsSymbol } from './consts.js';
|
||||
import { forEachChildren, round, now, clamp, lerp } from './helpers.js';
|
||||
import { buildTransformString } from './transforms.js';
|
||||
import { composeComplexValue } from './values.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 period = iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay);
|
||||
const currentIteration = ~~(tickableCurrentTime / period);
|
||||
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;
|
||||
// Derive elapsed from the same `~~` truncation that gave currentIteration. Using `% period` here can disagree with `~~(/period)` under float drift at iteration boundaries and write the wrong end of the tween for one frame.
|
||||
iterationElapsedTime = tickableCurrentTime - currentIteration * period || 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 && (
|
||||
// Timeline children render from their offset instead of their delay so the gap left by a truncated sibling is covered on seek.
|
||||
time >= (parent && tickableDelay > 0 ? 0 : 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 is per-iteration, compared to the delay to catch a backward seek into a looped iteration's delay region. Exclude the final settled end, where iterationTime clamps to duration and would falsely match the delay region when the delay exceeds the duration.
|
||||
iterationTime <= tickableDelay && tickablePrevTime > 0 && !isCurrentTimeEqualOrAboveDuration ||
|
||||
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;
|
||||
// Round to match the precision of tween._absoluteStartTime so equal-time boundary checks compare cleanly without floating point drift from the unrounded _offset.
|
||||
const absoluteTime = round(tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime, 12);
|
||||
|
||||
// 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;
|
||||
// The previous sibling stops writing at its truncated end, so this tween takes over the hold from that point.
|
||||
const tweenPrevRepEndTime = tweenPrevRep ? tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration : 0;
|
||||
const tweenPrevRepIsCrossParent = tweenPrevRep && tweenPrevRep.parent !== tween.parent;
|
||||
// Same parent keyframes take over at their own start, end plus delay equals the next start by construction.
|
||||
// Cross parent siblings take over at their update start.
|
||||
// Negative delay siblings take over at their own start instead.
|
||||
const tweenNextRepTakeover = !tweenNextRep || tweenNextRep._isOverridden ? tweenAbsEndTime :
|
||||
tweenNextRep.parent === tween.parent ? tweenAbsEndTime + tweenNextRep._delay :
|
||||
tweenNextRep._absoluteStartTime < tweenNextRep._absoluteUpdateStartTime ? tweenNextRep._absoluteStartTime : tweenNextRep._absoluteUpdateStartTime;
|
||||
|
||||
if ((forcedRender || (
|
||||
// Tail keyframes always re-evaluate the gate so an earlier keyframe cannot leave the target stale by writing past its own range after a backward seek.
|
||||
(tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenNextRepTakeover ||
|
||||
(tweenPrevRep && !tweenPrevRepIsCrossParent && (!tweenNextRep || tweenNextRep.parent !== tween.parent))) &&
|
||||
// A cross parent tween re-renders its from value from the previous sibling truncated end so the handoff gap holds.
|
||||
// A keyframe re-renders its from revert while the next keyframe time is stale so a backward jump over its range cannot leave the next value in place.
|
||||
(tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime ||
|
||||
(tweenPrevRepIsCrossParent && !tween._hasFromValue && !tweenPrevRep._isOverridden && absoluteTime >= tweenPrevRepEndTime) ||
|
||||
(tweenNextRep && !tweenNextRep._isOverridden && tweenNextRep.parent === tween.parent && tweenNextRep._currentTime !== 0 && iterationTime < tweenNextRep._startTime))
|
||||
)) &&
|
||||
// Non-first keyframes wait until the iteration reaches their own start before rendering, so the previous keyframe can handle the from-revert when scrubbed backward past this tween's range.
|
||||
(!tweenPrevRep || tweenPrevRepIsCrossParent || iterationTime >= tween._startTime) &&
|
||||
(!tweenHasComposition || (
|
||||
!tween._isOverridden &&
|
||||
(!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) &&
|
||||
// The next sibling owns the value past its takeover point, so yielding there keeps writes single owner in both directions.
|
||||
(!tweenNextRep || tweenNextRep._isOverridden || absoluteTime <= tweenNextRepTakeover) &&
|
||||
// The previous sibling owns the value up to its truncated end.
|
||||
// Cross parent tweens take over the hold from that point, explicit from values wait for their own start.
|
||||
(!tweenPrevRep || (tweenPrevRep._isOverridden || (!tweenPrevRepIsCrossParent ?
|
||||
absoluteTime >= tweenPrevRepEndTime + tween._delay :
|
||||
absoluteTime >= tween._absoluteStartTime || (!tween._hasFromValue && absoluteTime >= tweenPrevRepEndTime))))
|
||||
))
|
||||
) {
|
||||
|
||||
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. Object targets consume raw numbers, so rounding is dead work there.
|
||||
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 ns = tween._numbers;
|
||||
const fn = tween._fromNumbers;
|
||||
const tn = tween._toNumbers;
|
||||
const omt = 1 - tweenProgress;
|
||||
const fr = fn[0], fg = fn[1], fb = fn[2];
|
||||
const tr = tn[0], tg = tn[1], tb = tn[2];
|
||||
// RGB channels lerp in pseudo-linear space (square inputs, sqrt result) to approximate gamma-correct blending.
|
||||
// See https://developer.nvidia.com/gpugems/gpugems3/part-iv-image-effects/chapter-24-importance-being-linear.
|
||||
ns[0] = /** @type {Number} */(tweenModifier(Math.sqrt(fr * fr * omt + tr * tr * tweenProgress)));
|
||||
ns[1] = /** @type {Number} */(tweenModifier(Math.sqrt(fg * fg * omt + tg * tg * tweenProgress)));
|
||||
ns[2] = /** @type {Number} */(tweenModifier(Math.sqrt(fb * fb * omt + tb * tb * tweenProgress)));
|
||||
ns[3] = /** @type {Number} */(tweenModifier(lerp(fn[3], tn[3], tweenProgress)));
|
||||
// The rgba string is built only for the dispatch path or the internalRender composition tick (setters handles the color comp)
|
||||
if (!tween._setter || internalRender) {
|
||||
value = `rgba(${round(ns[0], 0)},${round(ns[1], 0)},${round(ns[2], 0)},${ns[3]})`;
|
||||
}
|
||||
} else if (tweenValueType === valueTypes.COMPLEX) {
|
||||
value = composeComplexValue(tween, tweenProgress, tweenPrecision);
|
||||
}
|
||||
|
||||
// For additive tweens and Animatables
|
||||
if (tweenHasComposition) {
|
||||
tween._number = number;
|
||||
}
|
||||
|
||||
if (!internalRender && tweenComposition !== compositionTypes.blend) {
|
||||
|
||||
const tweenProperty = tween.property;
|
||||
tweenTarget = tween.target;
|
||||
|
||||
if (tween._setter) {
|
||||
tween._setter(tweenTarget, number, tween);
|
||||
} else 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;
|
||||
}
|
||||
|
||||
} else if (tweenCurrentTime && tweenPrevRep && !tweenPrevRepIsCrossParent && iterationTime < tween._startTime) {
|
||||
// Mark the keyframe as reverted when the playhead moves before its start, the previous keyframe owns the from revert and writes it once.
|
||||
tween._currentTime = 0;
|
||||
}
|
||||
|
||||
if (tweenTransformsNeedUpdate && tween._renderTransforms) {
|
||||
tweenStyle.transform = buildTransformString(tweenTargetTransformsProperties);
|
||||
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
|
||||
// Skip past-end siblings on backward iteration so their progress=1 to-values don't render last and overwrite the active sibling's write. Compare against _delay + duration so children with a normalized delay are not skipped while still inside their active range.
|
||||
if (tlIsRunningBackwards && childTime > child._delay + child.duration) return;
|
||||
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 };
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('./consts.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
var transforms = require('./transforms.cjs');
|
||||
var values = require('./values.cjs');
|
||||
|
||||
/**
|
||||
* @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 === consts.tweenTypes.TRANSFORM) {
|
||||
const t = consts.shortTransforms.get(propertyName);
|
||||
return t ? t : propertyName;
|
||||
} else if (
|
||||
tweenType === consts.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 === consts.tweenTypes.ATTRIBUTE && (helpers.isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style))
|
||||
) {
|
||||
const cachedPropertyName = propertyNamesCache[propertyName];
|
||||
if (cachedPropertyName) {
|
||||
return cachedPropertyName;
|
||||
} else {
|
||||
const lowerCaseName = propertyName ? helpers.toLowerCase(propertyName) : propertyName;
|
||||
propertyNamesCache[propertyName] = lowerCaseName;
|
||||
return lowerCaseName;
|
||||
}
|
||||
} else {
|
||||
return propertyName;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @template {Renderable} T
|
||||
* @param {T} renderable
|
||||
* @param {Boolean} [inlineStylesOnly]
|
||||
* @return {T}
|
||||
*/
|
||||
const revertValues = (renderable, inlineStylesOnly = false) => {
|
||||
// Allow revertValues() to be called on timelines
|
||||
if (renderable._hasChildren) {
|
||||
helpers.forEachChildren(renderable, (/** @type {Renderable} */child) => revertValues(child, inlineStylesOnly), true);
|
||||
} else {
|
||||
const animation = /** @type {JSAnimation} */(renderable);
|
||||
animation.pause();
|
||||
helpers.forEachChildren(animation, (/** @type {Tween} */tween) => {
|
||||
const tweenProperty = tween.property;
|
||||
const tweenTarget = tween.target;
|
||||
const tweenType = tween._tweenType;
|
||||
const originalInlinedValue = tween._inlineValue;
|
||||
const tweenHadNoInlineValue = helpers.isNil(originalInlinedValue) || originalInlinedValue === consts.emptyString;
|
||||
if (tween._setter) {
|
||||
if (!inlineStylesOnly && !tweenHadNoInlineValue) {
|
||||
// Re-seed the original value to the _number / _numbers props so the setter can write the original state instead of re-applying the current frame.
|
||||
values.decomposeRawValue(originalInlinedValue, values.decomposedOriginalValue);
|
||||
if (values.decomposedOriginalValue.d) {
|
||||
const src = values.decomposedOriginalValue.d;
|
||||
const dst = tween._numbers;
|
||||
for (let i = 0, l = src.length; i < l; i++) dst[i] = src[i];
|
||||
} else {
|
||||
tween._number = values.decomposedOriginalValue.n;
|
||||
}
|
||||
tween._setter(tween.target, tween._number, tween);
|
||||
}
|
||||
} else if (tweenType === consts.tweenTypes.OBJECT) {
|
||||
if (!inlineStylesOnly && !tweenHadNoInlineValue) {
|
||||
tweenTarget[tweenProperty] = originalInlinedValue;
|
||||
}
|
||||
} else if (tweenTarget[consts.isDomSymbol]) {
|
||||
if (tweenType === consts.tweenTypes.ATTRIBUTE) {
|
||||
if (!inlineStylesOnly) {
|
||||
if (tweenHadNoInlineValue) {
|
||||
/** @type {DOMTarget} */(tweenTarget).removeAttribute(tweenProperty);
|
||||
} else {
|
||||
/** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(originalInlinedValue));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
|
||||
if (tweenType === consts.tweenTypes.TRANSFORM) {
|
||||
const cachedTransforms = tweenTarget[consts.transformsSymbol];
|
||||
if (tweenHadNoInlineValue) {
|
||||
delete cachedTransforms[tweenProperty];
|
||||
} else {
|
||||
cachedTransforms[tweenProperty] = originalInlinedValue;
|
||||
}
|
||||
if (tween._renderTransforms) {
|
||||
if (!Object.keys(cachedTransforms).length) {
|
||||
targetStyle.removeProperty('transform');
|
||||
} else {
|
||||
targetStyle.transform = transforms.buildTransformString(cachedTransforms);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (tweenHadNoInlineValue) {
|
||||
targetStyle.removeProperty(helpers.toLowerCase(tweenProperty));
|
||||
} else {
|
||||
targetStyle[tweenProperty] = originalInlinedValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (tweenTarget[consts.isDomSymbol] && animation._tail === tween) {
|
||||
animation.targets.forEach(t => {
|
||||
if (t.getAttribute && t.getAttribute('style') === consts.emptyString) {
|
||||
t.removeAttribute('style');
|
||||
} });
|
||||
}
|
||||
});
|
||||
}
|
||||
return renderable;
|
||||
};
|
||||
|
||||
/**
|
||||
* @template {Renderable} T
|
||||
* @param {T} renderable
|
||||
* @return {T}
|
||||
*/
|
||||
const cleanInlineStyles = renderable => revertValues(renderable, true);
|
||||
|
||||
exports.cleanInlineStyles = cleanInlineStyles;
|
||||
exports.revertValues = revertValues;
|
||||
exports.sanitizePropertyName = sanitizePropertyName;
|
||||
@@ -0,0 +1,6 @@
|
||||
export function sanitizePropertyName(propertyName: string, target: Target, tweenType: tweenTypes): string;
|
||||
export function revertValues<T extends Renderable>(renderable: T, inlineStylesOnly?: boolean): T;
|
||||
export function cleanInlineStyles<T extends Renderable>(renderable: T): T;
|
||||
import type { Target } from '../types/index.js';
|
||||
import { tweenTypes } from './consts.js';
|
||||
import type { Renderable } from '../types/index.js';
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { tweenTypes, isDomSymbol, transformsSymbol, emptyString, shortTransforms } from './consts.js';
|
||||
import { forEachChildren, toLowerCase, isNil, isSvg } from './helpers.js';
|
||||
import { buildTransformString } from './transforms.js';
|
||||
import { decomposeRawValue, decomposedOriginalValue } from './values.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
|
||||
* @param {Boolean} [inlineStylesOnly]
|
||||
* @return {T}
|
||||
*/
|
||||
const revertValues = (renderable, inlineStylesOnly = false) => {
|
||||
// Allow revertValues() to be called on timelines
|
||||
if (renderable._hasChildren) {
|
||||
forEachChildren(renderable, (/** @type {Renderable} */child) => revertValues(child, inlineStylesOnly), true);
|
||||
} else {
|
||||
const animation = /** @type {JSAnimation} */(renderable);
|
||||
animation.pause();
|
||||
forEachChildren(animation, (/** @type {Tween} */tween) => {
|
||||
const tweenProperty = tween.property;
|
||||
const tweenTarget = tween.target;
|
||||
const tweenType = tween._tweenType;
|
||||
const originalInlinedValue = tween._inlineValue;
|
||||
const tweenHadNoInlineValue = isNil(originalInlinedValue) || originalInlinedValue === emptyString;
|
||||
if (tween._setter) {
|
||||
if (!inlineStylesOnly && !tweenHadNoInlineValue) {
|
||||
// Re-seed the original value to the _number / _numbers props so the setter can write the original state instead of re-applying the current frame.
|
||||
decomposeRawValue(originalInlinedValue, decomposedOriginalValue);
|
||||
if (decomposedOriginalValue.d) {
|
||||
const src = decomposedOriginalValue.d;
|
||||
const dst = tween._numbers;
|
||||
for (let i = 0, l = src.length; i < l; i++) dst[i] = src[i];
|
||||
} else {
|
||||
tween._number = decomposedOriginalValue.n;
|
||||
}
|
||||
tween._setter(tween.target, tween._number, tween);
|
||||
}
|
||||
} else if (tweenType === tweenTypes.OBJECT) {
|
||||
if (!inlineStylesOnly && !tweenHadNoInlineValue) {
|
||||
tweenTarget[tweenProperty] = originalInlinedValue;
|
||||
}
|
||||
} else if (tweenTarget[isDomSymbol]) {
|
||||
if (tweenType === tweenTypes.ATTRIBUTE) {
|
||||
if (!inlineStylesOnly) {
|
||||
if (tweenHadNoInlineValue) {
|
||||
/** @type {DOMTarget} */(tweenTarget).removeAttribute(tweenProperty);
|
||||
} else {
|
||||
/** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(originalInlinedValue));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const targetStyle = /** @type {DOMTarget} */(tweenTarget).style;
|
||||
if (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 {
|
||||
targetStyle.transform = buildTransformString(cachedTransforms);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (tweenHadNoInlineValue) {
|
||||
targetStyle.removeProperty(toLowerCase(tweenProperty));
|
||||
} else {
|
||||
targetStyle[tweenProperty] = originalInlinedValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (tweenTarget[isDomSymbol] && animation._tail === tween) {
|
||||
animation.targets.forEach(t => {
|
||||
if (t.getAttribute && t.getAttribute('style') === emptyString) {
|
||||
t.removeAttribute('style');
|
||||
} });
|
||||
}
|
||||
});
|
||||
}
|
||||
return renderable;
|
||||
};
|
||||
|
||||
/**
|
||||
* @template {Renderable} T
|
||||
* @param {T} renderable
|
||||
* @return {T}
|
||||
*/
|
||||
const cleanInlineStyles = renderable => revertValues(renderable, true);
|
||||
|
||||
export { cleanInlineStyles, revertValues, sanitizePropertyName };
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var globals = require('./globals.cjs');
|
||||
var consts = require('./consts.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* DOMTarget,
|
||||
* DOMTargetsParam,
|
||||
* JSTargetsArray,
|
||||
* TargetsParam,
|
||||
* JSTargetsParam,
|
||||
* TargetsArray,
|
||||
* DOMTargetsArray,
|
||||
* } from '../types/index.js'
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {DOMTargetsParam|TargetsParam} v
|
||||
* @return {NodeList|HTMLCollection}
|
||||
*/
|
||||
function getNodeList(v) {
|
||||
const n = helpers.isStr(v) ? globals.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 (helpers.isNil(targets)) return /** @type {TargetsArray} */([]);
|
||||
if (!consts.isBrowser) return /** @type {JSTargetsArray} */(helpers.isArr(targets) && targets.flat(Infinity) || [targets]);
|
||||
if (helpers.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 (!helpers.isNil(item)) {
|
||||
const nodeList = getNodeList(item);
|
||||
if (nodeList) {
|
||||
for (let j = 0, jl = nodeList.length; j < jl; j++) {
|
||||
const subItem = nodeList[j];
|
||||
if (!helpers.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;
|
||||
for (let i = 0; i < parsedTargetsLength; i++) {
|
||||
const target = parsedTargetsArray[i];
|
||||
if (!target[consts.isRegisteredTargetSymbol]) {
|
||||
target[consts.isRegisteredTargetSymbol] = true;
|
||||
const isSvgType = helpers.isSvg(target);
|
||||
const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType;
|
||||
if (isDom) {
|
||||
target[consts.isDomSymbol] = true;
|
||||
target[consts.isSvgSymbol] = isSvgType;
|
||||
target[consts.transformsSymbol] = {};
|
||||
}
|
||||
}
|
||||
}
|
||||
return parsedTargetsArray;
|
||||
}
|
||||
|
||||
exports.getNodeList = getNodeList;
|
||||
exports.parseTargets = parseTargets;
|
||||
exports.registerTargets = registerTargets;
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* @import {
|
||||
* DOMTarget,
|
||||
* DOMTargetsParam,
|
||||
* JSTargetsArray,
|
||||
* TargetsParam,
|
||||
* JSTargetsParam,
|
||||
* TargetsArray,
|
||||
* DOMTargetsArray,
|
||||
* } from '../types/index.js'
|
||||
*/
|
||||
/**
|
||||
* @param {DOMTargetsParam|TargetsParam} v
|
||||
* @return {NodeList|HTMLCollection}
|
||||
*/
|
||||
export function getNodeList(v: DOMTargetsParam | TargetsParam): NodeList | HTMLCollection;
|
||||
/**
|
||||
* @overload
|
||||
* @param {DOMTargetsParam} targets
|
||||
* @return {DOMTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {JSTargetsParam} targets
|
||||
* @return {JSTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {TargetsParam} targets
|
||||
* @return {TargetsArray}
|
||||
*
|
||||
* @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
|
||||
*/
|
||||
export function parseTargets(targets: DOMTargetsParam): DOMTargetsArray;
|
||||
/**
|
||||
* @overload
|
||||
* @param {DOMTargetsParam} targets
|
||||
* @return {DOMTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {JSTargetsParam} targets
|
||||
* @return {JSTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {TargetsParam} targets
|
||||
* @return {TargetsArray}
|
||||
*
|
||||
* @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
|
||||
*/
|
||||
export function parseTargets(targets: JSTargetsParam): JSTargetsArray;
|
||||
/**
|
||||
* @overload
|
||||
* @param {DOMTargetsParam} targets
|
||||
* @return {DOMTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {JSTargetsParam} targets
|
||||
* @return {JSTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {TargetsParam} targets
|
||||
* @return {TargetsArray}
|
||||
*
|
||||
* @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
|
||||
*/
|
||||
export function parseTargets(targets: TargetsParam): TargetsArray;
|
||||
/**
|
||||
* @overload
|
||||
* @param {DOMTargetsParam} targets
|
||||
* @return {DOMTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {JSTargetsParam} targets
|
||||
* @return {JSTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {TargetsParam} targets
|
||||
* @return {TargetsArray}
|
||||
*
|
||||
* @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
|
||||
*/
|
||||
export function registerTargets(targets: DOMTargetsParam): DOMTargetsArray;
|
||||
/**
|
||||
* @overload
|
||||
* @param {DOMTargetsParam} targets
|
||||
* @return {DOMTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {JSTargetsParam} targets
|
||||
* @return {JSTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {TargetsParam} targets
|
||||
* @return {TargetsArray}
|
||||
*
|
||||
* @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
|
||||
*/
|
||||
export function registerTargets(targets: JSTargetsParam): JSTargetsArray;
|
||||
/**
|
||||
* @overload
|
||||
* @param {DOMTargetsParam} targets
|
||||
* @return {DOMTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {JSTargetsParam} targets
|
||||
* @return {JSTargetsArray}
|
||||
*
|
||||
* @overload
|
||||
* @param {TargetsParam} targets
|
||||
* @return {TargetsArray}
|
||||
*
|
||||
* @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
|
||||
*/
|
||||
export function registerTargets(targets: TargetsParam): TargetsArray;
|
||||
import type { DOMTargetsParam } from '../types/index.js';
|
||||
import type { TargetsParam } from '../types/index.js';
|
||||
import type { DOMTargetsArray } from '../types/index.js';
|
||||
import type { JSTargetsParam } from '../types/index.js';
|
||||
import type { JSTargetsArray } from '../types/index.js';
|
||||
import type { TargetsArray } from '../types/index.js';
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - 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;
|
||||
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 };
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('./consts.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
|
||||
/**
|
||||
* @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;
|
||||
if (inlineTransforms) {
|
||||
const cachedTransforms = target[consts.transformsSymbol];
|
||||
let pos = 0;
|
||||
const len = inlineTransforms.length;
|
||||
let fullTranslateValue;
|
||||
while (pos < len) {
|
||||
// Skip whitespace
|
||||
while (pos < len && inlineTransforms.charCodeAt(pos) === 32) pos++;
|
||||
if (pos >= len) break;
|
||||
// Read function name
|
||||
const nameStart = pos;
|
||||
while (pos < len && inlineTransforms.charCodeAt(pos) !== 40) pos++;
|
||||
if (pos >= len) break;
|
||||
const name = inlineTransforms.substring(nameStart, pos);
|
||||
// Scan to closing paren, recording top-level comma positions
|
||||
let depth = 1;
|
||||
const valueStart = pos + 1;
|
||||
let c1 = -1, c2 = -1;
|
||||
pos++;
|
||||
while (pos < len && depth > 0) {
|
||||
const c = inlineTransforms.charCodeAt(pos);
|
||||
if (c === 40) depth++;
|
||||
else if (c === 41) depth--;
|
||||
else if (c === 44 && depth === 1) {
|
||||
if (c1 === -1) c1 = pos;
|
||||
else if (c2 === -1) c2 = pos;
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
const valueEnd = pos - 1;
|
||||
// Decompose multi-arg functions into individual axis properties
|
||||
if (name === 'translate' || name === 'translate3d') {
|
||||
if (c1 === -1) {
|
||||
cachedTransforms.translateX = inlineTransforms.substring(valueStart, valueEnd).trim();
|
||||
} else {
|
||||
cachedTransforms.translateX = inlineTransforms.substring(valueStart, c1).trim();
|
||||
if (c2 === -1) {
|
||||
cachedTransforms.translateY = inlineTransforms.substring(c1 + 1, valueEnd).trim();
|
||||
} else {
|
||||
cachedTransforms.translateY = inlineTransforms.substring(c1 + 1, c2).trim();
|
||||
cachedTransforms.translateZ = inlineTransforms.substring(c2 + 1, valueEnd).trim();
|
||||
}
|
||||
}
|
||||
fullTranslateValue = inlineTransforms.substring(valueStart, valueEnd);
|
||||
} else if (name === 'scale' || name === 'scale3d') {
|
||||
if (c1 === -1) {
|
||||
cachedTransforms.scale = inlineTransforms.substring(valueStart, valueEnd).trim();
|
||||
} else {
|
||||
cachedTransforms.scaleX = inlineTransforms.substring(valueStart, c1).trim();
|
||||
if (c2 === -1) {
|
||||
cachedTransforms.scaleY = inlineTransforms.substring(c1 + 1, valueEnd).trim();
|
||||
} else {
|
||||
cachedTransforms.scaleY = inlineTransforms.substring(c1 + 1, c2).trim();
|
||||
cachedTransforms.scaleZ = inlineTransforms.substring(c2 + 1, valueEnd).trim();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cachedTransforms[name] = inlineTransforms.substring(valueStart, valueEnd);
|
||||
}
|
||||
}
|
||||
// Resolve the requested property from the cache
|
||||
if (propName === 'translate3d' && fullTranslateValue) {
|
||||
if (animationInlineStyles) animationInlineStyles[propName] = fullTranslateValue;
|
||||
return fullTranslateValue;
|
||||
}
|
||||
const cached = cachedTransforms[propName];
|
||||
if (!helpers.isUnd(cached)) {
|
||||
if (animationInlineStyles) animationInlineStyles[propName] = cached;
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
return propName === 'translate3d' ? '0px, 0px, 0px' :
|
||||
propName === 'rotate3d' ? '0, 0, 0, 0deg' :
|
||||
helpers.stringStartsWith(propName, 'scale') ? '1' :
|
||||
helpers.stringStartsWith(propName, 'rotate') || helpers.stringStartsWith(propName, 'skew') ? '0deg' : '0px';
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds a CSS transform string from the target's cached transform properties.
|
||||
* Iterates validTransforms in order (perspective > translate > rotate > scale > skew > matrix).
|
||||
* When adjacent axis properties are all present, emits a shorter shorthand (translateX + translateY -> translate(x, y))
|
||||
* The index is advanced past consumed properties so they are not emitted twice.
|
||||
* Properties without a grouping partner (e.g. translateY alone, scaleZ alone) emit individually.
|
||||
*
|
||||
* @param {Record<String, String>} props
|
||||
* @return {String}
|
||||
*/
|
||||
const buildTransformString = (props) => {
|
||||
let str = consts.emptyString;
|
||||
for (let i = 0, l = consts.validTransforms.length; i < l; i++) {
|
||||
const key = consts.validTransforms[i];
|
||||
const val = props[key];
|
||||
if (val !== undefined) {
|
||||
// Group translateX with adjacent translateY / translateZ
|
||||
if (key === 'translateX') {
|
||||
const next = props.translateY;
|
||||
if (next !== undefined) {
|
||||
const next2 = props.translateZ;
|
||||
if (next2 !== undefined) {
|
||||
str += `translate3d(${val},${next},${next2}) `;
|
||||
i += 2;
|
||||
} else {
|
||||
str += `translate(${val},${next}) `;
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Group scaleX with adjacent scaleY / scaleZ (only when standalone scale is absent)
|
||||
if (key === 'scaleX' && props.scale === undefined) {
|
||||
const next = props.scaleY;
|
||||
if (next !== undefined) {
|
||||
const next2 = props.scaleZ;
|
||||
if (next2 !== undefined) {
|
||||
str += `scale3d(${val},${next},${next2}) `;
|
||||
i += 2;
|
||||
} else {
|
||||
str += `scale(${val},${next}) `;
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// All other properties: emit individually using pre-built fragment string
|
||||
str += `${consts.transformsFragmentStrings[key]}${val}) `;
|
||||
}
|
||||
// Preserve non-animatable rotate3d in correct position (after rotateZ, before scale)
|
||||
if (key === 'rotateZ') {
|
||||
if (props.rotate3d !== undefined) str += `rotate3d(${props.rotate3d}) `;
|
||||
}
|
||||
}
|
||||
// Preserve non-animatable matrix/matrix3d from inline styles
|
||||
if (props.matrix !== undefined) str += `matrix(${props.matrix}) `;
|
||||
if (props.matrix3d !== undefined) str += `matrix3d(${props.matrix3d}) `;
|
||||
return str;
|
||||
};
|
||||
|
||||
exports.buildTransformString = buildTransformString;
|
||||
exports.parseInlineTransforms = parseInlineTransforms;
|
||||
@@ -0,0 +1,3 @@
|
||||
export function parseInlineTransforms(target: DOMTarget, propName: string, animationInlineStyles: any): string;
|
||||
export function buildTransformString(props: Record<string, string>): string;
|
||||
import type { DOMTarget } from '../types/index.js';
|
||||
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { transformsFragmentStrings, emptyString, validTransforms, transformsSymbol } 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;
|
||||
if (inlineTransforms) {
|
||||
const cachedTransforms = target[transformsSymbol];
|
||||
let pos = 0;
|
||||
const len = inlineTransforms.length;
|
||||
let fullTranslateValue;
|
||||
while (pos < len) {
|
||||
// Skip whitespace
|
||||
while (pos < len && inlineTransforms.charCodeAt(pos) === 32) pos++;
|
||||
if (pos >= len) break;
|
||||
// Read function name
|
||||
const nameStart = pos;
|
||||
while (pos < len && inlineTransforms.charCodeAt(pos) !== 40) pos++;
|
||||
if (pos >= len) break;
|
||||
const name = inlineTransforms.substring(nameStart, pos);
|
||||
// Scan to closing paren, recording top-level comma positions
|
||||
let depth = 1;
|
||||
const valueStart = pos + 1;
|
||||
let c1 = -1, c2 = -1;
|
||||
pos++;
|
||||
while (pos < len && depth > 0) {
|
||||
const c = inlineTransforms.charCodeAt(pos);
|
||||
if (c === 40) depth++;
|
||||
else if (c === 41) depth--;
|
||||
else if (c === 44 && depth === 1) {
|
||||
if (c1 === -1) c1 = pos;
|
||||
else if (c2 === -1) c2 = pos;
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
const valueEnd = pos - 1;
|
||||
// Decompose multi-arg functions into individual axis properties
|
||||
if (name === 'translate' || name === 'translate3d') {
|
||||
if (c1 === -1) {
|
||||
cachedTransforms.translateX = inlineTransforms.substring(valueStart, valueEnd).trim();
|
||||
} else {
|
||||
cachedTransforms.translateX = inlineTransforms.substring(valueStart, c1).trim();
|
||||
if (c2 === -1) {
|
||||
cachedTransforms.translateY = inlineTransforms.substring(c1 + 1, valueEnd).trim();
|
||||
} else {
|
||||
cachedTransforms.translateY = inlineTransforms.substring(c1 + 1, c2).trim();
|
||||
cachedTransforms.translateZ = inlineTransforms.substring(c2 + 1, valueEnd).trim();
|
||||
}
|
||||
}
|
||||
fullTranslateValue = inlineTransforms.substring(valueStart, valueEnd);
|
||||
} else if (name === 'scale' || name === 'scale3d') {
|
||||
if (c1 === -1) {
|
||||
cachedTransforms.scale = inlineTransforms.substring(valueStart, valueEnd).trim();
|
||||
} else {
|
||||
cachedTransforms.scaleX = inlineTransforms.substring(valueStart, c1).trim();
|
||||
if (c2 === -1) {
|
||||
cachedTransforms.scaleY = inlineTransforms.substring(c1 + 1, valueEnd).trim();
|
||||
} else {
|
||||
cachedTransforms.scaleY = inlineTransforms.substring(c1 + 1, c2).trim();
|
||||
cachedTransforms.scaleZ = inlineTransforms.substring(c2 + 1, valueEnd).trim();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cachedTransforms[name] = inlineTransforms.substring(valueStart, valueEnd);
|
||||
}
|
||||
}
|
||||
// Resolve the requested property from the cache
|
||||
if (propName === 'translate3d' && fullTranslateValue) {
|
||||
if (animationInlineStyles) animationInlineStyles[propName] = fullTranslateValue;
|
||||
return fullTranslateValue;
|
||||
}
|
||||
const cached = cachedTransforms[propName];
|
||||
if (!isUnd(cached)) {
|
||||
if (animationInlineStyles) animationInlineStyles[propName] = cached;
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
return propName === 'translate3d' ? '0px, 0px, 0px' :
|
||||
propName === 'rotate3d' ? '0, 0, 0, 0deg' :
|
||||
stringStartsWith(propName, 'scale') ? '1' :
|
||||
stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px';
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds a CSS transform string from the target's cached transform properties.
|
||||
* Iterates validTransforms in order (perspective > translate > rotate > scale > skew > matrix).
|
||||
* When adjacent axis properties are all present, emits a shorter shorthand (translateX + translateY -> translate(x, y))
|
||||
* The index is advanced past consumed properties so they are not emitted twice.
|
||||
* Properties without a grouping partner (e.g. translateY alone, scaleZ alone) emit individually.
|
||||
*
|
||||
* @param {Record<String, String>} props
|
||||
* @return {String}
|
||||
*/
|
||||
const buildTransformString = (props) => {
|
||||
let str = emptyString;
|
||||
for (let i = 0, l = validTransforms.length; i < l; i++) {
|
||||
const key = validTransforms[i];
|
||||
const val = props[key];
|
||||
if (val !== undefined) {
|
||||
// Group translateX with adjacent translateY / translateZ
|
||||
if (key === 'translateX') {
|
||||
const next = props.translateY;
|
||||
if (next !== undefined) {
|
||||
const next2 = props.translateZ;
|
||||
if (next2 !== undefined) {
|
||||
str += `translate3d(${val},${next},${next2}) `;
|
||||
i += 2;
|
||||
} else {
|
||||
str += `translate(${val},${next}) `;
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Group scaleX with adjacent scaleY / scaleZ (only when standalone scale is absent)
|
||||
if (key === 'scaleX' && props.scale === undefined) {
|
||||
const next = props.scaleY;
|
||||
if (next !== undefined) {
|
||||
const next2 = props.scaleZ;
|
||||
if (next2 !== undefined) {
|
||||
str += `scale3d(${val},${next},${next2}) `;
|
||||
i += 2;
|
||||
} else {
|
||||
str += `scale(${val},${next}) `;
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// All other properties: emit individually using pre-built fragment string
|
||||
str += `${transformsFragmentStrings[key]}${val}) `;
|
||||
}
|
||||
// Preserve non-animatable rotate3d in correct position (after rotateZ, before scale)
|
||||
if (key === 'rotateZ') {
|
||||
if (props.rotate3d !== undefined) str += `rotate3d(${props.rotate3d}) `;
|
||||
}
|
||||
}
|
||||
// Preserve non-animatable matrix/matrix3d from inline styles
|
||||
if (props.matrix !== undefined) str += `matrix(${props.matrix}) `;
|
||||
if (props.matrix3d !== undefined) str += `matrix3d(${props.matrix3d}) `;
|
||||
return str;
|
||||
};
|
||||
|
||||
export { buildTransformString, parseInlineTransforms };
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('./consts.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
|
||||
const angleUnitsMap = { 'deg': 1, 'rad': 180 / helpers.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 === consts.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 (!helpers.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 !== consts.doc)) ? parentNode : consts.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 === consts.valueTypes.UNIT;
|
||||
decomposedValue.u = unit;
|
||||
return decomposedValue;
|
||||
};
|
||||
|
||||
exports.convertValueUnit = convertValueUnit;
|
||||
@@ -0,0 +1,3 @@
|
||||
export function convertValueUnit(el: DOMTarget, decomposedValue: TweenDecomposedValue, unit: string, force?: boolean): TweenDecomposedValue;
|
||||
import type { DOMTarget } from '../types/index.js';
|
||||
import type { TweenDecomposedValue } from '../types/index.js';
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - 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 };
|
||||
@@ -0,0 +1,277 @@
|
||||
/**
|
||||
* Anime.js - core - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('./consts.cjs');
|
||||
var helpers = require('./helpers.cjs');
|
||||
var transforms = require('./transforms.cjs');
|
||||
var registry = require('../adapters/registry.cjs');
|
||||
var colors = require('./colors.cjs');
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* Target,
|
||||
* DOMTarget,
|
||||
* Tween,
|
||||
* TweenPropValue,
|
||||
* TweenDecomposedValue,
|
||||
* TargetsArray,
|
||||
* } from '../types/index.js'
|
||||
*/
|
||||
|
||||
/**
|
||||
* @template T, D
|
||||
* @param {T|undefined} targetValue
|
||||
* @param {D} defaultValue
|
||||
* @return {T|D}
|
||||
*/
|
||||
const setValue = (targetValue, defaultValue) => {
|
||||
return helpers.isUnd(targetValue) ? defaultValue : targetValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve against the target when it's a DOM element, otherwise fall back to :root so non-DOM targets like three.js meshes and custom adapters still pick up CSS variables defined on the document.
|
||||
*
|
||||
* @param {String} value
|
||||
* @param {Target} target
|
||||
* @return {String|Number}
|
||||
*/
|
||||
const resolveCssVar = (value, target) => {
|
||||
const match = value.match(consts.cssVariableMatchRgx);
|
||||
const el = target[consts.isDomSymbol] ? target : document.documentElement;
|
||||
let computed = getComputedStyle(/** @type {HTMLElement} */(el))?.getPropertyValue(match[1]);
|
||||
if ((!computed || computed.trim() === consts.emptyString) && match[2]) computed = match[2].trim();
|
||||
return computed || 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {TweenPropValue} value
|
||||
* @param {Target} target
|
||||
* @param {Number} index
|
||||
* @param {TargetsArray} targets
|
||||
* @param {Object|null} store
|
||||
* @param {Tween|null} prevTween
|
||||
* @return {any}
|
||||
*/
|
||||
const getFunctionValue = (value, target, index, targets, store, prevTween) => {
|
||||
if (helpers.isFnc(value)) {
|
||||
if (!store) {
|
||||
const computed = /** @type {Function} */(value)(target, index, targets, prevTween);
|
||||
// Fallback to 0 if the function returns undefined, NaN, null, false or 0
|
||||
return !isNaN(+computed) ? +computed : computed || 0;
|
||||
}
|
||||
const func = () => {
|
||||
const computed = /** @type {Function} */(value)(target, index, targets, prevTween);
|
||||
return !isNaN(+computed) ? +computed : computed || 0;
|
||||
};
|
||||
store.func = func;
|
||||
return func();
|
||||
}
|
||||
if (helpers.isStr(value) && helpers.stringStartsWith(value, consts.cssVarPrefix)) {
|
||||
if (!store) return resolveCssVar(/** @type {String} */(value), target);
|
||||
const func = () => resolveCssVar(/** @type {String} */(value), target);
|
||||
store.func = func;
|
||||
return func();
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Target} target
|
||||
* @param {String} prop
|
||||
* @return {tweenTypes}
|
||||
*/
|
||||
const getTweenType = (target, prop) => {
|
||||
return !target[consts.isDomSymbol] ? consts.tweenTypes.OBJECT :
|
||||
// Handle SVG attributes
|
||||
target[consts.isSvgSymbol] && helpers.isValidSVGAttribute(target, prop) ? consts.tweenTypes.ATTRIBUTE :
|
||||
// Handle CSS Transform properties differently than CSS to allow individual animations
|
||||
consts.validTransforms.includes(prop) || consts.shortTransforms.get(prop) ? consts.tweenTypes.TRANSFORM :
|
||||
// CSS variables
|
||||
helpers.stringStartsWith(prop, '--') ? consts.tweenTypes.CSS_VAR :
|
||||
// All other CSS properties
|
||||
prop in /** @type {DOMTarget} */(target).style ? consts.tweenTypes.CSS :
|
||||
// Handle other DOM Attributes
|
||||
prop in target ? consts.tweenTypes.OBJECT :
|
||||
consts.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[consts.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 = !helpers.isUnd(tweenType) ? tweenType : getTweenType(target, propName);
|
||||
const adapterProp = registry.resolveAdapterEntry(target, propName);
|
||||
if (adapterProp) {
|
||||
const value = adapterProp.get(target);
|
||||
if (value && animationInlineStyles) animationInlineStyles[propName] = value;
|
||||
return value == null ? 0 : value;
|
||||
}
|
||||
if (type === consts.tweenTypes.OBJECT) {
|
||||
const value = target[propName];
|
||||
if (value && animationInlineStyles) animationInlineStyles[propName] = value;
|
||||
return value || 0;
|
||||
}
|
||||
if (type === consts.tweenTypes.ATTRIBUTE) {
|
||||
const value = /** @type {DOMTarget} */(target).getAttribute(propName);
|
||||
if (value && animationInlineStyles) animationInlineStyles[propName] = value;
|
||||
return value;
|
||||
}
|
||||
return type === consts.tweenTypes.TRANSFORM ? transforms.parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) :
|
||||
type === consts.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: consts.valueTypes.NUMBER,
|
||||
n: 0,
|
||||
u: null,
|
||||
o: null,
|
||||
d: null,
|
||||
s: null,
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {String|Number|Object} rawValue
|
||||
* @param {TweenDecomposedValue} targetObject
|
||||
* @return {TweenDecomposedValue}
|
||||
*/
|
||||
const decomposeRawValue = (rawValue, targetObject) => {
|
||||
/** @type {valueTypes} */
|
||||
targetObject.t = consts.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;
|
||||
}
|
||||
// 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 : consts.unitsExecRgx.exec(str);
|
||||
if (unitMatch) {
|
||||
// Has a number and a unit
|
||||
targetObject.t = consts.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 (helpers.isCol(str)) {
|
||||
// Color string
|
||||
targetObject.t = consts.valueTypes.COLOR;
|
||||
targetObject.d = colors.convertColorStringValuesToRgbaArray(str);
|
||||
return targetObject;
|
||||
} else {
|
||||
// Is a more complex string (generally svg coords, calc() or filters CSS values)
|
||||
const matchedNumbers = str.match(consts.digitWithExponentRgx);
|
||||
targetObject.t = consts.valueTypes.COMPLEX;
|
||||
targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : [];
|
||||
targetObject.s = str.split(consts.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 = helpers.cloneArray(tween._toNumbers);
|
||||
targetObject.s = helpers.cloneArray(tween._strings);
|
||||
return targetObject;
|
||||
};
|
||||
|
||||
const decomposedOriginalValue = createDecomposedValueTargetObject();
|
||||
|
||||
/**
|
||||
* @param {Tween} tween
|
||||
* @param {Number} progress
|
||||
* @param {Number} precision
|
||||
* @return {String}
|
||||
*/
|
||||
const composeComplexValue = (tween, progress, precision) => {
|
||||
const mod = tween._modifier;
|
||||
const fn = tween._fromNumbers;
|
||||
const tn = tween._toNumbers;
|
||||
const ts = tween._strings;
|
||||
let v = ts[0];
|
||||
for (let j = 0, l = tn.length; j < l; j++) {
|
||||
const n = /** @type {Number} */(mod(helpers.round(helpers.lerp(fn[j], tn[j], progress), precision)));
|
||||
const s = ts[j + 1];
|
||||
v += `${s ? n + s : n}`;
|
||||
// Keep _numbers fresh for every tween, not only composed ones, so a non-composition setter that reads the lerped triplet such as three transformOrigin still animates.
|
||||
// Potential optimization, skip the write when nothing reads it: if (hasComposition || tween._setter) tween._numbers[j] = n;
|
||||
tween._numbers[j] = n;
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
exports.composeComplexValue = composeComplexValue;
|
||||
exports.createDecomposedValueTargetObject = createDecomposedValueTargetObject;
|
||||
exports.decomposeRawValue = decomposeRawValue;
|
||||
exports.decomposeTweenValue = decomposeTweenValue;
|
||||
exports.decomposedOriginalValue = decomposedOriginalValue;
|
||||
exports.getFunctionValue = getFunctionValue;
|
||||
exports.getOriginalAnimatableValue = getOriginalAnimatableValue;
|
||||
exports.getRelativeValue = getRelativeValue;
|
||||
exports.getTweenType = getTweenType;
|
||||
exports.setValue = setValue;
|
||||
@@ -0,0 +1,16 @@
|
||||
export function setValue<T, D>(targetValue: T | undefined, defaultValue: D): T | D;
|
||||
export function getFunctionValue(value: TweenPropValue, target: Target, index: number, targets: TargetsArray, store: any | null, prevTween: Tween | null): any;
|
||||
export function getTweenType(target: Target, prop: string): tweenTypes;
|
||||
export function getOriginalAnimatableValue(target: Target, propName: string, tweenType?: tweenTypes, animationInlineStyles?: any | void): string | number;
|
||||
export function getRelativeValue(x: number, y: number, operator: string): number;
|
||||
export function createDecomposedValueTargetObject(): TweenDecomposedValue;
|
||||
export function decomposeRawValue(rawValue: string | number | any, targetObject: TweenDecomposedValue): TweenDecomposedValue;
|
||||
export function decomposeTweenValue(tween: Tween, targetObject: TweenDecomposedValue): TweenDecomposedValue;
|
||||
export const decomposedOriginalValue: TweenDecomposedValue;
|
||||
export function composeComplexValue(tween: Tween, progress: number, precision: number): string;
|
||||
import type { TweenPropValue } from '../types/index.js';
|
||||
import type { Target } from '../types/index.js';
|
||||
import type { TargetsArray } from '../types/index.js';
|
||||
import type { Tween } from '../types/index.js';
|
||||
import { tweenTypes } from './consts.js';
|
||||
import type { TweenDecomposedValue } from '../types/index.js';
|
||||
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* Anime.js - core - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
import { valueTypes, unitsExecRgx, digitWithExponentRgx, tweenTypes, isDomSymbol, isSvgSymbol, validTransforms, shortTransforms, proxyTargetSymbol, cssVariableMatchRgx, emptyString, cssVarPrefix } from './consts.js';
|
||||
import { isUnd, isCol, isValidSVGAttribute, stringStartsWith, isFnc, isStr, round, lerp, cloneArray } from './helpers.js';
|
||||
import { parseInlineTransforms } from './transforms.js';
|
||||
import { resolveAdapterEntry } from '../adapters/registry.js';
|
||||
import { convertColorStringValuesToRgbaArray } from './colors.js';
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* Target,
|
||||
* DOMTarget,
|
||||
* Tween,
|
||||
* TweenPropValue,
|
||||
* TweenDecomposedValue,
|
||||
* TargetsArray,
|
||||
* } 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;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve against the target when it's a DOM element, otherwise fall back to :root so non-DOM targets like three.js meshes and custom adapters still pick up CSS variables defined on the document.
|
||||
*
|
||||
* @param {String} value
|
||||
* @param {Target} target
|
||||
* @return {String|Number}
|
||||
*/
|
||||
const resolveCssVar = (value, target) => {
|
||||
const match = value.match(cssVariableMatchRgx);
|
||||
const el = target[isDomSymbol] ? target : document.documentElement;
|
||||
let computed = getComputedStyle(/** @type {HTMLElement} */(el))?.getPropertyValue(match[1]);
|
||||
if ((!computed || computed.trim() === emptyString) && match[2]) computed = match[2].trim();
|
||||
return computed || 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {TweenPropValue} value
|
||||
* @param {Target} target
|
||||
* @param {Number} index
|
||||
* @param {TargetsArray} targets
|
||||
* @param {Object|null} store
|
||||
* @param {Tween|null} prevTween
|
||||
* @return {any}
|
||||
*/
|
||||
const getFunctionValue = (value, target, index, targets, store, prevTween) => {
|
||||
if (isFnc(value)) {
|
||||
if (!store) {
|
||||
const computed = /** @type {Function} */(value)(target, index, targets, prevTween);
|
||||
// Fallback to 0 if the function returns undefined, NaN, null, false or 0
|
||||
return !isNaN(+computed) ? +computed : computed || 0;
|
||||
}
|
||||
const func = () => {
|
||||
const computed = /** @type {Function} */(value)(target, index, targets, prevTween);
|
||||
return !isNaN(+computed) ? +computed : computed || 0;
|
||||
};
|
||||
store.func = func;
|
||||
return func();
|
||||
}
|
||||
if (isStr(value) && stringStartsWith(value, cssVarPrefix)) {
|
||||
if (!store) return resolveCssVar(/** @type {String} */(value), target);
|
||||
const func = () => resolveCssVar(/** @type {String} */(value), target);
|
||||
store.func = func;
|
||||
return func();
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @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);
|
||||
const adapterProp = resolveAdapterEntry(target, propName);
|
||||
if (adapterProp) {
|
||||
const value = adapterProp.get(target);
|
||||
if (value && animationInlineStyles) animationInlineStyles[propName] = value;
|
||||
return value == null ? 0 : value;
|
||||
}
|
||||
if (type === tweenTypes.OBJECT) {
|
||||
const value = target[propName];
|
||||
if (value && animationInlineStyles) animationInlineStyles[propName] = value;
|
||||
return value || 0;
|
||||
}
|
||||
if (type === tweenTypes.ATTRIBUTE) {
|
||||
const value = /** @type {DOMTarget} */(target).getAttribute(propName);
|
||||
if (value && animationInlineStyles) animationInlineStyles[propName] = value;
|
||||
return value;
|
||||
}
|
||||
return 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|Object} 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;
|
||||
}
|
||||
// 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)) {
|
||||
// Color string
|
||||
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();
|
||||
|
||||
/**
|
||||
* @param {Tween} tween
|
||||
* @param {Number} progress
|
||||
* @param {Number} precision
|
||||
* @return {String}
|
||||
*/
|
||||
const composeComplexValue = (tween, progress, precision) => {
|
||||
const mod = tween._modifier;
|
||||
const fn = tween._fromNumbers;
|
||||
const tn = tween._toNumbers;
|
||||
const ts = tween._strings;
|
||||
let v = ts[0];
|
||||
for (let j = 0, l = tn.length; j < l; j++) {
|
||||
const n = /** @type {Number} */(mod(round(lerp(fn[j], tn[j], progress), precision)));
|
||||
const s = ts[j + 1];
|
||||
v += `${s ? n + s : n}`;
|
||||
// Keep _numbers fresh for every tween, not only composed ones, so a non-composition setter that reads the lerped triplet such as three transformOrigin still animates.
|
||||
// Potential optimization, skip the write when nothing reads it: if (hasComposition || tween._setter) tween._numbers[j] = n;
|
||||
tween._numbers[j] = n;
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
export { composeComplexValue, createDecomposedValueTargetObject, decomposeRawValue, decomposeTweenValue, decomposedOriginalValue, getFunctionValue, getOriginalAnimatableValue, getRelativeValue, getTweenType, setValue };
|
||||
+1239
File diff suppressed because it is too large
Load Diff
+274
@@ -0,0 +1,274 @@
|
||||
export class Draggable {
|
||||
/**
|
||||
* @param {TargetsParam} target
|
||||
* @param {DraggableParams} [parameters]
|
||||
*/
|
||||
constructor(target: TargetsParam, parameters?: DraggableParams);
|
||||
containerArray: number[];
|
||||
$container: HTMLElement;
|
||||
useWin: boolean;
|
||||
/** @type {Window | HTMLElement} */
|
||||
$scrollContainer: Window | HTMLElement;
|
||||
$target: HTMLElement;
|
||||
$trigger: HTMLElement;
|
||||
fixed: boolean;
|
||||
isFinePointer: boolean;
|
||||
/** @type {[Number, Number, Number, Number]} */
|
||||
containerPadding: [number, number, number, number];
|
||||
/** @type {Number} */
|
||||
containerFriction: number;
|
||||
/** @type {Number} */
|
||||
releaseContainerFriction: number;
|
||||
/** @type {Number|Array<Number>} */
|
||||
snapX: number | Array<number>;
|
||||
/** @type {Number|Array<Number>} */
|
||||
snapY: number | Array<number>;
|
||||
/** @type {Number} */
|
||||
scrollSpeed: number;
|
||||
/** @type {Number} */
|
||||
scrollThreshold: number;
|
||||
/** @type {Number} */
|
||||
dragSpeed: number;
|
||||
/** @type {Number} */
|
||||
dragThreshold: number;
|
||||
/** @type {Number} */
|
||||
maxVelocity: number;
|
||||
/** @type {Number} */
|
||||
minVelocity: number;
|
||||
/** @type {Number} */
|
||||
velocityMultiplier: number;
|
||||
/** @type {Boolean|DraggableCursorParams} */
|
||||
cursor: boolean | DraggableCursorParams;
|
||||
/** @type {Spring} */
|
||||
releaseXSpring: Spring;
|
||||
/** @type {Spring} */
|
||||
releaseYSpring: Spring;
|
||||
/** @type {EasingFunction} */
|
||||
releaseEase: EasingFunction;
|
||||
/** @type {Boolean} */
|
||||
hasReleaseSpring: boolean;
|
||||
/** @type {Callback<this>} */
|
||||
onGrab: Callback<this>;
|
||||
/** @type {Callback<this>} */
|
||||
onDrag: Callback<this>;
|
||||
/** @type {Callback<this>} */
|
||||
onRelease: Callback<this>;
|
||||
/** @type {Callback<this>} */
|
||||
onUpdate: Callback<this>;
|
||||
/** @type {Callback<this>} */
|
||||
onSettle: Callback<this>;
|
||||
/** @type {Callback<this>} */
|
||||
onSnap: Callback<this>;
|
||||
/** @type {Callback<this>} */
|
||||
onResize: Callback<this>;
|
||||
/** @type {Callback<this>} */
|
||||
onAfterResize: Callback<this>;
|
||||
/** @type {[Number, Number]} */
|
||||
disabled: [number, number];
|
||||
/** @type {AnimatableObject} */
|
||||
animate: AnimatableObject;
|
||||
xProp: string;
|
||||
yProp: string;
|
||||
destX: number;
|
||||
destY: number;
|
||||
deltaX: number;
|
||||
deltaY: number;
|
||||
scroll: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
/** @type {[Number, Number, Number, Number]} */
|
||||
coords: [number, number, number, number];
|
||||
/** @type {[Number, Number]} */
|
||||
snapped: [number, number];
|
||||
/** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */
|
||||
pointer: [number, number, number, number, number, number, number, number];
|
||||
/** @type {[Number, Number]} */
|
||||
scrollView: [number, number];
|
||||
/** @type {[Number, Number, Number, Number]} */
|
||||
dragArea: [number, number, number, number];
|
||||
/** @type {[Number, Number, Number, Number]} */
|
||||
containerBounds: [number, number, number, number];
|
||||
/** @type {[Number, Number, Number, Number]} */
|
||||
scrollBounds: [number, number, number, number];
|
||||
/** @type {[Number, Number, Number, Number]} */
|
||||
targetBounds: [number, number, number, number];
|
||||
/** @type {[Number, Number]} */
|
||||
window: [number, number];
|
||||
/** @type {[Number, Number, Number]} */
|
||||
velocityStack: [number, number, number];
|
||||
/** @type {Number} */
|
||||
velocityStackIndex: number;
|
||||
/** @type {Number} */
|
||||
velocityTime: number;
|
||||
/** @type {Number} */
|
||||
velocity: number;
|
||||
/** @type {Number} */
|
||||
angle: number;
|
||||
/** @type {JSAnimation} */
|
||||
cursorStyles: JSAnimation;
|
||||
/** @type {JSAnimation} */
|
||||
triggerStyles: JSAnimation;
|
||||
/** @type {JSAnimation} */
|
||||
bodyStyles: JSAnimation;
|
||||
/** @type {JSAnimation} */
|
||||
targetStyles: JSAnimation;
|
||||
/** @type {JSAnimation} */
|
||||
touchActionStyles: JSAnimation;
|
||||
transforms: Transforms;
|
||||
overshootCoords: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
overshootTicker: Timer;
|
||||
updated: boolean;
|
||||
manual: boolean;
|
||||
updateTicker: Timer;
|
||||
contained: boolean;
|
||||
grabbed: boolean;
|
||||
dragged: boolean;
|
||||
released: boolean;
|
||||
canScroll: boolean;
|
||||
enabled: boolean;
|
||||
initialized: boolean;
|
||||
activeProp: string;
|
||||
resizeTicker: Timer;
|
||||
parameters: DraggableParams;
|
||||
resizeObserver: ResizeObserver;
|
||||
/**
|
||||
* @param {Number} dx
|
||||
* @param {Number} dy
|
||||
* @return {Number}
|
||||
*/
|
||||
computeVelocity(dx: number, dy: number): number;
|
||||
/**
|
||||
* @param {Number} x
|
||||
* @param {Boolean} [muteUpdateCallback]
|
||||
* @return {this}
|
||||
*/
|
||||
setX(x: number, muteUpdateCallback?: boolean): this;
|
||||
/**
|
||||
* @param {Number} y
|
||||
* @param {Boolean} [muteUpdateCallback]
|
||||
* @return {this}
|
||||
*/
|
||||
setY(y: number, muteUpdateCallback?: boolean): this;
|
||||
set x(x: number);
|
||||
get x(): number;
|
||||
set y(y: number);
|
||||
get y(): number;
|
||||
set progressX(x: number);
|
||||
get progressX(): number;
|
||||
set progressY(y: number);
|
||||
get progressY(): number;
|
||||
updateScrollCoords(): void;
|
||||
updateBoundingValues(): void;
|
||||
/**
|
||||
* @param {Array} bounds
|
||||
* @param {Number} x
|
||||
* @param {Number} y
|
||||
* @return {Number}
|
||||
*/
|
||||
isOutOfBounds(bounds: any[], x: number, y: number): number;
|
||||
refresh(): void;
|
||||
update(): void;
|
||||
stop(): this;
|
||||
/**
|
||||
* @param {Number} [duration]
|
||||
* @param {Number} [gap]
|
||||
* @param {EasingParam} [ease]
|
||||
* @return {this}
|
||||
*/
|
||||
scrollInView(duration?: number, gap?: number, ease?: EasingParam): this;
|
||||
handleHover(): void;
|
||||
/**
|
||||
* @param {Number} [duration]
|
||||
* @param {Number} [gap]
|
||||
* @param {EasingParam} [ease]
|
||||
* @return {this}
|
||||
*/
|
||||
animateInView(duration?: number, gap?: number, ease?: EasingParam): this;
|
||||
/**
|
||||
* @param {MouseEvent|TouchEvent} e
|
||||
*/
|
||||
handleDown(e: MouseEvent | TouchEvent): void;
|
||||
/**
|
||||
* @param {MouseEvent|TouchEvent} e
|
||||
*/
|
||||
handleMove(e: MouseEvent | TouchEvent): void;
|
||||
handleUp(): void;
|
||||
reset(): this;
|
||||
enable(): this;
|
||||
disable(): this;
|
||||
revert(): this;
|
||||
/**
|
||||
* @param {Event} e
|
||||
*/
|
||||
handleEvent(e: Event): void;
|
||||
}
|
||||
export function createDraggable(target: TargetsParam, parameters?: DraggableParams): Draggable;
|
||||
import type { DraggableCursorParams } from '../types/index.js';
|
||||
import type { Spring } from '../easings/spring/index.js';
|
||||
import type { EasingFunction } from '../types/index.js';
|
||||
import type { Callback } from '../types/index.js';
|
||||
import type { AnimatableObject } from '../types/index.js';
|
||||
import { JSAnimation } from '../animation/animation.js';
|
||||
declare class Transforms {
|
||||
/**
|
||||
* @param {DOMTarget|DOMProxy} $el
|
||||
*/
|
||||
constructor($el: DOMTarget | DOMProxy);
|
||||
$el: DOMTarget | DOMProxy;
|
||||
inlineTransforms: any[];
|
||||
point: DOMPoint;
|
||||
inversedMatrix: DOMMatrix;
|
||||
/**
|
||||
* @param {Number} x
|
||||
* @param {Number} y
|
||||
* @return {DOMPoint}
|
||||
*/
|
||||
normalizePoint(x: number, y: number): DOMPoint;
|
||||
/**
|
||||
* @callback TraverseParentsCallback
|
||||
* @param {DOMTarget} $el
|
||||
* @param {Number} i
|
||||
*/
|
||||
/**
|
||||
* @param {TraverseParentsCallback} cb
|
||||
*/
|
||||
traverseUp(cb: ($el: DOMTarget, i: number) => any): void;
|
||||
getMatrix(): DOMMatrix;
|
||||
remove(): void;
|
||||
revert(): void;
|
||||
}
|
||||
import { Timer } from '../timer/timer.js';
|
||||
import type { DraggableParams } from '../types/index.js';
|
||||
import type { EasingParam } from '../types/index.js';
|
||||
import type { TargetsParam } from '../types/index.js';
|
||||
import type { DOMTarget } from '../types/index.js';
|
||||
declare class DOMProxy {
|
||||
/** @param {Object} el */
|
||||
constructor(el: any);
|
||||
el: any;
|
||||
zIndex: number;
|
||||
parentElement: any;
|
||||
classList: {
|
||||
add: () => void;
|
||||
remove: () => void;
|
||||
};
|
||||
set x(v: any);
|
||||
get x(): any;
|
||||
set y(v: any);
|
||||
get y(): any;
|
||||
set width(v: any);
|
||||
get width(): any;
|
||||
set height(v: any);
|
||||
get height(): any;
|
||||
getBoundingClientRect(): {
|
||||
top: any;
|
||||
right: any;
|
||||
bottom: any;
|
||||
left: any;
|
||||
};
|
||||
}
|
||||
export {};
|
||||
+1236
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Anime.js - draggable - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var draggable = require('./draggable.cjs');
|
||||
|
||||
|
||||
|
||||
exports.Draggable = draggable.Draggable;
|
||||
exports.createDraggable = draggable.createDraggable;
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./draggable.js";
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Anime.js - draggable - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
export { Draggable, createDraggable } from './draggable.js';
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Anime.js - easings - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var helpers = require('../../core/helpers.cjs');
|
||||
var none = require('../none.cjs');
|
||||
|
||||
/**
|
||||
* @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 (helpers.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.none :
|
||||
t => t === 0 || t === 1 ? t :
|
||||
calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
|
||||
|
||||
exports.cubicBezier = cubicBezier;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export function cubicBezier(mX1?: number, mY1?: number, mX2?: number, mY2?: number): EasingFunction;
|
||||
import type { EasingFunction } from '../../types/index.js';
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Anime.js - easings - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - 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 };
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Anime.js - easings - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var parser = require('./parser.cjs');
|
||||
|
||||
|
||||
|
||||
exports.eases = parser.eases;
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { eases } from "./parser.js";
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Anime.js - easings - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
export { eases } from './parser.js';
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* Anime.js - easings - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var consts = require('../../core/consts.cjs');
|
||||
var helpers = require('../../core/helpers.cjs');
|
||||
var none = require('../none.cjs');
|
||||
|
||||
/**
|
||||
* @import {
|
||||
* EasingFunction,
|
||||
* EasingFunctionWithParams,
|
||||
* EasingParam,
|
||||
* BackEasing,
|
||||
* ElasticEasing,
|
||||
* PowerEasing,
|
||||
* } from '../../types/index.js'
|
||||
*/
|
||||
|
||||
|
||||
/** @type {PowerEasing} */
|
||||
const easeInPower = (p = 1.68) => t => helpers.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 = helpers.PI / 2;
|
||||
const doublePI = helpers.PI * 2;
|
||||
|
||||
/** @type {Record<String, EasingFunctionWithParams|EasingFunction>} */
|
||||
const easeInFunctions = {
|
||||
[consts.emptyString]: easeInPower,
|
||||
Quad: easeInPower(2),
|
||||
Cubic: easeInPower(3),
|
||||
Quart: easeInPower(4),
|
||||
Quint: easeInPower(5),
|
||||
/** @type {EasingFunction} */
|
||||
Sine: t => 1 - helpers.cos(t * halfPI),
|
||||
/** @type {EasingFunction} */
|
||||
Circ: t => 1 - helpers.sqrt(1 - t * t),
|
||||
/** @type {EasingFunction} */
|
||||
Expo: t => t ? helpers.pow(2, 10 * t - 10) : 0,
|
||||
/** @type {EasingFunction} */
|
||||
Bounce: t => {
|
||||
let pow2, b = 4;
|
||||
while (t < ((pow2 = helpers.pow(2, --b)) - 1) / 11);
|
||||
return 1 / helpers.pow(4, 3 - b) - 7.5625 * helpers.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 = helpers.clamp(+amplitude, 1, 10);
|
||||
const p = helpers.clamp(+period, consts.minValue, 2);
|
||||
const s = (p / doublePI) * helpers.asin(1 / a);
|
||||
const e = doublePI / p;
|
||||
return t => t === 0 || t === 1 ? t : -a * helpers.pow(2, -10 * (1 - t)) * helpers.sin(((1 - t) - s) * e);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {Object} EasesFunctions
|
||||
* @property {EasingFunction} linear
|
||||
* @property {EasingFunction} 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: 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 === consts.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: 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.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.none;
|
||||
}
|
||||
};
|
||||
|
||||
const deprecated = ['steps(', 'irregular(', 'linear(', 'cubicBezier('];
|
||||
|
||||
/**
|
||||
* @param {EasingParam} ease
|
||||
* @return {EasingFunction}
|
||||
*/
|
||||
const parseEase = ease => {
|
||||
if (helpers.isStr(ease)) {
|
||||
for (let i = 0, l = deprecated.length; i < l; i++) {
|
||||
if (helpers.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.none;
|
||||
}
|
||||
}
|
||||
}
|
||||
const easeFunc = helpers.isFnc(ease) ? ease : helpers.isStr(ease) ? parseEaseString(/** @type {String} */(ease)) : none.none;
|
||||
return easeFunc;
|
||||
};
|
||||
|
||||
exports.easeInPower = easeInPower;
|
||||
exports.easeTypes = easeTypes;
|
||||
exports.eases = eases;
|
||||
exports.parseEase = parseEase;
|
||||
exports.parseEaseString = parseEaseString;
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* @import {
|
||||
* EasingFunction,
|
||||
* EasingFunctionWithParams,
|
||||
* EasingParam,
|
||||
* BackEasing,
|
||||
* ElasticEasing,
|
||||
* PowerEasing,
|
||||
* } from '../../types/index.js'
|
||||
*/
|
||||
/** @type {PowerEasing} */
|
||||
export const easeInPower: PowerEasing;
|
||||
/**
|
||||
* @callback EaseType
|
||||
* @param {EasingFunction} Ease
|
||||
* @return {EasingFunction}
|
||||
*/
|
||||
/** @type {Record<String, EaseType>} */
|
||||
export const easeTypes: Record<string, EaseType>;
|
||||
export namespace eases {
|
||||
export let linear: EasingFunction;
|
||||
export let none: EasingFunction;
|
||||
let _in: PowerEasing;
|
||||
export { _in as in };
|
||||
export let out: PowerEasing;
|
||||
export let inOut: PowerEasing;
|
||||
export let outIn: PowerEasing;
|
||||
export let inQuad: EasingFunction;
|
||||
export let outQuad: EasingFunction;
|
||||
export let inOutQuad: EasingFunction;
|
||||
export let outInQuad: EasingFunction;
|
||||
export let inCubic: EasingFunction;
|
||||
export let outCubic: EasingFunction;
|
||||
export let inOutCubic: EasingFunction;
|
||||
export let outInCubic: EasingFunction;
|
||||
export let inQuart: EasingFunction;
|
||||
export let outQuart: EasingFunction;
|
||||
export let inOutQuart: EasingFunction;
|
||||
export let outInQuart: EasingFunction;
|
||||
export let inQuint: EasingFunction;
|
||||
export let outQuint: EasingFunction;
|
||||
export let inOutQuint: EasingFunction;
|
||||
export let outInQuint: EasingFunction;
|
||||
export let inSine: EasingFunction;
|
||||
export let outSine: EasingFunction;
|
||||
export let inOutSine: EasingFunction;
|
||||
export let outInSine: EasingFunction;
|
||||
export let inCirc: EasingFunction;
|
||||
export let outCirc: EasingFunction;
|
||||
export let inOutCirc: EasingFunction;
|
||||
export let outInCirc: EasingFunction;
|
||||
export let inExpo: EasingFunction;
|
||||
export let outExpo: EasingFunction;
|
||||
export let inOutExpo: EasingFunction;
|
||||
export let outInExpo: EasingFunction;
|
||||
export let inBounce: EasingFunction;
|
||||
export let outBounce: EasingFunction;
|
||||
export let inOutBounce: EasingFunction;
|
||||
export let outInBounce: EasingFunction;
|
||||
export let inBack: BackEasing;
|
||||
export let outBack: BackEasing;
|
||||
export let inOutBack: BackEasing;
|
||||
export let outInBack: BackEasing;
|
||||
export let inElastic: ElasticEasing;
|
||||
export let outElastic: ElasticEasing;
|
||||
export let inOutElastic: ElasticEasing;
|
||||
export let outInElastic: ElasticEasing;
|
||||
}
|
||||
export function parseEaseString(string: string): EasingFunction;
|
||||
export function parseEase(ease: EasingParam): EasingFunction;
|
||||
export type EaseType = (Ease: EasingFunction) => EasingFunction;
|
||||
export type EasesFunctions = {
|
||||
linear: EasingFunction;
|
||||
none: EasingFunction;
|
||||
in: PowerEasing;
|
||||
out: PowerEasing;
|
||||
inOut: PowerEasing;
|
||||
outIn: PowerEasing;
|
||||
inQuad: EasingFunction;
|
||||
outQuad: EasingFunction;
|
||||
inOutQuad: EasingFunction;
|
||||
outInQuad: EasingFunction;
|
||||
inCubic: EasingFunction;
|
||||
outCubic: EasingFunction;
|
||||
inOutCubic: EasingFunction;
|
||||
outInCubic: EasingFunction;
|
||||
inQuart: EasingFunction;
|
||||
outQuart: EasingFunction;
|
||||
inOutQuart: EasingFunction;
|
||||
outInQuart: EasingFunction;
|
||||
inQuint: EasingFunction;
|
||||
outQuint: EasingFunction;
|
||||
inOutQuint: EasingFunction;
|
||||
outInQuint: EasingFunction;
|
||||
inSine: EasingFunction;
|
||||
outSine: EasingFunction;
|
||||
inOutSine: EasingFunction;
|
||||
outInSine: EasingFunction;
|
||||
inCirc: EasingFunction;
|
||||
outCirc: EasingFunction;
|
||||
inOutCirc: EasingFunction;
|
||||
outInCirc: EasingFunction;
|
||||
inExpo: EasingFunction;
|
||||
outExpo: EasingFunction;
|
||||
inOutExpo: EasingFunction;
|
||||
outInExpo: EasingFunction;
|
||||
inBounce: EasingFunction;
|
||||
outBounce: EasingFunction;
|
||||
inOutBounce: EasingFunction;
|
||||
outInBounce: EasingFunction;
|
||||
inBack: BackEasing;
|
||||
outBack: BackEasing;
|
||||
inOutBack: BackEasing;
|
||||
outInBack: BackEasing;
|
||||
inElastic: ElasticEasing;
|
||||
outElastic: ElasticEasing;
|
||||
inOutElastic: ElasticEasing;
|
||||
outInElastic: ElasticEasing;
|
||||
};
|
||||
import type { PowerEasing } from '../../types/index.js';
|
||||
import type { EasingFunction } from '../../types/index.js';
|
||||
import type { BackEasing } from '../../types/index.js';
|
||||
import type { ElasticEasing } from '../../types/index.js';
|
||||
import type { EasingParam } from '../../types/index.js';
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Anime.js - easings - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - 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 {EasingFunction} linear
|
||||
* @property {EasingFunction} 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 };
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Anime.js - easings - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var index = require('./cubic-bezier/index.cjs');
|
||||
var index$1 = require('./steps/index.cjs');
|
||||
var index$2 = require('./linear/index.cjs');
|
||||
var index$3 = require('./irregular/index.cjs');
|
||||
var index$4 = require('./spring/index.cjs');
|
||||
var parser = require('./eases/parser.cjs');
|
||||
|
||||
|
||||
|
||||
exports.cubicBezier = index.cubicBezier;
|
||||
exports.steps = index$1.steps;
|
||||
exports.linear = index$2.linear;
|
||||
exports.irregular = index$3.irregular;
|
||||
exports.Spring = index$4.Spring;
|
||||
exports.createSpring = index$4.createSpring;
|
||||
exports.spring = index$4.spring;
|
||||
exports.eases = parser.eases;
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from "./cubic-bezier/index.js";
|
||||
export * from "./steps/index.js";
|
||||
export * from "./linear/index.js";
|
||||
export * from "./irregular/index.js";
|
||||
export * from "./spring/index.js";
|
||||
export * from "./eases/index.js";
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Anime.js - easings - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - 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';
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Anime.js - easings - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var helpers = require('../../core/helpers.cjs');
|
||||
var index = require('../linear/index.cjs');
|
||||
|
||||
/**
|
||||
* @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(helpers.clamp(randomValue, previousValue, 1));
|
||||
}
|
||||
values.push(1);
|
||||
return index.linear(...values);
|
||||
};
|
||||
|
||||
exports.irregular = irregular;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export function irregular(length?: number, randomness?: number): EasingFunction;
|
||||
import type { EasingFunction } from '../../types/index.js';
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Anime.js - easings - ESM
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - 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 };
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Anime.js - easings - CJS
|
||||
* @version v4.5.0
|
||||
* @license MIT
|
||||
* @copyright 2026 - Julian Garnier
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var helpers = require('../../core/helpers.cjs');
|
||||
var none = require('../none.cjs');
|
||||
|
||||
/**
|
||||
* @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.none;
|
||||
const totalPoints = argsLength - 1;
|
||||
const firstArg = args[0];
|
||||
const lastArg = args[totalPoints];
|
||||
const xPoints = [0];
|
||||
const yPoints = [helpers.parseNumber(firstArg)];
|
||||
for (let i = 1; i < totalPoints; i++) {
|
||||
const arg = args[i];
|
||||
const splitValue = helpers.isStr(arg) ?
|
||||
/** @type {String} */(arg).trim().split(' ') :
|
||||
[arg];
|
||||
const value = splitValue[0];
|
||||
const percent = splitValue[1];
|
||||
xPoints.push(!helpers.isUnd(percent) ? helpers.parseNumber(percent) / 100 : i / totalPoints);
|
||||
yPoints.push(helpers.parseNumber(value));
|
||||
}
|
||||
yPoints.push(helpers.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];
|
||||
}
|
||||
};
|
||||
|
||||
exports.linear = linear;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user