| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global.animal = factory());
- }(this, (function () {
- 'use strict';
- // --- Utils ---
- const isArr = (a) => Array.isArray(a);
- const isStr = (s) => typeof s === 'string';
- const isFunc = (f) => typeof f === 'function';
- const isNil = (v) => v === undefined || v === null;
- const isSVG = (el) => (typeof SVGElement !== 'undefined') && (el instanceof SVGElement);
- const isEl = (v) => (typeof Element !== 'undefined') && (v instanceof Element);
- const clamp01 = (n) => Math.max(0, Math.min(1, n));
- const toKebab = (s) => s.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
-
- const toArray = (targets) => {
- if (isArr(targets)) return targets;
- if (isStr(targets)) {
- if (typeof document === 'undefined') return [];
- return Array.from(document.querySelectorAll(targets));
- }
- if ((typeof NodeList !== 'undefined') && (targets instanceof NodeList)) return Array.from(targets);
- if ((typeof Element !== 'undefined') && (targets instanceof Element)) return [targets];
- if ((typeof Window !== 'undefined') && (targets instanceof Window)) return [targets];
- // Plain objects (for anime.js-style object tweening)
- if (!isNil(targets) && (typeof targets === 'object' || isFunc(targets))) return [targets];
- return [];
- };
- // Selection helper (chainable, still Array-compatible)
- const _layerHandlerByEl = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
- class Selection extends Array {
- animate(params) { return animate(this, params); }
- draw(params = {}) { return svgDraw(this, params); }
- inViewAnimate(params, options = {}) { return inViewAnimate(this, params, options); }
- // Layer.js plugin-style helper:
- // const $ = animal.$;
- // $('.btn').layer({ title: 'Hi' });
- // Clicking the element will open Layer.
- layer(options) {
- const LayerCtor =
- (typeof window !== 'undefined' && window.Layer) ? window.Layer :
- (typeof globalThis !== 'undefined' && globalThis.Layer) ? globalThis.Layer :
- (typeof Layer !== 'undefined' ? Layer : null);
- if (!LayerCtor) return this;
-
- this.forEach((el) => {
- if (!isEl(el)) return;
- // De-dupe / replace previous binding
- if (_layerHandlerByEl) {
- const prev = _layerHandlerByEl.get(el);
- if (prev) el.removeEventListener('click', prev);
- }
-
- const handler = () => {
- let opts = options;
- if (isFunc(options)) {
- opts = options(el);
- } else if (isNil(options)) {
- opts = null;
- }
- // If no explicit options, allow data-* configuration
- if (!opts || (typeof opts === 'object' && Object.keys(opts).length === 0)) {
- const d = el.dataset || {};
- opts = {
- title: d.layerTitle || el.getAttribute('data-layer-title') || (el.textContent || '').trim(),
- text: d.layerText || el.getAttribute('data-layer-text') || '',
- icon: d.layerIcon || el.getAttribute('data-layer-icon') || null,
- showCancelButton: (d.layerCancel === 'true') || (el.getAttribute('data-layer-cancel') === 'true')
- };
- }
-
- // Prefer builder API if present, fallback to static fire.
- if (LayerCtor.$ && isFunc(LayerCtor.$)) return LayerCtor.$(opts).fire();
- if (LayerCtor.fire && isFunc(LayerCtor.fire)) return LayerCtor.fire(opts);
- };
-
- if (_layerHandlerByEl) _layerHandlerByEl.set(el, handler);
- el.addEventListener('click', handler);
- });
-
- return this;
- }
-
- // Remove click bindings added by `.layer()`
- unlayer() {
- this.forEach((el) => {
- if (!isEl(el)) return;
- if (!_layerHandlerByEl) return;
- const prev = _layerHandlerByEl.get(el);
- if (prev) el.removeEventListener('click', prev);
- _layerHandlerByEl.delete(el);
- });
- return this;
- }
- }
-
- const $ = (targets) => Selection.from(toArray(targets));
- const UNITLESS_KEYS = ['opacity', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'zIndex', 'fontWeight', 'strokeDashoffset', 'strokeDasharray', 'strokeWidth'];
- const getUnit = (val, prop) => {
- if (UNITLESS_KEYS.includes(prop)) return '';
- const split = /[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(val);
- return split ? split[1] : undefined;
- };
-
- const isCssVar = (k) => isStr(k) && k.startsWith('--');
- // Keep this intentionally broad so "unknown" config keys don't accidentally become animated props.
- // Prefer putting non-anim-prop config under `params.options`.
- const isAnimOptionKey = (k) => [
- 'options',
- 'duration', 'delay', 'easing', 'direction', 'fill', 'loop', 'endDelay', 'autoplay',
- 'update', 'begin', 'complete',
- // WAAPI-ish common keys (ignored unless we explicitly support them)
- 'iterations', 'iterationStart', 'iterationComposite', 'composite', 'playbackRate',
- // Spring helpers
- 'springFrames'
- ].includes(k);
-
- const isEasingFn = (e) => typeof e === 'function';
-
- // Minimal cubic-bezier implementation (for JS engine easing)
- function cubicBezier(x1, y1, x2, y2) {
- // Inspired by https://github.com/gre/bezier-easing (simplified)
- const NEWTON_ITERATIONS = 4;
- const NEWTON_MIN_SLOPE = 0.001;
- const SUBDIVISION_PRECISION = 0.0000001;
- const SUBDIVISION_MAX_ITERATIONS = 10;
-
- const kSplineTableSize = 11;
- const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
-
- const float32ArraySupported = typeof Float32Array === 'function';
-
- function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
- function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
- function C(aA1) { return 3.0 * aA1; }
-
- function calcBezier(aT, aA1, aA2) {
- return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
- }
-
- function getSlope(aT, aA1, aA2) {
- return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
- }
-
- function binarySubdivide(aX, aA, aB) {
- let currentX, currentT, i = 0;
- do {
- currentT = aA + (aB - aA) / 2.0;
- currentX = calcBezier(currentT, x1, x2) - aX;
- if (currentX > 0.0) aB = currentT;
- else aA = currentT;
- } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
- return currentT;
- }
-
- function newtonRaphsonIterate(aX, aGuessT) {
- for (let i = 0; i < NEWTON_ITERATIONS; ++i) {
- const currentSlope = getSlope(aGuessT, x1, x2);
- if (currentSlope === 0.0) return aGuessT;
- const currentX = calcBezier(aGuessT, x1, x2) - aX;
- aGuessT -= currentX / currentSlope;
- }
- return aGuessT;
- }
-
- const sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
- for (let i = 0; i < kSplineTableSize; ++i) {
- sampleValues[i] = calcBezier(i * kSampleStepSize, x1, x2);
- }
-
- function getTForX(aX) {
- let intervalStart = 0.0;
- let currentSample = 1;
- const lastSample = kSplineTableSize - 1;
-
- for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
- intervalStart += kSampleStepSize;
- }
- --currentSample;
-
- const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
- const guessForT = intervalStart + dist * kSampleStepSize;
-
- const initialSlope = getSlope(guessForT, x1, x2);
- if (initialSlope >= NEWTON_MIN_SLOPE) return newtonRaphsonIterate(aX, guessForT);
- if (initialSlope === 0.0) return guessForT;
- return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
- }
-
- return (x) => {
- if (x === 0 || x === 1) return x;
- return calcBezier(getTForX(x), y1, y2);
- };
- }
-
- function resolveJsEasing(easing, springValues) {
- if (isEasingFn(easing)) return easing;
- if (typeof easing === 'object' && easing && !Array.isArray(easing)) {
- // Spring: map linear progress -> simulated spring curve (0..1)
- const values = springValues || getSpringValues(easing);
- const last = Math.max(0, values.length - 1);
- return (t) => {
- const p = clamp01(t);
- const idx = p * last;
- const i0 = Math.floor(idx);
- const i1 = Math.min(last, i0 + 1);
- const frac = idx - i0;
- const v0 = values[i0] ?? p;
- const v1 = values[i1] ?? p;
- return v0 + (v1 - v0) * frac;
- };
- }
- if (Array.isArray(easing) && easing.length === 4) {
- return cubicBezier(easing[0], easing[1], easing[2], easing[3]);
- }
- // Common named easings
- switch (easing) {
- case 'linear': return (t) => t;
- case 'ease': return cubicBezier(0.25, 0.1, 0.25, 1);
- case 'ease-in': return cubicBezier(0.42, 0, 1, 1);
- case 'ease-out': return cubicBezier(0, 0, 0.58, 1);
- case 'ease-in-out': return cubicBezier(0.42, 0, 0.58, 1);
- default: return (t) => t;
- }
- }
- // --- Spring Physics (Simplified) ---
- // Returns an array of [time, value] or just value for WAAPI linear easing
- function spring({ stiffness = 100, damping = 10, mass = 1, velocity = 0, precision = 0.01 } = {}) {
- const values = [];
- let t = 0;
- const timeStep = 1 / 60; // 60fps simulation
- let current = 0;
- let v = velocity;
- const target = 1;
- let running = true;
- while (running && t < 10) { // Safety break at 10s
- const fSpring = -stiffness * (current - target);
- const fDamper = -damping * v;
- const a = (fSpring + fDamper) / mass;
-
- v += a * timeStep;
- current += v * timeStep;
-
- values.push(current);
- t += timeStep;
- if (Math.abs(current - target) < precision && Math.abs(v) < precision) {
- running = false;
- }
- }
- if (values[values.length - 1] !== 1) values.push(1);
-
- return values;
- }
-
- // Cache spring curves by config (perf: avoid recomputing for many targets)
- // LRU-ish capped cache to avoid unbounded growth in long-lived apps.
- const SPRING_CACHE_MAX = 50;
- const springCache = new Map();
- function springCacheGet(key) {
- const v = springCache.get(key);
- if (!v) return v;
- // refresh LRU
- springCache.delete(key);
- springCache.set(key, v);
- return v;
- }
- function springCacheSet(key, values) {
- if (springCache.has(key)) springCache.delete(key);
- springCache.set(key, values);
- if (springCache.size > SPRING_CACHE_MAX) {
- const firstKey = springCache.keys().next().value;
- if (firstKey !== undefined) springCache.delete(firstKey);
- }
- }
- function getSpringValues(config = {}) {
- const {
- stiffness = 100,
- damping = 10,
- mass = 1,
- velocity = 0,
- precision = 0.01
- } = config || {};
- const key = `${stiffness}|${damping}|${mass}|${velocity}|${precision}`;
- const cached = springCacheGet(key);
- if (cached) return cached;
- const values = spring({ stiffness, damping, mass, velocity, precision });
- springCacheSet(key, values);
- return values;
- }
-
- function downsample(values, maxFrames = 120) {
- if (!values || values.length <= maxFrames) return values || [];
- const out = [];
- const lastIndex = values.length - 1;
- const step = lastIndex / (maxFrames - 1);
- for (let i = 0; i < maxFrames; i++) {
- const idx = i * step;
- const i0 = Math.floor(idx);
- const i1 = Math.min(lastIndex, i0 + 1);
- const frac = idx - i0;
- const v0 = values[i0];
- const v1 = values[i1];
- out.push(v0 + (v1 - v0) * frac);
- }
- if (out[out.length - 1] !== 1) out[out.length - 1] = 1;
- return out;
- }
- // --- WAAPI Core ---
- const TRANSFORMS = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective', 'x', 'y'];
-
- const ALIASES = {
- x: 'translateX',
- y: 'translateY',
- z: 'translateZ'
- };
- // Basic rAF loop for non-WAAPI props or fallback
- class RafEngine {
- constructor() {
- this.animations = [];
- this.tick = this.tick.bind(this);
- this.running = false;
- }
- add(anim) {
- this.animations.push(anim);
- if (!this.running) {
- this.running = true;
- requestAnimationFrame(this.tick);
- }
- }
- remove(anim) {
- this.animations = this.animations.filter(a => a !== anim);
- }
- tick(t) {
- const now = t;
- this.animations = this.animations.filter(anim => {
- return anim.tick(now); // return true to keep
- });
- if (this.animations.length) {
- requestAnimationFrame(this.tick);
- } else {
- this.running = false;
- }
- }
- }
- const rafEngine = new RafEngine();
-
- // --- WAAPI update sampler (only used when update callback is provided) ---
- class WaapiUpdateSampler {
- constructor() {
- this.items = new Set();
- this._running = false;
- this._tick = this._tick.bind(this);
- }
- add(item) {
- this.items.add(item);
- if (!this._running) {
- this._running = true;
- requestAnimationFrame(this._tick);
- }
- }
- remove(item) {
- this.items.delete(item);
- }
- _tick(t) {
- if (!this.items.size) {
- this._running = false;
- return;
- }
- let anyActive = false;
- let anyChanged = false;
- this.items.forEach((item) => {
- const { anim, target, update } = item;
- if (!anim || !anim.effect) return;
- let dur = item._dur || 0;
- if (!dur) {
- const timing = readWaapiEffectTiming(anim.effect);
- dur = timing.duration || 0;
- item._dur = dur;
- }
- if (!dur) return;
- const p = clamp01((anim.currentTime || 0) / dur);
- if (anim.playState === 'running') anyActive = true;
- if (item._lastP !== p) {
- anyChanged = true;
- item._lastP = p;
- update({ target, progress: p, time: t });
- }
- if (anim.playState === 'finished' || anim.playState === 'idle') {
- this.items.delete(item);
- }
- });
- if (this.items.size && (anyActive || anyChanged)) {
- requestAnimationFrame(this._tick);
- } else {
- this._running = false;
- }
- }
- }
- const waapiUpdateSampler = new WaapiUpdateSampler();
-
- function readWaapiEffectTiming(effect) {
- // We compute this once per animation and cache it to avoid per-frame getComputedTiming().
- // We primarily cache `duration` to preserve existing behavior (progress maps to one iteration).
- let duration = 0;
- let endTime = 0;
- if (!effect) return { duration, endTime };
- try {
- const ct = effect.getComputedTiming ? effect.getComputedTiming() : null;
- if (ct) {
- if (typeof ct.duration === 'number' && Number.isFinite(ct.duration)) duration = ct.duration;
- if (typeof ct.endTime === 'number' && Number.isFinite(ct.endTime)) endTime = ct.endTime;
- }
- } catch (e) {
- // ignore
- }
- if (!endTime) endTime = duration || 0;
- return { duration, endTime };
- }
-
- function getDefaultUnit(prop) {
- if (!prop) return '';
- if (UNITLESS_KEYS.includes(prop)) return '';
- if (prop.startsWith('scale')) return '';
- if (prop === 'opacity') return '';
- if (prop.startsWith('rotate') || prop.startsWith('skew')) return 'deg';
- return 'px';
- }
-
- function normalizeTransformPartValue(prop, v) {
- if (typeof v !== 'number') return v;
- if (prop && prop.startsWith('scale')) return '' + v;
- if (prop && (prop.startsWith('rotate') || prop.startsWith('skew'))) return v + 'deg';
- return v + 'px';
- }
-
- // --- JS Interpolator (anime.js-ish, simplified) ---
- class JsAnimation {
- constructor(target, propValues, opts = {}, callbacks = {}) {
- this.target = target;
- this.propValues = propValues;
- this.duration = opts.duration ?? 1000;
- this.delay = opts.delay ?? 0;
- this.direction = opts.direction ?? 'normal';
- this.loop = opts.loop ?? 1;
- this.endDelay = opts.endDelay ?? 0;
- this.easing = opts.easing ?? 'linear';
- this.autoplay = opts.autoplay !== false;
-
- this.update = callbacks.update;
- this.begin = callbacks.begin;
- this.complete = callbacks.complete;
-
- this._resolve = null;
- this.finished = new Promise((res) => (this._resolve = res));
-
- this._started = false;
- this._running = false;
- this._paused = false;
- this._cancelled = false;
- this._startTime = 0;
- this._progress = 0;
- this._didBegin = false;
-
- this._ease = resolveJsEasing(this.easing, opts.springValues);
-
- this._tween = this._buildTween();
- this.tick = this.tick.bind(this);
-
- if (this.autoplay) this.play();
- }
-
- _readCurrentValue(k) {
- const t = this.target;
- // JS object
- if (!isEl(t) && !isSVG(t)) return t[k];
-
- // scroll
- if (k === 'scrollTop' || k === 'scrollLeft') return t[k];
-
- // CSS var
- if (isEl(t) && isCssVar(k)) {
- const cs = getComputedStyle(t);
- return (cs.getPropertyValue(k) || t.style.getPropertyValue(k) || '').trim();
- }
-
- // style
- if (isEl(t)) {
- const cs = getComputedStyle(t);
- // Prefer computed style (kebab) because many props aren't direct keys on cs
- const v = cs.getPropertyValue(toKebab(k));
- if (v && v.trim()) return v.trim();
- // Fallback to inline style access
- if (k in t.style) return t.style[k];
- }
-
- // SVG attribute
- if (isSVG(t)) {
- const attr = toKebab(k);
- if (t.hasAttribute(attr)) return t.getAttribute(attr);
- if (t.hasAttribute(k)) return t.getAttribute(k);
- }
-
- // Generic property
- return t[k];
- }
-
- _writeValue(k, v) {
- const t = this.target;
- // JS object
- if (!isEl(t) && !isSVG(t)) {
- t[k] = v;
- return;
- }
-
- // scroll
- if (k === 'scrollTop' || k === 'scrollLeft') {
- t[k] = v;
- return;
- }
-
- // CSS var
- if (isEl(t) && isCssVar(k)) {
- t.style.setProperty(k, v);
- return;
- }
-
- // style
- if (isEl(t) && (k in t.style)) {
- t.style[k] = v;
- return;
- }
-
- // SVG attribute
- if (isSVG(t)) {
- const attr = toKebab(k);
- t.setAttribute(attr, v);
- return;
- }
-
- // Generic property
- t[k] = v;
- }
-
- _buildTween() {
- const tween = {};
- Object.keys(this.propValues).forEach((k) => {
- const raw = this.propValues[k];
- const fromRaw = isArr(raw) ? raw[0] : this._readCurrentValue(k);
- const toRaw = isArr(raw) ? raw[1] : raw;
-
- const fromStr = isNil(fromRaw) ? '0' : ('' + fromRaw).trim();
- const toStr = isNil(toRaw) ? '0' : ('' + toRaw).trim();
-
- const fromNum = parseFloat(fromStr);
- const toNum = parseFloat(toStr);
- const fromNumOk = !Number.isNaN(fromNum);
- const toNumOk = !Number.isNaN(toNum);
-
- // numeric tween (with unit preservation)
- if (fromNumOk && toNumOk) {
- const unit = getUnit(toStr, k) ?? getUnit(fromStr, k) ?? '';
- tween[k] = { type: 'number', from: fromNum, to: toNum, unit };
- } else {
- // Non-numeric: fall back to "switch" (still useful for seek endpoints)
- tween[k] = { type: 'discrete', from: fromStr, to: toStr };
- }
- });
- return tween;
- }
-
- _apply(progress, time) {
- this._progress = clamp01(progress);
- Object.keys(this._tween).forEach((k) => {
- const t = this._tween[k];
- if (t.type === 'number') {
- const eased = this._ease ? this._ease(this._progress) : this._progress;
- const val = t.from + (t.to - t.from) * eased;
- if (!isEl(this.target) && !isSVG(this.target) && t.unit === '') {
- this._writeValue(k, val);
- } else {
- this._writeValue(k, (val + t.unit));
- }
- } else {
- const val = this._progress >= 1 ? t.to : t.from;
- this._writeValue(k, val);
- }
- });
-
- if (this.update) this.update({ target: this.target, progress: this._progress, time });
- }
-
- seek(progress) {
- // Seek does not auto-play; it's intended for scroll-linked or manual control.
- const t = (typeof performance !== 'undefined' ? performance.now() : 0);
- this._apply(progress, t);
- }
-
- play() {
- if (this._cancelled) return;
- if (!this._started) {
- this._started = true;
- this._startTime = performance.now() + this.delay - (this._progress * this.duration);
- // begin fired on first active tick to avoid firing during delay.
- }
- this._paused = false;
- if (!this._running) {
- this._running = true;
- rafEngine.add(this);
- }
- }
-
- pause() {
- this._paused = true;
- }
-
- cancel() {
- this._cancelled = true;
- this._running = false;
- rafEngine.remove(this);
- // Resolve to avoid hanging awaits
- if (this._resolve) this._resolve();
- }
-
- finish() {
- this.seek(1);
- this._running = false;
- rafEngine.remove(this);
- if (this.complete) this.complete(this.target);
- if (this._resolve) this._resolve();
- }
-
- tick(now) {
- if (this._cancelled) return false;
- if (this._paused) return true;
-
- if (!this._started) {
- this._started = true;
- this._startTime = now + this.delay;
- }
-
- if (now < this._startTime) return true;
- if (!this._didBegin) {
- this._didBegin = true;
- if (this.begin) this.begin(this.target);
- }
-
- const totalDur = this.duration + (this.endDelay || 0);
- const elapsed = now - this._startTime;
- const iter = totalDur > 0 ? Math.floor(elapsed / totalDur) : 0;
- const inIter = totalDur > 0 ? (elapsed - iter * totalDur) : elapsed;
-
- const iterations = this.loop === true ? Infinity : this.loop;
- if (iterations !== Infinity && iter >= iterations) {
- this._apply(this._mapDirection(1, iterations - 1));
- this._running = false;
- if (this.complete) this.complete(this.target);
- if (this._resolve) this._resolve();
- return false;
- }
-
- // if we're in endDelay portion, hold the end state
- let p = clamp01(inIter / this.duration);
- if (this.duration <= 0) p = 1;
- if (this.endDelay && inIter > this.duration) p = 1;
-
- this._apply(this._mapDirection(p, iter), now);
-
- // Keep running until loops exhausted
- return true;
- }
-
- _mapDirection(p, iterIndex) {
- const dir = this.direction;
- const flip = (dir === 'reverse') || (dir === 'alternate-reverse');
- const isAlt = (dir === 'alternate') || (dir === 'alternate-reverse');
- let t = flip ? (1 - p) : p;
- if (isAlt && (iterIndex % 2 === 1)) t = 1 - t;
- return t;
- }
- }
-
- // --- Controls (Motion One-ish, chainable / thenable) ---
- class Controls {
- constructor({ waapi = [], js = [], finished }) {
- this.animations = waapi; // backward compat with old `.animations` usage
- this.jsAnimations = js;
- this.finished = finished || Promise.resolve();
- }
- then(onFulfilled, onRejected) { return this.finished.then(onFulfilled, onRejected); }
- catch(onRejected) { return this.finished.catch(onRejected); }
- finally(onFinally) { return this.finished.finally(onFinally); }
-
- play() {
- if (this._onPlay) this._onPlay.forEach((fn) => fn && fn());
- if (this._ensureWaapiUpdate) this._ensureWaapiUpdate();
- this.animations.forEach((a) => a && a.play && a.play());
- this.jsAnimations.forEach((a) => a && a.play && a.play());
- return this;
- }
- pause() {
- this.animations.forEach((a) => a && a.pause && a.pause());
- this.jsAnimations.forEach((a) => a && a.pause && a.pause());
- return this;
- }
- cancel() {
- this.animations.forEach((a) => a && a.cancel && a.cancel());
- this.jsAnimations.forEach((a) => a && a.cancel && a.cancel());
- return this;
- }
- finish() {
- this.animations.forEach((a) => a && a.finish && a.finish());
- this.jsAnimations.forEach((a) => a && a.finish && a.finish());
- return this;
- }
- seek(progress) {
- const p = clamp01(progress);
- const t = (typeof performance !== 'undefined' ? performance.now() : 0);
- this.animations.forEach((anim) => {
- if (anim && anim.effect) {
- let timing = this._waapiTimingByAnim && this._waapiTimingByAnim.get(anim);
- if (!timing) {
- timing = readWaapiEffectTiming(anim.effect);
- if (this._waapiTimingByAnim) this._waapiTimingByAnim.set(anim, timing);
- }
- const dur = timing.duration || 0;
- if (!dur) return;
- anim.currentTime = dur * p;
- const target = this._waapiTargetByAnim && this._waapiTargetByAnim.get(anim);
- if (this._fireUpdate && target) this._fireUpdate({ target, progress: p, time: t });
- }
- });
- this.jsAnimations.forEach((a) => a && a.seek && a.seek(p));
- return this;
- }
- }
- // --- Main Animation Logic ---
- function animate(targets, params) {
- const elements = toArray(targets);
- const safeParams = params || {};
- const optionsNamespace = (safeParams.options && typeof safeParams.options === 'object') ? safeParams.options : {};
- // `params.options` provides a safe namespace for config keys without risking them being treated as animated props.
- // Top-level keys still win for backward compatibility.
- const merged = { ...optionsNamespace, ...safeParams };
- const {
- duration = 1000,
- delay = 0,
- easing = 'ease-out',
- direction = 'normal',
- fill = 'forwards',
- loop = 1,
- endDelay = 0,
- autoplay = true,
- springFrames = 120,
- update, // callback
- begin, // callback
- complete // callback
- } = merged;
- let isSpring = false;
- let springValuesRaw = null;
- let springValuesSampled = null;
- let springDurationMs = null;
- if (typeof easing === 'object' && !Array.isArray(easing)) {
- isSpring = true;
- springValuesRaw = getSpringValues(easing);
- const frames = (typeof springFrames === 'number' && springFrames > 1) ? Math.floor(springFrames) : 120;
- springValuesSampled = downsample(springValuesRaw, frames);
- springDurationMs = springValuesRaw.length * 1000 / 60;
- }
-
- // Callback aggregation (avoid double-calling when WAAPI+JS both run)
- const cbState = typeof WeakMap !== 'undefined' ? new WeakMap() : null;
- const getState = (t) => {
- if (!cbState) return { begun: false, completed: false, lastUpdateBucket: -1 };
- let s = cbState.get(t);
- if (!s) {
- s = { begun: false, completed: false, lastUpdateBucket: -1 };
- cbState.set(t, s);
- }
- return s;
- };
- const fireBegin = (t) => {
- if (!begin) return;
- const s = getState(t);
- if (s.begun) return;
- s.begun = true;
- begin(t);
- };
- const fireComplete = (t) => {
- if (!complete) return;
- const s = getState(t);
- if (s.completed) return;
- s.completed = true;
- complete(t);
- };
- const fireUpdate = (payload) => {
- if (!update) return;
- const t = payload && payload.target;
- const time = payload && payload.time;
- if (!t) return update(payload);
- const s = getState(t);
- const bucket = Math.floor(((typeof time === 'number' ? time : (typeof performance !== 'undefined' ? performance.now() : 0))) / 16);
- if (bucket === s.lastUpdateBucket) return;
- s.lastUpdateBucket = bucket;
- update(payload);
- };
- const propEntries = [];
- Object.keys(safeParams).forEach((key) => {
- if (key === 'options') return;
- if (isAnimOptionKey(key)) return;
- propEntries.push({ key, canonical: ALIASES[key] || key, val: safeParams[key] });
- });
- // Create animations but don't play if autoplay is false
- const waapiAnimations = [];
- const jsAnimations = [];
- const engineInfo = {
- isSpring,
- waapiKeys: [],
- jsKeys: []
- };
- const waapiKeySet = new Set();
- const jsKeySet = new Set();
-
- const onPlayHooks = [];
- const waapiUpdateItems = [];
- const waapiTargetByAnim = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
- const waapiTimingByAnim = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
- let waapiUpdateStarted = false;
- const ensureWaapiUpdate = () => {
- if (waapiUpdateStarted) return;
- waapiUpdateStarted = true;
- waapiUpdateItems.forEach((item) => waapiUpdateSampler.add(item));
- };
- const promises = elements.map((el) => {
- // Route props per target (fix mixed HTML/SVG/object target arrays).
- const waapiProps = {};
- const jsProps = {};
- propEntries.forEach(({ key, canonical, val }) => {
- const isTransform = TRANSFORMS.includes(canonical) || TRANSFORMS.includes(key);
- if (!el || (!isEl(el) && !isSVG(el))) {
- jsProps[key] = val;
- jsKeySet.add(key);
- return;
- }
- const isSvgTarget = isSVG(el);
- if (isSvgTarget) {
- if (isTransform || key === 'opacity' || key === 'filter') {
- waapiProps[canonical] = val;
- waapiKeySet.add(canonical);
- } else {
- jsProps[key] = val;
- jsKeySet.add(key);
- }
- return;
- }
- // HTML element
- if (isCssVar(key)) {
- jsProps[key] = val;
- jsKeySet.add(key);
- return;
- }
- const isCssLike = isTransform || key === 'opacity' || key === 'filter' || (isEl(el) && (key in el.style));
- if (isCssLike) {
- waapiProps[canonical] = val;
- waapiKeySet.add(canonical);
- } else {
- jsProps[key] = val;
- jsKeySet.add(key);
- }
- });
- // 1. WAAPI Animation
- let waapiAnim = null;
- let waapiPromise = Promise.resolve();
-
- if (Object.keys(waapiProps).length > 0) {
- const buildFrames = (propValues) => {
- // Spring: share sampled progress; per-target we only compute start/end once per prop.
- if (isSpring && springValuesSampled && springValuesSampled.length) {
- const cs = (isEl(el) && typeof getComputedStyle !== 'undefined') ? getComputedStyle(el) : null;
- const metas = Object.keys(propValues).map((k) => {
- const raw = propValues[k];
- const rawFrom = Array.isArray(raw) ? raw[0] : undefined;
- const rawTo = Array.isArray(raw) ? raw[1] : raw;
- const toNum = parseFloat(('' + rawTo).trim());
- const fromNumExplicit = Array.isArray(raw) ? parseFloat(('' + rawFrom).trim()) : NaN;
- const isT = TRANSFORMS.includes(ALIASES[k] || k) || TRANSFORMS.includes(k);
- const unit = getUnit(('' + rawTo), k) ?? getUnit(('' + rawFrom), k) ?? getDefaultUnit(k);
-
- let fromNum = 0;
- if (Number.isFinite(fromNumExplicit)) {
- fromNum = fromNumExplicit;
- } else if (k.startsWith('scale')) {
- fromNum = 1;
- } else if (k === 'opacity' && cs) {
- const n = parseFloat(cs.opacity);
- if (!Number.isNaN(n)) fromNum = n;
- } else if (!isT && cs) {
- const cssVal = cs.getPropertyValue(toKebab(k));
- const n = parseFloat(cssVal);
- if (!Number.isNaN(n)) fromNum = n;
- }
-
- const to = Number.isFinite(toNum) ? toNum : 0;
- return { k, isT, unit: unit ?? '', from: fromNum, to };
- });
-
- const frames = new Array(springValuesSampled.length);
- for (let i = 0; i < springValuesSampled.length; i++) {
- const v = springValuesSampled[i];
- const frame = {};
- let transformStr = '';
- for (let j = 0; j < metas.length; j++) {
- const m = metas[j];
- const current = m.from + (m.to - m.from) * v;
- const outVal = (m.unit === '' ? ('' + current) : (current + m.unit));
- if (m.isT) transformStr += `${m.k}(${outVal}) `;
- else frame[m.k] = outVal;
- }
- if (transformStr) frame.transform = transformStr.trim();
- frames[i] = frame;
- }
- if (frames[0] && Object.keys(frames[0]).length === 0) frames.shift();
- return frames;
- }
-
- // Non-spring: 2-keyframe path
- const frame0 = {};
- const frame1 = {};
- let transform0 = '';
- let transform1 = '';
- Object.keys(propValues).forEach((k) => {
- const val = propValues[k];
- const isT = TRANSFORMS.includes(ALIASES[k] || k) || TRANSFORMS.includes(k);
- if (Array.isArray(val)) {
- const from = isT ? normalizeTransformPartValue(k, val[0]) : val[0];
- const to = isT ? normalizeTransformPartValue(k, val[1]) : val[1];
- if (isT) {
- transform0 += `${k}(${from}) `;
- transform1 += `${k}(${to}) `;
- } else {
- frame0[k] = from;
- frame1[k] = to;
- }
- } else {
- if (isT) transform1 += `${k}(${normalizeTransformPartValue(k, val)}) `;
- else frame1[k] = val;
- }
- });
- if (transform0) frame0.transform = transform0.trim();
- if (transform1) frame1.transform = transform1.trim();
- const out = [frame0, frame1];
- if (Object.keys(out[0]).length === 0) out.shift();
- return out;
- };
- const finalFrames = buildFrames(waapiProps);
- const opts = {
- duration: isSpring ? springDurationMs : duration,
- delay,
- fill,
- iterations: loop,
- easing: isSpring ? 'linear' : easing,
- direction,
- endDelay
- };
- const animation = el.animate(finalFrames, opts);
- if (!autoplay) animation.pause();
- waapiAnim = animation;
- waapiPromise = animation.finished;
- waapiAnimations.push(waapiAnim);
- if (waapiTargetByAnim) waapiTargetByAnim.set(waapiAnim, el);
- if (waapiTimingByAnim) waapiTimingByAnim.set(waapiAnim, readWaapiEffectTiming(waapiAnim.effect));
-
- if (begin) {
- // Fire begin when play starts (and also for autoplay on next frame)
- onPlayHooks.push(() => fireBegin(el));
- if (autoplay && typeof requestAnimationFrame !== 'undefined') requestAnimationFrame(() => fireBegin(el));
- }
- if (complete) {
- waapiAnim.addEventListener?.('finish', () => fireComplete(el));
- }
- if (update) {
- const timing = (waapiTimingByAnim && waapiTimingByAnim.get(waapiAnim)) || readWaapiEffectTiming(waapiAnim.effect);
- const item = { anim: waapiAnim, target: el, update: fireUpdate, _lastP: null, _dur: timing.duration || 0 };
- waapiUpdateItems.push(item);
- // Ensure removal on finish/cancel
- waapiAnim.addEventListener?.('finish', () => waapiUpdateSampler.remove(item));
- waapiAnim.addEventListener?.('cancel', () => waapiUpdateSampler.remove(item));
- // Start sampler only when needed (autoplay or explicit play)
- if (autoplay) ensureWaapiUpdate();
- }
- }
- // 2. JS Animation (Fallback / Attributes)
- let jsPromise = Promise.resolve();
- if (Object.keys(jsProps).length > 0) {
- const jsAnim = new JsAnimation(
- el,
- jsProps,
- { duration, delay, easing, autoplay, direction, loop, endDelay, springValues: isSpring ? springValuesRaw : null },
- { update: fireUpdate, begin: fireBegin, complete: fireComplete }
- );
- jsAnimations.push(jsAnim);
- jsPromise = jsAnim.finished;
- }
- return Promise.all([waapiPromise, jsPromise]);
- });
- const finished = Promise.all(promises);
- const controls = new Controls({ waapi: waapiAnimations, js: jsAnimations, finished });
- controls.engine = engineInfo;
- controls._onPlay = onPlayHooks;
- controls._fireUpdate = fireUpdate;
- controls._waapiTargetByAnim = waapiTargetByAnim;
- controls._waapiTimingByAnim = waapiTimingByAnim;
- controls._ensureWaapiUpdate = update ? ensureWaapiUpdate : null;
- if (!autoplay) controls.pause();
- engineInfo.waapiKeys = Array.from(waapiKeySet);
- engineInfo.jsKeys = Array.from(jsKeySet);
- return controls;
- }
- // --- SVG Draw ---
- function svgDraw(targets, params = {}) {
- const elements = toArray(targets);
- elements.forEach(el => {
- if (!isSVG(el)) return;
- const len = el.getTotalLength ? el.getTotalLength() : 0;
- el.style.strokeDasharray = len;
- el.style.strokeDashoffset = len;
-
- animate(el, {
- strokeDashoffset: [len, 0],
- ...params
- });
- });
- }
- // --- In View ---
- function inViewAnimate(targets, params, options = {}) {
- const elements = toArray(targets);
- const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- animate(entry.target, params);
- if (options.once !== false) observer.unobserve(entry.target);
- }
- });
- }, { threshold: options.threshold || 0.1 });
-
- elements.forEach(el => observer.observe(el));
- // Return cleanup so callers can disconnect observers in long-lived pages (esp. once:false).
- return () => {
- try {
- elements.forEach((el) => observer.unobserve(el));
- observer.disconnect();
- } catch (e) {
- // ignore
- }
- };
- }
-
- // --- Scroll Linked ---
- function scroll(animationPromise, options = {}) {
- // options: container (default window), range [start, end] (default viewport logic)
- const container = options.container || window;
- const target = options.target || document.body; // Element to track for progress
- // If passing an animation promise, we control its WAAPI animations
-
- const controls = animationPromise;
- // Back-compat: old return value was a Promise with `.animations`
- const hasSeek = controls && isFunc(controls.seek);
- const anims = (controls && controls.animations) || (animationPromise && animationPromise.animations) || [];
- const jsAnims = (controls && controls.jsAnimations) || [];
- if (!hasSeek && !anims.length && !jsAnims.length) return;
-
- // Cache WAAPI timing per animation to avoid repeated getComputedTiming() during scroll.
- const timingCache = (typeof WeakMap !== 'undefined') ? new WeakMap() : null;
- const getEndTime = (anim) => {
- if (!anim || !anim.effect) return 0;
- if (timingCache) {
- const cached = timingCache.get(anim);
- if (cached) return cached;
- }
- const timing = readWaapiEffectTiming(anim.effect);
- const end = timing.duration || 0;
- if (timingCache && end) timingCache.set(anim, end);
- return end;
- };
- const updateScroll = () => {
- let progress = 0;
-
- if (container === window) {
- const scrollY = window.scrollY;
- const winH = window.innerHeight;
- const docH = document.body.scrollHeight;
-
- // Simple progress: how far down the page (0 to 1)
- // Or element based?
- // Motion One defaults to element entering view.
-
- if (options.target) {
- const rect = options.target.getBoundingClientRect();
- const start = winH;
- const end = -rect.height;
- // progress 0 when rect.top == start (just entering)
- // progress 1 when rect.top == end (just left)
-
- const totalDistance = start - end;
- const currentDistance = start - rect.top;
- progress = currentDistance / totalDistance;
- } else {
- // Whole page scroll
- progress = scrollY / (docH - winH);
- }
- } else if (container && (typeof Element !== 'undefined') && (container instanceof Element)) {
- // Scroll container progress
- const el = container;
- const scrollTop = el.scrollTop;
- const max = (el.scrollHeight - el.clientHeight) || 1;
- if (options.target) {
- const containerRect = el.getBoundingClientRect();
- const rect = options.target.getBoundingClientRect();
- const start = containerRect.height;
- const end = -rect.height;
- const totalDistance = start - end;
- const currentDistance = start - (rect.top - containerRect.top);
- progress = currentDistance / totalDistance;
- } else {
- progress = scrollTop / max;
- }
- }
-
- // Clamp
- progress = clamp01(progress);
-
- if (hasSeek) {
- controls.seek(progress);
- return;
- }
-
- anims.forEach((anim) => {
- if (anim.effect) {
- const end = getEndTime(anim);
- if (!end) return;
- anim.currentTime = end * progress;
- }
- });
- };
- let rafId = 0;
- const onScroll = () => {
- if (rafId) return;
- rafId = requestAnimationFrame(() => {
- rafId = 0;
- updateScroll();
- });
- };
-
- const eventTarget = (container && container.addEventListener) ? container : window;
- eventTarget.addEventListener('scroll', onScroll, { passive: true });
- updateScroll(); // Initial
-
- return () => {
- if (rafId) cancelAnimationFrame(rafId);
- eventTarget.removeEventListener('scroll', onScroll);
- };
- }
- // --- Timeline ---
- function timeline(defaults = {}) {
- const steps = [];
- const api = {
- currentTime: 0,
- add: (targets, params, offset) => {
- const animParams = { ...defaults, ...params };
- let start = api.currentTime;
-
- if (offset !== undefined) {
- if (isStr(offset) && offset.startsWith('-=')) start -= parseFloat(offset.slice(2));
- else if (isStr(offset) && offset.startsWith('+=')) start += parseFloat(offset.slice(2));
- else if (typeof offset === 'number') start = offset;
- }
-
- const dur = animParams.duration || 1000;
- const step = { targets, animParams, start, _scheduled: false };
- steps.push(step);
-
- // Backward compatible: schedule immediately (existing docs rely on this)
- if (start <= 0) {
- animate(targets, animParams);
- step._scheduled = true;
- } else {
- setTimeout(() => {
- animate(targets, animParams);
- }, start);
- step._scheduled = true;
- }
-
- api.currentTime = Math.max(api.currentTime, start + dur);
- return api;
- },
- // Optional: if you create a timeline and want to defer scheduling yourself
- play: () => {
- steps.forEach((s) => {
- if (s._scheduled) return;
- if (s.start <= 0) animate(s.targets, s.animParams);
- else setTimeout(() => animate(s.targets, s.animParams), s.start);
- s._scheduled = true;
- });
- return api;
- }
- };
- return api;
- }
- // --- Export ---
- // transform `$` to be the main export `animal`, with statics attached
- const animal = $;
-
- // Extend $ behavior to act as a global selector and property accessor
- Object.assign(animal, {
- animate,
- timeline,
- draw: svgDraw,
- svgDraw,
- inViewAnimate,
- spring,
- scroll,
- $: animal // Self-reference for backward compatibility
- });
- // Expose Layer if available or allow lazy loading
- Object.defineProperty(animal, 'Layer', {
- get: () => {
- return (typeof window !== 'undefined' && window.Layer) ? window.Layer :
- (typeof globalThis !== 'undefined' && globalThis.Layer) ? globalThis.Layer :
- (typeof Layer !== 'undefined' ? Layer : null);
- }
- });
- // Shortcut for Layer.fire or new Layer()
- // Allows $.fire({ title: 'Hi' }) or $.layer({ title: 'Hi' })
- animal.fire = (options) => {
- const L = animal.Layer;
- if (L) return (L.fire ? L.fire(options) : new L(options).fire());
- console.warn('Layer module not loaded.');
- return Promise.reject('Layer module not loaded');
- };
- // 'layer' alias for static usage
- animal.layer = animal.fire;
- return animal;
- })));
|