Percent preloader
effect · loader · T1 · v1.0.0 · readyAbout
A timed counter from 0 % to 100 %, slowing towards the end, for intros and page transitions. It is decorative timing, not real loading progress: wire real progress by rendering the host's own number instead. `onComplete` fires when it reaches 100 %, and at once when motion is reduced, so a sequence can go on.
Use the item page's Replay (R) to count again.
Layers
- Native
- Registered custom properties, at-rule()
- JS
- Without a registered integer property (or a way to detect one in CSS) the count would jump from 0 to 100; the frame scheduler counts instead.
- Static
- Shows 100 %.
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
- at-rule(): Baseline limited · chrome 148, chrome_android 148, edge 148, firefox 157, firefox_android 157 · Feature query for at-rules (`@supports at-rule(@property)`); where it is missing, items fall back to their JS layer even if the at-rule itself works.
Samsung Internet: Chromium-based; not tracked by web-features.
Skin
| Variable | Default | Meaning |
|---|---|---|
--percent-preloader-duration | 2s | Time from 0 % to 100 % (read by the JS layer too). |
Accessibility
Static layer: shows 100 % and completes at once.
The counting number is hidden from assistive technology; a status region says Loading, then Loaded.
Sources
- reel · thedesignshop.tds · "Easter Eggs" reel; technique only (P6).
Code
Self-contained: copy every file, keeping the folder structure.
mechanism.module.css/* web-effects percent-preloader 1.0.0 · MIT-0 */
/* Mechanism of the percent preloader (D2.8, D3.11), shared by both styling variants.
Driver / renderer split (D2.7): the count (0–100) lives in the integer
--_percent-preloader-value, which .value renders with a CSS counter. L1: a CSS animation of
that registered property, where CSS can detect @property support. L2: the frame scheduler
writes it inline (data-layer="js"). L3 (base rules): the counter shows 100. Both layers ease
out with the same cubic (use-percent-preloader.ts). */
@property --_percent-preloader-value {
syntax: "<integer>";
inherits: false;
initial-value: 0;
}
.root {
--_percent-preloader-duration: var(--percent-preloader-duration, 2s);
}
.value {
counter-reset: percent 100;
font-variant-numeric: tabular-nums;
}
.value::after {
content: counter(percent) "%";
}
/* Visually hidden, still read. */
.status {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}
@keyframes count {
from {
--_percent-preloader-value: 0;
}
to {
--_percent-preloader-value: 100;
}
}
/* L1 native (gated on the override attribute, D3.6a). The easing is easeOutCubic, which the JS
layer computes as 1 - (1 - t)³. */
@supports at-rule(@property) {
:root:not([data-fx-layer]) .value,
:root[data-fx-layer="native"] .value {
counter-reset: percent var(--_percent-preloader-value);
animation: count var(--_percent-preloader-duration)
cubic-bezier(0.33, 1, 0.68, 1) both;
}
}
/* L2 JS driver. */
.root[data-layer="js"] .value {
counter-reset: percent var(--_percent-preloader-value);
}
/* L3 under reduced motion (unless forced). */
@media (prefers-reduced-motion: reduce) {
:root:not([data-fx-layer]) .value {
counter-reset: percent 100;
animation: none;
}
}
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);
}
tailwind/PercentPreloader.tsx// web-effects percent-preloader 1.0.0 · MIT-0
"use client";
import mechanism from "../mechanism.module.css";
import { usePercentPreloader } from "../use-percent-preloader";
/**
* Counts from 0 % to 100 % over `--percent-preloader-duration`, eased out. `onComplete`: called
* at 100 %, or at once when motion is reduced. Remount (a new `key`) to count again.
*/
export function PercentPreloader({
onComplete,
className = "",
}: {
onComplete?: () => void;
className?: string;
}) {
const { complete, rootProps, valueProps } = usePercentPreloader(onComplete);
return (
<div {...rootProps} className={`${mechanism.root} ${className}`}>
<span
{...valueProps}
className={`${mechanism.value} leading-none font-black tracking-tight`}
/>
<span role="status" className={mechanism.status}>
{complete ? "Loaded" : "Loading"}
</span>
</div>
);
}
time.ts// web-effects percent-preloader 1.0.0 · MIT-0
// Pure helpers of the JS layer (unit-tested).
/** A CSS <time> ("2s", "1500ms") in milliseconds; `fallback` for anything else. */
export function parseTime(value: string, fallback: number): number {
const match = /^\s*(\d*\.?\d+)(ms|s)\s*$/.exec(value);
if (!match) return fallback;
return Number(match[1]) * (match[2] === "s" ? 1000 : 1);
}
/** easeOutCubic, the same curve as the CSS layer's cubic-bezier(0.33, 1, 0.68, 1). */
export const easeOut = (t: number) => 1 - (1 - t) ** 3;
/** The counter's value after `elapsed` of `duration` ms. */
export function countAt(elapsed: number, duration: number): number {
const t = Math.min(Math.max(elapsed / duration, 0), 1);
return Math.round(100 * easeOut(t));
}
use-percent-preloader.ts// web-effects percent-preloader 1.0.0 · MIT-0
"use client";
import {
useEffect,
useLayoutEffect,
useRef,
useState,
type AnimationEvent,
} from "react";
import { frameScheduler } from "./primitives/frame-scheduler/scheduler";
import { useLayer } from "./primitives/layer-select/use-layer";
import { countAt, parseTime } from "./time";
// Behaviour shared by both styling variants (P8): layer decision, the L2 driver, completion.
// Completion: the native animation's end, the JS count reaching 100, or at once on the static
// layer (no count), so a sequence waiting on it always goes on.
const property = "--_percent-preloader-value";
const fallbackDuration = 2000;
export function usePercentPreloader(onComplete?: () => void) {
const valueRef = useRef<HTMLSpanElement>(null);
const [complete, setComplete] = useState(false);
const done = useRef(onComplete);
useLayoutEffect(() => {
done.current = onComplete;
});
// Literal on purpose: the generator checks it against the CSS @supports condition (D3.6b).
const layer = useLayer("at-rule(@property)");
useEffect(() => {
if (layer === null || layer === "native") return;
const finish = () => {
setComplete(true);
done.current?.();
};
if (layer === "static") {
finish();
return;
}
const el = valueRef.current;
if (!el) return;
const duration = parseTime(
getComputedStyle(el).getPropertyValue("--_percent-preloader-duration"),
fallbackDuration,
);
const start = performance.now();
const stop = frameScheduler.loop({
write(time) {
const value = countAt(time - start, duration);
el.style.setProperty(property, String(value));
if (value === 100) {
stop();
finish();
}
},
});
return () => {
stop();
el.style.removeProperty(property);
};
}, [layer]);
return {
complete,
rootProps: { "data-layer": layer === "js" ? "js" : undefined },
valueProps: {
ref: valueRef,
"aria-hidden": true,
// Native layer: the count animation's end. Other animations on the element are ignored.
onAnimationEnd: (event: AnimationEvent) => {
if (!event.animationName.endsWith("count")) return;
setComplete(true);
done.current?.();
},
},
};
}