📚 Documentação inicial do ALETHEIA

- MANUAL-PRODUTO.md: Manual do usuário final
- MANUAL-VENDAS.md: Estratégia comercial e vendas
- MANUAL-TECNICO.md: Infraestrutura e deploy
- README.md: Visão geral do projeto
This commit is contained in:
2026-02-10 15:08:15 -03:00
commit 20a26affaa
16617 changed files with 3202171 additions and 0 deletions

View File

@@ -0,0 +1,317 @@
import { supportsLinearEasing, attachTimeline, isGenerator, isWaapiSupportedEasing } from 'motion-dom';
import { millisecondsToSeconds, secondsToMilliseconds, noop } from 'motion-utils';
import { anticipate } from '../../easing/anticipate.mjs';
import { backInOut } from '../../easing/back.mjs';
import { circInOut } from '../../easing/circ.mjs';
import { DOMKeyframesResolver } from '../../render/dom/DOMKeyframesResolver.mjs';
import { BaseAnimation } from './BaseAnimation.mjs';
import { MainThreadAnimation } from './MainThreadAnimation.mjs';
import { acceleratedValues } from './utils/accelerated-values.mjs';
import { startWaapiAnimation } from './waapi/index.mjs';
import { getFinalKeyframe } from './waapi/utils/get-final-keyframe.mjs';
import { supportsWaapi } from './waapi/utils/supports-waapi.mjs';
/**
* 10ms is chosen here as it strikes a balance between smooth
* results (more than one keyframe per frame at 60fps) and
* keyframe quantity.
*/
const sampleDelta = 10; //ms
/**
* Implement a practical max duration for keyframe generation
* to prevent infinite loops
*/
const maxDuration = 20000;
/**
* Check if an animation can run natively via WAAPI or requires pregenerated keyframes.
* WAAPI doesn't support spring or function easings so we run these as JS animation before
* handing off.
*/
function requiresPregeneratedKeyframes(options) {
return (isGenerator(options.type) ||
options.type === "spring" ||
!isWaapiSupportedEasing(options.ease));
}
function pregenerateKeyframes(keyframes, options) {
/**
* Create a main-thread animation to pregenerate keyframes.
* We sample this at regular intervals to generate keyframes that we then
* linearly interpolate between.
*/
const sampleAnimation = new MainThreadAnimation({
...options,
keyframes,
repeat: 0,
delay: 0,
isGenerator: true,
});
let state = { done: false, value: keyframes[0] };
const pregeneratedKeyframes = [];
/**
* Bail after 20 seconds of pre-generated keyframes as it's likely
* we're heading for an infinite loop.
*/
let t = 0;
while (!state.done && t < maxDuration) {
state = sampleAnimation.sample(t);
pregeneratedKeyframes.push(state.value);
t += sampleDelta;
}
return {
times: undefined,
keyframes: pregeneratedKeyframes,
duration: t - sampleDelta,
ease: "linear",
};
}
const unsupportedEasingFunctions = {
anticipate,
backInOut,
circInOut,
};
function isUnsupportedEase(key) {
return key in unsupportedEasingFunctions;
}
class AcceleratedAnimation extends BaseAnimation {
constructor(options) {
super(options);
const { name, motionValue, element, keyframes } = this.options;
this.resolver = new DOMKeyframesResolver(keyframes, (resolvedKeyframes, finalKeyframe) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe), name, motionValue, element);
this.resolver.scheduleResolve();
}
initPlayback(keyframes, finalKeyframe) {
let { duration = 300, times, ease, type, motionValue, name, startTime, } = this.options;
/**
* If element has since been unmounted, return false to indicate
* the animation failed to initialised.
*/
if (!motionValue.owner || !motionValue.owner.current) {
return false;
}
/**
* If the user has provided an easing function name that isn't supported
* by WAAPI (like "anticipate"), we need to provide the corressponding
* function. This will later get converted to a linear() easing function.
*/
if (typeof ease === "string" &&
supportsLinearEasing() &&
isUnsupportedEase(ease)) {
ease = unsupportedEasingFunctions[ease];
}
/**
* If this animation needs pre-generated keyframes then generate.
*/
if (requiresPregeneratedKeyframes(this.options)) {
const { onComplete, onUpdate, motionValue, element, ...options } = this.options;
const pregeneratedAnimation = pregenerateKeyframes(keyframes, options);
keyframes = pregeneratedAnimation.keyframes;
// If this is a very short animation, ensure we have
// at least two keyframes to animate between as older browsers
// can't animate between a single keyframe.
if (keyframes.length === 1) {
keyframes[1] = keyframes[0];
}
duration = pregeneratedAnimation.duration;
times = pregeneratedAnimation.times;
ease = pregeneratedAnimation.ease;
type = "keyframes";
}
const animation = startWaapiAnimation(motionValue.owner.current, name, keyframes, { ...this.options, duration, times, ease });
// Override the browser calculated startTime with one synchronised to other JS
// and WAAPI animations starting this event loop.
animation.startTime = startTime !== null && startTime !== void 0 ? startTime : this.calcStartTime();
if (this.pendingTimeline) {
attachTimeline(animation, this.pendingTimeline);
this.pendingTimeline = undefined;
}
else {
/**
* Prefer the `onfinish` prop as it's more widely supported than
* the `finished` promise.
*
* Here, we synchronously set the provided MotionValue to the end
* keyframe. If we didn't, when the WAAPI animation is finished it would
* be removed from the element which would then revert to its old styles.
*/
animation.onfinish = () => {
const { onComplete } = this.options;
motionValue.set(getFinalKeyframe(keyframes, this.options, finalKeyframe));
onComplete && onComplete();
this.cancel();
this.resolveFinishedPromise();
};
}
return {
animation,
duration,
times,
type,
ease,
keyframes: keyframes,
};
}
get duration() {
const { resolved } = this;
if (!resolved)
return 0;
const { duration } = resolved;
return millisecondsToSeconds(duration);
}
get time() {
const { resolved } = this;
if (!resolved)
return 0;
const { animation } = resolved;
return millisecondsToSeconds(animation.currentTime || 0);
}
set time(newTime) {
const { resolved } = this;
if (!resolved)
return;
const { animation } = resolved;
animation.currentTime = secondsToMilliseconds(newTime);
}
get speed() {
const { resolved } = this;
if (!resolved)
return 1;
const { animation } = resolved;
return animation.playbackRate;
}
set speed(newSpeed) {
const { resolved } = this;
if (!resolved)
return;
const { animation } = resolved;
animation.playbackRate = newSpeed;
}
get state() {
const { resolved } = this;
if (!resolved)
return "idle";
const { animation } = resolved;
return animation.playState;
}
get startTime() {
const { resolved } = this;
if (!resolved)
return null;
const { animation } = resolved;
// Coerce to number as TypeScript incorrectly types this
// as CSSNumberish
return animation.startTime;
}
/**
* Replace the default DocumentTimeline with another AnimationTimeline.
* Currently used for scroll animations.
*/
attachTimeline(timeline) {
if (!this._resolved) {
this.pendingTimeline = timeline;
}
else {
const { resolved } = this;
if (!resolved)
return noop;
const { animation } = resolved;
attachTimeline(animation, timeline);
}
return noop;
}
play() {
if (this.isStopped)
return;
const { resolved } = this;
if (!resolved)
return;
const { animation } = resolved;
if (animation.playState === "finished") {
this.updateFinishedPromise();
}
animation.play();
}
pause() {
const { resolved } = this;
if (!resolved)
return;
const { animation } = resolved;
animation.pause();
}
stop() {
this.resolver.cancel();
this.isStopped = true;
if (this.state === "idle")
return;
this.resolveFinishedPromise();
this.updateFinishedPromise();
const { resolved } = this;
if (!resolved)
return;
const { animation, keyframes, duration, type, ease, times } = resolved;
if (animation.playState === "idle" ||
animation.playState === "finished") {
return;
}
/**
* WAAPI doesn't natively have any interruption capabilities.
*
* Rather than read commited styles back out of the DOM, we can
* create a renderless JS animation and sample it twice to calculate
* its current value, "previous" value, and therefore allow
* Motion to calculate velocity for any subsequent animation.
*/
if (this.time) {
const { motionValue, onUpdate, onComplete, element, ...options } = this.options;
const sampleAnimation = new MainThreadAnimation({
...options,
keyframes,
duration,
type,
ease,
times,
isGenerator: true,
});
const sampleTime = secondsToMilliseconds(this.time);
motionValue.setWithVelocity(sampleAnimation.sample(sampleTime - sampleDelta).value, sampleAnimation.sample(sampleTime).value, sampleDelta);
}
const { onStop } = this.options;
onStop && onStop();
this.cancel();
}
complete() {
const { resolved } = this;
if (!resolved)
return;
resolved.animation.finish();
}
cancel() {
const { resolved } = this;
if (!resolved)
return;
resolved.animation.cancel();
}
static supports(options) {
const { motionValue, name, repeatDelay, repeatType, damping, type } = options;
if (!motionValue ||
!motionValue.owner ||
!(motionValue.owner.current instanceof HTMLElement)) {
return false;
}
const { onUpdate, transformTemplate } = motionValue.owner.getProps();
return (supportsWaapi() &&
name &&
acceleratedValues.has(name) &&
/**
* If we're outputting values to onUpdate then we can't use WAAPI as there's
* no way to read the value from WAAPI every frame.
*/
!onUpdate &&
!transformTemplate &&
!repeatDelay &&
repeatType !== "mirror" &&
damping !== 0 &&
type !== "inertia");
}
}
export { AcceleratedAnimation };

