diff --git a/api/component-image.ts b/api/component-image.ts index 4c0e123..b2f5cae 100644 --- a/api/component-image.ts +++ b/api/component-image.ts @@ -1,13 +1,15 @@ import { apiHandler } from "../server/api-security.js"; -import { componentShareCard } from "../server/component-seo.js"; +import { componentScreenshot, componentShareCard } from "../server/component-seo.js"; import { shareImage } from "../server/forum-image.js"; import { HttpError } from "../server/http.js"; export function GET(req: Request) { return apiHandler(req, async () => { - const preview = componentShareCard(new URL(req.url).searchParams.get("slug") ?? ""); + const slug = new URL(req.url).searchParams.get("slug") ?? ""; + const preview = componentShareCard(slug); if (!preview) throw new HttpError(404, "component_missing", "This component is unavailable."); - const bytes = await shareImage(preview.key, preview.card); + // A real picture of the component when one has been captured; the text card otherwise. + const bytes = await componentScreenshot(slug) ?? await shareImage(preview.key, preview.card); return new Response(new Uint8Array(bytes), { headers: { "content-type": "image/png", "content-length": String(bytes.length), "cache-control": "public, max-age=300", "content-disposition": "inline", "content-security-policy": "sandbox; default-src 'none'", diff --git a/package.json b/package.json index a27f69e..600ef47 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "build:server": "vite build --ssr server/node-server.ts --outDir dist-server --emptyOutDir", "start": "node dist-server/node-server.js", "db:migrate": "tsx scripts/migrate.ts", + "og:components": "tsx scripts/capture-component-og.ts", "test:postgres": "tsx scripts/test-postgres.ts" }, "dependencies": { diff --git a/scripts/capture-component-og.ts b/scripts/capture-component-og.ts new file mode 100644 index 0000000..6767f74 --- /dev/null +++ b/scripts/capture-component-og.ts @@ -0,0 +1,132 @@ +/** + * Photographs each library component for its share image. + * + * corepack pnpm og:components # every component + * corepack pnpm og:components draw-a-line # just one + * + * Starts the Vite dev server, opens /components/?og=1 in headless Chrome (your own install; + * set CHROME_PATH if it isn't in the usual place), waits for the page to signal it's ready, and + * saves a 1200 × 630 PNG to public/og/components/.png. It then rewrites + * shared/component-og.ts with a short hash of each picture so share links refresh when one changes. + * No packages beyond what the project already uses. + */ +import { spawn, type ChildProcess } from "node:child_process"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createServer } from "vite"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const output = path.join(root, "public", "og", "components"); +const manifest = path.join(root, "shared", "component-og.ts"); +const WIDTH = 1200; +const HEIGHT = 630; +const READY_TIMEOUT_MS = 30_000; + +function chromePath() { + const candidates = [ + process.env.CHROME_PATH, + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + "/usr/bin/google-chrome", + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + ].filter((candidate): candidate is string => Boolean(candidate)); + const found = candidates.find((candidate) => existsSync(candidate)); + if (!found) throw new Error("Chrome wasn't found. Set CHROME_PATH to your Chrome or Chromium executable."); + return found; +} + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** A tiny Chrome DevTools Protocol client over the page's WebSocket. */ +async function connect(port: number) { + let target: { webSocketDebuggerUrl: string } | undefined; + for (let attempt = 0; attempt < 50 && !target; attempt++) { + try { + const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json() as { type: string; webSocketDebuggerUrl: string }[]; + target = targets.find((entry) => entry.type === "page"); + } catch { + // Chrome is still starting. + } + if (!target) await sleep(200); + } + if (!target) throw new Error("Couldn't reach headless Chrome."); + const socket = new WebSocket(target.webSocketDebuggerUrl); + await new Promise((resolve, reject) => { socket.addEventListener("open", resolve, { once: true }); socket.addEventListener("error", reject, { once: true }); }); + let id = 0; + const pending = new Map; error?: { message: string } }) => void>(); + const errors: string[] = []; + socket.addEventListener("message", (event) => { + const message = JSON.parse(String(event.data)); + if (message.id && pending.has(message.id)) { pending.get(message.id)!(message); pending.delete(message.id); } + if (message.method === "Runtime.exceptionThrown") errors.push(message.params.exceptionDetails.exception?.description ?? message.params.exceptionDetails.text); + }); + const send = (method: string, params: Record = {}) => new Promise>((resolve, reject) => { + const call = ++id; + pending.set(call, (message) => (message.error ? reject(new Error(`${method}: ${message.error.message}`)) : resolve(message.result ?? {}))); + socket.send(JSON.stringify({ id: call, method, params })); + }); + return { send, errors, close: () => socket.close() }; +} + +async function main() { + const only = process.argv.slice(2); + const server = await createServer({ root, logLevel: "warn", server: { port: 5390, strictPort: false } }); + await server.listen(); + const base = server.resolvedUrls?.local[0] ?? "http://localhost:5390/"; + const profile = mkdtempSync(path.join(tmpdir(), "opencircle-og-")); + let chrome: ChildProcess | undefined; + try { + const { COMPONENT_META } = await server.ssrLoadModule("/shared/component-meta.ts") as typeof import("../shared/component-meta"); + const { COMPONENT_SCREENSHOTS } = await server.ssrLoadModule("/shared/component-og.ts") as typeof import("../shared/component-og"); + const slugs = COMPONENT_META.map((component) => component.slug).filter((slug) => !only.length || only.includes(slug)); + const unknown = only.filter((slug) => !COMPONENT_META.some((component) => component.slug === slug)); + if (unknown.length) throw new Error(`Unknown component: ${unknown.join(", ")}`); + + const port = 9300 + Math.floor(Math.random() * 400); + chrome = spawn(chromePath(), ["--headless=new", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--no-first-run", "--hide-scrollbars", "--force-color-profile=srgb", "--enable-unsafe-swiftshader", "about:blank"], { stdio: "ignore" }); + const page = await connect(port); + await page.send("Page.enable"); + await page.send("Runtime.enable"); + await page.send("Emulation.setDeviceMetricsOverride", { width: WIDTH, height: HEIGHT, deviceScaleFactor: 1, mobile: false }); + await page.send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-reduced-motion", value: "no-preference" }] }); + + mkdirSync(output, { recursive: true }); + const hashes: Record = { ...COMPONENT_SCREENSHOTS }; + for (const slug of slugs) { + await page.send("Page.navigate", { url: new URL(`components/${slug}?og=1`, base).href }); + const started = Date.now(); + let ready = false; + while (!ready && Date.now() - started < READY_TIMEOUT_MS) { + await sleep(250); + const result = await page.send("Runtime.evaluate", { expression: "window.__ogReady === true", returnByValue: true }) as { result?: { value?: boolean } }; + ready = result.result?.value === true; + } + if (!ready) throw new Error(`${slug} didn't signal it was ready within ${READY_TIMEOUT_MS / 1000}s.${page.errors.length ? ` Page errors: ${page.errors.join(" | ")}` : ""}`); + const shot = await page.send("Page.captureScreenshot", { format: "png", clip: { x: 0, y: 0, width: WIDTH, height: HEIGHT, scale: 1 } }) as { data: string }; + const bytes = Buffer.from(shot.data, "base64"); + writeFileSync(path.join(output, `${slug}.png`), bytes); + hashes[slug] = createHash("sha256").update(bytes).digest("hex").slice(0, 12); + console.log(`${slug}: public/og/components/${slug}.png (${Math.round(bytes.length / 1024)} KB)`); + } + page.close(); + + const current = readFileSync(manifest, "utf8"); + const entries = Object.keys(hashes).sort().map((slug) => ` ${JSON.stringify(slug)}: ${JSON.stringify(hashes[slug])},`).join("\n"); + const next = current.replace(/export const COMPONENT_SCREENSHOTS[^=]*= \{[\s\S]*?\};/, `export const COMPONENT_SCREENSHOTS: Readonly> = {\n${entries}\n};`); + writeFileSync(manifest, next); + console.log(`Updated shared/component-og.ts for ${slugs.length} component${slugs.length === 1 ? "" : "s"}.`); + } finally { + chrome?.kill(); + await server.close(); + rmSync(profile, { recursive: true, force: true }); + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error); + process.exit(1); +}); diff --git a/server/component-seo.ts b/server/component-seo.ts index 637a501..d9decf7 100644 --- a/server/component-seo.ts +++ b/server/component-seo.ts @@ -1,4 +1,7 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; import { componentMeta, componentSlugFromPath } from "../shared/component-meta.js"; +import { COMPONENT_SCREENSHOTS } from "../shared/component-og.js"; import { componentImageVersion, componentSeoDocument } from "../shared/component-seo.js"; import type { SeoDocument } from "../shared/seo.js"; import type { ShareCard } from "./forum-image.js"; @@ -16,3 +19,19 @@ export function componentShareCard(slug: string): { key: string; card: ShareCard card: { label: "Component", title: component.name, description: component.description, author: component.tags.map((tag) => `#${tag}`).join(" "), category: component.category }, }; } + +/** + * The captured picture of a component (public/og/components/.png), when one has been taken. + * Built sites serve it from dist/, development from public/. Only known slugs reach the file system. + */ +export async function componentScreenshot(slug: string): Promise { + if (!componentMeta(slug) || !COMPONENT_SCREENSHOTS[slug]) return null; + for (const folder of ["dist", "public"]) { + try { + return await readFile(path.resolve(process.cwd(), folder, "og", "components", `${slug}.png`)); + } catch { + // Try the next location. + } + } + return null; +} diff --git a/shared/component-meta.ts b/shared/component-meta.ts index 967e1ae..3957c1d 100644 --- a/shared/component-meta.ts +++ b/shared/component-meta.ts @@ -6,6 +6,8 @@ export interface ComponentMeta { category: string; tags: string[]; credit?: string; + /** Where the credit points, shown as a link beside it. */ + creditUrl?: string; } export const COMPONENT_META: readonly ComponentMeta[] = [ @@ -31,6 +33,8 @@ export const COMPONENT_META: readonly ComponentMeta[] = [ description: "A toy train set on a tilted table. Move across it to lay track; the train follows, climbs a bridge wherever you cross your own line and puffs your app icons onto the table. It all fades once you stop.", category: "Motion", tags: ["train", "2.5d", "canvas", "interactive"], + credit: "Inspired by the Draw a line section on tekcify.com.", + creditUrl: "https://tekcify.com/", }, { slug: "scroll-deck", @@ -38,6 +42,8 @@ export const COMPONENT_META: readonly ComponentMeta[] = [ 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"], + credit: "Motion rebuilt from the tekcify.com hero.", + creditUrl: "https://tekcify.com/", }, ]; diff --git a/shared/component-og.ts b/shared/component-og.ts new file mode 100644 index 0000000..96bdf0b --- /dev/null +++ b/shared/component-og.ts @@ -0,0 +1,6 @@ +/** + * Generated by `corepack pnpm og:components` (scripts/capture-component-og.mjs); don't edit by hand. + * A short hash of each component's captured share image in public/og/components/.png. + * A component missing here falls back to the text share card. + */ +export const COMPONENT_SCREENSHOTS: Readonly> = {}; diff --git a/shared/component-seo.ts b/shared/component-seo.ts index f53066e..9572b59 100644 --- a/shared/component-seo.ts +++ b/shared/component-seo.ts @@ -1,11 +1,13 @@ import { BRAND_NAME, DEFAULT_SITE_URL } from "./brand.js"; import type { ComponentMeta } from "./component-meta.js"; +import { COMPONENT_SCREENSHOTS } from "./component-og.js"; import { shareImageVersion } from "./share-image.js"; import { seoDocument, type SeoDocument } from "./seo.js"; -/** Changes with the card's wording, so an edited description is not served from a cached image. */ -export function componentImageVersion(component: Pick): string { - return shareImageVersion(component.name, component.description, component.category, ...component.tags); +/** Changes with the card's wording or a new screenshot, so neither is served from a cached image. */ +export function componentImageVersion(component: Pick & { slug?: string }): string { + const screenshot = component.slug ? COMPONENT_SCREENSHOTS[component.slug] : undefined; + return shareImageVersion(component.name, component.description, component.category, ...component.tags, ...(screenshot ? [screenshot] : [])); } export function componentSeoDocument(component: ComponentMeta, origin = DEFAULT_SITE_URL): SeoDocument { diff --git a/src/components/library/scaled-preview.tsx b/src/components/library/scaled-preview.tsx index 98dd5f3..abe3e35 100644 --- a/src/components/library/scaled-preview.tsx +++ b/src/components/library/scaled-preview.tsx @@ -2,17 +2,27 @@ 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 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. + * full-width component keeps its real layout in a smaller frame. + * + * - `height`: a fixed design height too (a whole screen, like a hero); the frame takes its scaled height. + * - `fill`: the content gets the frame's own (scaled) height to fill. Default for non-interactive previews. + * - otherwise the frame takes the scaled height of the content. + * - `interactive`: stays usable; without it the preview is purely visual (inert, ignores the pointer). */ -export function ScaledPreview({ width, height: designHeight, children, className, interactive = false }: { width: number; height?: number; children: ReactNode; className?: string; interactive?: boolean }) { +export function ScaledPreview({ width, height: designHeight, children, className, interactive = false, fill = !interactive }: { + width: number; + height?: number; + children: ReactNode; + className?: string; + interactive?: boolean; + fill?: 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); + const sized = Boolean(designHeight) || !fill; useLayoutEffect(() => { const element = frame.current; @@ -23,24 +33,24 @@ export function ScaledPreview({ width, height: designHeight, children, className if (next <= 0) return; setScale(next); if (designHeight) setHeight(designHeight * next); - else if (interactive) setHeight(inner.offsetHeight * next); - else setFrameHeight(element.clientHeight / next); + else if (fill) setFrameHeight(element.clientHeight / next); + else setHeight(inner.offsetHeight * next); }; update(); const observer = new ResizeObserver(update); observer.observe(element); observer.observe(inner); return () => observer.disconnect(); - }, [width, designHeight, interactive]); + }, [width, designHeight, fill]); return (
-
+
{children}
diff --git a/src/library/items/scroll-deck.tsx b/src/library/items/scroll-deck.tsx index 58c073c..7a32802 100644 --- a/src/library/items/scroll-deck.tsx +++ b/src/library/items/scroll-deck.tsx @@ -377,7 +377,7 @@ export function ScrollDeck({ ref={root} onPointerMove={onPointer} onPointerLeave={() => { 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}`} + className={`relative w-full ${contained ? "h-full min-h-[30rem] overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden" : ""} ${dark ? "bg-[#0d0e12] text-white" : "bg-[#efefed] text-neutral-950"} ${className}`} >
diff --git a/src/library/registry.tsx b/src/library/registry.tsx index 931aff0..b7ab843 100644 --- a/src/library/registry.tsx +++ b/src/library/registry.tsx @@ -21,14 +21,23 @@ export interface LibraryItem extends ComponentMeta { /** Packages beyond React and Tailwind CSS. */ dependencies: string[]; usage: string; - /** Bento shape on the library grid: big is 2×2, wide 2×1, tall 1×2. */ - card: "big" | "wide" | "tall"; + /** + * Its tile on the 6-column library grid: how many columns it spans (6, 4 or 2), and the preview's + * natural width ÷ height. Tiles without an aspect take their row's height, so pair them with one that has it. + */ + card: { span: 2 | 4 | 6; aspect?: number }; /** Width the component is laid out at before scaling down to fit, for full-width components. */ designWidth?: number; /** 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; + /** + * How the share-image capture shows it off (scripts/capture-component-og.mjs). + * `pointer`: a path in fractions of the frame, traced with the mouse over `duration` ms. + * `scroll`: scroll the component's own scroller to this fraction. `settle`: ms to wait before the shot. + */ + og?: { pointer?: [number, number][]; duration?: number; scroll?: number; settle?: number }; /** Live demo with sample props; receives the canvas theme, and whether it fills the screen. */ Demo: ComponentType<{ theme: CanvasTheme; fullscreen?: boolean }>; } @@ -36,6 +45,7 @@ export interface LibraryItem extends ComponentMeta { function FooterDemo() { return ( `, - card: "wide", + card: { span: 6, aspect: 1200 / 430 }, designWidth: 1200, Demo: FooterDemo, }, @@ -139,7 +149,7 @@ export const LIBRARY: LibraryItem[] = [ theme="dark" icons={[{ src: "/figma.png", label: "Figma" }, { src: "/linear.png", label: "Linear" }]} />`, - card: "tall", + card: { span: 2 }, Demo: FolderDemo, }, { @@ -154,8 +164,9 @@ export const LIBRARY: LibraryItem[] = [ description="Lay track with your cursor." cargo={[{ icon: , color: "#6d28d9", label: "App" }]} />`, - card: "big", + card: { span: 4, aspect: 16 / 9 }, thumbWidth: 900, + og: { pointer: [[0.12, 0.78], [0.3, 0.86], [0.5, 0.7], [0.62, 0.48], [0.8, 0.58], [0.9, 0.82]], duration: 2600, settle: 650 }, Demo: TrainDemo, }, { @@ -171,10 +182,11 @@ export const LIBRARY: LibraryItem[] = [ headline={["~From~ a real problem", "~to~ an app people ~actually~ use."]} cards={[{ name: "Harbor", caption: "harbor.app", icon: , colors: ["#5f8f88", "#3c6660"] }]} />`, - card: "big", + card: { span: 4, aspect: 16 / 10 }, designWidth: 1440, designHeight: 900, thumbWidth: 1200, + og: { scroll: 0.42, settle: 2600 }, Demo: DeckDemo, }, ]; diff --git a/src/pages/Components.tsx b/src/pages/Components.tsx index b0dca67..72c90b3 100644 --- a/src/pages/Components.tsx +++ b/src/pages/Components.tsx @@ -1,6 +1,6 @@ import { useEffect, useMemo, useRef, useState, type RefObject } from "react"; import { createPortal } from "react-dom"; -import { Link, useParams } from "react-router-dom"; +import { Link, useParams, useSearchParams } from "react-router-dom"; import { AnimatePresence, motion } from "motion/react"; import { Widget4Icon } from "@solar-icons/react/bold-duotone"; import { AddIcon, AltArrowLeftIcon, AltArrowRightIcon, CloseCircleIcon, FullScreenIcon, MagnifierIcon, MoonIcon, RestartIcon, Sun2Icon } from "@solar-icons/react/linear"; @@ -19,15 +19,12 @@ import { findItem, itemMarkdown, LIBRARY, searchLibrary, type CanvasTheme, type import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 380, damping: 34 } as const; -/** 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", +/** Columns each tile spans: 6 on wide screens, 2 on tablets, stacked on phones. Heights follow each component's own shape. */ +const SPAN: Record = { + 6: "sm:col-span-2 lg:col-span-6", + 4: "sm:col-span-2 lg:col-span-4", + 2: "lg:col-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", @@ -36,6 +33,9 @@ const canvasBackground = (canvas: CanvasTheme) => ({ export default function Components() { usePageMeta(); const { slug } = useParams(); + const [params] = useSearchParams(); + // The share-image capture opens /components/?og=1 and photographs just the component. + if (slug && params.has("og")) return ; return (
@@ -79,24 +79,17 @@ function Library() { setSubmitting(true)}>Submit a component ) : ( -
    +
      {results.map((item) => ( + className={SPAN[item.card.span]}> ))} - {!searching && Array.from({ length: PLACEHOLDERS }, (_, index) => ( -
    • - - - -
    • - ))} {!searching && ( -
    • -