Easter eggs
composition · delight · loader · page-transition · T1 · v1.0.0 · readyAbout
A page with hidden surprises. A click anywhere outside links and controls covers the screen with a turning radial wave around a mascot. The next click shows a dark screen counting to 100 %; when it reaches 100, the screen breaks into columns that retract one after another and uncover the page. Then it starts over.
Click anywhere on the page (or press E); click again to load and reveal.
Built from
- Effects
- Percent preloader, Radial wave, Staircase reveal
- Primitives
- Click anywhere, Frame scheduler, Layer select
Layers
- Native
- Registered custom properties, at-rule()
- JS
- From its effects: percent-preloader.
- Static
- The same sequence without motion: a still pattern, then the page at once (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
- 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 |
|---|---|---|
--easter-eggs-screen | #171717 | Colour of the counting screen and of the staircase that uncovers the page. |
--easter-eggs-z-index | 50 | Stacking level of the screens over the page. |
Accessibility
Each effect's static layer: the pattern is still, the count completes at once and the page shows without the staircase.
The loading state is announced once (the preloader's status). The sequence is decoration: nothing on the page depends on it.
Sources
- reel · thedesignshop.tds · "Easter Eggs" reel; technique only (P6).
Code
Self-contained: copy every file, keeping the folder structure.
effects/percent-preloader/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;
}
}
effects/percent-preloader/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>
);
}
effects/percent-preloader/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));
}
effects/percent-preloader/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?.();
},
},
};
}
effects/radial-wave/mechanism.module.css/* web-effects radial-wave 1.0.0 · MIT-0 */
/* Mechanism of the radial wave (D2.8, D3.11), shared by both styling variants.
.field fills .root and is a size container; the SVG pattern inside is a square of side
142cqmax, centred: at least the box's diagonal, so turning it never uncovers a corner. The
whole SVG element turns (a compositor transform), never its paths. .field also carries the
intro, a scale-up from the centre, on its own element so the two transforms compose.
L1: CSS animations, run by every supported browser, so the native layer has no feature gate
and there is no L2. L3 (base rules): the full pattern, still. */
.root {
--_radial-wave-color: var(--radial-wave-color, #7c6cf0);
--_radial-wave-background: var(--radial-wave-background, #141414);
--_radial-wave-duration: var(--radial-wave-duration, 60s);
--_radial-wave-intro-duration: var(--radial-wave-intro-duration, 1.2s);
position: relative;
display: grid;
place-items: center;
overflow: hidden;
background: var(--_radial-wave-background);
}
.field {
position: absolute;
inset: 0;
container-type: size;
}
/* Centred by position and margins, not grid alignment: an item larger than its grid area grows
the track instead of centring. Layout only, so it stays independent of the rotation. */
.pattern {
position: absolute;
top: 50%;
left: 50%;
width: 142cqmax;
height: 142cqmax;
margin: -71cqmax 0 0 -71cqmax;
fill: var(--_radial-wave-color);
}
/* Above the pattern, still. */
.center {
position: relative;
}
@keyframes turn {
to {
transform: rotate(1turn);
}
}
@keyframes grow {
from {
transform: scale(0.2);
opacity: 0;
}
}
/* L1 native (gated on the override attribute, D3.6a). */
:root:not([data-fx-layer]) .pattern,
:root[data-fx-layer="native"] .pattern {
animation: turn var(--_radial-wave-duration) linear infinite;
}
:root:not([data-fx-layer]) .root[data-intro] .field,
:root[data-fx-layer="native"] .root[data-intro] .field {
animation: grow var(--_radial-wave-intro-duration)
cubic-bezier(0.22, 1, 0.36, 1) both;
}
/* L3 under reduced motion (unless forced). */
@media (prefers-reduced-motion: reduce) {
:root:not([data-fx-layer]) .pattern,
:root:not([data-fx-layer]) .root[data-intro] .field {
animation: none;
}
}
effects/radial-wave/pattern.tsx// web-effects radial-wave 1.0.0 · MIT-0
import { useId } from "react";
import mechanism from "./mechanism.module.css";
import { rayAngles, rayPath, type WaveShape } from "./rays";
// The pattern, shared by both styling variants (P8): one ray as a path (rays.ts), repeated
// around the centre with <use>, computed while rendering, so no script runs in the browser.
export function Pattern(shape: WaveShape) {
// useId's delimiters are not safe in a URL fragment; the remaining characters stay unique.
const id = `radial-wave-${useId().replace(/[^\w-]/g, "")}`;
return (
<div className={mechanism.field}>
<svg
className={mechanism.pattern}
viewBox="-100 -100 200 200"
aria-hidden="true"
focusable="false"
>
<defs>
<path id={id} d={rayPath(shape)} />
</defs>
{rayAngles(shape.rays).map((angle) => (
<use key={angle} href={`#${id}`} transform={`rotate(${angle})`} />
))}
</svg>
</div>
);
}
effects/radial-wave/rays.ts// web-effects radial-wave 1.0.0 · MIT-0
// Geometry of the radial wave (pure, unit-tested), in a viewBox from -100 to 100. All rays are
// one shape turned around the centre, so only one is computed: a wedge along the x axis, bent
// sideways along a sine wave. Its centre line sits at angle
// θ(r) = amplitude · sin(2π · waves · r / 100); its edges a fixed angle either side of it, so the
// ray widens outwards. Edges are smoothed with quadratic curves; coordinates are rounded.
export type WaveShape = {
/** Number of rays around the circle. */
rays: number;
/** Full waves along a ray, centre to edge. */
waves: number;
/** Largest sideways bend, in radians. */
amplitude: number;
/** Share of each ray's sector it fills (0–1); the rest is gap. */
fill: number;
};
/** Rays start a little off the centre, where they would merge into a blot. */
const inner = 6;
/** The pattern reaches the circle the rotating square is cut from. */
const outer = 100;
/** Points per ray edge: smooth at full-screen size. */
const samples = 48;
/** A tenth of a viewBox unit: under a pixel even when the pattern fills a large screen. */
const round = (n: number) => Math.round(n * 10) / 10;
type Point = [number, number];
const polar = (r: number, angle: number): Point => [
r * Math.cos(angle),
r * Math.sin(angle),
];
const format = ([x, y]: Point) => `${round(x)} ${round(y)}`;
const mid = (a: Point, b: Point): Point => [
(a[0] + b[0]) / 2,
(a[1] + b[1]) / 2,
];
/**
* A smooth curve along the samples: straight to the first midpoint, then quadratic segments with
* each inner sample as control point and the next midpoint as anchor (continuous tangents), then
* straight to the last sample. Symmetric: reversing the samples traces the same curve.
* `start` is "M" for the first edge, "L" to continue the outline.
*/
function smooth(points: Point[], start: "M" | "L"): string {
const last = points.length - 1;
let d = `${start}${format(points[0])}L${format(mid(points[0], points[1]))}`;
for (let i = 1; i < last; i++)
d += `Q${format(points[i])} ${format(mid(points[i], points[i + 1]))}`;
return `${d}L${format(points[last])}`;
}
/** SVG path data of the ray along the x axis (angle 0), as a closed shape. */
export function rayPath({ rays, waves, amplitude, fill }: WaveShape): string {
const half = (Math.PI / rays) * fill;
const radii = Array.from(
{ length: samples + 1 },
(_, i) => inner + ((outer - inner) * i) / samples,
);
const centre = radii.map(
(r) => amplitude * Math.sin((2 * Math.PI * waves * r) / outer),
);
const left = radii.map((r, i) => polar(r, centre[i] - half));
const right = radii.map((r, i) => polar(r, centre[i] + half)).reverse();
return `${smooth(left, "M")}${smooth(right, "L")}Z`;
}
/** Rotation of each ray, in degrees. */
export function rayAngles(rays: number): number[] {
return Array.from({ length: rays }, (_, i) => round((360 * i) / rays));
}
effects/radial-wave/tailwind/RadialWave.tsx// web-effects radial-wave 1.0.0 · MIT-0
import type { ReactNode } from "react";
import mechanism from "../mechanism.module.css";
import { Pattern } from "../pattern";
/**
* Wavy rays radiating from the centre of the box, turning slowly; `children` sit still in the
* middle. The box takes its size from the host (give it a height). `rays`: count; `waves`: full
* waves centre to edge; `amplitude`: sideways bend in radians; `fill`: share of each sector the
* ray covers; `intro`: grow out of the centre on mount.
*/
export function RadialWave({
children,
rays = 48,
waves = 4,
amplitude = 0.12,
fill = 0.5,
intro = true,
className = "",
}: {
children?: ReactNode;
rays?: number;
waves?: number;
amplitude?: number;
fill?: number;
intro?: boolean;
className?: string;
}) {
return (
<div
data-intro={intro || undefined}
className={`${mechanism.root} ${className}`}
>
<Pattern rays={rays} waves={waves} amplitude={amplitude} fill={fill} />
{children !== undefined && (
<div className={mechanism.center}>{children}</div>
)}
</div>
);
}
effects/staircase-reveal/cover.tsx// web-effects staircase-reveal 1.0.0 · MIT-0
import type { CSSProperties } from "react";
import mechanism from "./mechanism.module.css";
// The cover, shared by both styling variants (P8): `steps` columns, each told its position in
// the sequence, counted from the side the reveal starts at.
export function Cover({
steps,
from,
}: {
steps: number;
from: "left" | "right";
}) {
return (
<div className={mechanism.cover} aria-hidden="true">
{Array.from({ length: steps }, (_, index) => (
<span
key={index}
className={mechanism.step}
style={
{
"--_staircase-reveal-order":
from === "left" ? index : steps - 1 - index,
} as CSSProperties
}
/>
))}
</div>
);
}
effects/staircase-reveal/mechanism.module.css/* web-effects staircase-reveal 1.0.0 · MIT-0 */
/* Mechanism of the staircase reveal (D2.8, D3.11), shared by both styling variants.
.cover lies over the content: a row of equal .step columns, each with its position in the
sequence set inline (--_staircase-reveal-order). Each column shrinks upwards (scaleY 1 → 0,
origin at the top) after order × stagger, so the content appears from the bottom in steps.
L1: CSS animations, run by every supported browser, so the native layer has no feature gate
and there is no L2. L3 (base rules): no cover at all. */
.root {
--_staircase-reveal-cover: var(--staircase-reveal-cover, #171717);
--_staircase-reveal-duration: var(--staircase-reveal-duration, 600ms);
--_staircase-reveal-stagger: var(--staircase-reveal-stagger, 80ms);
--_staircase-reveal-delay: var(--staircase-reveal-delay, 0ms);
--_staircase-reveal-easing: var(
--staircase-reveal-easing,
cubic-bezier(0.65, 0, 0.35, 1)
);
position: relative;
}
/* Never catches pointer events: the content is usable as soon as it shows. Clips the last
column's overlap (below). */
.cover {
position: absolute;
inset: 0;
display: none;
overflow: hidden;
pointer-events: none;
}
/* Columns overlap by a pixel so no hairline of content shows between them. */
.step {
flex: 1 0 0;
margin-inline-end: -1px;
background: var(--_staircase-reveal-cover);
transform-origin: 50% 0;
}
@keyframes retract {
from {
transform: scaleY(1);
}
to {
transform: scaleY(0);
}
}
/* L1 native (gated on the override attribute, D3.6a). `both`: covered before the column's
delay, gone after its end. */
:root:not([data-fx-layer]) .cover,
:root[data-fx-layer="native"] .cover {
display: flex;
}
:root:not([data-fx-layer]) .step,
:root[data-fx-layer="native"] .step {
animation: retract var(--_staircase-reveal-duration)
var(--_staircase-reveal-easing) both;
animation-delay: calc(
var(--_staircase-reveal-delay) + var(--_staircase-reveal-order) *
var(--_staircase-reveal-stagger)
);
}
/* L3 under reduced motion (unless forced): no cover. */
@media (prefers-reduced-motion: reduce) {
:root:not([data-fx-layer]) .cover {
display: none;
}
}
effects/staircase-reveal/tailwind/StaircaseReveal.tsx// web-effects staircase-reveal 1.0.0 · MIT-0
import type { ReactNode } from "react";
import { Cover } from "../cover";
import mechanism from "../mechanism.module.css";
/**
* Reveals `children` from under a cover of `steps` columns retracting one after another,
* starting `from` the left or the right. Runs on mount; give it a new `key` to replay.
*/
export function StaircaseReveal({
children,
steps = 8,
from = "left",
className = "",
}: {
children: ReactNode;
steps?: number;
from?: "left" | "right";
className?: string;
}) {
return (
<div className={`${mechanism.root} ${className}`}>
{children}
<Cover steps={steps} from={from} />
</div>
);
}
mechanism.module.css/* web-effects easter-eggs 1.0.0 · MIT-0 */
/* Mechanism of the easter eggs composition, shared by both styling variants. Each stage is a
fixed screen over the viewport; the page underneath is never replaced, only made inert while
covered. The counting screen and the staircase cover are one colour, so the cover takes over
from the screen without a seam: the composition sets the staircase's skin variable from its own. */
.root {
--_easter-eggs-screen: var(--easter-eggs-screen, #171717);
--_easter-eggs-z-index: var(--easter-eggs-z-index, 50);
--staircase-reveal-cover: var(--_easter-eggs-screen);
}
.screen {
position: fixed;
inset: 0;
z-index: var(--_easter-eggs-z-index);
}
.counting {
background: var(--_easter-eggs-screen);
}
/* The staircase stays mounted after it retracts: it must never catch a click. */
.reveal {
pointer-events: none;
}
primitives/click-anywhere/click-anywhere.ts// web-effects click-anywhere 1.0.0 · MIT-0
// Click-anywhere trigger (D2.6a): calls `onTrigger` with a running count when the page is
// clicked outside its interactive elements, and optionally when a key is pressed outside them.
// Listeners are passive and never prevent anything: the page keeps every interaction it had.
import { interactiveSelector, triggers } from "./ignore";
export type ClickAnywhereOptions = {
/** Called with 1, 2, 3, … on each trigger. */
onTrigger: (count: number) => void;
/** A key (`KeyboardEvent.key`, e.g. "e") that triggers too, for keyboard users. */
key?: string;
/** Elements whose clicks do not count (default: links, buttons, form fields, focusable elements). */
ignore?: string;
};
const elementOf = (target: EventTarget | null) =>
target instanceof Element ? target : null;
export function trackClickAnywhere(
target: Document | HTMLElement,
{ onTrigger, key, ignore = interactiveSelector }: ClickAnywhereOptions,
): () => void {
let count = 0;
const trigger = () => onTrigger(++count);
const onClick = (event: Event) => {
const selected = getSelection()?.toString() ?? "";
if (triggers(elementOf(event.target), selected, ignore)) trigger();
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== key || event.repeat) return;
if (event.altKey || event.ctrlKey || event.metaKey) return;
if (triggers(elementOf(event.target), "", ignore)) trigger();
};
target.addEventListener("click", onClick, { passive: true });
if (key) target.addEventListener("keydown", onKeyDown as EventListener);
return () => {
target.removeEventListener("click", onClick);
target.removeEventListener("keydown", onKeyDown as EventListener);
};
}
primitives/click-anywhere/ignore.ts// web-effects click-anywhere 1.0.0 · MIT-0
// Which clicks and key presses count as "anywhere": everything except interaction the page
// already handles. Pure, so it is testable without a DOM.
/** Elements whose clicks belong to them, not to the page (D2.6a: never hijack real controls). */
export const interactiveSelector = [
"a[href]",
"button",
"input",
"select",
"textarea",
"label",
"summary",
"dialog",
'[contenteditable]:not([contenteditable="false"])',
'[role="button"]',
'[role="link"]',
'[tabindex]:not([tabindex="-1"])',
].join(", ");
type Closest = { closest: (selector: string) => unknown } | null;
/** Whether an event on `target` triggers: outside every ignored element and not ending a text selection. */
export function triggers(
target: Closest,
selectedText: string,
ignore: string,
): boolean {
if (selectedText !== "") return false;
return !target?.closest(ignore);
}
primitives/click-anywhere/use-click-anywhere.ts// web-effects click-anywhere 1.0.0 · MIT-0
import { useEffect, useLayoutEffect, useRef, type RefObject } from "react";
import { trackClickAnywhere } from "./click-anywhere";
/**
* Calls `onTrigger` (the latest one) on clicks anywhere in `target` (default: the document)
* outside interactive elements, and on `key`, while `enabled`.
*/
export function useClickAnywhere(
onTrigger: (count: number) => void,
{
enabled = true,
key,
ignore,
target,
}: {
enabled?: boolean;
key?: string;
ignore?: string;
target?: RefObject<HTMLElement | null>;
} = {},
) {
const latest = useRef(onTrigger);
useLayoutEffect(() => {
latest.current = onTrigger;
});
useEffect(() => {
if (!enabled) return;
return trackClickAnywhere(target?.current ?? document, {
onTrigger: (count) => latest.current(count),
key,
ignore,
});
}, [enabled, key, ignore, target]);
}
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/EasterEggs.tsx// web-effects easter-eggs 1.0.0 · MIT-0
"use client";
import type { ReactNode } from "react";
import { PercentPreloader } from "../effects/percent-preloader/tailwind/PercentPreloader";
import { RadialWave } from "../effects/radial-wave/tailwind/RadialWave";
import { StaircaseReveal } from "../effects/staircase-reveal/tailwind/StaircaseReveal";
import mechanism from "../mechanism.module.css";
import { useEasterEggs } from "../use-easter-eggs";
/**
* Hidden surprises over `children` (the page): a click anywhere shows a radial wave around
* `mascot`; the next click a screen counting to 100 %, after which a staircase uncovers the
* page. `triggerKey`: a key that does the same as a click.
*/
export function EasterEggs({
mascot,
triggerKey,
children,
className = "",
}: {
mascot?: ReactNode;
triggerKey?: string;
children: ReactNode;
className?: string;
}) {
const { stage, reveals, complete } = useEasterEggs(triggerKey);
return (
<div className={`${mechanism.root} ${className}`}>
<div inert={stage !== "page"}>{children}</div>
{stage === "wave" && (
<div className={mechanism.screen}>
<RadialWave className="size-full">{mascot}</RadialWave>
</div>
)}
{stage === "counting" && (
<div
className={`${mechanism.screen} ${mechanism.counting} flex items-end justify-end p-8 text-white`}
>
<PercentPreloader onComplete={complete} className="text-8xl" />
</div>
)}
{reveals > 0 && (
<div className={`${mechanism.screen} ${mechanism.reveal}`}>
<StaircaseReveal key={reveals} className="size-full">
{null}
</StaircaseReveal>
</div>
)}
</div>
);
}
use-easter-eggs.ts// web-effects easter-eggs 1.0.0 · MIT-0
import { useState } from "react";
import { useClickAnywhere } from "./primitives/click-anywhere/use-click-anywhere";
/** What covers the page: nothing, the radial wave, or the counting screen. */
export type EasterEggsStage = "page" | "wave" | "counting";
/**
* The click sequence, shared by both styling variants: a click anywhere (or `triggerKey`) shows
* the wave over the page, the next one the counting screen; `complete` (the preloader at 100 %)
* uncovers the page again and counts one more reveal, which replays the staircase. Clicks while
* counting are ignored.
*/
export function useEasterEggs(triggerKey?: string) {
const [stage, setStage] = useState<EasterEggsStage>("page");
const [reveals, setReveals] = useState(0);
useClickAnywhere(
() =>
setStage((current) =>
current === "page" ? "wave" : current === "wave" ? "counting" : current,
),
{ key: triggerKey },
);
const complete = () => {
setStage("page");
setReveals((count) => count + 1);
};
return { stage, reveals, complete };
}