← All items

Scroll progress

primitive · scroll · T1 · v1.0.0 · ready

About

The L2 driver for scroll-driven effects (D2.7). It writes the same 0–1 value a native `view()` timeline would, for the `cover`, `contain` and `exit-crossing` ranges, so the effect's CSS renders identically on both layers.

Layers

Native
Scroll-driven animations
JS
Browsers without animation-timeline: view().
Static
No driver; the effect shows its static state.

Browser support (native layer)

  • Scroll-driven animations: Baseline low · chrome 115, chrome_android 115, edge 115, firefox 159, firefox_android 159, safari 26, safari_ios 26 · Firefox reportedly needs a non-zero animation-duration.

Samsung Internet: Chromium-based; not tracked by web-features.

Accessibility

Not mounted on the static layer, which reduced motion selects.

Sources

  • original

Code

Download zip

Self-contained: copy every file, keeping the folder structure.

primitives/frame-scheduler/scheduler.ts
// web-effects frame-scheduler 1.0.0 · MIT-0
// Shared animation-frame scheduler (D3.9). One requestAnimationFrame loop for every caller.
// Each frame runs all `read` callbacks, then all `write` callbacks, so DOM measurements and
// DOM writes never interleave (no forced synchronous layout). Hidden tabs pause it for free,
// because browsers stop requestAnimationFrame there. Pausing off-screen work is the caller's job.

export type FrameTask = {
  /** Measure the DOM. Runs before every write of the same frame. */
  read?: (time: number) => void;
  /** Mutate the DOM (styles, custom properties). */
  write?: (time: number) => void;
};

export type FrameScheduler = {
  /** Runs `task` every frame until the returned function is called. */
  loop: (task: FrameTask) => () => void;
  /** Runs `task` once, on the next frame. Requesting a pending task again is a no-op. */
  once: (task: FrameTask) => () => void;
};

type FrameApi = {
  request: (callback: (time: number) => void) => number;
  cancel: (handle: number) => void;
};

// Resolved per call, not at import, so importing this module is safe during server rendering.
const browserFrames: FrameApi = {
  request: (callback) => requestAnimationFrame(callback),
  cancel: (handle) => cancelAnimationFrame(handle),
};

export function createScheduler(
  frames: FrameApi = browserFrames,
): FrameScheduler {
  const looping = new Set<FrameTask>();
  const pending = new Set<FrameTask>();
  let handle: number | null = null;

  const tick = (time: number) => {
    handle = null;
    const tasks = [...looping, ...pending];
    pending.clear();
    for (const task of tasks) task.read?.(time);
    for (const task of tasks) task.write?.(time);
    if (looping.size > 0 || pending.size > 0) handle = frames.request(tick);
  };

  const start = () => {
    if (handle === null) handle = frames.request(tick);
  };

  const stopIfIdle = () => {
    if (handle !== null && looping.size === 0 && pending.size === 0) {
      frames.cancel(handle);
      handle = null;
    }
  };

  return {
    loop(task) {
      looping.add(task);
      start();
      return () => {
        looping.delete(task);
        stopIfIdle();
      };
    },
    once(task) {
      pending.add(task);
      start();
      return () => {
        pending.delete(task);
        stopIfIdle();
      };
    },
  };
}

/** The scheduler every primitive shares. */
export const frameScheduler: FrameScheduler = createScheduler();
scroll-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
// L2 scroll-progress driver: writes the `view()` progress of an element into a custom property
// (D2.7). Measures on scroll and resize through the shared scheduler (one read and one write per
// frame at most) and stops measuring while the element is off-screen (D3.9), after writing its
// final clamped value.
import { frameScheduler } from "./primitives/frame-scheduler/scheduler";
import { viewProgress, type ViewRange } from "./view-progress";

export type ScrollProgressOptions = {
  /** Custom property to write, the item's private name, e.g. "--_card-stack-progress" (D2.19). */
  property: string;
  range?: ViewRange;
  /**
   * The element's nearest scroll container, as CSS `view()` would pick it. Omit for the page.
   * Not detected automatically: pass it when the subject scrolls inside another element.
   */
  scroller?: HTMLElement;
};

/**
 * The scroller's scrollport (padding box minus a horizontal scrollbar) in viewport coordinates.
 * Fractional on purpose: clientTop/clientHeight round to whole pixels, while view() uses the
 * exact box (a 0.5 px rounding error measurably shifted progress against native).
 */
