CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-spring--web

React DOM support for the react-spring animation library with spring-physics based animations

Pending
Overview
Eval results
Files

imperative-control.mddocs/

Imperative Control

Classes and utilities for imperative animation control and advanced use cases. These provide direct control over spring animations outside of the declarative hook patterns.

Capabilities

Controller Class

Controls spring animations imperatively with full lifecycle management.

/**
 * Core controller class for managing spring animations
 * Provides imperative API for advanced animation control
 */
class Controller<State extends Lookup = Lookup> {
  constructor(props?: ControllerUpdate<State>);
  
  /**
   * Start animations with optional configuration
   * @param props - Animation configuration and target values
   * @returns Promise resolving when animations complete
   */
  start(props?: ControllerUpdate<State>): Promise<AnimationResult<State>>;
  
  /**
   * Stop animations for specified keys or all animations
   * @param keys - Animation keys to stop, or undefined for all
   * @returns Controller instance for chaining
   */
  stop(keys?: OneOrMore<string>): this;
  
  /**
   * Update animation configuration without starting
   * @param props - New animation configuration
   * @returns Controller instance for chaining
   */
  update(props: ControllerUpdate<State>): this;
  
  /**
   * Set immediate values without animation
   * @param props - Values to set immediately
   * @returns Controller instance for chaining
   */
  set(props: Partial<State>): this;
  
  /**
   * Get current animated values
   * @returns Current spring values
   */
  get(): State;
  
  /**
   * Check if any animations are currently running
   * @returns True if animations are active
   */
  isAnimating(): boolean;
  
  /**
   * Access individual SpringValue instances
   */
  springs: { [P in keyof State]: SpringValue<State[P]> };
}

interface ControllerUpdate<State extends Lookup = Lookup> {
  /** Target values for animations */
  to?: Partial<State> | ((state: State) => Partial<State>);
  /** Initial values for animations */
  from?: Partial<State>;
  /** Animation configuration */
  config?: SpringConfig | ((key: string) => SpringConfig);
  /** Delay before animation starts */
  delay?: number | ((key: string) => number);
  /** Immediate properties (no animation) */
  immediate?: boolean | OneOrMore<string> | ((key: string) => boolean);
  /** Reset animation state */
  reset?: boolean | OneOrMore<string>;
  /** Reverse animation direction */
  reverse?: boolean;
  /** Loop configuration */
  loop?: LoopProps;
  /** Callback when animation starts */
  onStart?: (result: AnimationResult<State>) => void;
  /** Callback during animation */
  onChange?: (result: AnimationResult<State>) => void;
  /** Callback when animation completes */
  onRest?: (result: AnimationResult<State>) => void;
}

interface AnimationResult<State extends Lookup = Lookup> {
  value: State;
  finished: boolean;
  cancelled: boolean;
}

Usage Examples:

import { Controller } from "@react-spring/web";

// Basic controller usage
const controller = new Controller({
  opacity: 0,
  transform: 'translateX(0px)',
});

// Start animation
controller.start({
  to: { opacity: 1, transform: 'translateX(100px)' },
  config: { duration: 1000 },
});

// Stop animation
controller.stop();

// Chained operations
controller
  .set({ opacity: 0 })
  .start({ to: { opacity: 1 } })
  .then(() => console.log('Animation complete'));

SpringValue Class

Represents a single animated value with its own lifecycle.

/**
 * Single animated value with spring physics
 * Extends FrameValue with spring-specific functionality
 */
class SpringValue<T = any> extends FrameValue<T> {
  constructor(value?: T, props?: SpringUpdate<T>);
  
  /**
   * Start animation to new value
   * @param props - Animation configuration or target value
   * @returns Promise resolving when animation completes
   */
  start(props?: SpringUpdate<T>): Promise<AnimationResult<SpringValue<T>>>;
  
  /**
   * Stop the current animation
   * @returns SpringValue instance for chaining
   */
  stop(): this;
  
  /**
   * Set value immediately without animation
   * @param value - New value to set
   * @returns SpringValue instance for chaining
   */
  set(value: T | FluidValue<T>): this;
  
  /**
   * Get current value
   * @returns Current animated value
   */
  get(): T;
  
