← All items

Staggered scroll

composition · scroll · text · card · T1 · v1.0.0 · ready

About

A page section paced by the scroll in four beats: the intro paragraph lights word by word as scrolling begins, a line of giant type slides to the left, project cards stick and stack, each covered card shrinking and dimming, and a closing line of giant type slides to the right.

Scroll the page.

Built from

Effects
Scroll drift, Scroll text reveal, Sticky card stack
Primitives
Frame scheduler, Layer select, Scroll progress

Layers

Native
Registered custom properties, Scroll-driven animations
JS
From its effects: scroll-drift, scroll-text-reveal, sticky-card-stack.
Static
The intro fully lit, the giant lines at rest, the cards in a plain column (each effect's static layer).

Browser support (native layer)

  • Registered custom properties: Baseline low · chrome 85, chrome_android 85, edge 85, firefox 128, firefox_android 128, safari 16.4, safari_ios 16.4
  • 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

Each effect's static layer: all words visible, no drift, cards in a column.

The giant lines repeat text meant to be decoration; keep the information they carry elsewhere on the page.

Sources

  • reel · thedesignshop.tds · "Staggered Scroll" reel; technique only (P6).

Code

Download zip

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

effects/scroll-drift/mechanism.module.css
/* web-effects scroll-drift 1.0.0 · MIT-0 */
/* Mechanism of the scroll drift (D2.8, D3.11), shared by both styling variants.
   Driver / renderer split (D2.7): .root's progress through its view range (0–1) lives in
   --_scroll-drift-progress. L1: a native view() timeline animates it on .root. L2: the
   scroll-progress driver writes it inline (data-layer="js"). L3: no transform. .root is the
   measured box and never moves; .drift, inside it, translates from `from` to `to` along the
   axis, so the movement cannot feed back into the measurement. */
@property --_scroll-drift-progress {
  syntax: "<number>";
  inherits: true;
  initial-value: 0;
}

.root {
  --_scroll-drift-from: var(--scroll-drift-from, 0px);
  --_scroll-drift-to: var(--scroll-drift-to, -20vw);
  display: block;
}

.drift {
  display: block;
  --_scroll-drift-offset: calc(
    var(--_scroll-drift-from) +
      (var(--_scroll-drift-to) - var(--_scroll-drift-from)) *
      var(--_scroll-drift-progress)
  );
  --_scroll-drift-transform: translateX(var(--_scroll-drift-offset));
}

.root[data-axis="y"] .drift {
  --_scroll-drift-transform: translateY(var(--_scroll-drift-offset));
}

@keyframes progress {
  from {
    --_scroll-drift-progress: 0;
  }
  to {
    --_scroll-drift-progress: 1;
  }
}

/* L1 native (gated on the override attribute, D3.6a). The `animation` shorthand resets the
   range, so each range is set after it. */
@supports (animation-timeline: view()) {
  :root:not([data-fx-layer]) .root,
  :root[data-fx-layer="native"] .root {
    animation: progress 1s linear both;
    animation-timeline: view();
    animation-range: cover;
  }

  :root:not([data-fx-layer]) .root[data-range="contain"],
  :root[data-fx-layer="native"] .root[data-range="contain"] {
    animation-range: contain;
  }

  :root:not([data-fx-layer]) .root[data-range="exit-crossing"],
  :root[data-fx-layer="native"] .root[data-range="exit-crossing"] {
    animation-range: exit-crossing;
  }

  :root:not([data-fx-layer]) .drift,
  :root[data-fx-layer="native"] .drift {
    transform: var(--_scroll-drift-transform);
  }
}

/* L2 JS driver. */
.root[data-layer="js"] .drift {
  transform: var(--_scroll-drift-transform);
}

/* L3 under reduced motion: no drift. */
@media (prefers-reduced-motion: reduce) {
  :root:not([data-fx-layer]) .root {
    animation: none;
  }

  :root:not([data-fx-layer]) .drift {
    transform: none;
  }
}
effects/scroll-drift/tailwind/ScrollDrift.tsx
// web-effects scroll-drift 1.0.0 · MIT-0
"use client";

import type { ReactNode } from "react";
import type { ViewRange } from "../../../primitives/scroll-progress/view-progress";
import mechanism from "../mechanism.module.css";
import { useScrollDrift } from "../use-scroll-drift";

/**
 * Moves `children` from `from` to `to` (CSS lengths) along `axis` while the box scrolls through
 * `range`. Without `from` / `to`, the skin variables apply. Sideways drift: clip the overflow in
 * the host (e.g. `overflow-x: clip` on a wrapper).
 */
export function ScrollDrift({
  children,
  axis = "x",
  range = "cover",
  from,
  to,
  className = "",
}: {
  children: ReactNode;
  axis?: "x" | "y";
  range?: ViewRange;
  from?: string;
  to?: string;
  className?: string;
}) {
  const { rootProps } = useScrollDrift({ axis, range, from, to });
  return (
    <div {...rootProps} className={`${mechanism.root} ${className}`}>
      <div className={mechanism.drift}>{children}</div>
    </div>
  );
}
effects/scroll-drift/use-scroll-drift.ts
// web-effects scroll-drift 1.0.0 · MIT-0
import { useRef, type CSSProperties } from "react";
import { useLayer } from "../../primitives/layer-select/use-layer";
import type { ViewRange } from "../../primitives/scroll-progress/view-progress";
import { useScrollProgress } from "../../primitives/scroll-progress/use-scroll-progress";

// Behaviour shared by both styling variants (P8): layer decision, the L2 driver, and the inline
// custom properties the mechanism CSS reads. `from` and `to` override the skin per instance by
// setting the private aliases inline (an inline value beats the mechanism's alias declaration).

export function useScrollDrift({
  axis,
  range,
  from,
  to,
}: {
  axis: "x" | "y";
  range: ViewRange;
  from?: string;
  to?: string;
}) {
  const ref = useRef<HTMLDivElement>(null);
  // Literal on purpose: the generator checks it against the CSS @supports condition (D3.6b).
  const driven = useLayer("(animation-timeline: view())") === "js";
  useScrollProgress(ref, {
    enabled: driven,
    property: "--_scroll-drift-progress",
    range,
  });
  const style: Record<string, string> = {};
  if (from !== undefined) style["--_scroll-drift-from"] = from;
  if (to !== undefined) style["--_scroll-drift-to"] = to;
  return {
    rootProps: {
      ref,
      "data-layer": driven ? "js" : undefined,
      "data-axis": axis,
      "data-range": range,
      style: style as CSSProperties,
    },
  };
}
effects/scroll-text-reveal/mechanism.module.css
/* web-effects scroll-text-reveal 1.0.0 · MIT-0 */
/* Mechanism of the scroll text reveal (D2.8, D3.11), shared by both styling variants.
   Driver / renderer split (D2.7): the paragraph's progress through its view range (0–1) lives in
   --_scroll-text-reveal-progress. L1: a native view() timeline animates it. L2: the
   scroll-progress driver writes it inline (data-layer="js"). L3: no opacity applies. Each word
   knows its index and the word count (set inline) and lights over its own slice of the range,
   which ends at --_scroll-text-reveal-end. */
@property --_scroll-text-reveal-progress {
  syntax: "<number>";
  inherits: true;
  initial-value: 0;
}

.root {
  --_scroll-text-reveal-dim: var(--scroll-text-reveal-dim, 0.2);
  --_scroll-text-reveal-end: var(--scroll-text-reveal-end, 0.6);
}

.word {
  /* 0 before this word's slice, 1 after it. */
  --_scroll-text-reveal-lit: clamp(
    0,
    var(--_scroll-text-reveal-progress) / var(--_scroll-text-reveal-end) *
      var(--_scroll-text-reveal-count) - var(--_scroll-text-reveal-index),
    1
  );
  --_scroll-text-reveal-opacity: calc(
    var(--_scroll-text-reveal-dim) + (1 - var(--_scroll-text-reveal-dim)) *
      var(--_scroll-text-reveal-lit)
  );
}

@keyframes progress {
  from {
    --_scroll-text-reveal-progress: 0;
  }
  to {
    --_scroll-text-reveal-progress: 1;
  }
}

/* L1 native (gated on the override attribute, D3.6a). The `animation` shorthand resets the
   range, so each range is set after it. */
@supports (animation-timeline: view()) {
  :root:not([data-fx-layer]) .root,
  :root[data-fx-layer="native"] .root {
    animation: progress 1s linear both;
    animation-timeline: view();
    animation-range: cover;
  }

  :root:not([data-fx-layer]) .root[data-range="contain"],
  :root[data-fx-layer="native"] .root[data-range="contain"] {
    animation-range: contain;
  }

  :root:not([data-fx-layer]) .root[data-range="exit-crossing"],
  :root[data-fx-layer="native"] .root[data-range="exit-crossing"] {
    animation-range: exit-crossing;
  }

  :root:not([data-fx-layer]) .word,
  :root[data-fx-layer="native"] .word {
    opacity: var(--_scroll-text-reveal-opacity);
  }
}

/* L2 JS driver. */
.root[data-layer="js"] .word {
  opacity: var(--_scroll-text-reveal-opacity);
}

/* L3 under reduced motion: every word at full opacity. */
@media (prefers-reduced-motion: reduce) {
  :root:not([data-fx-layer]) .root {
    animation: none;
  }

  :root:not([data-fx-layer]) .word {
    opacity: 1;
  }
}
effects/scroll-text-reveal/tailwind/ScrollTextReveal.tsx
// web-effects scroll-text-reveal 1.0.0 · MIT-0
"use client";

import type { ViewRange } from "../../../primitives/scroll-progress/view-progress";
import mechanism from "../mechanism.module.css";
import { Words } from "../text";
import { useScrollTextReveal } from "../use-scroll-text-reveal";
import { tokenize } from "../words";

/**
 * A paragraph whose words brighten one after another as it scrolls through `range`: `cover` for
 * text mid-page, `exit-crossing` for text at the top of the page. `children`: plain text.
 */
export function ScrollTextReveal({
  children,
  range = "cover",
  className = "",
}: {
  children: string;
  range?: ViewRange;
  className?: string;
}) {
  const { tokens, count } = tokenize(children);
  const { rootProps, wordStyle } = useScrollTextReveal(range, count);
  return (
    <p {...rootProps} className={`${mechanism.root} ${className}`}>
      <Words tokens={tokens} wordStyle={wordStyle} />
    </p>
  );
}
effects/scroll-text-reveal/text.tsx
// web-effects scroll-text-reveal 1.0.0 · MIT-0
import type { CSSProperties } from "react";
import mechanism from "./mechanism.module.css";
import type { Token } from "./words";

// The split text, shared by both styling variants (P8): each word in a span that knows its
// index, the whitespace between them unchanged.

export function Words({
  tokens,
  wordStyle,
}: {
  tokens: Token[];
  wordStyle: (index: number) => CSSProperties;
}) {
  return tokens.map((token, position) =>
    "word" in token ? (
      <span
        key={position}
        className={mechanism.word}
        style={wordStyle(token.index)}
      >
        {token.word}
      </span>
    ) : (
      token.space
    ),
  );
}
effects/scroll-text-reveal/use-scroll-text-reveal.ts
// web-effects scroll-text-reveal 1.0.0 · MIT-0
import { useRef, type CSSProperties } from "react";
import { useLayer } from "../../primitives/layer-select/use-layer";
import type { ViewRange } from "../../primitives/scroll-progress/view-progress";
import { useScrollProgress } from "../../primitives/scroll-progress/use-scroll-progress";

// Behaviour shared by both styling variants (P8): layer decision, the L2 driver, and the inline
// custom properties the mechanism CSS reads. The variants add presentation classes only.

export function useScrollTextReveal(range: ViewRange, count: number) {
  const ref = useRef<HTMLParagraphElement>(null);
  // Literal on purpose: the generator checks it against the CSS @supports condition (D3.6b).
  const driven = useLayer("(animation-timeline: view())") === "js";
  useScrollProgress(ref, {
    enabled: driven,
    property: "--_scroll-text-reveal-progress",
    range,
  });
  return {
    rootProps: {
      ref,
      "data-layer": driven ? "js" : undefined,
      "data-range": range,
      style: { "--_scroll-text-reveal-count": count } as CSSProperties,
    },
    wordStyle: (index: number) =>
      ({ "--_scroll-text-reveal-index": index }) as CSSProperties,
  };
}
effects/scroll-text-reveal/words.ts
// web-effects scroll-text-reveal 1.0.0 · MIT-0
// Splitting the text into words (pure, unit-tested). Whitespace runs are kept as separators, so
// the rendered text equals the original and wraps exactly as it would unsplit.

export type Token = { word: string; index: number } | { space: string };

export function tokenize(text: string): { tokens: Token[]; count: number } {
  const tokens: Token[] = [];
  let count = 0;
  for (const part of text.split(/(\s+)/)) {
    if (part === "") continue;
    if (/^\s+$/.test(part)) tokens.push({ space: part });
    else tokens.push({ word: part, index: count++ });
  }
  return { tokens, count };
}
effects/sticky-card-stack/mechanism.module.css
/* web-effects sticky-card-stack 1.0.0 · MIT-0 */
/* Mechanism of the sticky card stack (D2.8, D3.11), shared by both styling variants.
   Driver / renderer split (D2.7): the stack's progress through its `exit-crossing` view range
   (0–1) lives in --_sticky-card-stack-progress. L1: a native view() timeline animates it.
   L2: the scroll-progress driver writes it inline (data-layer="js"). L3: it stays 0 and no
   transform applies. Each card derives its own share from its index (set inline). */
@property --_sticky-card-stack-progress {
  syntax: "<number>";
  inherits: true;
  initial-value: 0;
}

.stack {
  --_sticky-card-stack-top: var(--sticky-card-stack-top, 1rem);
  --_sticky-card-stack-peek: var(--sticky-card-stack-peek, 0.75rem);
  --_sticky-card-stack-scale: var(--sticky-card-stack-scale, 0.92);
  --_sticky-card-stack-dim: var(--sticky-card-stack-dim, 0.35);
  margin: 0;
  padding: 0;
  list-style: none;
}

.card {
  position: sticky;
  top: calc(
    var(--_sticky-card-stack-top) + var(--_sticky-card-stack-index) *
      var(--_sticky-card-stack-peek)
  );
  transform-origin: 50% 0;
  /* This card's share of the stack progress: 0 while uncovered, 1 once the next card covers it.
     Assumes equal card heights (notes.md). */
  --_sticky-card-stack-local: clamp(
    0,
    var(--_sticky-card-stack-progress) * var(--_sticky-card-stack-count) -
      var(--_sticky-card-stack-index),
    1
  );
  --_sticky-card-stack-transform: scale(
    calc(
      1 - var(--_sticky-card-stack-local) *
        (1 - var(--_sticky-card-stack-scale))
    )
  );
  /* filter, not an overlay: follows any card shape the host passes in (D3.4 exception). */
  --_sticky-card-stack-filter: brightness(
    calc(1 - var(--_sticky-card-stack-local) * var(--_sticky-card-stack-dim))
  );
}

@keyframes progress {
  from {
    --_sticky-card-stack-progress: 0;
  }
  to {
    --_sticky-card-stack-progress: 1;
  }
}

/* L1 native (gated on the override attribute, D3.6a). The renderer applies only while a driver
   runs: identity transforms would still create containing blocks for the host's fixed elements. */
@supports (animation-timeline: view()) {
  :root:not([data-fx-layer]) .stack,
  :root[data-fx-layer="native"] .stack {
    animation: progress 1s linear both;
    animation-timeline: view();
    animation-range: exit-crossing;
  }

  :root:not([data-fx-layer]) .card,
  :root[data-fx-layer="native"] .card {
    transform: var(--_sticky-card-stack-transform);
    filter: var(--_sticky-card-stack-filter);
  }
}

/* L2 JS driver. */
.stack[data-layer="js"] .card {
  transform: var(--_sticky-card-stack-transform);
  filter: var(--_sticky-card-stack-filter);
}

/* L3 under reduced motion: cards still stack (sticky is layout), nothing scales or dims. */
@media (prefers-reduced-motion: reduce) {
  :root:not([data-fx-layer]) .stack {
    animation: none;
  }

  :root:not([data-fx-layer]) .card {
    transform: none;
    filter: none;
  }
}

/* Keyboard focus inside a covered card (D3.8): raise the card above the stack and undo its
   shrink and dim, in every layer. :focus-visible, not :focus-within, so a mouse click on a
   button inside a card does not make it jump. Specificity beats the layer rules above. */
:root .stack .card:has(:focus-visible) {
  z-index: 1;
  transform: none;
  filter: none;
}
effects/sticky-card-stack/tailwind/StickyCardStack.tsx
// web-effects sticky-card-stack 1.0.0 · MIT-0
"use client";

import { Children, type ReactNode } from "react";
import mechanism from "../mechanism.module.css";
import { useStickyCardStack } from "../use-sticky-card-stack";

/** Cards that stick near the top and stack; each covered card shrinks and dims. One child per card. */
export function StickyCardStack({
  children,
  className = "",
}: {
  children: ReactNode;
  className?: string;
}) {
  const cards = Children.toArray(children);
  const { stackProps, cardStyle } = useStickyCardStack(cards.length);
  return (
    <ol
      {...stackProps}
      className={`${mechanism.stack} flex flex-col gap-6 ${className}`}
    >
      {cards.map((card, index) => (
        <li key={index} className={mechanism.card} style={cardStyle(index)}>
          {card}
        </li>
      ))}
    </ol>
  );
}
effects/sticky-card-stack/use-sticky-card-stack.ts
// web-effects sticky-card-stack 1.0.0 · MIT-0
import { useRef, type CSSProperties } from "react";
import { useLayer } from "../../primitives/layer-select/use-layer";
import { useScrollProgress } from "../../primitives/scroll-progress/use-scroll-progress";

// Behaviour shared by both styling variants (P8): layer decision, the L2 driver, and the inline
// custom properties the mechanism CSS reads. The variants add presentation classes only.

export function useStickyCardStack(count: number) {
  const ref = useRef<HTMLOListElement>(null);
  // Literal on purpose: the generator checks it against the CSS @supports condition (D3.6b).
  const driven = useLayer("(animation-timeline: view())") === "js";
  useScrollProgress(ref, {
    enabled: driven,
    property: "--_sticky-card-stack-progress",
    range: "exit-crossing",
  });

  return {
    stackProps: {
      ref,
      "data-layer": driven ? "js" : undefined,
      style: { "--_sticky-card-stack-count": count } as CSSProperties,
    },
    cardStyle: (index: number) =>
      ({ "--_sticky-card-stack-index": index }) as CSSProperties,
  };
}
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();
primitives/layer-select/layer.ts
// web-effects layer-select 1.0.0 · MIT-0
// Browser side of layer selection: reads the current inputs and notifies on change.
// Framework-free, for plain-browser hosts; use-layer.ts wraps it for React.
import {
  layerAttribute,
  parseLayer,
  selectLayer,
  type Layer,
} from "./select-layer";

const reducedMotionQuery = "(prefers-reduced-motion: reduce)";

/**
 * The layer for an item whose native layer needs `supports` (an `@supports` condition, the same
 * text as in the item's CSS), or null when the item has no native layer.
 */
export function currentLayer(
  supports: string | null,
  prerequisitesMet = true,
): Layer {
  return selectLayer({
    nativeSupported: supports !== null && CSS.supports(supports),
    reducedMotion: matchMedia(reducedMotionQuery).matches,
    prerequisitesMet,
    override: parseLayer(document.documentElement.getAttribute(layerAttribute)),
  });
}

/** Calls `onChange` when reduced motion or the forced override changes. Returns a stop function. */
export function watchLayerInputs(onChange: () => void): () => void {
  const media = matchMedia(reducedMotionQuery);
  media.addEventListener("change", onChange);
  const observer = new MutationObserver(onChange);
  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: [layerAttribute],
  });
  return () => {
    media.removeEventListener("change", onChange);
    observer.disconnect();
  };
}
primitives/layer-select/select-layer.ts
// web-effects layer-select 1.0.0 · MIT-0
// Layer selection (D2.4, D3.6). CSS decides on its own: `@supports` enables L1, and the base
// rules are the L3 static state, so server-rendered HTML works without JS. JavaScript only
// decides whether to mount an L2 driver; this is that decision, as a pure function.
//
// Forced override (R6.1): an attribute on <html>. Item CSS honours it by writing native-layer
// and reduced-motion rules as `:root:not([data-fx-layer]) .x, :root[data-fx-layer="native"] .x`.
// The showcase sets the attribute from `?driver=`; items never read the host's URL.

