Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions api/component-image.ts
Original file line number Diff line number Diff line change
@@ -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'",
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
132 changes: 132 additions & 0 deletions scripts/capture-component-og.ts
Original file line number Diff line number Diff line change
@@ -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/<slug>?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/<slug>.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<number, (message: { result?: Record<string, unknown>; 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<string, unknown> = {}) => new Promise<Record<string, unknown>>((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<string, string> = { ...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<Record<string, string>> = {\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);
});
19 changes: 19 additions & 0 deletions server/component-seo.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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/<slug>.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<Buffer | null> {
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;
}
6 changes: 6 additions & 0 deletions shared/component-meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = [
Expand All @@ -31,13 +33,17 @@ 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",
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"],
credit: "Motion rebuilt from the tekcify.com hero.",
creditUrl: "https://tekcify.com/",
},
];

Expand Down
6 changes: 6 additions & 0 deletions shared/component-og.ts
Original file line number Diff line number Diff line change
@@ -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/<slug>.png.
* A component missing here falls back to the text share card.
*/
export const COMPONENT_SCREENSHOTS: Readonly<Record<string, string>> = {};
8 changes: 5 additions & 3 deletions shared/component-seo.ts
Original file line number Diff line number Diff line change
@@ -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<ComponentMeta, "name" | "description" | "category" | "tags">): 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<ComponentMeta, "name" | "description" | "category" | "tags"> & { 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 {
Expand Down
30 changes: 20 additions & 10 deletions src/components/library/scaled-preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLDivElement>(null);
const content = useRef<HTMLDivElement>(null);
const [scale, setScale] = useState(0.4);
const [height, setHeight] = useState<number | undefined>(undefined);
const [frameHeight, setFrameHeight] = useState<number | undefined>(undefined);
const sized = Boolean(designHeight) || !fill;

useLayoutEffect(() => {
const element = frame.current;
Expand All @@ -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 (
<div
ref={frame}
className={`relative overflow-hidden ${interactive ? "" : "pointer-events-none"} ${className ?? ""}`}
style={interactive || designHeight ? { height } : undefined}
style={sized ? { height } : undefined}
{...(interactive ? {} : { "aria-hidden": true, inert: true })}
>
<div ref={content} className="absolute left-0 top-0 origin-top-left" style={{ width, height: designHeight ?? (interactive ? undefined : frameHeight), transform: `scale(${scale})` }}>
<div ref={content} className="absolute left-0 top-0 origin-top-left" style={{ width, height: designHeight ?? (fill ? frameHeight : undefined), transform: `scale(${scale})` }}>
{children}
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/library/items/scroll-deck.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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}`}
>
<style>{"@keyframes deck-flip{from{transform:rotateX(-90deg);opacity:0}to{transform:rotateX(0);opacity:1}}"}</style>
<div ref={track} style={contained ? undefined : { height: `${(length + 1) * 100}svh` }}>
Expand Down
Loading
Loading