  /**
   * Get current velocity
   * @returns Current animation velocity
   */
  getVelocity(): number;
  
  /**
   * Check if animation is currently running
   * @returns True if animating
   */
  isAnimating(): boolean;
  
  /**
   * Advance animation by one frame
   * @param dt - Delta time in milliseconds
   * @returns True if animation should continue
   */
  advance(dt: number): boolean;
}

interface SpringUpdate<T = any> {
  /** Target value */
  to?: T | FluidValue<T>;
  /** Initial value */
  from?: T;
  /** Animation configuration */
  config?: SpringConfig;
  /** Delay before animation starts */
  delay?: number;
  /** Set value immediately */
  immediate?: boolean;
  /** Reset animation state */
  reset?: boolean;
  /** Loop configuration */
  loop?: LoopProps;
  /** Animation callbacks */
  onStart?: (value: SpringValue<T>) => void;
  onChange?: (value: SpringValue<T>) => void;
  onRest?: (value: SpringValue<T>) => void;
}

Usage Examples:

import { SpringValue } from "@react-spring/web";

// Create spring value
const opacity = new SpringValue(0);

// Animate to new value
opacity.start({
  to: 1,
  config: { tension: 300, friction: 30 },
  onRest: () => console.log('Fade complete'),
});

// Use in component
function Component() {
  return (
    <animated.div style={{ opacity }}>
      Content
    </animated.div>
  );
}

SpringRef Class

Reference object for imperative control of hook-based springs.

/**
 * Reference for imperative control of spring hooks
 * Provides imperative API for hook-based springs
 */
class SpringRef<State extends Lookup = Lookup> {
  constructor();
  
  /**
   * Start animations on all controlled springs
   * @param props - Animation configuration
   * @returns Promise resolving when animations complete
   */
  start(props?: ControllerUpdate<State>): Promise<AnimationResult<State>[]>;
  
  /**
   * Stop animations on all controlled springs
   * @param keys - Animation keys to stop
   * @returns SpringRef instance for chaining
   */
  stop(keys?: OneOrMore<string>): this;
  
  /**
   * Update configuration on all controlled springs
   * @param props - New animation configuration
   * @returns SpringRef instance for chaining
   */
  update(props: ControllerUpdate<State>): this;
  
  /**
   * Set immediate values on all controlled springs
   * @param props - Values to set immediately
   * @returns SpringRef instance for chaining
   */
  set(props: Partial<State>): this;
  
  /**
   * Get current values from all controlled springs
   * @returns Array of current spring states
   */
  get(): State[];
  
  /**
   * Access the underlying controllers
   */
  controllers: Controller<State>[];
  
  /**
   * Current number of controlled springs
   */
  length: number;
}

Usage Examples:

import { useSpring, useSpringRef } from "@react-spring/web";

function RefControlled() {
  const springRef = useSpringRef();
  const styles = useSpring({
    ref: springRef,
    from: { opacity: 0 },
    to: { opacity: 1 },
  });

  const handleClick = () => {
    // Imperative control
    springRef.start({
      to: { opacity: Math.random() },
      config: { duration: 500 },
    });
  };

  return (
    <animated.div style={styles} onClick={handleClick}>
      Click to animate
    </animated.div>
  );
}

SpringContext

React context for sharing spring configuration across components.

/**
 * React context for sharing spring configuration
 * Provides default props for nested spring animations
 */
class SpringContext {
  static Provider: React.Provider<Partial<ControllerUpdate>>;
  static Consumer: React.Consumer<Partial<ControllerUpdate>>;
}

Usage Examples:

import { SpringContext } from "@react-spring/web";

function App() {
  return (
    <SpringContext.Provider value={{
      config: { tension: 300, friction: 30 },
      immediate: false,
    }}>
      <AnimatedComponents />
    </SpringContext.Provider>
  );
}

FrameValue Class

Base class for frame-based animated values.

/**
 * Base class for frame-based animated values
 * Provides core animation frame management
 */
class FrameValue<T = any> extends FluidValue<T> {
  constructor(value?: T);
  
  /**
   * Advance animation by one frame
   * @param dt - Delta time in milliseconds
   * @returns True if animation should continue
   */
  advance(dt: number): boolean;
  
  /**
   * Reset animation state
   */
  reset(): void;
  