export const layers = ["native", "js", "static"] as const;
export type Layer = (typeof layers)[number];

export const layerAttribute = "data-fx-layer";

export function parseLayer(value: string | null | undefined): Layer | null {
  return layers.find((layer) => layer === value) ?? null;
}

export type LayerInputs = {
  /** The item's `@supports` condition holds; false for items without a native layer. */
  nativeSupported: boolean;
  reducedMotion: boolean;
  /** Inputs the effect cannot work without (e.g. a fine pointer) are present. */
  prerequisitesMet: boolean;
  /** Forced layer from the `data-fx-layer` attribute; wins over everything else. */
  override: Layer | null;
};

export function selectLayer({
  nativeSupported,
  reducedMotion,
  prerequisitesMet,
  override,
}: LayerInputs): Layer {
  if (override) return override;
  if (reducedMotion || !prerequisitesMet) return "static";
  return nativeSupported ? "native" : "js";
}
primitives/layer-select/use-layer.ts
// web-effects layer-select 1.0.0 · MIT-0
import { useCallback, useSyncExternalStore } from "react";
import { currentLayer, watchLayerInputs } from "./layer";
import type { Layer } from "./select-layer";

/**
 * The active layer, or null during server rendering and hydration (CSS alone decides until then).
 * Mount the L2 driver when this returns "js".
 */
