Skip to content

Public Utilities API

AnimX exports several internal utility functions and managers alongside its core animation API. These tools are primarily useful for advanced users building Custom Plugins or complex interactive behaviors.

You can import any of these directly from the main package:

js
import { measure, resizeManager, parseEase, createTracker } from 'animx';

Global Configuration

config(options)

Configure global AnimX settings.

  • strictMode (boolean): If true, AnimX throws an Error on missing targets or invalid parameters instead of silently failing. Useful for development and debugging.
js
import { config } from 'animx';

config({ strictMode: true });

High-Frequency Trackers

createTracker(target, prop, config?)

Creates a reusable setter function optimized for rapid, high-frequency updates (e.g., mouse-following, scroll-linked animations). Instead of creating and garbage-collecting a new Tween object 60 times a second, this reuses the underlying animation logic.

  • target: A DOM element or selector string.
  • prop: The CSS property or AnimX shorthand to animate (e.g., 'x', 'rotation').
  • config: (Optional) { duration, ease, overwrite }. Defaults to { duration: 0.3, ease: 'cubic.out', overwrite: 'auto' }.
  • Returns: A setter function (value) => Tween. The active tween is available on the setter via .tween.
js
import { createTracker } from 'animx';

const setX = createTracker('.cursor', 'x', { duration: 0.2, ease: 'expo.out' });

document.addEventListener('mousemove', (e) => {
  // Highly optimized! Re-uses the internal tween seamlessly
  setX(e.clientX);
});

Responsive Contexts

responsive()

Creates a media-query-scoped animation context. Animations registered inside this context will automatically be reverted (killed and inline styles restored) when the breakpoint changes.

  • Returns: A ResponsiveContext instance.

Context Methods

  • add(query, handler): Adds a listener for a CSS media query string (e.g., '(max-width: 768px)'). The handler receives a context object, which has an add(tween) method to register animations for automatic cleanup. The handler can also return a cleanup function.
  • remove(query): Removes a condition and reverts its animations.
  • revert() / kill(): Reverts and removes ALL registered conditions on this context instance.
js
import { responsive, animate } from 'animx';

const ctx = responsive();

ctx.add('(min-width: 768px)', (context) => {
  // Add animation to the context for automatic cleanup
  context.add(
    animate('.hero', { x: 100, duration: 1 })
  );

  // You can also return a manual cleanup function
  return () => console.log("Cleaned up desktop layout!");
});

Tween Management

defaults(config)

Sets the global default properties for all newly created tweens (unless overridden in the specific tween).

js
import { defaults } from 'animx';

defaults({
  duration: 1.2,
  ease: 'power2.inOut'
});

stop(target, props?) / kill(target, props?)

Instantly kills all active tweens targeting a specific element. Optionally limits the kill to specific properties.

  • target: The target element, selector, or object.
  • props: (Optional) A specific property string ('x') or object map of properties to kill.

stopAll() / killAll()

Instantly kills all active tweens globally.

getAnimations(target)

Returns an array of all active Tween instances currently animating the given target.

getAll()

Returns a snapshot array of all active Tween instances globally.


Property Measurement

measure(target, prop, unit?)

Instantly measures the current computed value of a CSS property on a DOM element.

  • target: A DOM element or selector string.
  • prop: The CSS property to measure (e.g., 'width', 'x', 'opacity').
  • unit: (Optional) The unit to return (e.g., 'px', '%').
  • Returns: A numeric value or a string.
js
import { measure } from 'animx';

const currentX = measure('.box', 'x', 'px'); // 150px

Target Resolution

resolveTargets(targets)

Takes a mixed input and normalizes it into a flat, deduplicated array of valid targets. It automatically handles CSS selector queries and natively supports plain JavaScript objects (for value-tweening).

  • targets: Can be a selector string ('.box'), a single Node, a NodeList, a plain object, or an array containing any combination of these.
  • Returns: Array<Element | Object>
js
import { resolveTargets } from 'animx';

const targets = resolveTargets(['.box', document.getElementById('hero')]);

Easing Utilities

parseEase(ease)

Converts a standard easing string or an array of bezier control points into an executable math function.

  • ease: A string (e.g., 'expo.out', 'back.inOut(2)') or a custom function.
  • Returns: A function that takes a progress value (0 to 1) and returns an eased progress value.

getEaseNames()

Returns a list of all built-in easing string identifiers.

  • Returns: string[]

Global Managers

resizeManager

A centralized layout awareness system. It debounces and batches layout recalculations on window resize or DOM mutations, preventing layout thrashing when multiple components need to react to screen size changes.

  • resizeManager.add(callback): Registers a callback to run on the next frame after a resize event. Returns an unsubscribe function.
  • resizeManager.remove(callback): Unregisters a specific callback.
  • resizeManager.observe(element): Explicitly tells the internal ResizeObserver to monitor a specific DOM element for layout changes.
  • resizeManager.unobserve(element): Stops observing the specific element.
js
import { resizeManager } from 'animx';

// Run custom logic on resize
const stopListening = resizeManager.add(() => {
  console.log('Window resized or layout mutated!');
});

// Watch a specific element's layout
resizeManager.observe(document.querySelector('.dynamic-box'));

loop (Master Ticker)

The centralized requestAnimationFrame loop that drives all AnimX animations. By default, the loop automatically goes to "sleep" when no animations are running to save battery. However, adding a custom callback will keep the loop awake continuously until you explicitly remove it.

  • loop.add(callback): Runs a custom function on every frame. The callback receives (time, delta) parameters. Returns an unsubscribe function.
  • loop.remove(callback): Removes a specific callback.
  • loop.timeScale: Get or set the global speed multiplier for all animations (e.g., loop.timeScale = 0.5 runs everything at half speed).
  • loop.fps: (Read-only) Returns the current rolling average frames-per-second.
js
import { loop } from 'animx';

// Hook into the master render loop
const stopLooping = loop.add((time, delta) => {
  console.log(`Frame rendered! Time elapsed: ${time}ms`);
});

// The loop will now run forever. To let it sleep again, you MUST call:
stopLooping();
// OR: loop.remove(yourCallbackFunction);

JSON Engine

fromJSON(doc, options?)

Parses and executes an AnimX JSON document, constructing and returning a timeline.

  • doc: A valid JSON string or parsed Object conforming to the AnimX schema.
  • options: (Optional) Configuration options.
  • Returns: Timeline

validateSchema(doc)

Validates an object against the AnimX JSON Schema without executing it.

  • doc: The JSON object to validate.
  • Returns: { valid: boolean, errors: string[] }

registerCallback(name, fn)

Registers a named callback that can be triggered from within a JSON animation document.

  • name: String identifier for the callback.
  • fn: The function to execute.