diff --git a/shared/component-meta.ts b/shared/component-meta.ts index 4fa029a..967e1ae 100644 --- a/shared/component-meta.ts +++ b/shared/component-meta.ts @@ -32,6 +32,13 @@ export const COMPONENT_META: readonly ComponentMeta[] = [ category: "Motion", tags: ["train", "2.5d", "canvas", "interactive"], }, + { + slug: "scroll-deck", + name: "Scroll Deck", + description: "A pinned, scroll-scrubbed hero: cards rise into a fan, scatter and tumble in 3D around a second headline that reveals word by word, then sweep back into a fan that turns on its pivot.", + category: "Motion", + tags: ["scroll", "cards", "3d", "hero"], + }, ]; export function componentMeta(slug: string | undefined): ComponentMeta | undefined { diff --git a/src/components/library/scaled-preview.tsx b/src/components/library/scaled-preview.tsx index 75e5ccc..98dd5f3 100644 --- a/src/components/library/scaled-preview.tsx +++ b/src/components/library/scaled-preview.tsx @@ -7,7 +7,7 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from "react"; * height to fill; with `interactive` it stays usable and the frame takes the * scaled height of its content. */ -export function ScaledPreview({ width, children, className, interactive = false }: { width: number; children: ReactNode; className?: string; interactive?: boolean }) { +export function ScaledPreview({ width, height: designHeight, children, className, interactive = false }: { width: number; height?: number; children: ReactNode; className?: string; interactive?: boolean }) { const frame = useRef(null); const content = useRef(null); const [scale, setScale] = useState(0.4); @@ -22,7 +22,8 @@ export function ScaledPreview({ width, children, className, interactive = false const next = Math.min(1, element.clientWidth / width); if (next <= 0) return; setScale(next); - if (interactive) setHeight(inner.offsetHeight * next); + if (designHeight) setHeight(designHeight * next); + else if (interactive) setHeight(inner.offsetHeight * next); else setFrameHeight(element.clientHeight / next); }; update(); @@ -30,16 +31,16 @@ export function ScaledPreview({ width, children, className, interactive = false observer.observe(element); observer.observe(inner); return () => observer.disconnect(); - }, [width, interactive]); + }, [width, designHeight, interactive]); return (
-
+
{children}
diff --git a/src/library/items/draw-a-line.tsx b/src/library/items/draw-a-line.tsx index 6439709..412a648 100644 --- a/src/library/items/draw-a-line.tsx +++ b/src/library/items/draw-a-line.tsx @@ -193,6 +193,12 @@ export function DrawALine({ let spin = 0; let flyerCount = 0; const leans = CARS.map(() => 0); + // Coupling slack: each wagon rides on a spring against the engine's acceleration. + // Braking bunches the wagons up, then they spring back and stretch out. + const slack = CARS.map(() => 0); + const slackSpeed = CARS.map(() => 0); + let lastSpeed = 0; + let accel = 0; let previous = 0; let frame = 0; let visible = true; @@ -542,8 +548,32 @@ export function DrawALine({ // The train: shadows on the table now, bodies sorted with everything else. CARS.forEach((car, index) => { - const d = s - car.back; + const d = s - car.back + slack[index]; if (d - car.length / 2 < first) return; + if (index > 0) { + // The coupling bar between this wagon and the car ahead shows the slack. + const ahead = CARS[index - 1]; + const front = d + car.length / 2 - 1; + const rear = s - ahead.back + slack[index - 1] - ahead.length / 2 + 1; + const a = at(points, front); + const b = at(points, rear); + const za = elevation(front, now) + RAIL + 6.5; + const zb = elevation(rear, now) + RAIL + 6.5; + drawables.push({ + key: -(a.y + b.y) / 2 + Math.max(za, zb) * 1.2 + 0.4, + run: () => { + const from = project(a.x, a.y, za); + const to = project(b.x, b.y, zb); + ctx.globalAlpha = fade; + ctx.strokeStyle = palette.steel; + ctx.lineWidth = 2.4 * from.scale; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + }, + }); + } const p = at(points, d); const angle = headingAt(points, d); const f = { x: Math.cos(angle), y: Math.sin(angle) }; @@ -615,13 +645,26 @@ export function DrawALine({ const goal = Math.max(0, points[points.length - 1].d - LEAD); const wanted = Math.min(520, Math.max(0, (goal - s) * 2.6)); speed += (wanted - speed) * (1 - Math.exp(-dt * 4)); + if (dt > 0) { + accel += ((speed - lastSpeed) / dt - accel) * (1 - Math.exp(-dt * 10)); + lastSpeed = speed; + // Inertia pushes the wagons forward when braking (positive slack closes the gap), back when pulling away. + for (let index = 1; index < CARS.length; index++) { + const push = still ? 0 : -accel * 0.7 * (index === 1 ? 1 : 1.6); + slackSpeed[index] += (push - 120 * slack[index] - 11 * slackSpeed[index]) * dt; + slack[index] += slackSpeed[index] * dt; + } + // Keep the cars from overlapping: the gaps are about 7 units at rest. + slack[1] = clamp(slack[1], -8, 6); + slack[2] = clamp(slack[2], -16, slack[1] + 5); + } s = Math.min(goal, s + speed * dt); spin += (speed * dt) / 4.2; travelled += speed * dt; // Cars lean out of curves in proportion to speed. CARS.forEach((car, index) => { - const d = s - car.back; + const d = s - car.back + slack[index]; let turn = headingAt(points, d + 12) - headingAt(points, d - 12); turn = Math.atan2(Math.sin(turn), Math.cos(turn)) / 24; const target = still ? 0 : clamp(-turn * speed * 0.04, -0.22, 0.22); @@ -662,7 +705,11 @@ export function DrawALine({ // Nobody drawing and the train at rest: fade the scene away, then start clean. if (!drawing && speed < 8) { fade = Math.max(0, fade - dt / FADE_S); - if (fade === 0) { points = []; bridges = []; head = null; s = 0; speed = 0; travelled = 0; } + if (fade === 0) { + points = []; bridges = []; head = null; s = 0; speed = 0; lastSpeed = 0; accel = 0; travelled = 0; + slack.fill(0); + slackSpeed.fill(0); + } } } diff --git a/src/library/items/scroll-deck.tsx b/src/library/items/scroll-deck.tsx new file mode 100644 index 0000000..58c073c --- /dev/null +++ b/src/library/items/scroll-deck.tsx @@ -0,0 +1,434 @@ +/* Scroll Deck: a pinned, scroll-scrubbed hero where the cards are the show. + Cards rise in fanned along the bottom under a big intro line. Scrolling blows + the intro away and scatters the cards around the screen, tumbling in depth, + while a second headline reveals word by word. The cards then sweep back into + a fan below it (edges first) and the whole fan turns on its pivot. + Between scrolls the cards stay alive: a resting tilt, a slow wobble, pointer + parallax and a sheen that follows each card's angle. + Self-contained React + Tailwind: CSS 3D transforms written to the cards each + frame. No other packages. */ + +import * as React from "react"; + +export type DeckCard = { + name: string; + /** Small print along the bottom, like a web address. */ + caption?: string; + icon: React.ReactNode; + /** Gradient from top-left to bottom-right. */ + colors: [string, string]; +}; + +export type ScrollDeckProps = { + cards: DeckCard[]; + /** The big first line. */ + intro: React.ReactNode; + /** Small line under the intro, e.g. a link pill. */ + introNote?: React.ReactNode; + /** The second headline, split around the cycling icon. Wrap words in ~tildes~ to mute them. */ + headline: [string, string]; + subtitle?: React.ReactNode; + /** Buttons or links under the second headline. */ + actions?: React.ReactNode; + /** "contained" scrolls inside its own box (give it a height); "page" pins to the window while you scroll. */ + scroll?: "contained" | "page"; + /** How many screens of scrolling the sequence takes. */ + length?: number; + theme?: "light" | "dark"; + className?: string; +}; + +type Pose = [x: number, y: number, rotation: number]; + +/* ---------- Choreography ---------- */ + +// The timeline runs in beats; scroll progress maps onto 0…END. +const END = 5.7; +const SCRUB = 6; // how quickly the cards catch up with the scroll, per second + +// Seven slots, tuned as a set. Positions are fractions of the stage, from its centre. +const INTRO_DROP = [0, 0.02, 0.06, 0.11]; // how much lower each step from the middle sits +const SCATTER: Pose[] = [[-0.36, -0.05, -14], [-0.31, -0.36, 10], [0.3, -0.37, -8], [-0.22, 0.36, 8], [0.28, 0.34, -10], [0.41, 0, 12], [-0.45, 0.28, -18]]; +const SCATTER_NARROW: Pose[] = [[-0.4, -0.36, -14], [0.38, -0.38, 10], [-0.44, 0.3, 8], [-0.3, 0.36, 10], [0.3, 0.38, -8], [0.02, -0.44, -6], [0.05, 0.46, 4]]; +// Each card's tumble while scattered: tilt back, turn, and depth (in camera units). +const TUMBLE: [number, number, number][] = [[0.38, -0.55, 0.6], [-0.32, 0.5, -0.4], [0.42, 0.6, 1.2], [-0.45, -0.4, 0.2], [0.3, -0.62, 0.9], [-0.36, 0.52, -0.2], [0.5, 0.34, 0.4]]; + +// The camera: 32° field of view from 10 units away, so the stage is 5.735 units tall. +const VIEW_HEIGHT = 2 * 10 * Math.tan((16 * Math.PI) / 180); + +const clamp01 = (t: number) => Math.min(1, Math.max(0, t)); +const mix = (a: number, b: number, t: number) => a + (b - a) * t; +const beat = (t: number, start: number, duration: number) => clamp01((t - start) / duration); +const ease = { + in3: (t: number) => t * t * t, + out4: (t: number) => 1 - Math.pow(1 - t, 4), + inOut4: (t: number) => (t < 0.5 ? 8 * t ** 4 : 1 - Math.pow(-2 * t + 2, 4) / 2), + sine: (t: number) => -(Math.cos(Math.PI * t) - 1) / 2, +}; + +/** Splits "~From~ a real problem" into words, muting the ones inside tildes. */ +function words(text: string) { + const out: { text: string; muted: boolean }[] = []; + let muted = false; + for (const chunk of text.split(/(~)/)) { + if (chunk === "~") { muted = !muted; continue; } + for (const word of chunk.split(/\s+/).filter(Boolean)) out.push({ text: word, muted }); + } + return out; +} + +/* ---------- Pieces ---------- */ + +function Card({ card, mark, sheen }: { card: DeckCard; mark: React.ReactNode; sheen: (element: HTMLDivElement | null) => void }) { + // Proportions follow a 300 × 400 card face. + const u = (value: number) => `calc(var(--cw) * ${value / 300})`; + return ( +
+
+
+ + {card.name} + + + {card.icon} + + {card.caption && ( + + {card.caption} + + )} + {mark} +
+ ); +} + +/** The inline tile in the headline, flipping through each card's icon in turn. */ +function CyclingIcon({ cards }: { cards: DeckCard[] }) { + const [index, setIndex] = React.useState(0); + React.useEffect(() => { + if (cards.length < 2) return; + const timer = window.setInterval(() => setIndex((value) => (value + 1) % cards.length), 1800); + return () => window.clearInterval(timer); + }, [cards.length]); + const card = cards[index % Math.max(1, cards.length)]; + if (!card) return null; + return ( + + + {card.icon} + + + ); +} + +/* ---------- Component ---------- */ + +export function ScrollDeck({ + cards, + intro, + introNote, + headline, + subtitle, + actions, + scroll = "contained", + length = 3.4, + theme = "light", + className = "", +}: ScrollDeckProps) { + const root = React.useRef(null); + const track = React.useRef(null); + const stage = React.useRef(null); + const layer = React.useRef(null); + const introRef = React.useRef(null); + const hint = React.useRef(null); + const copy = React.useRef(null); + const wordRefs = React.useRef<(HTMLSpanElement | null)[]>([]); + const extras = React.useRef<(HTMLDivElement | null)[]>([]); + const cardRefs = React.useRef<(HTMLDivElement | null)[]>([]); + const shadowRefs = React.useRef<(HTMLDivElement | null)[]>([]); + const sheenRefs = React.useRef<(HTMLDivElement | null)[]>([]); + const pointer = React.useRef({ x: 0, y: 0 }); + const dark = theme === "dark"; + const contained = scroll === "contained"; + const count = cards.length; + const lead = words(headline[0]); + const trail = words(headline[1]); + + React.useEffect(() => { + const box = root.current; + const view = stage.current; + const space = track.current; + const cardLayer = layer.current; + if (!box || !view || !space || !cardLayer) return; + const still = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false; + const mid = (count - 1) / 2; + let width = 0; + let height = 0; + let cardWidth = 0; + let narrow = false; + let target = 0; + let shown = 0; + let frame = 0; + let previous = 0; + let visible = true; + let born = -1; // when the cards started rising in, in seconds + const eased = { x: 0, y: 0 }; + + // Slot order on the intro fan is shifted by one from the final fan, so cards cross as they sweep. + const introPose = (index: number): Pose => { + const slot = ((index + 1) % count) - mid; + const step = Math.abs(slot); + const drop = step < INTRO_DROP.length ? INTRO_DROP[step] : INTRO_DROP[INTRO_DROP.length - 1] + (step - 3) * 0.06; + return [slot * (narrow ? 0.15 : 0.11) * width, (0.35 + drop) * height, slot * 5]; + }; + const scatterPose = (index: number): Pose => { + const table = narrow ? SCATTER_NARROW : SCATTER; + const [x, y, r] = table[index % table.length]; + const flip = Math.floor(index / table.length) % 2 ? -1 : 1; // past seven cards, mirror the set + return [x * flip * width, y * height, r * flip]; + }; + const fan = () => { + const radius = height * (narrow ? 0.8 : 1.18); + const pivot = height * (narrow ? 0.62 : 0.6) + (cardWidth * 4) / 3 / 2 + radius - height / 2; + return { radius, pivot, spread: narrow ? 9 : 10.5 }; + }; + const fanPose = (index: number): Pose => { + const { radius, pivot, spread } = fan(); + const angle = (index - mid) * spread; + const radians = (angle * Math.PI) / 180; + return [Math.sin(radians) * radius, pivot - Math.cos(radians) * radius, angle]; + }; + + const measure = () => { + if (contained) { + space.style.height = `${box.clientHeight * (length + 1)}px`; + view.style.height = `${box.clientHeight}px`; + } + width = view.clientWidth; + height = view.clientHeight; + narrow = width < 768; + cardWidth = narrow ? Math.min(150, Math.max(104, width * 0.3)) : Math.min(236, Math.max(112, width * 0.15)); + view.style.setProperty("--cw", `${cardWidth}px`); + view.style.setProperty("--stage-w", `${width}px`); + cardLayer.style.perspective = `${(10 * height) / VIEW_HEIGHT}px`; + }; + + const progress = () => { + if (contained) return clamp01(box.scrollTop / Math.max(1, box.scrollHeight - box.clientHeight)); + const rect = space.getBoundingClientRect(); + return clamp01(-rect.top / Math.max(1, rect.height - window.innerHeight)); + }; + + const render = (now: number) => { + if (!width || !height) return; + const t = shown * END; + const unit = height / VIEW_HEIGHT; // pixels per camera unit + const age = born < 0 ? 0 : now - born; + + // The cards: intro → scatter (centre first) → fan (edges first) → the fan turns. + const spread = ease.out4(beat(t, 0.25, 1.7)) * (1 - ease.inOut4(beat(t, 2.7, 1.3))); + const turn = -14 * ease.sine(beat(t, 4.3, 1.4)); + const turnRadians = (turn * Math.PI) / 180; + const { pivot } = fan(); + const ranks = Array.from({ length: count }, (_, index) => Math.abs(index - mid)); + cardRefs.current.forEach((element, index) => { + if (!element) return; + const out = ease.out4(beat(t, 0.25 + 0.04 * ranks[index], 1.7)); + const back = ease.inOut4(beat(t, 2.7 + 0.05 * (mid - ranks[index]), 1.5)); + const a = introPose(index); + const b = scatterPose(index); + const c = fanPose(index); + let x = mix(mix(a[0], b[0], out), c[0], back); + let y = mix(mix(a[1], b[1], out), c[1], back); + const rotation = mix(mix(a[2], b[2], out), c[2], back) + turn; + const scale = mix(mix(1, narrow ? 1 : 1.05, out), 1, back); + // Turn the fan around its pivot below the stage. + const dy = y - pivot; + [x, y] = [x * Math.cos(turnRadians) - dy * Math.sin(turnRadians), pivot + x * Math.sin(turnRadians) + dy * Math.cos(turnRadians)]; + + // Depth and tilt, as a camera would see a card in 3D. + const [tiltBack, twist, depth] = TUMBLE[index % TUMBLE.length]; + const base = 0.07 * index; + const z = base + spread * depth; + const fit = (10 - base) / 10; // keep the base stack the same size on screen + const delay = 0.05 + 0.075 * ranks[index]; + const rise = still ? 0 : Math.pow(1 - clamp01((age - delay) / 1.25), 4); + const spin = still ? 0 : Math.pow(1 - clamp01((age - delay) / 1.6), 3); + const wobble = still ? 0 : 0.018 + 0.06 * spread; + const tiltX = mix(0.12, tiltBack, spread) + 0.14 * eased.y + Math.sin(0.7 * now + 1.7 * index) * wobble; + const tiltY = mix(0, twist, spread) + 0.2 * eased.x + Math.cos(0.55 * now + 2.3 * index) * wobble - 2.4 * spin; + const px = x * fit + eased.x * z * 0.06 * unit; + const py = y * fit + rise * 0.85 * height + eased.y * z * 0.04 * unit; + element.style.transform = `translate(-50%, -50%) translate3d(${px.toFixed(1)}px, ${py.toFixed(1)}px, ${(z * unit).toFixed(1)}px) rotateX(${(-tiltX).toFixed(4)}rad) rotateY(${tiltY.toFixed(4)}rad) rotateZ(${((rotation * Math.PI) / 180 - 0.35 * rise).toFixed(4)}rad) scale(${(scale * fit).toFixed(4)})`; + + // A soft contact shadow, squashed as the card turns away. + const shadow = shadowRefs.current[index]; + if (shadow) { + const sx = Math.max(0.35, Math.abs(Math.cos(tiltY))); + const sy = Math.max(0.35, Math.abs(Math.cos(tiltX))); + shadow.style.transform = `translate(-50%, -50%) translate(${x.toFixed(1)}px, ${(y + 0.035 * cardWidth * (1 + z) + cardWidth * 0.1 + rise * height).toFixed(1)}px) rotate(${rotation.toFixed(2)}deg) scale(${sx.toFixed(3)}, ${sy.toFixed(3)})`; + shadow.style.opacity = String(((dark ? 0.5 : 0.22) * (1 - rise) * (1 - 0.35 * spread)).toFixed(3)); + } + const sheen = sheenRefs.current[index]; + if (sheen) sheen.style.backgroundPosition = `${(50 + tiltY * 70 - tiltX * 30).toFixed(1)}% 0`; + }); + + // The intro line blows away; the scroll hint fades. + const gone = ease.in3(beat(t, 0, 1.2)); + if (introRef.current) { + introRef.current.style.opacity = String(1 - gone); + introRef.current.style.transform = `translateY(${-120 * gone}%) scale(${1 - 0.4 * gone})`; + introRef.current.style.filter = gone > 0.01 ? `blur(${(10 * gone).toFixed(1)}px)` : ""; + } + if (hint.current) { + const fade = beat(t, 0, 0.4); + hint.current.style.opacity = String(1 - fade); + hint.current.style.transform = `translateY(${20 * fade}px)`; + } + + // The headline reveals word by word, then its subtitle and actions, then rises. + wordRefs.current.forEach((element, index) => { + if (!element) return; + const reveal = ease.out4(beat(t, 1.3 + 0.06 * index, 0.7)); + element.style.opacity = String(reveal); + element.style.transform = `translateY(${(70 * (1 - reveal)).toFixed(1)}%)`; + element.style.filter = reveal < 0.99 ? `blur(${(8 * (1 - reveal)).toFixed(1)}px)` : ""; + }); + extras.current.forEach((element, index) => { + if (!element) return; + const reveal = 1 - Math.pow(1 - beat(t, 2.1 + 0.12 * index, 0.6), 3); + element.style.opacity = String(reveal); + element.style.transform = `translateY(${(24 * (1 - reveal)).toFixed(1)}px)`; + }); + if (copy.current) { + const rise = ease.inOut4(beat(t, 2.7, 1.3)); + copy.current.style.transform = `translateY(${(-rise * height * (narrow ? 0.15 : 0.18)).toFixed(1)}px)`; + copy.current.style.pointerEvents = t > 1.6 ? "auto" : "none"; + } + }; + + const tick = (time: number) => { + frame = requestAnimationFrame(tick); + const now = time / 1000; + const dt = previous ? Math.min(0.05, now - previous) : 1 / 60; + previous = now; + if (!visible) return; + if (born < 0) born = now; + shown = still ? target : shown + (target - shown) * (1 - Math.exp(-dt * SCRUB)); + if (Math.abs(target - shown) < 0.0002) shown = target; + const follow = 1 - Math.pow(0.002, dt); + eased.x += (pointer.current.x - eased.x) * follow; + eased.y += (pointer.current.y - eased.y) * follow; + render(now); + }; + + const onScroll = () => { target = progress(); }; + measure(); + target = progress(); + shown = target; + render(performance.now() / 1000); + const sizer = new ResizeObserver(() => { measure(); render(performance.now() / 1000); }); + sizer.observe(box); + const watcher = new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; }); + watcher.observe(view); + const source: HTMLElement | Window = contained ? box : window; + source.addEventListener("scroll", onScroll, { passive: true }); + frame = requestAnimationFrame(tick); + return () => { + cancelAnimationFrame(frame); + sizer.disconnect(); + watcher.disconnect(); + source.removeEventListener("scroll", onScroll); + }; + }, [contained, count, length, dark]); + + const onPointer = (event: React.PointerEvent) => { + const rect = event.currentTarget.getBoundingClientRect(); + pointer.current = { x: ((event.clientX - rect.left) / rect.width) * 2 - 1, y: ((event.clientY - rect.top) / rect.height) * 2 - 1 }; + }; + + const mark = ( + + + + + ); + let wordIndex = 0; + const wordRef = () => { + const index = wordIndex++; + return (element: HTMLSpanElement | null) => { wordRefs.current[index] = element; }; + }; + const renderWords = (list: { text: string; muted: boolean }[]) => + list.map((word, index) => ( + + {word.text}{" "} + + )); + + return ( +
{ pointer.current = { x: 0, y: 0 }; }} + className={`relative w-full ${contained ? "h-full min-h-[30rem] overflow-y-auto overscroll-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden" : ""} ${dark ? "bg-[#0d0e12] text-white" : "bg-[#efefed] text-neutral-950"} ${className}`} + > + +
+
+
+

{intro}

+ {introNote &&
{introNote}
} +
+ +
+

+ {renderWords(lead)} + {" "} + {renderWords(trail)} +

+ {subtitle &&
{ extras.current[0] = element; }} className={`mt-5 max-w-md text-[0.95rem] leading-relaxed opacity-0 ${dark ? "text-white/60" : "text-neutral-600"}`}>{subtitle}
} + {actions &&
{ extras.current[1] = element; }} className="mt-6 flex flex-wrap items-center justify-center gap-3 opacity-0">{actions}
} +
+ + {/* Shadows lie flat under the cards; the cards themselves live in 3D. */} +
+ {cards.map((card, index) => ( +
{ shadowRefs.current[index] = element; }} + className="absolute left-1/2 top-1/2 rounded-[10%] bg-black opacity-0 blur-[14px]" + style={{ width: "var(--cw)", height: "calc(var(--cw) * 4 / 3)" }} + /> + ))} +
+
+ {cards.map((card, index) => ( +
{ cardRefs.current[index] = element; }} + className="absolute left-1/2 top-1/2 will-change-transform" + style={{ width: "var(--cw)", height: "calc(var(--cw) * 4 / 3)", transform: "translate(-50%, -50%) translateY(120vh)" }} + > + { sheenRefs.current[index] = element; }} /> +
+ ))} +
+ + +
+
+
+ ); +} + +export default ScrollDeck; diff --git a/src/library/registry.tsx b/src/library/registry.tsx index 23fecec..931aff0 100644 --- a/src/library/registry.tsx +++ b/src/library/registry.tsx @@ -1,10 +1,12 @@ import type { ComponentType } from "react"; import { componentMarkdown } from "@shared/components"; import { componentMeta, type ComponentMeta } from "@shared/component-meta"; -import { BoltIcon, CodeSquareIcon, GalleryIcon, PaletteIcon } from "@solar-icons/react/bold-duotone"; +import { BoltIcon, ChartSquareIcon, ChatRoundDotsIcon, CodeSquareIcon, GalleryIcon, MapPointIcon, NotebookIcon, PaletteIcon, WalletIcon } from "@solar-icons/react/bold-duotone"; import { DrawALine } from "./items/draw-a-line"; import drawALineSource from "./items/draw-a-line.tsx?raw"; import { IconFolder } from "./items/icon-folder"; +import { ScrollDeck } from "./items/scroll-deck"; +import scrollDeckSource from "./items/scroll-deck.tsx?raw"; import iconFolderSource from "./items/icon-folder.tsx?raw"; import { SplitFooter } from "./items/split-footer"; import splitFooterSource from "./items/split-footer.tsx?raw"; @@ -19,12 +21,16 @@ export interface LibraryItem extends ComponentMeta { /** Packages beyond React and Tailwind CSS. */ dependencies: string[]; usage: string; - /** Bento card size on the library grid. */ - card: "wide" | "tall"; + /** Bento shape on the library grid: big is 2×2, wide 2×1, tall 1×2. */ + card: "big" | "wide" | "tall"; /** Width the component is laid out at before scaling down to fit, for full-width components. */ designWidth?: number; - /** Live demo with sample props; receives the preview canvas theme. */ - Demo: ComponentType<{ theme: CanvasTheme }>; + /** With designWidth: a fixed screen height, so the preview is a whole screen (a hero) scaled to fit. */ + designHeight?: number; + /** Width the grid thumbnail is drawn at before scaling into its card. */ + thumbWidth?: number; + /** Live demo with sample props; receives the canvas theme, and whether it fills the screen. */ + Demo: ComponentType<{ theme: CanvasTheme; fullscreen?: boolean }>; } function FooterDemo() { @@ -80,6 +86,28 @@ function TrainDemo({ theme }: { theme: CanvasTheme }) { ); } +const DECK_CARDS = [ + { name: "Harbor", caption: "harbor.app", icon: , colors: ["#5f8f88", "#3c6660"] }, + { name: "Ledger", caption: "ledger.money", icon: , colors: ["#2a2c3c", "#11121a"] }, + { name: "Plume", caption: "plume.studio", icon: , colors: ["#8b5cf6", "#4c1d95"] }, + { name: "Fieldnote", caption: "fieldnote.io", icon: , colors: ["#3a3a3f", "#1a1414"] }, + { name: "Orbit", caption: "orbit.dev", icon: , colors: ["#1e3a8a", "#0b1640"] }, + { name: "Wayfare", caption: "wayfare.travel", icon: , colors: ["#c2734f", "#7a3a22"] }, + { name: "Quill", caption: "quill.to", icon: , colors: ["#ea7a45", "#b4451c"] }, +] satisfies { name: string; caption: string; icon: React.ReactNode; colors: [string, string] }[]; + +function DeckDemo({ theme }: { theme: CanvasTheme }) { + return ( + + ); +} + /** The library's wording lives in shared/component-meta so the server can describe a page without these demos. */ export const LIBRARY: LibraryItem[] = [ { @@ -126,9 +154,29 @@ export const LIBRARY: LibraryItem[] = [ description="Lay track with your cursor." cargo={[{ icon: , color: "#6d28d9", label: "App" }]} />`, - card: "wide", + card: "big", + thumbWidth: 900, Demo: TrainDemo, }, + { + ...componentMeta("scroll-deck")!, + file: "scroll-deck.tsx", + source: scrollDeckSource, + dependencies: [], + usage: `import { ScrollDeck } from "./scroll-deck"; + +, colors: ["#5f8f88", "#3c6660"] }]} +/>`, + card: "big", + designWidth: 1440, + designHeight: 900, + thumbWidth: 1200, + Demo: DeckDemo, + }, ]; export function findItem(slug: string | undefined) { diff --git a/src/pages/Components.tsx b/src/pages/Components.tsx index a4c08e6..b0dca67 100644 --- a/src/pages/Components.tsx +++ b/src/pages/Components.tsx @@ -1,8 +1,9 @@ -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState, type RefObject } from "react"; +import { createPortal } from "react-dom"; import { Link, useParams } from "react-router-dom"; import { AnimatePresence, motion } from "motion/react"; import { Widget4Icon } from "@solar-icons/react/bold-duotone"; -import { AddIcon, AltArrowLeftIcon, AltArrowRightIcon, MagnifierIcon, MoonIcon, RestartIcon, Sun2Icon } from "@solar-icons/react/linear"; +import { AddIcon, AltArrowLeftIcon, AltArrowRightIcon, CloseCircleIcon, FullScreenIcon, MagnifierIcon, MoonIcon, RestartIcon, Sun2Icon } from "@solar-icons/react/linear"; import { AccountCorner } from "@/components/account-corner"; import { Dock } from "@/components/dock"; import { CodeView } from "@/components/library/code-view"; @@ -18,13 +19,19 @@ import { findItem, itemMarkdown, LIBRARY, searchLibrary, type CanvasTheme, type import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 380, damping: 34 } as const; -/** - * Grey cards that complete the grid's last row on wide screens, beside the - * Submit card. Wide cards take 2×2 cells and tall ones 1×2 in the 3-column grid. - * Phones skip them. - */ -const CELLS = LIBRARY.reduce((sum, item) => sum + (item.card === "wide" ? 4 : 2), 0); -const PLACEHOLDERS = (3 - ((CELLS + 1) % 3)) % 3; +/** Bento shapes on the 4-column grid (2 columns on tablets, stacked on phones). */ +const SHAPE: Record = { + big: "sm:col-span-2 sm:row-span-2", + wide: "sm:col-span-2", + tall: "sm:row-span-2", +}; +const CELLS: Record = { big: 4, wide: 2, tall: 2 }; +/** Grey 1×1 cards that, with the Submit card, fill the last rows of the wide-screen bento. */ +const PLACEHOLDERS = (4 - ((LIBRARY.reduce((sum, item) => sum + CELLS[item.card], 0) + 1) % 4)) % 4; +const canvasBackground = (canvas: CanvasTheme) => ({ + backgroundImage: `radial-gradient(${canvas === "dark" ? "rgba(255,255,255,.06)" : "rgba(15,23,42,.08)"} 1px, transparent 1px)`, + backgroundSize: "18px 18px", +}); export default function Components() { usePageMeta(); @@ -72,24 +79,24 @@ function Library() { setSubmitting(true)}>Submit a component ) : ( -
    +
      {results.map((item) => ( + className={SHAPE[item.card]}> ))} {!searching && Array.from({ length: PLACEHOLDERS }, (_, index) => ( -
    • +
    • ))} {!searching && ( -
    • - - -
+ setRun((value) => value + 1)} onExpand={() => setFullscreen(true)} className="absolute right-3 top-3" /> {/* Full-width components keep their real layout and scale down to the canvas. */} {item.designWidth - ? + ? :
}
+ {fullscreen && setFullscreen(false)} />} + @@ -246,6 +243,74 @@ function Detail({ slug }: { slug: string }) { ); } +/** Canvas theme, replay, and full screen (or close, inside full screen), floating over the canvas. */ +function PreviewControls({ canvas, onCanvas, onReplay, onExpand, onClose, closeRef, className }: { + canvas: CanvasTheme; + onCanvas: (canvas: CanvasTheme) => void; + onReplay: () => void; + onExpand?: () => void; + onClose?: () => void; + closeRef?: RefObject; + className?: string; +}) { + const button = cn("flex size-8 items-center justify-center rounded-full transition-colors", canvas === "dark" ? "hover:bg-white/10 hover:text-white" : "hover:bg-black/[0.06] hover:text-slate-900"); + return ( +
+ + + {onExpand && ( + + )} + {onClose && ( + + )} +
+ ); +} + +/** The component on its own, filling the screen. Esc or the close button returns to the page. */ +function FullscreenPreview({ item, canvas, onCanvas, onClose }: { item: LibraryItem; canvas: CanvasTheme; onCanvas: (canvas: CanvasTheme) => void; onClose: () => void }) { + const [run, setRun] = useState(0); + const closeRef = useRef(null); + const close = useRef(onClose); + useEffect(() => { close.current = onClose; }); + + useEffect(() => { + const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null; + closeRef.current?.focus(); + const overflow = document.body.style.overflow; + document.body.style.overflow = "hidden"; + const key = (event: KeyboardEvent) => { if (event.key === "Escape") close.current(); }; + document.addEventListener("keydown", key); + return () => { + document.body.style.overflow = overflow; + document.removeEventListener("keydown", key); + opener?.focus(); + }; + }, []); + + return createPortal( +
+ setRun((value) => value + 1)} onClose={onClose} closeRef={closeRef} className="fixed right-4 top-[calc(1rem+env(safe-area-inset-top))]" /> +
+ {/* A whole-screen design (a hero) takes the real screen here; full-width pieces still scale to fit. */} + {item.designWidth && !item.designHeight + ? + : } +
+
, + document.body, + ); +} + /** Every component in a sticky column at the far left, for scrolling between them on wide screens. */ function ComponentNav({ current }: { current: string }) { return ( diff --git a/tests/component-library.test.tsx b/tests/component-library.test.tsx index 0aeb9d8..7ec709f 100644 --- a/tests/component-library.test.tsx +++ b/tests/component-library.test.tsx @@ -168,6 +168,26 @@ describe("component library page", () => { expect(findItem("draw-a-line")!.source).toContain("export function DrawALine"); }); + it("shows Scroll Deck with its cards and both headlines", () => { + expect(searchLibrary("scroll").map((item) => item.slug)).toContain("scroll-deck"); + mount("/components/scroll-deck"); + expect(screen.getByRole("heading", { level: 1, name: "Scroll Deck" })).toBeTruthy(); + expect(screen.getByRole("heading", { level: 2, name: "We build apps." })).toBeTruthy(); + expect(screen.getByRole("heading", { level: 2, name: /real problem.*actually use\./ })).toBeTruthy(); + expect(screen.getAllByText("Harbor").length).toBeGreaterThan(0); + }); + + it("opens a component full screen and closes it with Escape", async () => { + const user = userEvent.setup(); + mount("/components/scroll-deck"); + await user.click(screen.getByRole("button", { name: "Full screen" })); + const dialog = screen.getByRole("dialog", { name: "Scroll Deck, full screen" }); + expect(within(dialog).getByRole("heading", { level: 2, name: "We build apps." })).toBeTruthy(); + expect(document.activeElement).toBe(within(dialog).getByRole("button", { name: "Close full screen" })); + await user.keyboard("{Escape}"); + expect(screen.queryByRole("dialog", { name: "Scroll Deck, full screen" })).toBeNull(); + }); + it("explains a missing component", () => { mount("/components/does-not-exist"); expect(screen.getByText("This component isn't here")).toBeTruthy();