View File

@@ -0,0 +1,118 @@
import { time } from '../../frameloop/sync-time.mjs';
import { flushKeyframeResolvers } from '../../render/utils/KeyframesResolver.mjs';
import { instantAnimationState } from '../../utils/use-instant-transition-state.mjs';
import { canAnimate } from './utils/can-animate.mjs';
import { getFinalKeyframe } from './waapi/utils/get-final-keyframe.mjs';
/**
* Maximum time allowed between an animation being created and it being
* resolved for us to use the latter as the start time.
*
* This is to ensure that while we prefer to "start" an animation as soon
* as it's triggered, we also want to avoid a visual jump if there's a big delay
* between these two moments.
*/
const MAX_RESOLVE_DELAY = 40;
class BaseAnimation {
constructor({ autoplay = true, delay = 0, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", ...options }) {
// Track whether the animation has been stopped. Stopped animations won't restart.
this.isStopped = false;
this.hasAttemptedResolve = false;
this.createdAt = time.now();
this.options = {
autoplay,
delay,
type,
repeat,
repeatDelay,
repeatType,
...options,
};
this.updateFinishedPromise();
}
/**
* This method uses the createdAt and resolvedAt to calculate the
* animation startTime. *Ideally*, we would use the createdAt time as t=0
* as the following frame would then be the first frame of the animation in
* progress, which would feel snappier.
*
* However, if there's a delay (main thread work) between the creation of
* the animation and the first commited frame, we prefer to use resolvedAt
* to avoid a sudden jump into the animation.
*/
calcStartTime() {
if (!this.resolvedAt)
return this.createdAt;
return this.resolvedAt - this.createdAt > MAX_RESOLVE_DELAY
? this.resolvedAt
: this.createdAt;
}
/**
* A getter for resolved data. If keyframes are not yet resolved, accessing
* this.resolved will synchronously flush all pending keyframe resolvers.
* This is a deoptimisation, but at its worst still batches read/writes.
*/
get resolved() {
if (!this._resolved && !this.hasAttemptedResolve) {
flushKeyframeResolvers();
}
return this._resolved;
}
/**
* A method to be called when the keyframes resolver completes. This method
* will check if its possible to run the animation and, if not, skip it.
* Otherwise, it will call initPlayback on the implementing class.
*/
onKeyframesResolved(keyframes, finalKeyframe) {
this.resolvedAt = time.now();
this.hasAttemptedResolve = true;
const { name, type, velocity, delay, onComplete, onUpdate, isGenerator, } = this.options;
/**
* If we can't animate this value with the resolved keyframes
* then we should complete it immediately.
*/
if (!isGenerator && !canAnimate(keyframes, name, type, velocity)) {
// Finish immediately
if (instantAnimationState.current || !delay) {
onUpdate &&
onUpdate(getFinalKeyframe(keyframes, this.options, finalKeyframe));
onComplete && onComplete();
this.resolveFinishedPromise();
return;
}
// Finish after a delay
else {
this.options.duration = 0;
}
}
const resolvedAnimation = this.initPlayback(keyframes, finalKeyframe);
if (resolvedAnimation === false)
return;
this._resolved = {
keyframes,
finalKeyframe,
...resolvedAnimation,
};
this.onPostResolved();
}
onPostResolved() { }
/**
* Allows the returned animation to be awaited or promise-chained. Currently
* resolves when the animation finishes at all but in a future update could/should
* reject if its cancels.
*/
then(resolve, reject) {
return this.currentFinishedPromise.then(resolve, reject);
}
flatten() {
this.options.type = "keyframes";
this.options.ease = "linear";
}
updateFinishedPromise() {
this.currentFinishedPromise = new Promise((resolve) => {
this.resolveFinishedPromise = resolve;
});
}
}
export { BaseAnimation };

View File

@@ -0,0 +1,389 @@
import { isGenerator, calcGeneratorDuration } from 'motion-dom';
import { invariant, millisecondsToSeconds, secondsToMilliseconds } from 'motion-utils';
import { KeyframeResolver } from '../../render/utils/KeyframesResolver.mjs';
import { clamp } from '../../utils/clamp.mjs';
import { mix } from '../../utils/mix/index.mjs';
import { pipe } from '../../utils/pipe.mjs';
import { inertia } from '../generators/inertia.mjs';
import { keyframes } from '../generators/keyframes.mjs';
import { spring } from '../generators/spring/index.mjs';
import { BaseAnimation } from './BaseAnimation.mjs';
import { frameloopDriver } from './drivers/driver-frameloop.mjs';
import { getFinalKeyframe } from './waapi/utils/get-final-keyframe.mjs';
const generators = {
decay: inertia,
inertia,
tween: keyframes,
keyframes: keyframes,
spring,
};
const percentToProgress = (percent) => percent / 100;
/**
* Animation that runs on the main thread. Designed to be WAAPI-spec in the subset of
* features we expose publically. Mostly the compatibility is to ensure visual identity
* between both WAAPI and main thread animations.
*/
class MainThreadAnimation extends BaseAnimation {
constructor(options) {
super(options);
/**
* The time at which the animation was paused.
*/
this.holdTime = null;
/**
* The time at which the animation was cancelled.
*/
this.cancelTime = null;
/**
* The current time of the animation.
*/
this.currentTime = 0;
/**
* Playback speed as a factor. 0 would be stopped, -1 reverse and 2 double speed.
*/
this.playbackSpeed = 1;
/**
* The state of the animation to apply when the animation is resolved. This
* allows calls to the public API to control the animation before it is resolved,
* without us having to resolve it first.
*/
this.pendingPlayState = "running";
/**
* The time at which the animation was started.
*/
this.startTime = null;
this.state = "idle";
/**
* This method is bound to the instance to fix a pattern where
* animation.stop is returned as a reference from a useEffect.
*/
this.stop = () => {
this.resolver.cancel();
this.isStopped = true;
if (this.state === "idle")
return;
this.teardown();
const { onStop } = this.options;
onStop && onStop();
};
const { name, motionValue, element, keyframes } = this.options;
const KeyframeResolver$1 = (element === null || element === void 0 ? void 0 : element.KeyframeResolver) || KeyframeResolver;
const onResolved = (resolvedKeyframes, finalKeyframe) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe);
this.resolver = new KeyframeResolver$1(keyframes, onResolved, name, motionValue, element);
this.resolver.scheduleResolve();
}
flatten() {
super.flatten();
// If we've already resolved the animation, re-initialise it
if (this._resolved) {
Object.assign(this._resolved, this.initPlayback(this._resolved.keyframes));
}
}
initPlayback(keyframes$1) {
const { type = "keyframes", repeat = 0, repeatDelay = 0, repeatType, velocity = 0, } = this.options;
const generatorFactory = isGenerator(type)
? type
: generators[type] || keyframes;
/**
* If our generator doesn't support mixing numbers, we need to replace keyframes with
* [0, 100] and then make a function that maps that to the actual keyframes.
*
* 100 is chosen instead of 1 as it works nicer with spring animations.
*/
let mapPercentToKeyframes;
let mirroredGenerator;
if (generatorFactory !== keyframes &&
typeof keyframes$1[0] !== "number") {
if (process.env.NODE_ENV !== "production") {
invariant(keyframes$1.length === 2, `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes$1}`);
}
mapPercentToKeyframes = pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1]));
keyframes$1 = [0, 100];
}
const generator = generatorFactory({ ...this.options, keyframes: keyframes$1 });
/**
* If we have a mirror repeat type we need to create a second generator that outputs the
* mirrored (not reversed) animation and later ping pong between the two generators.
*/
if (repeatType === "mirror") {
mirroredGenerator = generatorFactory({
...this.options,
keyframes: [...keyframes$1].reverse(),
velocity: -velocity,
});
}
/**
* If duration is undefined and we have repeat options,
* we need to calculate a duration from the generator.
*
* We set it to the generator itself to cache the duration.
* Any timeline resolver will need to have already precalculated
* the duration by this step.
*/
if (generator.calculatedDuration === null) {
generator.calculatedDuration = calcGeneratorDuration(generator);
}
const { calculatedDuration } = generator;
const resolvedDuration = calculatedDuration + repeatDelay;
const totalDuration = resolvedDuration * (repeat + 1) - repeatDelay;
return {
generator,
mirroredGenerator,
mapPercentToKeyframes,
calculatedDuration,
resolvedDuration,
totalDuration,
};
}
onPostResolved() {
const { autoplay = true } = this.options;
this.play();
if (this.pendingPlayState === "paused" || !autoplay) {
this.pause();
}
else {
this.state = this.pendingPlayState;
}
}
tick(timestamp, sample = false) {
const { resolved } = this;
// If the animations has failed to resolve, return the final keyframe.
if (!resolved) {
const { keyframes } = this.options;
return { done: true, value: keyframes[keyframes.length - 1] };
}
const { finalKeyframe, generator, mirroredGenerator, mapPercentToKeyframes, keyframes, calculatedDuration, totalDuration, resolvedDuration, } = resolved;
if (this.startTime === null)
return generator.next(0);
const { delay, repeat, repeatType, repeatDelay, onUpdate } = this.options;
/**
* requestAnimationFrame timestamps can come through as lower than
* the startTime as set by performance.now(). Here we prevent this,
* though in the future it could be possible to make setting startTime
* a pending operation that gets resolved here.
*/
if (this.speed > 0) {
this.startTime = Math.min(this.startTime, timestamp);
}
else if (this.speed < 0) {
this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime);
}
// Update currentTime
if (sample) {
this.currentTime = timestamp;
}
else if (this.holdTime !== null) {
this.currentTime = this.holdTime;
}
else {
// Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
// 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
// example.
this.currentTime =
Math.round(timestamp - this.startTime) * this.speed;
}
// Rebase on delay
const timeWithoutDelay = this.currentTime - delay * (this.speed >= 0 ? 1 : -1);
const isInDelayPhase = this.speed >= 0
? timeWithoutDelay < 0
: timeWithoutDelay > totalDuration;
this.currentTime = Math.max(timeWithoutDelay, 0);
// If this animation has finished, set the current time to the total duration.
if (this.state === "finished" && this.holdTime === null) {
this.currentTime = totalDuration;
}
let elapsed = this.currentTime;
let frameGenerator = generator;
if (repeat) {
/**
* Get the current progress (0-1) of the animation. If t is >
* than duration we'll get values like 2.5 (midway through the
* third iteration)
*/
const progress = Math.min(this.currentTime, totalDuration) / resolvedDuration;
/**
* Get the current iteration (0 indexed). For instance the floor of
* 2.5 is 2.
*/
let currentIteration = Math.floor(progress);
/**
* Get the current progress of the iteration by taking the remainder
* so 2.5 is 0.5 through iteration 2
*/
let iterationProgress = progress % 1.0;
/**
* If iteration progress is 1 we count that as the end
* of the previous iteration.
*/
if (!iterationProgress && progress >= 1) {
iterationProgress = 1;
}
iterationProgress === 1 && currentIteration--;
currentIteration = Math.min(currentIteration, repeat + 1);
/**
* Reverse progress if we're not running in "normal" direction
*/
const isOddIteration = Boolean(currentIteration % 2);
if (isOddIteration) {
if (repeatType === "reverse") {
iterationProgress = 1 - iterationProgress;
if (repeatDelay) {
iterationProgress -= repeatDelay / resolvedDuration;
}
}
else if (repeatType === "mirror") {
frameGenerator = mirroredGenerator;
}
}
elapsed = clamp(0, 1, iterationProgress) * resolvedDuration;
}
/**
* If we're in negative time, set state as the initial keyframe.
* This prevents delay: x, duration: 0 animations from finishing
* instantly.
*/
const state = isInDelayPhase
? { done: false, value: keyframes[0] }
: frameGenerator.next(elapsed);
if (mapPercentToKeyframes) {
state.value = mapPercentToKeyframes(state.value);
}
let { done } = state;
if (!isInDelayPhase && calculatedDuration !== null) {
done =
this.speed >= 0
? this.currentTime >= totalDuration
: this.currentTime <= 0;
}
const isAnimationFinished = this.holdTime === null &&
(this.state === "finished" || (this.state === "running" && done));
if (isAnimationFinished && finalKeyframe !== undefined) {
state.value = getFinalKeyframe(keyframes, this.options, finalKeyframe);
}
if (onUpdate) {
onUpdate(state.value);
}
if (isAnimationFinished) {
this.finish();
}
return state;
}
get duration() {
const { resolved } = this;
return resolved ? millisecondsToSeconds(resolved.calculatedDuration) : 0;
}
get time() {
return millisecondsToSeconds(this.currentTime);
}
set time(newTime) {
newTime = secondsToMilliseconds(newTime);
this.currentTime = newTime;
if (this.holdTime !== null || this.speed === 0) {
this.holdTime = newTime;
}
else if (this.driver) {
this.startTime = this.driver.now() - newTime / this.speed;
}
}
get speed() {
return this.playbackSpeed;
}
set speed(newSpeed) {
const hasChanged = this.playbackSpeed !== newSpeed;
this.playbackSpeed = newSpeed;
if (hasChanged) {
this.time = millisecondsToSeconds(this.currentTime);
}
}
play() {
if (!this.resolver.isScheduled) {
this.resolver.resume();
}
if (!this._resolved) {
this.pendingPlayState = "running";
return;
}
if (this.isStopped)
return;
const { driver = frameloopDriver, onPlay, startTime } = this.options;
if (!this.driver) {
this.driver = driver((timestamp) => this.tick(timestamp));
}
onPlay && onPlay();
const now = this.driver.now();
if (this.holdTime !== null) {
this.startTime = now - this.holdTime;
}
else if (!this.startTime) {
this.startTime = startTime !== null && startTime !== void 0 ? startTime : this.calcStartTime();
}
else if (this.state === "finished") {
this.startTime = now;
}
if (this.state === "finished") {
this.updateFinishedPromise();
}
this.cancelTime = this.startTime;
this.holdTime = null;
/**
* Set playState to running only after we've used it in
* the previous logic.
*/
this.state = "running";
this.driver.start();
}
pause() {
var _a;
if (!this._resolved) {
this.pendingPlayState = "paused";
return;
}
this.state = "paused";
this.holdTime = (_a = this.currentTime) !== null && _a !== void 0 ? _a : 0;
}
complete() {
if (this.state !== "running") {
this.play();
}
this.pendingPlayState = this.state = "finished";
this.holdTime = null;
}
finish() {
this.teardown();
this.state = "finished";
const { onComplete } = this.options;
onComplete && onComplete();
}
cancel() {
if (this.cancelTime !== null) {
this.tick(this.cancelTime);
}
this.teardown();
this.updateFinishedPromise();
}
teardown() {
this.state = "idle";
this.stopDriver();
this.resolveFinishedPromise();
this.updateFinishedPromise();
this.startTime = this.cancelTime = null;
this.resolver.cancel();
}
stopDriver() {
if (!this.driver)
return;
this.driver.stop();
this.driver = undefined;
}
sample(time) {
this.startTime = 0;
return this.tick(time, true);
}
}
// Legacy interface
function animateValue(options) {
return new MainThreadAnimation(options);
}
export { MainThreadAnimation, animateValue };