  /**
   * Check if animation has finished
   * @returns True if animation is complete
   */
  isFinished(): boolean;
}

Interpolation Class

Advanced interpolation functionality for complex animations.

/**
 * Advanced interpolation between animated values
 * Supports complex value transformations and mappings
 */
class Interpolation<Input = any, Output = any> extends FrameValue<Output> {
  constructor(
    source: OneOrMore<FluidValue<Input>>,
    args: InterpolatorArgs<Input, Output>
  );
  
  /**
   * Create new interpolation from this one
   * @param args - Interpolation configuration
   * @returns New Interpolation instance
   */
  interpolate<NewOutput>(
    args: InterpolatorArgs<Output, NewOutput>
  ): Interpolation<Output, NewOutput>;
}

interface InterpolatorArgs<Input, Output> {
  /** Input range for interpolation */
  range?: number[];
  /** Output range for interpolation */
  output?: readonly Output[];
  /** Interpolation function */
  map?: (input: Input) => Output;
  /** Extrapolation mode */
  extrapolate?: 'extend' | 'clamp' | 'identity';
}

BailSignal Class

Signal for stopping async animations.

/**
 * Signal for stopping async animations
 * Used to cancel long-running or complex animations
 */
class BailSignal extends Error {
  constructor(reason?: string);
}

Advanced Usage Patterns

Custom Animation Loops

import { Controller } from "@react-spring/web";

const controller = new Controller({ rotation: 0 });

async function infiniteRotation() {
  while (true) {
    await controller.start({
      to: { rotation: 360 },
      config: { duration: 2000 },
    });
    controller.set({ rotation: 0 });
  }
}

infiniteRotation();

Complex State Management

import { Controller, SpringValue } from "@react-spring/web";

class AnimationManager {
  private opacity = new SpringValue(1);
  private position = new Controller({ x: 0, y: 0 });
  
  async fadeOut() {
    await this.opacity.start({ to: 0 });
  }
  
  async moveTo(x: number, y: number) {
    await this.position.start({ to: { x, y } });
  }
  
  getStyles() {
    return {
      opacity: this.opacity,
      transform: this.position.springs.x.to(
        (x, y) => `translate(${x}px, ${y}px)`
      ),
    };
  }
}

Additional Core Classes

FrameValue

Base class for frame-based animated values.

/**
 * Base class for frame-based animated values
 * Provides core animation lifecycle and value management
 */
class FrameValue<T = any> {
  constructor(value?: T);
  
  /**
   * Current animated value
   */
  readonly value: T;
  
  /**
   * Check if animation is currently running
   * @returns True if animating
   */
  isAnimating(): boolean;
  
  /**
   * Advance animation by one frame
   * @param dt - Delta time in milliseconds
   * @returns True if animation should continue
   */
  advance(dt: number): boolean;
  
  /**
   * Set value immediately without animation
   * @param value - New value to set
   */
  setValue(value: T): void;
  
  /**
   * Get current value
   * @returns Current animated value
   */
  getValue(): T;
}

Interpolation

Interpolation class for mapping values between different ranges.

/**
 * Interpolation class for value mapping and transformation
 * Supports range mapping, easing functions, and complex transformations
 */
class Interpolation<Output = any> extends FrameValue<Output> {
  constructor(source: any, args: any);
  
  /**
   * Current interpolated output value
   */
  readonly value: Output;
  
  /**
   * Source values being interpolated
   */
  readonly source: any;
  
  /**
   * Update interpolation configuration
   * @param config - New interpolation settings
   */
  update(config: any): void;
}

BailSignal

Signal class for terminating animations early.

/**
 * Signal class used to terminate animations early
 * Provides mechanism for graceful animation cancellation
 */
class BailSignal {
  constructor(reason?: string);
  
  /**
   * Reason for bailing out of animation
   */
  readonly reason?: string;
  
  /**
   * Check if this is a bail signal
   * @param value - Value to check
   * @returns True if value is BailSignal
   */
  static is(value: any): value is BailSignal;
}

Install with Tessl CLI

npx tessl i tessl/npm-react-spring--web

docs

animated-components.md

animation-hooks.md

imperative-control.md

index.md

transform-system.md

tile.json