function scrollport(scroller: HTMLElement): { top: number; height: number } {
  const rect = scroller.getBoundingClientRect();
  const style = getComputedStyle(scroller);
  const borderTop = Number.parseFloat(style.borderTopWidth);
  const borderBottom = Number.parseFloat(style.borderBottomWidth);
  const scrollbar = Math.max(
    0,
    scroller.offsetHeight -
      scroller.clientHeight -
      Math.round(borderTop + borderBottom),
  );
  return {
    top: rect.top + borderTop,
    height: rect.height - borderTop - borderBottom - scrollbar,
  };
}

export function trackScrollProgress(
  element: HTMLElement,
  { property, range = "cover", scroller }: ScrollProgressOptions,
): () => void {
  let progress = Number.NaN;
  let written = Number.NaN;
  let visible = true;

  const task = {
    read() {
      const rect = element.getBoundingClientRect();
      const port = scroller
        ? scrollport(scroller)
        : { top: 0, height: document.documentElement.clientHeight };
      progress = viewProgress(range, {
        top: rect.top - port.top,
        height: rect.height,
        viewport: port.height,
      });
    },
    write() {
      if (progress === written) return;
      element.style.setProperty(property, String(progress));
      written = progress;
    },
  };

  const request = () => {
    if (visible) frameScheduler.once(task);
  };
  const cancelPending = frameScheduler.once(task);

  const observer = new IntersectionObserver(
    ([entry]) => {
      visible = entry.isIntersecting;
      // One measurement on every visibility change, so leaving the viewport writes 0 or 1.
      frameScheduler.once(task);
    },
    { root: scroller ?? null },
  );
  observer.observe(element);

  const target: HTMLElement | Window = scroller ?? window;
  target.addEventListener("scroll", request, { passive: true });
  window.addEventListener("resize", request, { passive: true });

  return () => {
    cancelPending();
    observer.disconnect();
    target.removeEventListener("scroll", request);
    window.removeEventListener("resize", request);
    element.style.removeProperty(property);
  };
}
use-scroll-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
import { useEffect, type RefObject } from "react";
import { trackScrollProgress } from "./scroll-progress";
import type { ViewRange } from "./view-progress";

/** Runs the L2 driver on `ref` while `enabled` (typically `useLayer(...) === "js"`). */
export function useScrollProgress(
  ref: RefObject<HTMLElement | null>,
  {
    enabled,
    property,
    range = "cover",
    scroller,
  }: {
    enabled: boolean;
    property: string;
    range?: ViewRange;
    scroller?: RefObject<HTMLElement | null>;
  },
) {
  useEffect(() => {
    const element = ref.current;
    if (!enabled || !element) return;
    return trackScrollProgress(element, {
      property,
      range,
      scroller: scroller?.current ?? undefined,
    });
  }, [ref, enabled, property, range, scroller]);
}
view-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
// Progress of a subject through its scrollport, matching the CSS `view()` timeline (block
// axis, no inset) for the `cover`, `contain` and `exit-crossing` ranges. The L2 driver writes this value so
// that item CSS renders identically on L1 (native timeline) and L2 (D2.7).

export const viewRanges = ["cover", "contain", "exit-crossing"] as const;
export type ViewRange = (typeof viewRanges)[number];

export type ViewGeometry = {
  /** Subject's top edge, relative to the scrollport's top edge, in px. */
  top: number;
  /** Subject's height in px. */
  height: number;
  /** Scrollport's height in px. */
  viewport: number;
};

/**
 * 0 at the start of the range, 1 at its end, clamped. Positions are expressed as the subject's
 * top edge: progress grows as `top` decreases (content scrolls up).
 *   cover:   from the subject's top at the scrollport's bottom (top = viewport)
 *            to its bottom at the scrollport's top (top = -height).
 *   contain: from the subject fully inside, or fully covering, the scrollport for the first time
 *            to the last time; when it is exactly as tall as the scrollport the range is a point.
 *   exit-crossing: from the subject's top at the scrollport's top (top = 0) to its bottom there
 *            (top = -height); progress follows scroll distance over the subject's own height.
 */
export function viewProgress(
  range: ViewRange,
  { top, height, viewport }: ViewGeometry,
): number {
  const [start, end] = rangeEdges(range, height, viewport);
  if (start === end) return top > start ? 0 : 1;
  return Math.min(Math.max((start - top) / (start - end), 0), 1);
}

/** Range start and end, as values of the subject's `top`. */
function rangeEdges(
  range: ViewRange,
  height: number,
  viewport: number,
): [number, number] {
  switch (range) {
    case "cover":
      return [viewport, -height];
    case "contain":
      return [Math.max(viewport - height, 0), Math.min(viewport - height, 0)];
    case "exit-crossing":
      return [0, -height];
  }
}