View File

@@ -0,0 +1,17 @@
import { time } from '../../../frameloop/sync-time.mjs';
import { frame, cancelFrame, frameData } from '../../../frameloop/frame.mjs';
const frameloopDriver = (update) => {
const passTimestamp = ({ timestamp }) => update(timestamp);
return {
start: () => frame.update(passTimestamp, true),
stop: () => cancelFrame(passTimestamp),
/**
* If we're processing this frame we can use the
* framelocked timestamp to keep things in sync.
*/
now: () => (frameData.isProcessing ? frameData.timestamp : time.now()),
};
};
export { frameloopDriver };

View File

@@ -0,0 +1,14 @@
/**
* A list of values that can be hardware-accelerated.
*/
const acceleratedValues = new Set([
"opacity",
"clipPath",
"filter",
"transform",
// TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved
// or until we implement support for linear() easing.
// "background-color"
]);
export { acceleratedValues };

View File

@@ -0,0 +1,42 @@
import { isGenerator } from 'motion-dom';
import { warning } from 'motion-utils';
import { isAnimatable } from '../../utils/is-animatable.mjs';
function hasKeyframesChanged(keyframes) {
const current = keyframes[0];
if (keyframes.length === 1)
return true;
for (let i = 0; i < keyframes.length; i++) {
if (keyframes[i] !== current)
return true;
}
}
function canAnimate(keyframes, name, type, velocity) {
/**
* Check if we're able to animate between the start and end keyframes,
* and throw a warning if we're attempting to animate between one that's
* animatable and another that isn't.
*/
const originKeyframe = keyframes[0];
if (originKeyframe === null)
return false;
/**
* These aren't traditionally animatable but we do support them.
* In future we could look into making this more generic or replacing
* this function with mix() === mixImmediate
*/
if (name === "display" || name === "visibility")
return true;
const targetKeyframe = keyframes[keyframes.length - 1];
const isOriginAnimatable = isAnimatable(originKeyframe, name);
const isTargetAnimatable = isAnimatable(targetKeyframe, name);
warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". ${originKeyframe} is not an animatable value - to enable this animation set ${originKeyframe} to a value animatable to ${targetKeyframe} via the \`style\` property.`);
// Always skip if any of these are true
if (!isOriginAnimatable || !isTargetAnimatable) {
return false;
}
return (hasKeyframesChanged(keyframes) ||
((type === "spring" || isGenerator(type)) && velocity));
}
export { canAnimate };

