diff --git a/src/components/community-sections.tsx b/src/components/community-sections.tsx index 05e1cfe..573d7f8 100644 --- a/src/components/community-sections.tsx +++ b/src/components/community-sections.tsx @@ -5,7 +5,7 @@ export function CommunitySections({ section, children, actions, disabled = false const navigate = useNavigate(); return { onChange?.(); navigate(value === "events" ? "/events" : value === "submissions" ? "/community?tab=questions&mine=1" : `/community?tab=${value}`); }}>
- DiscussionsQuestionsEventsMy submissions + DiscussionsQuestionsEventsMy submissions {actions &&
{actions}
}
{children} diff --git a/src/components/library/code-view.tsx b/src/components/library/code-view.tsx index e26135d..e114737 100644 --- a/src/components/library/code-view.tsx +++ b/src/components/library/code-view.tsx @@ -18,15 +18,11 @@ export async function copyText(text: string, done: string) { export function CodeView({ code, label, maxHeight = "32rem" }: { code: string; label: string; maxHeight?: string }) { const [copied, setCopied] = useState(false); const lines = useMemo(() => highlightLines(code.trimEnd()), [code]); - const extension = /\.(\w+)$/.exec(label)?.[1]; return (
- - {extension && {extension}} - {label} - + {label} + + + + + + {open && ( + + {options.map((option) => ( + + ))} + + )} + + + ); +} diff --git a/src/components/library/scaled-preview.tsx b/src/components/library/scaled-preview.tsx index 85347df..75e5ccc 100644 --- a/src/components/library/scaled-preview.tsx +++ b/src/components/library/scaled-preview.tsx @@ -3,14 +3,16 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from "react"; /** * Renders children at a fixed design width and scales them down to fit, so a * full-width component keeps its real layout in a smaller frame. As a card - * thumbnail it's purely visual; with `interactive` it stays usable and the - * frame takes the scaled height of its content. + * thumbnail it's purely visual and the content gets the frame's full (scaled) + * 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 }) { const frame = useRef(null); const content = useRef(null); const [scale, setScale] = useState(0.4); const [height, setHeight] = useState(undefined); + const [frameHeight, setFrameHeight] = useState(undefined); useLayoutEffect(() => { const element = frame.current; @@ -18,8 +20,10 @@ export function ScaledPreview({ width, children, className, interactive = false if (!element || !inner) return; const update = () => { const next = Math.min(1, element.clientWidth / width); + if (next <= 0) return; setScale(next); if (interactive) setHeight(inner.offsetHeight * next); + else setFrameHeight(element.clientHeight / next); }; update(); const observer = new ResizeObserver(update); @@ -35,7 +39,7 @@ export function ScaledPreview({ width, children, className, interactive = false style={interactive ? { height } : undefined} {...(interactive ? {} : { "aria-hidden": true, inert: true })} > -
+
{children}
diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsx index 9ee5def..995960c 100644 --- a/src/components/ui/tabs.tsx +++ b/src/components/ui/tabs.tsx @@ -5,6 +5,7 @@ import { cn } from "@/lib/utils" const Tabs = TabsPrimitive.Root +/** Tab rows stay on one line on every screen; when they don't fit, they slide sideways instead of wrapping. */ const TabsList = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef @@ -12,7 +13,7 @@ const TabsList = React.forwardRef< = points[last].d) return points[last]; + let low = 0; + let high = last; + while (high - low > 1) { + const mid = (low + high) >> 1; + if (points[mid].d <= d) low = mid; + else high = mid; + } + const a = points[low]; + const b = points[high]; + const t = (d - a.d) / (b.d - a.d || 1); + return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t, d }; +} + +function heading(points: Point[], d: number) { + const ahead = at(points, d + 8); + const behind = at(points, d - 8); + return Math.atan2(ahead.y - behind.y, ahead.x - behind.x); +} + +function Engine({ color }: { color: string }) { + return ( + + + + + + + + + + + + + + {[9, 21, 32].map((cx) => ( + + + + + ))} + + ); +} + +function Wagon({ color, cargo }: { color: string; cargo?: TrainCargo }) { + return ( + <> + + + + + + {[9, 27].map((cx) => ( + + + + + ))} + + {cargo && ( + + {cargo.icon} + + )} + + ); +} + +function PuffedIcon({ puff, cargo, onDone }: { puff: Puff; cargo: TrainCargo; onDone: (id: number) => void }) { + const ref = React.useRef(null); + React.useLayoutEffect(() => { + const element = ref.current; + if (!element || typeof element.animate !== "function") { onDone(puff.id); return; } + const place = (x: number, y: number, scale: number, rotate: number) => `translate(${x}px, ${y}px) translate(-50%, -50%) scale(${scale}) rotate(${rotate}deg)`; + const animation = element.animate([ + { transform: place(puff.x, puff.y, 0.3, 0), opacity: 0 }, + { transform: place(puff.x + puff.dx * 0.55, puff.y + puff.dy * 0.55, 1, puff.rot * 0.6), opacity: 0.55, offset: 0.2 }, + { transform: place(puff.x + puff.dx, puff.y + puff.dy, 1, puff.rot), opacity: 0.35, offset: 0.6 }, + { transform: place(puff.x + puff.dx, puff.y + puff.dy - 18, 0.94, puff.rot), opacity: 0 }, + ], { duration: 2400, easing: "cubic-bezier(.2,.8,.3,1)", fill: "forwards" }); + animation.onfinish = () => onDone(puff.id); + return () => animation.cancel(); + }, [puff, onDone]); + + return ( +
+ {cargo.icon} +
+ ); +} + +export function DrawALine({ + title = ["Draw a", "line."], + description = "Lay track with your cursor. The train hauls our apps along it, puffing them out as it goes.", + cargo, + color = "#5b30d6", + theme = "light", + className = "", +}: DrawALineProps) { + const card = React.useRef(null); + const canvas = React.useRef(null); + const cars = React.useRef<(HTMLDivElement | null)[]>([]); + const pointer = React.useRef<{ x: number; y: number } | null>(null); + const lastInput = React.useRef(-Infinity); + const [puffs, setPuffs] = React.useState([]); + const removePuff = React.useCallback((id: number) => setPuffs((all) => all.filter((puff) => puff.id !== id)), []); + const dark = theme === "dark"; + const cargoCount = cargo.length; + + React.useEffect(() => { + const root = card.current; + const surface = canvas.current; + if (!root || !surface) return; + const context = surface.getContext("2d"); + const still = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false; + const ties = dark ? "rgba(255,255,255,.16)" : "rgba(15,23,42,.16)"; + const rails = dark ? "rgba(255,255,255,.72)" : "rgba(24,24,27,.78)"; + + let points: Point[] = []; + let head: { x: number; y: number } | null = null; + let fade = 1; + let s = 0; + let speed = 0; + let travelled = 0; + let flip = 1; + let puffId = 0; + let previous = 0; + let frame = 0; + let visible = true; + let width = 0; + let height = 0; + + const lay = (x: number, y: number) => { + const last = points[points.length - 1]; + if (!last) { points.push({ x, y, d: 0 }); s = 0; return; } + const step = Math.hypot(x - last.x, y - last.y); + if (step >= 4) points.push({ x, y, d: last.d + step }); + }; + + const resize = () => { + const ratio = Math.min(window.devicePixelRatio || 1, 2); + width = root.clientWidth; + height = root.clientHeight; + surface.width = Math.round(width * ratio); + surface.height = Math.round(height * ratio); + context?.setTransform(ratio, 0, 0, ratio, 0, 0); + }; + + const draw = () => { + if (!context) return; + context.clearRect(0, 0, width, height); + if (points.length < 2) return; + context.globalAlpha = fade; + const first = points[0].d; + const end = points[points.length - 1].d; + context.lineCap = "round"; + + // Sleepers sit at fixed distances, so they stay put as the track is trimmed behind the train. + context.strokeStyle = ties; + context.lineWidth = 4; + context.beginPath(); + for (let d = Math.ceil(first / TIE_GAP) * TIE_GAP; d <= end; d += TIE_GAP) { + const p = at(points, d); + const angle = heading(points, d); + const nx = -Math.sin(angle) * TIE_HALF; + const ny = Math.cos(angle) * TIE_HALF; + context.moveTo(p.x - nx, p.y - ny); + context.lineTo(p.x + nx, p.y + ny); + } + context.stroke(); + + context.strokeStyle = rails; + context.lineWidth = 2.4; + context.lineJoin = "round"; + for (const side of [-1, 1]) { + context.beginPath(); + for (let d = first; d <= end + 4.9; d += 5) { + const p = at(points, Math.min(d, end)); + const angle = heading(points, Math.min(d, end)); + const x = p.x - Math.sin(angle) * GAUGE * side; + const y = p.y + Math.cos(angle) * GAUGE * side; + if (d === first) context.moveTo(x, y); + else context.lineTo(x, y); + } + context.stroke(); + } + + // Fade the far end of the track out behind the last wagon. + const tail = points[0]; + const tailFade = context.createRadialGradient(tail.x, tail.y, 0, tail.x, tail.y, 70); + tailFade.addColorStop(0, "rgba(0,0,0,1)"); + tailFade.addColorStop(1, "rgba(0,0,0,0)"); + context.globalCompositeOperation = "destination-out"; + context.fillStyle = tailFade; + context.fillRect(tail.x - 70, tail.y - 70, 140, 140); + context.globalCompositeOperation = "source-over"; + context.globalAlpha = 1; + }; + + const place = () => { + const ready = points.length > 1; + const first = ready ? points[0].d : 0; + if (ready) { + // Keep the train upright: past vertical it turns around instead of riding upside down. + const cos = Math.cos(heading(points, s - CARS[0].back)); + if (cos < -0.2) flip = -1; + else if (cos > 0.2) flip = 1; + } + CARS.forEach((car, index) => { + const element = cars.current[index]; + if (!element) return; + const d = s - car.back; + const shown = ready && d - car.width / 2 >= first; + element.style.opacity = shown ? String(fade) : "0"; + if (!ready) return; + const p = at(points, d); + const angle = heading(points, d); + element.style.transform = `translate(${p.x}px, ${p.y}px) rotate(${angle}rad) scale(1, ${flip}) translate(${-car.width / 2}px, ${-car.rail}px)`; + }); + }; + + const puff = () => { + if (still || !cargoCount) return; + const nose = at(points, s - CARS[0].back); + const angle = heading(points, s - CARS[0].back); + // The chimney sits a little forward of the engine's centre, above the track. + const x = nose.x + Math.cos(angle) * 4 + Math.sin(angle) * 22 * flip; + const y = nose.y + Math.sin(angle) * 4 - Math.cos(angle) * 22 * flip; + const id = ++puffId; + setPuffs((all) => [...all.slice(-7), { + id, x, y, + dx: (Math.random() - 0.5) * 180, + dy: -70 - Math.random() * 90, + rot: (Math.random() - 0.5) * 50, + cargo: id % cargoCount, + }]); + }; + + const step = (time: number) => { + frame = requestAnimationFrame(step); + const dt = Math.min(0.05, previous ? (time - previous) / 1000 : 0); + previous = time; + if (!visible || document.hidden || width === 0) return; + + // The head of the track eases after the cursor, so quick flicks still lay smooth curves. + const target = pointer.current; + const drawing = performance.now() - lastInput.current <= IDLE_MS; + if (target) { + // Only movement brings the track back; a cursor resting on the card lets it fade. + if (drawing) fade = 1; + const from = head ?? target; + const ease = 1 - Math.exp(-dt * 18); + head = { x: from.x + (target.x - from.x) * ease, y: from.y + (target.y - from.y) * ease }; + lay(head.x, head.y); + } + + if (points.length > 1) { + const goal = Math.max(0, points[points.length - 1].d - LEAD); + const wanted = Math.min(560, Math.max(0, (goal - s) * 2.6)); + speed += (wanted - speed) * (1 - Math.exp(-dt * 4)); + s = Math.min(goal, s + speed * dt); + travelled += speed * dt; + if (travelled > 170 && speed > 60) { travelled = 0; puff(); } + // Drop track the train has left behind. + while (points.length > 2 && points[1].d < s - TAIL) points.shift(); + + // Nobody drawing and the train at rest: fade it all away, then start clean. + if (!drawing && speed < 8) { + fade = Math.max(0, fade - dt / FADE_S); + if (fade === 0) { points = []; head = null; s = 0; speed = 0; travelled = 0; } + } + } + draw(); + place(); + }; + + resize(); + draw(); + place(); + const sizer = new ResizeObserver(() => { resize(); draw(); place(); }); + sizer.observe(root); + const watcher = new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; }); + watcher.observe(root); + frame = requestAnimationFrame(step); + return () => { + cancelAnimationFrame(frame); + sizer.disconnect(); + watcher.disconnect(); + }; + }, [dark, cargoCount]); + + // Pointer position in the card's own pixels, even when the card is drawn scaled. + const track = (event: React.PointerEvent) => { + const root = card.current; + if (!root) return; + const rect = root.getBoundingClientRect(); + const scale = rect.width / (root.offsetWidth || rect.width || 1); + pointer.current = { x: (event.clientX - rect.left) / scale, y: (event.clientY - rect.top) / scale }; + lastInput.current = performance.now(); + }; + const release = () => { pointer.current = null; lastInput.current = performance.now(); }; + + return ( +
+
+

+ {title[0]} {title[1]} +

+ {description &&

{description}

} +
+ + +
+ {CARS.map((car, index) => ( +
{ cars.current[index] = element; }} + className="absolute left-0 top-0 opacity-0 transition-opacity duration-300" + style={{ width: car.width, height: car.height, transformOrigin: "0 0" }} + > + {index === 0 ? : } +
+ ))} + {puffs.map((puff) => )} +
+
+ ); +} + +export default DrawALine; diff --git a/src/library/registry.tsx b/src/library/registry.tsx index 68a1040..3238166 100644 --- a/src/library/registry.tsx +++ b/src/library/registry.tsx @@ -1,6 +1,8 @@ import type { ComponentType } from "react"; import { componentMarkdown } from "@shared/components"; import { BoltIcon, CodeSquareIcon, GalleryIcon, PaletteIcon } 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 iconFolderSource from "./items/icon-folder.tsx?raw"; import { SplitFooter } from "./items/split-footer"; @@ -53,7 +55,7 @@ const tile = (node: React.ReactNode, background: string, label: string) => ({ no function FolderDemo({ theme }: { theme: CanvasTheme }) { return ( -
+
, "linear-gradient(160deg,#a855f7,#6d28d9)", "Colour"), + tile(, "linear-gradient(160deg,#38bdf8,#1d4ed8)", "Media"), + tile(, "linear-gradient(160deg,#34d399,#047857)", "Code"), + tile(, "linear-gradient(160deg,#fbbf24,#ea580c)", "Motion"), + ].map(({ node, background, label }) => ({ icon: node, color: background, label }))} + /> + ); +} + export const LIBRARY: LibraryItem[] = [ { slug: "split-footer", @@ -112,6 +128,25 @@ export const LIBRARY: LibraryItem[] = [ card: "tall", Demo: FolderDemo, }, + { + slug: "draw-a-line", + name: "Draw a Line", + description: "Move across the card to lay track. A little train follows it, puffing your app icons out as it goes, and it all fades once you stop.", + category: "Motion", + tags: ["train", "cursor", "canvas", "interactive"], + file: "draw-a-line.tsx", + source: drawALineSource, + dependencies: [], + usage: `import { DrawALine } from "./draw-a-line"; + +, color: "#6d28d9", label: "App" }]} +/>`, + card: "wide", + Demo: TrainDemo, + }, ]; export function findItem(slug: string | undefined) { diff --git a/src/pages/Components.tsx b/src/pages/Components.tsx index 84eb030..a4c08e6 100644 --- a/src/pages/Components.tsx +++ b/src/pages/Components.tsx @@ -2,24 +2,29 @@ import { useEffect, useMemo, useState } from "react"; 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, CopyIcon, DocumentTextIcon, MagnifierIcon, MoonIcon, RestartIcon, Sun2Icon } from "@solar-icons/react/linear"; +import { AddIcon, AltArrowLeftIcon, AltArrowRightIcon, MagnifierIcon, MoonIcon, RestartIcon, Sun2Icon } from "@solar-icons/react/linear"; import { AccountCorner } from "@/components/account-corner"; import { Dock } from "@/components/dock"; -import { CodeView, copyText } from "@/components/library/code-view"; +import { CodeView } from "@/components/library/code-view"; +import { CopyMenu } from "@/components/library/copy-menu"; import { ScaledPreview } from "@/components/library/scaled-preview"; import { SubmitDialog } from "@/components/library/submit-dialog"; import { MetalButton } from "@/components/metal-button"; import { SiteFooter } from "@/components/site-footer"; import { EmptyState } from "@/components/ui/empty-state"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; -import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { usePageMeta } from "@/hooks/use-page-meta"; import { findItem, itemMarkdown, LIBRARY, searchLibrary, type CanvasTheme, type LibraryItem } from "@/library/registry"; import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 380, damping: 34 } as const; -/** Grey cards that hold the grid's shape until more components arrive. Phones skip them. */ -const PLACEHOLDERS = 2; +/** + * 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; export default function Components() { usePageMeta(); @@ -28,11 +33,9 @@ export default function Components() {
- -
- {slug ? : } -
-
+
+ {slug ? : } +
@@ -69,7 +72,7 @@ function Library() { setSubmitting(true)}>Submit a component ) : ( -
    +
      {results.map((item) => ( ))} -
      - void copyText(item.source, `${item.file} copied.`)}> - void copyText(itemMarkdown(item), "Markdown copied.")}> -
      + itemMarkdown(item), done: "Markdown copied." }, + { id: "code", label: "Copy code", text: () => item.source, done: `${item.file} copied.` }, + ]} />
@@ -243,19 +246,6 @@ function Detail({ slug }: { slug: string }) { ); } -function IconAction({ label, onClick, children }: { label: string; onClick: () => void; children: React.ReactNode }) { - return ( - - - - {children} - - - {label} - - ); -} - /** 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 88aae94..0aeb9d8 100644 --- a/tests/component-library.test.tsx +++ b/tests/component-library.test.tsx @@ -144,10 +144,15 @@ describe("component library page", () => { expect(within(nav).getByRole("link", { name: /Split Footer/ }).getAttribute("aria-current")).toBe("page"); // userEvent provides the clipboard; read back exactly what was copied. + // One copy button: Markdown by default, code from its menu, which then becomes the default. + await user.click(screen.getByRole("button", { name: "Copy Markdown" })); + expect(await navigator.clipboard.readText()).toBe(itemMarkdown(footer)); + await user.click(screen.getByRole("button", { name: "More copy options" })); + await user.click(screen.getByRole("menuitem", { name: "Copy code" })); + expect(await navigator.clipboard.readText()).toBe(footer.source); + expect(screen.queryByRole("menu")).toBeNull(); await user.click(screen.getByRole("button", { name: "Copy code" })); expect(await navigator.clipboard.readText()).toBe(footer.source); - await user.click(screen.getByRole("button", { name: "Copy as Markdown" })); - expect(await navigator.clipboard.readText()).toBe(itemMarkdown(footer)); await user.click(screen.getByRole("tab", { name: "Code" })); expect(screen.getByLabelText("split-footer.tsx").textContent).toContain("export function SplitFooter"); @@ -155,6 +160,14 @@ describe("component library page", () => { expect(await screen.findByRole("heading", { level: 1, name: "Icon Folder" })).toBeTruthy(); }); + it("shows Draw a Line on its own page and finds it by search", async () => { + expect(searchLibrary("train").map((item) => item.slug)).toEqual(["draw-a-line"]); + mount("/components/draw-a-line"); + expect(screen.getByRole("heading", { level: 1, name: "Draw a Line" })).toBeTruthy(); + expect(screen.getByRole("heading", { level: 2, name: "Draw a line." })).toBeTruthy(); + expect(findItem("draw-a-line")!.source).toContain("export function DrawALine"); + }); + it("explains a missing component", () => { mount("/components/does-not-exist"); expect(screen.getByText("This component isn't here")).toBeTruthy();