Falling Text

Words drop and pile up under matter-js physics, triggered automatically, on scroll, click or hover; draggable with the mouse.

pnpm dlx shadcn@latest add @leo/falling-text

Props

NameTypeDefaultDescription
backgroundColorstring | undefinedtransparent
classNamestring | undefined-
fontSizestring | undefined1rem
gravitynumber | undefined1
highlightWordsstring[] | undefined["fall,", "pile", "mouse"]Words starting with any of these strings get the highlight style.
mouseConstraintStiffnessnumber | undefined0.2
settleStepsnumber | undefined0Physics steps (1/60 s each) simulated before the first frame, so the words already lie on the floor. 0 starts the fall visibly.
textstring | undefinedWords fall, bounce and pile up on the floor. Grab one with the mouse and throw it around.
triggerundefined | "auto" | "scroll" | "click" | "hover"auto
wireframesboolean | undefinedfalse

Dependencies

  • matter-js@^0.20.0

Source

"use client";

import Matter from "matter-js";
import React, { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";

export interface FallingTextProps {
  text?: string;
  /** Words starting with any of these strings get the highlight style. */
  highlightWords?: string[];
  trigger?: "auto" | "scroll" | "click" | "hover";
  backgroundColor?: string;
  wireframes?: boolean;
  gravity?: number;
  mouseConstraintStiffness?: number;
  fontSize?: string;
  /** Physics steps (1/60 s each) simulated before the first frame, so the words already lie on the floor. 0 starts the fall visibly. */
  settleSteps?: number;
  className?: string;
}

const DEFAULT_TEXT =
  "Words fall, bounce and pile up on the floor. Grab one with the mouse and throw it around.";
const DEFAULT_HIGHLIGHT_WORDS: string[] = ["fall,", "pile", "mouse"];

// Fixed step so the simulation depends on rAF timestamps only, not on the refresh rate.
const STEP = 1000 / 60;
// Longest frame gap that is simulated in full; a longer one (background tab) is clamped.
const MAX_FRAME_MS = 100;
// Upstream advances the world twice per frame (Runner plus a manual update); two sub-steps keep that fall speed.
const SUBSTEPS = 2;

// matter-js types omit the DOM handlers it registers on the element.
type MouseWithHandlers = Matter.Mouse &
  Record<"mousemove" | "mousedown" | "mouseup" | "mousewheel", EventListener>;

const FallingText: React.FC<FallingTextProps> = ({
  text = DEFAULT_TEXT,
  highlightWords = DEFAULT_HIGHLIGHT_WORDS,
  trigger = "auto",
  backgroundColor = "transparent",
  wireframes = false,
  gravity = 1,
  mouseConstraintStiffness = 0.2,
  fontSize = "1rem",
  settleSteps = 0,
  className,
}) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const textRef = useRef<HTMLDivElement | null>(null);
  const canvasContainerRef = useRef<HTMLDivElement | null>(null);

  const [effectStarted, setEffectStarted] = useState(false);

  const words = text.split(" ");

  useEffect(() => {
    if (trigger === "auto") {
      setEffectStarted(true);
      return;
    }
    if (trigger === "scroll" && containerRef.current) {
      const observer = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) {
            setEffectStarted(true);
            observer.disconnect();
          }
        },
        { threshold: 0.1 },
      );
      observer.observe(containerRef.current);
      return () => observer.disconnect();
    }
  }, [trigger]);

  // biome-ignore lint/correctness/useExhaustiveDependencies: `text` and `highlightWords` only change the words that are measured when the simulation (re)starts
  useEffect(() => {
    if (!effectStarted) return;

    const build = (): (() => void) | undefined => {
      const { Engine, Render, World, Bodies, Mouse, MouseConstraint } = Matter;

      if (!containerRef.current || !canvasContainerRef.current || !textRef.current) return;
      const container = containerRef.current;
      const canvasContainer = canvasContainerRef.current;

      const containerRect = container.getBoundingClientRect();
      const width = containerRect.width;
      const height = containerRect.height;

      if (width <= 0 || height <= 0) return;

      const engine = Engine.create();
      engine.world.gravity.y = gravity;

      const render = Render.create({
        element: canvasContainer,
        engine,
        options: {
          width,
          height,
          background: backgroundColor,
          wireframes,
        },
      });

      const boundaryOptions = {
        isStatic: true,
        render: { fillStyle: "transparent" },
      };
      const floor = Bodies.rectangle(width / 2, height + 25, width, 50, boundaryOptions);
      const leftWall = Bodies.rectangle(-25, height / 2, 50, height, boundaryOptions);
      const rightWall = Bodies.rectangle(width + 25, height / 2, 50, height, boundaryOptions);
      const ceiling = Bodies.rectangle(width / 2, -25, width, 50, boundaryOptions);

      const wordSpans = textRef.current.querySelectorAll<HTMLElement>("[data-word]");
      const wordBodies = [...wordSpans].map((elem) => {
        const rect = elem.getBoundingClientRect();

        const x = rect.left - containerRect.left + rect.width / 2;
        const y = rect.top - containerRect.top + rect.height / 2;

        const body = Bodies.rectangle(x, y, rect.width, rect.height, {
          render: { fillStyle: "transparent" },
          restitution: 0.8,
          frictionAir: 0.01,
          friction: 0.2,
        });
        Matter.Body.setVelocity(body, {
          x: (Math.random() - 0.5) * 5,
          y: 0,
        });
        Matter.Body.setAngularVelocity(body, (Math.random() - 0.5) * 0.05);

        return { elem, body };
      });

      for (const { elem, body } of wordBodies) {
        elem.style.position = "absolute";
        elem.style.left = `${body.position.x}px`;
        elem.style.top = `${body.position.y}px`;
        elem.style.transform = `translate(-50%, -50%) rotate(${body.angle}rad)`;
      }

      const mouse = Mouse.create(container) as MouseWithHandlers;
      // Matter's wheel handler calls preventDefault, which would block page scrolling over the text.
      const mouseSource = mouse.element;
      mouseSource.removeEventListener("mousewheel", mouse.mousewheel);
      mouseSource.removeEventListener("DOMMouseScroll", mouse.mousewheel);
      const mouseConstraint = MouseConstraint.create(engine, {
        mouse,
        constraint: {
          stiffness: mouseConstraintStiffness,
          render: { visible: false },
        },
      });
      render.mouse = mouse;

      World.add(engine.world, [
        floor,
        leftWall,
        rightWall,
        ceiling,
        mouseConstraint,
        ...wordBodies.map((wb) => wb.body),
      ]);

      const advance = () => {
        for (let i = 0; i < SUBSTEPS; i++) Engine.update(engine, STEP);
      };
      const syncDom = () => {
        for (const { body, elem } of wordBodies) {
          const { x, y } = body.position;
          elem.style.left = `${x}px`;
          elem.style.top = `${y}px`;
          elem.style.transform = `translate(-50%, -50%) rotate(${body.angle}rad)`;
        }
      };

      for (let i = 0; i < settleSteps; i++) advance();
      syncDom();

      Render.run(render);

      let animationFrameId = 0;
      let previous = 0;
      let accumulator = 0;
      const updateLoop = (now: number) => {
        accumulator += previous ? Math.min(MAX_FRAME_MS, now - previous) : STEP;
        previous = now;
        while (accumulator >= STEP) {
          advance();
          accumulator -= STEP;
        }
        syncDom();
        animationFrameId = requestAnimationFrame(updateLoop);
      };
      animationFrameId = requestAnimationFrame(updateLoop);

      return () => {
        cancelAnimationFrame(animationFrameId);
        Render.stop(render);
        mouseSource.removeEventListener("mousemove", mouse.mousemove);
        mouseSource.removeEventListener("mousedown", mouse.mousedown);
        mouseSource.removeEventListener("mouseup", mouse.mouseup);
        mouseSource.removeEventListener("touchmove", mouse.mousemove);
        mouseSource.removeEventListener("touchstart", mouse.mousedown);
        mouseSource.removeEventListener("touchend", mouse.mouseup);
        render.canvas.parentNode?.removeChild(render.canvas);
        World.clear(engine.world, false);
        Engine.clear(engine);
        // Back to flow layout, so a restart measures the words where the text puts them.
        for (const { elem } of wordBodies) {
          elem.style.position = "";
          elem.style.left = "";
          elem.style.top = "";
          elem.style.transform = "";
        }
      };
    };

    // Web fonts change word widths, so the words are measured only once they have loaded.
    let cancelled = false;
    let teardown: (() => void) | undefined;
    const fontsReady = document.fonts?.ready ?? Promise.resolve();
    fontsReady
      .catch(() => undefined)
      .then(() => {
        if (!cancelled) teardown = build();
      });
    return () => {
      cancelled = true;
      teardown?.();
    };
  }, [
    effectStarted,
    gravity,
    wireframes,
    backgroundColor,
    mouseConstraintStiffness,
    settleSteps,
    text,
    highlightWords,
  ]);

  const handleTrigger = () => {
    if (!effectStarted && (trigger === "click" || trigger === "hover")) {
      setEffectStarted(true);
    }
  };

  return (
    // biome-ignore lint/a11y/noStaticElementInteractions lint/a11y/useKeyWithClickEvents: click and hover only start the effect; the words stay readable plain text
    <div
      ref={containerRef}
      className={cn(
        "relative z-[1] w-full h-full cursor-pointer text-center pt-8 overflow-hidden",
        className,
      )}
      onClick={trigger === "click" ? handleTrigger : undefined}
      onMouseEnter={trigger === "hover" ? handleTrigger : undefined}
    >
      <div
        ref={textRef}
        className="inline-block"
        style={{
          fontSize,
          lineHeight: 1.4,
        }}
      >
        {words.map((word, i) => {
          const isHighlighted = highlightWords.some((hw) => word.startsWith(hw));
          return (
            // biome-ignore lint/suspicious/noArrayIndexKey: words are positional and may repeat
            <React.Fragment key={i}>
              {i > 0 ? " " : null}
              <span
                data-word=""
                className={cn(
                  "inline-block mx-[2px] select-none",
                  isHighlighted && "text-cyan-500 font-bold",
                )}
              >
                {word}
              </span>
            </React.Fragment>
          );
        })}
      </div>

      <div className="absolute top-0 left-0 z-0" ref={canvasContainerRef} aria-hidden="true" />
    </div>
  );
};

export { FallingText };
export default FallingText;