View File

@@ -0,0 +1,112 @@
import { NativeAnimationControls, isGenerator, createGeneratorEasing, supportsLinearEasing } from 'motion-dom';
import { invariant, secondsToMilliseconds } from 'motion-utils';
import { startWaapiAnimation } from './index.mjs';
import { browserNumberValueTypes } from '../../../render/dom/value-types/number-browser.mjs';
import { getFinalKeyframe } from './utils/get-final-keyframe.mjs';
import { setCSSVar, setStyle } from './utils/style.mjs';
import { supportsPartialKeyframes } from './utils/supports-partial-keyframes.mjs';
import { supportsWaapi } from './utils/supports-waapi.mjs';
const state = new WeakMap();
function hydrateKeyframes(valueName, keyframes, read) {
for (let i = 0; i < keyframes.length; i++) {
if (keyframes[i] === null) {
keyframes[i] = i === 0 ? read() : keyframes[i - 1];
}
if (typeof keyframes[i] === "number" &&
browserNumberValueTypes[valueName]) {
keyframes[i] = browserNumberValueTypes[valueName].transform(keyframes[i]);
}
}
if (!supportsPartialKeyframes() && keyframes.length < 2) {
keyframes.unshift(read());
}
}
const defaultEasing = "easeOut";
function getElementAnimationState(element) {
const animationState = state.get(element) || new Map();
state.set(element, animationState);
return state.get(element);
}
class NativeAnimation extends NativeAnimationControls {
constructor(element, valueName, valueKeyframes, options) {
const isCSSVar = valueName.startsWith("--");
invariant(typeof options.type !== "string", `animateMini doesn't support "type" as a string. Did you mean to import { spring } from "framer-motion"?`);
const existingAnimation = getElementAnimationState(element).get(valueName);
existingAnimation && existingAnimation.stop();
const readInitialKeyframe = () => {
return valueName.startsWith("--")
? element.style.getPropertyValue(valueName)
: window.getComputedStyle(element)[valueName];
};
if (!Array.isArray(valueKeyframes)) {
valueKeyframes = [valueKeyframes];
}
hydrateKeyframes(valueName, valueKeyframes, readInitialKeyframe);
// TODO: Replace this with toString()?
if (isGenerator(options.type)) {
const generatorOptions = createGeneratorEasing(options, 100, options.type);
options.ease = supportsLinearEasing()
? generatorOptions.ease
: defaultEasing;
options.duration = secondsToMilliseconds(generatorOptions.duration);
options.type = "keyframes";
}
else {
options.ease = options.ease || defaultEasing;
}
const onFinish = () => {
this.setValue(element, valueName, getFinalKeyframe(valueKeyframes, options));
this.cancel();
this.resolveFinishedPromise();
};
const init = () => {
this.setValue = isCSSVar ? setCSSVar : setStyle;
this.options = options;
this.updateFinishedPromise();
this.removeAnimation = () => {
const elementState = state.get(element);
elementState && elementState.delete(valueName);
};
};
if (!supportsWaapi()) {
super();
init();
onFinish();
}
else {
super(startWaapiAnimation(element, valueName, valueKeyframes, options));
init();
if (options.autoplay === false) {
this.animation.pause();
}
this.animation.onfinish = onFinish;
getElementAnimationState(element).set(valueName, this);
}
}
/**
* Allows the returned animation to be awaited or promise-chained. Currently
* resolves when the animation finishes at all but in a future update could/should
* reject if its cancels.
*/
then(resolve, reject) {
return this.currentFinishedPromise.then(resolve, reject);
}
updateFinishedPromise() {
this.currentFinishedPromise = new Promise((resolve) => {
this.resolveFinishedPromise = resolve;
});
}
play() {
if (this.state === "finished") {
this.updateFinishedPromise();
}
super.play();
}
cancel() {
this.removeAnimation();
super.cancel();
}
}
export { NativeAnimation };