export function useLayer(
  supports: string | null,
  prerequisitesMet = true,
): Layer | null {
  const getSnapshot = useCallback(
    () => currentLayer(supports, prerequisitesMet),
    [supports, prerequisitesMet],
  );
  return useSyncExternalStore(watchLayerInputs, getSnapshot, () => null);
}
primitives/scroll-progress/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 "../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);
  };
}
primitives/scroll-progress/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]);
}
primitives/scroll-progress/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];
  }
}
tailwind/StaggeredScroll.tsx
// web-effects staggered-scroll 1.0.0 · MIT-0
import type { ReactNode } from "react";
import { ScrollDrift } from "../effects/scroll-drift/tailwind/ScrollDrift";
import { ScrollTextReveal } from "../effects/scroll-text-reveal/tailwind/ScrollTextReveal";
import { StickyCardStack } from "../effects/sticky-card-stack/tailwind/StickyCardStack";

/**
 * A page section in four scroll beats: `intro` (plain text, at the top of the page) lights word
 * by word as scrolling begins; `title` slides left as giant type; `cards` (one child per card)
 * stack while they stick; `closing` slides right as giant type.
 */
export function StaggeredScroll({
  intro,
  title,
  cards,
  closing,
  className = "",
}: {
  intro: string;
  title: ReactNode;
  cards: ReactNode;
  closing: ReactNode;
  className?: string;
}) {
  return (
    <div className={className}>
      <ScrollTextReveal
        range="exit-crossing"
        className="max-w-3xl text-4xl leading-tight font-semibold"
      >
        {intro}
      </ScrollTextReveal>
      <GiantLine from="10vw" to="-50vw">
        {title}
      </GiantLine>
      <StickyCardStack>{cards}</StickyCardStack>
      <GiantLine from="-50vw" to="10vw">
        {closing}
      </GiantLine>
    </div>
  );
}

/** One line of giant type drifting sideways, clipped so it never widens the page. */
function GiantLine({
  from,
  to,
  children,
}: {
  from: string;
  to: string;
  children: ReactNode;
}) {
  return (
    <div className="overflow-x-clip py-[20vh]">
      <ScrollDrift from={from} to={to}>
        <p className="text-[12vw] leading-none font-black tracking-tight whitespace-nowrap uppercase">
          {children}
        </p>
      </ScrollDrift>
    </div>
  );
}