Scroll mask reveal
A panel that opens as it scrolls into view, with a wipe, a curtain, a circle, blinds or a slow zoom, while its content drifts a little behind the page. Use it to pace the sections of a case study.
A panel that opens as it scrolls into view, with a wipe, a curtain, a circle, blinds or a slow zoom, while its content drifts a little behind the page. Use it to pace the sections of a case study.
/**
* MIT License
*
* Copyright (c) 2024 Eduardo Calvo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Rewritten for Tastebud in plain React and CSS, without Tailwind or framer-motion.
*/
"use client";
import { type CSSProperties, type ReactNode, type RefObject, useEffect, useRef, useSyncExternalStore } from "react";
import styles from "./scroll-mask-image.module.css";
/**
* The scroll range the reveal plays over, as two "<target edge> <scroller edge>" pairs.
* Each edge is start, center, end or a number from 0 to 1, e.g. ["start 0.9", "end 0.6"]:
* the reveal starts when the panel's top reaches 90% down the scroller and ends when its foot reaches 60%.
*/
export type ScrollOffset = [string, string];
export type ScrollMaskShape = "wipe" | "curtain" | "circle" | "blinds" | "scale";
export type ScrollMaskDirection = "left" | "right" | "up" | "down";
export interface ScrollMaskPanelProps {
/** What the panel shows: a label, a number, a chart, anything. It fills the panel and drifts with it. */
children?: ReactNode;
/** Fill colour of the panel. */
color?: string;
/** Text colour on it. Defaults to near-black; use white on a dark fill. */
ink?: string;
/** Names the panel for screen readers when its content does not. */
label?: string;
mask?: ScrollMaskShape;
/** Only left/right apply to "wipe" and "blinds"; only up/down apply to "curtain". */
direction?: ScrollMaskDirection;
/** How far the content drifts against the scroll, in px. Keep it under the content's own padding. */
parallax?: number;
/** The scroll range the reveal plays over, e.g. ["start end", "end start"]. */
offset?: ScrollOffset;
/** A scrolling box that drives the reveal instead of the window. */
container?: RefObject<HTMLElement | null>;
/** Stay open once fully shown instead of closing again on the way back up. */
once?: boolean;
className?: string;
style?: CSSProperties;
}
const DEFAULT_PARALLAX_PX = 60;
const CIRCLE_MAX_RADIUS_PERCENT = 90;
const BLIND_BAND_SIZE_PX = 40;
const SCALE_START = 1.12;
const REVEAL_SPEED_MULTIPLIER = 2.5;
/** The smoothing spring that follows the scroll: stiffness, damping and mass. */
const SPRING = { stiffness: 260, damping: 32, mass: 0.4 };
// The reveal has to land while the frame is still well in view, not as it leaves.
const DEFAULT_OFFSET: ScrollOffset = ["start 0.9", "end 0.6"];
const NO_CLIP = "inset(0% 0% 0% 0%)";
const clampUnit = (value: number) => Math.min(1, Math.max(0, value));
const buildClipPath = (mask: ScrollMaskShape, direction: ScrollMaskDirection, progress: number): string => {
const hidden = clampUnit(1 - progress) * 100;
if (mask === "wipe") {
return direction === "right" ? `inset(0% 0% 0% ${hidden}%)` : `inset(0% ${hidden}% 0% 0%)`;
}
if (mask === "curtain") {
return direction === "down" ? `inset(${hidden}% 0% 0% 0%)` : `inset(0% 0% ${hidden}% 0%)`;
}
if (mask === "circle") {
return `circle(${clampUnit(progress) * CIRCLE_MAX_RADIUS_PERCENT}% at 50% 50%)`;
}
return NO_CLIP;
};
const buildBlindsMask = (direction: ScrollMaskDirection, progress: number): string => {
const reveal = clampUnit(progress) * BLIND_BAND_SIZE_PX;
const axis = direction === "left" || direction === "right" ? "to right" : "to bottom";
return `repeating-linear-gradient(${axis}, #000 0px, #000 ${reveal}px, transparent ${reveal}px, transparent ${BLIND_BAND_SIZE_PX}px)`;
};
/** An edge word or number as a share of a length: start 0, center 0.5, end 1. */
function edge(word: string | undefined, fallback: number) {
if (word === "start") return 0;
if (word === "center") return 0.5;
if (word === "end") return 1;
const n = Number.parseFloat(word ?? "");
return Number.isFinite(n) ? n : fallback;
}
/** How far through the offset range the target is, from 0 to 1. */
function scrollProgress(target: HTMLElement, scroller: HTMLElement | null, offset: ScrollOffset) {
const box = target.getBoundingClientRect();
const view = scroller ? scroller.getBoundingClientRect() : { top: 0, height: window.innerHeight };
const [a, b] = offset.map((pair) => pair.trim().split(/\s+/));
// Where the target's top sits, measured from the scroller's top, at the start and at the end.
const startTop = edge(a[1], 1) * view.height - edge(a[0], 0) * box.height;
const endTop = edge(b[1], 0) * view.height - edge(b[0], 1) * box.height;
const top = box.top - view.top;
if (startTop === endTop) return top <= endTop ? 1 : 0;
return clampUnit((startTop - top) / (startTop - endTop));
}
const REDUCE = "(prefers-reduced-motion: reduce)";
const subscribeReduce = (onChange: () => void) => {
const query = window.matchMedia(REDUCE);
query.addEventListener("change", onChange);
return () => query.removeEventListener("change", onChange);
};
function useReducedMotion() {
return useSyncExternalStore(
subscribeReduce,
() => window.matchMedia(REDUCE).matches,
() => false,
);
}
/**
* A flat colour panel that opens as it scrolls into view: wiped in from a side, lifted like a curtain,
* opened from the middle as a circle, drawn in as blinds or eased down from a slight zoom,
* with a little counter-drift on its content so it feels set behind the page.
*/
export function ScrollMaskPanel({
children,
color = "#f4f4f2",
ink = "#1e1e1e",
label,
mask = "wipe",
direction = "left",
parallax = DEFAULT_PARALLAX_PX,
offset = DEFAULT_OFFSET,
container,
once = false,
className = "",
style,
}: ScrollMaskPanelProps) {
const frameRef = useRef<HTMLDivElement>(null);
const layerRef = useRef<HTMLDivElement>(null);
const reduceMotion = useReducedMotion();
const overscan = reduceMotion ? 0 : Math.abs(parallax);
const [startEdge, endEdge] = offset;
useEffect(() => {
const frame = frameRef.current;
const layer = layerRef.current;
if (!frame || !layer) return;
const range: ScrollOffset = [startEdge, endEdge];
const scroller = container?.current ?? null;
const paint = (latest: number, reveal: number) => {
// The mask sits on the frame, not the layer: the layer is taller than the frame so the
// drift has room, and a clip measured on that taller box would miss the frame's edges.
const clip = reduceMotion || mask === "blinds" || mask === "scale" ? NO_CLIP : buildClipPath(mask, direction, reveal);
const blinds = reduceMotion || mask !== "blinds" ? "none" : buildBlindsMask(direction, reveal);
frame.style.clipPath = clip;
frame.style.maskImage = blinds;
frame.style.setProperty("-webkit-mask-image", blinds);
// Scales down into place from a slight zoom, never up, so no edge ever shows.
const scale = reduceMotion || mask !== "scale" ? 1 : SCALE_START + (1 - SCALE_START) * reveal;
const drift = reduceMotion ? 0 : overscan - latest * overscan * 2;
layer.style.transform = `translate3d(0, ${drift.toFixed(2)}px, 0) scale(${scale.toFixed(4)})`;
layer.style.opacity = reduceMotion || mask !== "scale" ? "1" : String(reveal);
};
// Starts closed, so a panel already in view opens as the page arrives.
let value = 0;
let velocity = 0;
let maxReveal = 0;
let raf = 0;
let last = 0;
const draw = () => {
let reveal = clampUnit(value * REVEAL_SPEED_MULTIPLIER);
if (once) {
maxReveal = Math.max(maxReveal, reveal);
reveal = maxReveal;
}
paint(value, reveal);
};
// A spring follows the scroll position, so the reveal eases after the wheel rather than stepping with it.
const tick = (now: number) => {
const dt = Math.min((now - last) / 1000, 1 / 30);
last = now;
const target = scrollProgress(frame, scroller, range);
const h = dt / 4;
for (let i = 0; i < 4; i++) {
const force = -SPRING.stiffness * (value - target) - SPRING.damping * velocity;
velocity += (force / SPRING.mass) * h;
value += velocity * h;
}
if (Math.abs(value - target) < 0.0005 && Math.abs(velocity) < 0.005) {
value = target;
velocity = 0;
raf = 0;
} else {
raf = requestAnimationFrame(tick);
}
draw();
};
const wake = () => {
if (raf) return;
last = performance.now();
raf = requestAnimationFrame(tick);
};
draw();
wake();
const source: HTMLElement | Window = scroller ?? window;
source.addEventListener("scroll", wake, { passive: true });
window.addEventListener("resize", wake);
return () => {
cancelAnimationFrame(raf);
source.removeEventListener("scroll", wake);
window.removeEventListener("resize", wake);
};
}, [container, direction, endEdge, mask, once, overscan, reduceMotion, startEdge]);
return (
<div
ref={frameRef}
role={label ? "group" : undefined}
aria-label={label}
className={`${styles.frame} ${className}`}
style={{ background: color, color: ink, ...style }}
>
<div
ref={layerRef}
className={styles.layer}
style={{ height: `calc(100% + ${overscan * 2}px)`, top: -overscan, padding: `${overscan}px 0`, background: color }}
>
<div className={styles.content}>{children}</div>
</div>
</div>
);
}
/* Scroll mask reveal: the frame carries the mask, the taller colour layer inside it drifts. */
.frame {
position: relative;
overflow: hidden;
border-radius: 20px;
background: #f4f4f2;
color: #1e1e1e;
}
.layer {
position: absolute;
right: 0;
left: 0;
box-sizing: border-box;
will-change: transform;
}
/* The content box is the frame's own size; the layer's padding gives the drift its room. */
.content {
position: relative;
width: 100%;
height: 100%;
}