View File

@@ -0,0 +1,34 @@
import { resolveElements, getValueTransition } from 'motion-dom';
import { invariant, secondsToMilliseconds } from 'motion-utils';
import { NativeAnimation } from './NativeAnimation.mjs';
function animateElements(elementOrSelector, keyframes, options, scope) {
const elements = resolveElements(elementOrSelector, scope);
const numElements = elements.length;
invariant(Boolean(numElements), "No valid element provided.");
const animations = [];
for (let i = 0; i < numElements; i++) {
const element = elements[i];
const elementTransition = { ...options };
/**
* Resolve stagger function if provided.
*/
if (typeof elementTransition.delay === "function") {
elementTransition.delay = elementTransition.delay(i, numElements);
}
for (const valueName in keyframes) {
const valueKeyframes = keyframes[valueName];
const valueOptions = {
...getValueTransition(elementTransition, valueName),
};
valueOptions.duration = valueOptions.duration
? secondsToMilliseconds(valueOptions.duration)
: valueOptions.duration;
valueOptions.delay = secondsToMilliseconds(valueOptions.delay || 0);
animations.push(new NativeAnimation(element, valueName, valueKeyframes, valueOptions));
}
}
return animations;
}
export { animateElements };

View File

@@ -0,0 +1,13 @@
import { GroupPlaybackControls } from 'motion-dom';
import { createAnimationsFromSequence } from '../../sequence/create.mjs';
import { animateElements } from './animate-elements.mjs';
function animateSequence(definition, options) {
const animations = [];
createAnimationsFromSequence(definition, options).forEach(({ keyframes, transition }, element) => {
animations.push(...animateElements(element, keyframes, transition));
});
return new GroupPlaybackControls(animations);
}
export { animateSequence };

View File

@@ -0,0 +1,12 @@
import { GroupPlaybackControls } from 'motion-dom';
import { animateElements } from './animate-elements.mjs';
const createScopedWaapiAnimate = (scope) => {
function scopedAnimate(elementOrSelector, keyframes, options) {
return new GroupPlaybackControls(animateElements(elementOrSelector, keyframes, options, scope));
}
return scopedAnimate;
};
const animateMini = /*@__PURE__*/ createScopedWaapiAnimate();
export { animateMini, createScopedWaapiAnimate };

View File

@@ -0,0 +1,23 @@
import { mapEasingToNativeEasing } from 'motion-dom';
function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duration = 300, repeat = 0, repeatType = "loop", ease = "easeInOut", times, } = {}) {
const keyframeOptions = { [valueName]: keyframes };
if (times)
keyframeOptions.offset = times;
const easing = mapEasingToNativeEasing(ease, duration);
/**
* If this is an easing array, apply to keyframes, not animation as a whole
*/
if (Array.isArray(easing))
keyframeOptions.easing = easing;
return element.animate(keyframeOptions, {
delay,
duration,
easing: !Array.isArray(easing) ? easing : "linear",
fill: "both",
iterations: repeat + 1,
direction: repeatType === "reverse" ? "alternate" : "normal",
});
}
export { startWaapiAnimation };

View File

@@ -0,0 +1,12 @@
const isNotNull = (value) => value !== null;
function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe) {
const resolvedKeyframes = keyframes.filter(isNotNull);
const index = repeat && repeatType !== "loop" && repeat % 2 === 1
? 0
: resolvedKeyframes.length - 1;
return !index || finalKeyframe === undefined
? resolvedKeyframes[index]
: finalKeyframe;
}
export { getFinalKeyframe };

View File

@@ -0,0 +1,8 @@
function setCSSVar(element, name, value) {
element.style.setProperty(`--${name}`, value);
}
function setStyle(element, name, value) {
element.style[name] = value;
}
export { setCSSVar, setStyle };

View File

@@ -0,0 +1,13 @@
import { memo } from 'motion-utils';
const supportsPartialKeyframes = /*@__PURE__*/ memo(() => {
try {
document.createElement("div").animate({ opacity: [1] });
}
catch (e) {
return false;
}
return true;
});
export { supportsPartialKeyframes };

View File

@@ -0,0 +1,5 @@
import { memo } from 'motion-utils';
const supportsWaapi = /*@__PURE__*/ memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
export { supportsWaapi };