diff --git a/api/component-image.ts b/api/component-image.ts new file mode 100644 index 0000000..4c0e123 --- /dev/null +++ b/api/component-image.ts @@ -0,0 +1,23 @@ +import { apiHandler } from "../server/api-security.js"; +import { 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") ?? ""); + if (!preview) throw new HttpError(404, "component_missing", "This component is unavailable."); + const bytes = 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'", + "cross-origin-resource-policy": "cross-origin", + } }); + }); +} + +export async function HEAD(req: Request) { + const response = await GET(req); + await response.body?.cancel(); + return new Response(null, { status: response.status, headers: response.headers }); +} diff --git a/api/home-image.ts b/api/home-image.ts new file mode 100644 index 0000000..cee9c6f --- /dev/null +++ b/api/home-image.ts @@ -0,0 +1,20 @@ +import { apiHandler } from "../server/api-security.js"; +import { homeImage } from "../server/home-image.js"; +import { readHomeCard } from "../server/home-seo.js"; + +export function GET(req: Request) { + return apiHandler(req, async () => { + const bytes = await homeImage(await readHomeCard()); + 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'", + "cross-origin-resource-policy": "cross-origin", + } }); + }); +} + +export async function HEAD(req: Request) { + const response = await GET(req); + await response.body?.cancel(); + return new Response(null, { status: response.status, headers: response.headers }); +} diff --git a/api/page-image.ts b/api/page-image.ts new file mode 100644 index 0000000..8ccd040 --- /dev/null +++ b/api/page-image.ts @@ -0,0 +1,23 @@ +import { apiHandler } from "../server/api-security.js"; +import { shareImage } from "../server/forum-image.js"; +import { HttpError } from "../server/http.js"; +import { pageShareCard } from "../server/page-seo.js"; + +export function GET(req: Request) { + return apiHandler(req, async () => { + const preview = pageShareCard(new URL(req.url).searchParams.get("path") ?? ""); + if (!preview) throw new HttpError(404, "page_missing", "This page has no share card."); + const bytes = 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'", + "cross-origin-resource-policy": "cross-origin", + } }); + }); +} + +export async function HEAD(req: Request) { + const response = await GET(req); + await response.body?.cancel(); + return new Response(null, { status: response.status, headers: response.headers }); +} diff --git a/docs/api.md b/docs/api.md index e0675ce..b6872fe 100644 --- a/docs/api.md +++ b/docs/api.md @@ -37,6 +37,9 @@ The frontend calls same-origin API routes. Vite serves these during development; | `GET /api/blog-admin?id=ID` | Approved admin session. | One post with its history. | | `POST /api/blog-admin` | Admin session, same-origin JSON and `X-OpenCircle-Admin: 1`. `{ "action": "review", "decision": "approve" \| "changes" \| "reject", "reason" }` or `{ "action": "moderate", "operation": "hide" \| "restore" \| "feature" \| "unfeature", "reason" }`, each with `requestId`, `id` and `version`. | The updated post. Requesting changes and declining need a reason of at least 5 characters; hiding needs at least 3. | | `GET /api/blog-image?slug=SLUG` | None. | A 1200×630 PNG share card for a published post. | +| `GET /api/component-image?slug=SLUG` | None. | A 1200×630 PNG share card for a library component. | +| `GET /api/page-image?path=PATH` | None. | A 1200×630 PNG share card for an indexed page such as `/tools`. | +| `GET /api/home-image` | None. | A 1200×630 PNG of the current top three on the leaderboard. | Admin actions are `hide`, `unhide` and `remove`, with a `login`, or `config`, with complete invite and weight settings. The exact request and response types live in [`shared/types.ts`](../shared/types.ts). diff --git a/server/component-seo.ts b/server/component-seo.ts new file mode 100644 index 0000000..637a501 --- /dev/null +++ b/server/component-seo.ts @@ -0,0 +1,18 @@ +import { componentMeta, componentSlugFromPath } from "../shared/component-meta.js"; +import { componentImageVersion, componentSeoDocument } from "../shared/component-seo.js"; +import type { SeoDocument } from "../shared/seo.js"; +import type { ShareCard } from "./forum-image.js"; + +export function componentPageSeoDocument(pathname: string, origin: string): SeoDocument | null { + const slug = componentSlugFromPath(pathname); + return slug ? componentSeoDocument(componentMeta(slug)!, origin) : null; +} + +export function componentShareCard(slug: string): { key: string; card: ShareCard } | null { + const component = componentMeta(slug); + if (!component) return null; + return { + key: `component:${component.slug}:${componentImageVersion(component)}`, + card: { label: "Component", title: component.name, description: component.description, author: component.tags.map((tag) => `#${tag}`).join(" "), category: component.category }, + }; +} diff --git a/server/forum-image.ts b/server/forum-image.ts index 93e3599..a0a2e06 100644 --- a/server/forum-image.ts +++ b/server/forum-image.ts @@ -8,7 +8,7 @@ import type { ForumSharePreview } from "../shared/forum-seo.js"; const images = new Map>(); let fonts: Promise | undefined; let logo: Promise | undefined; -const text = (value: string, style: CSSProperties) => h("div", { style }, value); +export const text = (value: string, style: CSSProperties) => h("div", { style }, value); /** The text on a 1200×630 link-preview card. */ export interface ShareCard { label: string; title: string; description: string; author: string; category: string } @@ -17,21 +17,41 @@ export function forumImage(preview: ForumSharePreview): Promise { return shareImage(`${preview.id}:${preview.version}`, { label: preview.kind === "question" ? "Question" : "Discussion", title: preview.title, description: preview.description, author: preview.author, category: preview.category }); } -/** Renders once per key; the few most recent cards stay cached. */ export function shareImage(key: string, card: ShareCard): Promise { + return cachedImage(key, () => render(card)); +} + +/** Renders once per key; the few most recent images stay cached. */ +export function cachedImage(key: string, make: () => Promise): Promise { const cached = images.get(key); if (cached) return cached; - const image = render(card).catch(error => { images.delete(key); throw error; }); + const image = make().catch(error => { images.delete(key); throw error; }); images.set(key, image); if (images.size > 24) images.delete(images.keys().next().value!); return image; } -async function render(preview: ShareCard) { +/** The brand fonts and logo every card is drawn with. */ +export async function cardAssets() { fonts ??= Promise.all([400, 600].map(weight => readFile(path.resolve(`public/fonts/Aspekta-${weight}.ttf`)))).catch(error => { fonts = undefined; throw error; }); logo ??= readFile(path.resolve("public/favicon.svg")).then(bytes => `data:image/svg+xml;base64,${bytes.toString("base64")}`).catch(error => { logo = undefined; throw error; }); const [[regular, semibold], logoData] = await Promise.all([fonts, logo]); - const svg = await satori(h("div", { style: { + return { regular, semibold, logoData }; +} + +/** Draws a 1200×630 card from its element tree. */ +export async function renderCard(element: ReturnType, { regular, semibold }: Awaited>) { + const svg = await satori(element, { + width: 1200, height: 630, + fonts: [{ name: "Aspekta", data: regular, weight: 400, style: "normal" }, { name: "Aspekta", data: semibold, weight: 600, style: "normal" }], + }); + return (await renderAsync(svg, { font: { loadSystemFonts: false } })).asPng(); +} + +async function render(preview: ShareCard) { + const assets = await cardAssets(); + const { logoData } = assets; + return renderCard(h("div", { style: { width: 1200, height: 630, position: "relative", display: "flex", backgroundColor: "#04060a", color: "#f4f7fb", fontFamily: "Aspekta", } }, @@ -45,9 +65,5 @@ async function render(preview: ShareCard) { ), h("div", { style: { position: "absolute", bottom: 52, left: 64, width: 1072, height: 44, display: "flex", alignItems: "center", gap: 24, fontSize: 22, color: "#a5afbf" } }, text(preview.author, { maxWidth: 400, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }), text(preview.category, {}), text("opencircle.cc", { marginLeft: "auto" }), - )), { - width: 1200, height: 630, - fonts: [{ name: "Aspekta", data: regular, weight: 400, style: "normal" }, { name: "Aspekta", data: semibold, weight: 600, style: "normal" }], - }); - return (await renderAsync(svg, { font: { loadSystemFonts: false } })).asPng(); + )), assets); } diff --git a/server/home-image.ts b/server/home-image.ts new file mode 100644 index 0000000..ffe1d47 --- /dev/null +++ b/server/home-image.ts @@ -0,0 +1,82 @@ +import { createElement as h } from "react"; +import type { Board } from "../shared/types.js"; +import { cachedImage, cardAssets, renderCard, text } from "./forum-image.js"; + +const GOLD = "#f4c556"; +const MUTED = "#9a9ca3"; +const AVATAR_HOST = "avatars.githubusercontent.com"; +const AVATAR_MAX_BYTES = 512 * 1024; + +export interface PodiumSeat { rank: 1 | 2 | 3; name: string; login: string; score: number; avatarUrl: string } +export interface HomeCard { seats: PodiumSeat[] } + +/** The top three members and the size of the circle, as the card shows them. */ +export function homeCard(board: Pick): HomeCard { + const seats = board.members + .filter((member): member is typeof member & { rank: 1 | 2 | 3 } => member.rank >= 1 && member.rank <= 3) + .sort((a, b) => a.rank - b.rank) + .map((member) => ({ rank: member.rank, name: member.nickname, login: member.login, score: member.score, avatarUrl: member.avatarUrl })); + return { seats }; +} + +export const homeCardKey = (card: HomeCard) => `home:${card.seats.map((seat) => `${seat.login}=${seat.score}`).join(",")}`; + +/** Satori cannot fetch pictures, so avatars are read here and embedded. Anything but a small GitHub avatar is skipped. */ +async function avatarData(url: string): Promise { + try { + const source = new URL(url); + if (source.protocol !== "https:" || source.hostname !== AVATAR_HOST) return null; + source.searchParams.set("s", "160"); + const response = await fetch(source, { redirect: "error", signal: AbortSignal.timeout(3000) }); + const type = response.headers.get("content-type")?.split(";")[0]; + if (!response.ok || (type !== "image/png" && type !== "image/jpeg")) return null; + const bytes = Buffer.from(await response.arrayBuffer()); + return bytes.length <= AVATAR_MAX_BYTES ? `data:${type};base64,${bytes.toString("base64")}` : null; + } catch { return null; } +} + +const svg = (markup: string) => `data:image/svg+xml;base64,${Buffer.from(markup).toString("base64")}`; +const GITHUB_MARK = svg(''); +const CROWN = svg(``); + +/** Column heights, so first place stands tallest. */ +const COLUMN = { 1: 300, 2: 210, 3: 150 } as const; +const ORDER = [2, 1, 3] as const; +const AVATAR = 62; + +function seat(entry: PodiumSeat | undefined, rank: 1 | 2 | 3, avatar: string | null) { + const picture = avatar + ? h("img", { src: avatar, width: AVATAR, height: AVATAR, style: { borderRadius: 999 } }) + : h("div", { style: { width: AVATAR, height: AVATAR, borderRadius: 999, background: "linear-gradient(180deg, #d9dade, #8f9097)" } }); + return h("div", { key: rank, style: { display: "flex", flexDirection: "column", alignItems: "center", width: 150 } }, + rank === 1 && h("img", { src: CROWN, width: 40, height: 30, style: { marginBottom: 8 } }), + picture, + h("div", { style: { display: "flex", flexDirection: "column", alignItems: "center", height: 58, marginTop: 10, marginBottom: 14 } }, + text(entry?.name ?? "Open seat", { maxWidth: 150, fontSize: 20, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", color: entry ? "#f4f4f5" : MUTED }), + entry && text(`${entry.score.toLocaleString("en-US")} pts`, { marginTop: 2, fontSize: 18, color: MUTED })), + h("div", { style: { + display: "flex", justifyContent: "center", width: 150, height: COLUMN[rank], paddingTop: 24, + borderRadius: "22px 22px 0 0", background: "linear-gradient(180deg, #f5f5f6 0%, #dcdcdf 40%, #0a0a0c 100%)", + fontSize: 40, fontWeight: 600, color: "#9d9da3", + } }, String(rank))); +} + +/** The home page's share card: the headline on the left, the current top three on a podium. */ +export function homeImage(card: HomeCard): Promise { + return cachedImage(homeCardKey(card), async () => { + const [assets, avatars] = await Promise.all([cardAssets(), Promise.all(card.seats.map((entry) => avatarData(entry.avatarUrl)))]); + const avatarFor = (rank: number) => avatars[card.seats.findIndex((entry) => entry.rank === rank)] ?? null; + return renderCard( + h("div", { style: { width: 1200, height: 630, position: "relative", display: "flex", background: "linear-gradient(135deg, #1b1c20 0%, #0a0a0c 55%, #050506 100%)", color: "#f4f4f5", fontFamily: "Aspekta" } }, + h("div", { style: { position: "absolute", left: 80, top: 112, display: "flex", flexDirection: "column", fontSize: 62, fontWeight: 400, lineHeight: 1.1, letterSpacing: -2.5 } }, + text("Paste your username.", {}), text("Take your place.", { color: "#8d8f96" })), + h("div", { style: { position: "absolute", left: 80, top: 287, width: 222, height: 70, display: "flex", alignItems: "center", justifyContent: "center", gap: 14, borderRadius: 999, border: "2px solid rgba(255,255,255,0.4)", background: "linear-gradient(180deg, #26272b, #0d0e10)", fontSize: 24, fontWeight: 600 } }, + h("img", { src: GITHUB_MARK, width: 26, height: 26 }), text("Get ranked", {})), + text("OpenCircle", { position: "absolute", left: 80, bottom: 70, fontSize: 40, fontWeight: 600, letterSpacing: -1.5, color: "#d6d8dd" }), + h("div", { style: { position: "absolute", left: 642, bottom: 0, display: "flex", alignItems: "flex-end", gap: 14 } }, + ORDER.map((rank) => seat(card.seats.find((entry) => entry.rank === rank), rank, avatarFor(rank)))), + ), + assets, + ); + }); +} diff --git a/server/home-seo.ts b/server/home-seo.ts new file mode 100644 index 0000000..485c92a --- /dev/null +++ b/server/home-seo.ts @@ -0,0 +1,34 @@ +import { DEFAULT_SITE_URL } from "../shared/brand.js"; +import { PODIUM_PATHS, podiumImage } from "../shared/podium-seo.js"; +import { seoDocument, type SeoDocument } from "../shared/seo.js"; +import { shareImageVersion } from "../shared/share-image.js"; +import { getStore } from "./db.js"; +import { HttpError } from "./http.js"; +import { homeCard, homeCardKey } from "./home-image.js"; + +/** Reads the saved board only: a share card must never wait on, or trigger, a GitHub refresh. */ +export async function readHomeCard() { + const board = await getStore().getBoard(); + if (!board) throw new HttpError(503, "board_unavailable", "The leaderboard isn't ready yet."); + return homeCard(board); +} + +/** Home and the community page share the live podium. Without a board to read they keep the static card. */ +export async function homeSeoDocument(pathname: string, origin = DEFAULT_SITE_URL): Promise { + if (!PODIUM_PATHS.has(pathname)) return null; + try { + const card = await readHomeCard(); + const document = seoDocument(pathname, origin); + return { + ...document, + image: podiumImage( + document.url, + shareImageVersion(homeCardKey(card)), + card.seats.length ? `OpenCircle leaderboard: ${card.seats.map((seat) => `${seat.rank}. ${seat.name}`).join(", ")}` : undefined, + ), + }; + } catch (error) { + console.error(error); + return null; + } +} diff --git a/server/node-server.ts b/server/node-server.ts index e89a68b..68e7ae3 100644 --- a/server/node-server.ts +++ b/server/node-server.ts @@ -55,7 +55,12 @@ import * as forumImage from "../api/forum-image.js"; import * as blog from "../api/blog.js"; import * as blogAdmin from "../api/blog-admin.js"; import * as blogImage from "../api/blog-image.js"; +import * as componentImage from "../api/component-image.js"; +import * as homeImage from "../api/home-image.js"; +import * as pageImage from "../api/page-image.js"; import { blogPageSeoDocument, blogSitemapEntries } from "./blog-seo.js"; +import { componentPageSeoDocument } from "./component-seo.js"; +import { homeSeoDocument } from "./home-seo.js"; import { sitemapXml } from "../shared/seo.js"; type Handler = (req: Request) => Promise; @@ -84,6 +89,9 @@ const routes: Record> = { community: community as Record, tools: tools as Record, components: components as Record, + "component-image": componentImage as Record, + "home-image": homeImage as Record, + "page-image": pageImage as Record, vote: vote as Record, "repository-stars": repositoryStars as Record, board: board as Record, @@ -218,7 +226,7 @@ export function createAppServer(distDirectory = path.resolve(process.cwd(), "dis const raw = readFileSync(INDEX, "utf8"); const origin = originFromHtml(raw, process.env.SITE_URL || DEFAULT_SITE_URL); let document = seoDocument(pathname, origin); - try { document = await communitySeoDocument(pathname, origin) ?? await eventSeoDocument(pathname, origin) ?? await blogPageSeoDocument(pathname, origin) ?? document; } + try { document = await communitySeoDocument(pathname, origin) ?? await eventSeoDocument(pathname, origin) ?? await blogPageSeoDocument(pathname, origin) ?? componentPageSeoDocument(pathname, origin) ?? await homeSeoDocument(pathname, origin) ?? document; } catch (error) { console.error(error); document = { ...document, status: 503 }; diff --git a/server/page-seo.ts b/server/page-seo.ts new file mode 100644 index 0000000..20c4883 --- /dev/null +++ b/server/page-seo.ts @@ -0,0 +1,14 @@ +import { pageName, SEO_PAGES } from "../shared/seo.js"; +import { shareImageVersion } from "../shared/share-image.js"; +import type { ShareCard } from "./forum-image.js"; + +/** The indexed pages that use the plain card; the home page draws its own. */ +export function pageShareCard(path: string): { key: string; card: ShareCard } | null { + const page = SEO_PAGES.find((entry) => entry.path === path && entry.index && entry.path !== "/"); + if (!page) return null; + const title = pageName(page); + return { + key: `page:${page.path}:${shareImageVersion(title, page.description)}`, + card: { label: "Open Source Circle", title, description: page.description, author: "", category: "" }, + }; +} diff --git a/server/vite-seo.ts b/server/vite-seo.ts index 3262a06..a7d7beb 100644 --- a/server/vite-seo.ts +++ b/server/vite-seo.ts @@ -2,6 +2,7 @@ import type { Plugin } from "vite"; import { DEFAULT_SITE_URL } from "../shared/brand"; import { forumPreviewId } from "../shared/forum-seo"; import { blogSlugFromPath } from "../shared/blog-paths"; +import { componentSlugFromPath } from "../shared/component-meta"; import { applySeo, llmsTxt, robotsTxt, seoDocument, siteOrigin, sitemapXml } from "../shared/seo"; /** @@ -19,7 +20,7 @@ export function seo(siteUrl: string | undefined): Plugin { async handler(html, ctx) { const ready = html.replaceAll("%SITE_URL%", origin); const pathname = new URL(ctx.originalUrl ?? "/", origin).pathname; - const module = forumPreviewId(pathname) ? { path: "/server/forum-seo.ts", name: "communitySeoDocument" } : /^\/events\/[a-z0-9-]+$/.test(pathname) ? { path: "/server/event-seo.ts", name: "eventSeoDocument" } : blogSlugFromPath(pathname) ? { path: "/server/blog-seo.ts", name: "blogPageSeoDocument" } : null; + const module = forumPreviewId(pathname) ? { path: "/server/forum-seo.ts", name: "communitySeoDocument" } : /^\/events\/[a-z0-9-]+$/.test(pathname) ? { path: "/server/event-seo.ts", name: "eventSeoDocument" } : blogSlugFromPath(pathname) ? { path: "/server/blog-seo.ts", name: "blogPageSeoDocument" } : componentSlugFromPath(pathname) ? { path: "/server/component-seo.ts", name: "componentPageSeoDocument" } : pathname === "/" || pathname === "/community" ? { path: "/server/home-seo.ts", name: "homeSeoDocument" } : null; const dynamic = ctx.server && module ? await ctx.server.ssrLoadModule(module.path) : null; const document = module && dynamic ? await dynamic[module.name](pathname, origin) : null; return applySeo(ready, document ?? seoDocument(pathname, origin)); diff --git a/shared/component-meta.ts b/shared/component-meta.ts new file mode 100644 index 0000000..4fa029a --- /dev/null +++ b/shared/component-meta.ts @@ -0,0 +1,44 @@ +/** What the library says about each component. Shared so the server can describe a page without loading its demo. */ +export interface ComponentMeta { + slug: string; + name: string; + description: string; + category: string; + tags: string[]; + credit?: string; +} + +export const COMPONENT_META: readonly ComponentMeta[] = [ + { + slug: "split-footer", + name: "Split Footer", + description: "A dark brand panel lit by drifting ASCII light beside a white link panel, with the wordmark fading up from the bottom.", + category: "Layout", + tags: ["footer", "ascii", "canvas", "landing"], + credit: "Adapted from the Dailo landing footer.", + }, + { + slug: "icon-folder", + name: "Icon Folder", + description: "A glass folder with app icons fanned out of it. Pops in on view; hover, tap or Enter spreads the icons wider.", + category: "Display", + tags: ["folder", "icons", "glass", "hover"], + credit: "Adapted from the 21st.dev Icon Folder.", + }, + { + slug: "draw-a-line", + name: "Draw a Line", + 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"], + }, +]; + +export function componentMeta(slug: string | undefined): ComponentMeta | undefined { + return COMPONENT_META.find((component) => component.slug === slug); +} + +export function componentSlugFromPath(pathname: string): string | null { + const slug = /^\/components\/([a-z0-9-]+)$/.exec(pathname)?.[1]; + return slug && componentMeta(slug) ? slug : null; +} diff --git a/shared/component-seo.ts b/shared/component-seo.ts new file mode 100644 index 0000000..f53066e --- /dev/null +++ b/shared/component-seo.ts @@ -0,0 +1,23 @@ +import { BRAND_NAME, DEFAULT_SITE_URL } from "./brand.js"; +import type { ComponentMeta } from "./component-meta.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); +} + +export function componentSeoDocument(component: ComponentMeta, origin = DEFAULT_SITE_URL): SeoDocument { + const path = `/components/${component.slug}`; + const document = seoDocument(path, origin); + return { + ...document, path, url: new URL(path, document.url).href, + title: `${component.name} · Components · ${BRAND_NAME}`, heading: component.name, + description: component.description, summary: component.description, + image: { + url: new URL(`/api/component-image?${new URLSearchParams({ slug: component.slug, v: componentImageVersion(component) })}`, document.url).href, + alt: `Component: ${component.name}`, contentType: "image/png", width: 1200, height: 630, + }, + }; +} diff --git a/shared/podium-seo.ts b/shared/podium-seo.ts new file mode 100644 index 0000000..dea0a98 --- /dev/null +++ b/shared/podium-seo.ts @@ -0,0 +1,10 @@ +import type { SeoDocument } from "./seo.js"; + +/** Pages that share the leaderboard podium card. */ +export const PODIUM_PATHS: ReadonlySet = new Set(["/", "/community"]); + +/** The podium card. The server adds a version once it knows the standings; the browser uses the plain address. */ +export function podiumImage(origin: string, version?: string, alt = "OpenCircle community leaderboard"): NonNullable { + const query = version ? `?${new URLSearchParams({ v: version })}` : ""; + return { url: new URL(`/api/home-image${query}`, origin).href, alt, contentType: "image/png", width: 1200, height: 630 }; +} diff --git a/shared/seo.ts b/shared/seo.ts index d0decce..d5c0e6c 100644 --- a/shared/seo.ts +++ b/shared/seo.ts @@ -1,5 +1,6 @@ import { BRAND_NAME, DEFAULT_SITE_URL } from "./brand"; import { blogSlugFromPath } from "./blog-paths"; +import { shareImageVersion } from "./share-image"; export const GITHUB_URL = "https://github.com/opencirclehq/open-circle"; export const X_URL = "https://x.com/_Cybersmith"; @@ -152,6 +153,14 @@ export function pageFor(pathname: string) { return byPath.get(path.startsWith("/community/") ? "/community" : path); } +/** The page's own name, without the site suffix, as shown on its share card. */ +export const pageName = (page: Pick) => page.title.split(" · ")[0]; + +function pageImage(origin: string, path: string, name: string, description: string) { + const query = new URLSearchParams({ path, v: shareImageVersion(name, description) }); + return { url: `${origin}/api/page-image?${query}`, alt: `${name} on ${BRAND_NAME}`, contentType: "image/png", width: 1200, height: 630 }; +} + export function seoDocument(pathname: string, originInput = DEFAULT_SITE_URL): SeoDocument { const origin = siteOrigin(originInput); const path = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname || "/"; @@ -161,8 +170,11 @@ export function seoDocument(pathname: string, originInput = DEFAULT_SITE_URL): S : blogSlugFromPath(path) ? { ...byPath.get("/blog")!, path } : /^\/components\/[a-z0-9-]+$/.test(path) ? { ...byPath.get("/components")!, path } : NOT_FOUND); const canonicalPath = path.startsWith("/community/") ? path : page.path || (path.startsWith("/") ? path : "/"); + const name = pageName(page); + const card = path !== "/" && page.index && byPath.get(path) === page; return { ...page, + ...(card && { image: pageImage(origin, path, name, page.description) }), path: canonicalPath, status: page.path ? 200 : 404, robots: page.index ? "index, follow, max-image-preview:large" : "noindex, nofollow", @@ -214,7 +226,7 @@ export function structuredData(originInput = DEFAULT_SITE_URL) { export function robotsTxt(originInput = DEFAULT_SITE_URL) { const origin = siteOrigin(originInput); - return ["User-agent: *", "Allow: /", "Allow: /api/event-cover", "Allow: /api/forum-image", "Allow: /api/blog-image", "Disallow: /admin", "Disallow: /portfolio", "Disallow: /api/", "", `Sitemap: ${origin}/sitemap.xml`, ""].join("\n"); + return ["User-agent: *", "Allow: /", "Allow: /api/event-cover", "Allow: /api/forum-image", "Allow: /api/blog-image", "Allow: /api/component-image", "Allow: /api/home-image", "Allow: /api/page-image", "Disallow: /admin", "Disallow: /portfolio", "Disallow: /api/", "", `Sitemap: ${origin}/sitemap.xml`, ""].join("\n"); } /** Static pages, plus dynamic entries (published posts) when the server knows them. */ diff --git a/shared/share-image.ts b/shared/share-image.ts new file mode 100644 index 0000000..d3bd295 --- /dev/null +++ b/shared/share-image.ts @@ -0,0 +1,6 @@ +/** A short, stable fingerprint of what a card shows, so a changed card gets a new image address. */ +export function shareImageVersion(...parts: (string | number)[]): string { + let hash = 2166136261; + for (const character of parts.join("\n")) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619); + return (hash >>> 0).toString(36); +} diff --git a/src/hooks/use-page-meta.ts b/src/hooks/use-page-meta.ts index 6187e16..64cf10b 100644 --- a/src/hooks/use-page-meta.ts +++ b/src/hooks/use-page-meta.ts @@ -4,6 +4,9 @@ import { DEFAULT_SITE_URL } from "@shared/brand"; import { seoDocument, type SeoDocument } from "@shared/seo"; import { forumPreviewId, forumSeoDocument, type ForumSharePreview } from "@shared/forum-seo"; import { blogSlugFromPath } from "@shared/blog-paths"; +import { componentMeta, componentSlugFromPath } from "@shared/component-meta"; +import { componentSeoDocument } from "@shared/component-seo"; +import { PODIUM_PATHS, podiumImage } from "@shared/podium-seo"; /** The site's own origin. og:url always points here, unlike a cross-posted article's canonical link. */ export function currentOrigin() { @@ -28,10 +31,15 @@ export function usePageMeta() { const origin = currentOrigin(); const id = forumPreviewId(pathname); // Posts set their own tags once loaded, like events and community threads. - const dynamic = !!id || /^\/events\/[a-z0-9-]+$/.test(pathname) || !!blogSlugFromPath(pathname); + const dynamic = !!id || /^\/events\/[a-z0-9-]+$/.test(pathname) || !!blogSlugFromPath(pathname) || PODIUM_PATHS.has(pathname); // og:url names this page even when a cross-posted article's canonical link points elsewhere. const shared = document.querySelector('meta[property="og:url"]')?.getAttribute("content") ?? document.querySelector('link[rel="canonical"]')?.getAttribute("href"); - if (!dynamic || !shared || !URL.canParse(shared) || new URL(shared).pathname !== pathname) applyPageMeta(seoDocument(pathname, origin)); + const component = componentMeta(componentSlugFromPath(pathname) ?? undefined); + if (component) applyPageMeta(componentSeoDocument(component, origin)); + else if (!dynamic || !shared || !URL.canParse(shared) || new URL(shared).pathname !== pathname) { + const page = seoDocument(pathname, origin); + applyPageMeta(PODIUM_PATHS.has(pathname) ? { ...page, image: podiumImage(origin) } : page); + } if (!id) return; const controller = new AbortController(); void fetch(`/api/forum-preview?${new URLSearchParams({ id })}`, { signal: controller.signal, credentials: "omit", cache: "no-store" }) diff --git a/src/library/registry.tsx b/src/library/registry.tsx index fc589ec..23fecec 100644 --- a/src/library/registry.tsx +++ b/src/library/registry.tsx @@ -1,5 +1,6 @@ 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 { DrawALine } from "./items/draw-a-line"; import drawALineSource from "./items/draw-a-line.tsx?raw"; @@ -10,12 +11,7 @@ import splitFooterSource from "./items/split-footer.tsx?raw"; export type CanvasTheme = "dark" | "light"; -export interface LibraryItem { - slug: string; - name: string; - description: string; - category: string; - tags: string[]; +export interface LibraryItem extends ComponentMeta { /** File name the source is copied as. */ file: string; /** The exact source rendered in the preview. */ @@ -23,7 +19,6 @@ export interface LibraryItem { /** Packages beyond React and Tailwind CSS. */ dependencies: string[]; usage: string; - credit?: string; /** Bento card size on the library grid. */ card: "wide" | "tall"; /** Width the component is laid out at before scaling down to fit, for full-width components. */ @@ -85,13 +80,10 @@ function TrainDemo({ theme }: { theme: CanvasTheme }) { ); } +/** The library's wording lives in shared/component-meta so the server can describe a page without these demos. */ export const LIBRARY: LibraryItem[] = [ { - slug: "split-footer", - name: "Split Footer", - description: "A dark brand panel lit by drifting ASCII light beside a white link panel, with the wordmark fading up from the bottom.", - category: "Layout", - tags: ["footer", "ascii", "canvas", "landing"], + ...componentMeta("split-footer")!, file: "split-footer.tsx", source: splitFooterSource, dependencies: [], @@ -103,17 +95,12 @@ export const LIBRARY: LibraryItem[] = [ groups={[{ title: "Product", links: [{ label: "Pricing", href: "/pricing" }] }]} socials={[{ label: "Acme on X", href: "https://x.com/acme", icon: "x" }]} />`, - credit: "Adapted from the Dailo landing footer.", card: "wide", designWidth: 1200, Demo: FooterDemo, }, { - slug: "icon-folder", - name: "Icon Folder", - description: "A glass folder with app icons fanned out of it. Pops in on view; hover, tap or Enter spreads the icons wider.", - category: "Display", - tags: ["folder", "icons", "glass", "hover"], + ...componentMeta("icon-folder")!, file: "icon-folder.tsx", source: iconFolderSource, dependencies: [], @@ -124,16 +111,11 @@ export const LIBRARY: LibraryItem[] = [ theme="dark" icons={[{ src: "/figma.png", label: "Figma" }, { src: "/linear.png", label: "Linear" }]} />`, - credit: "Adapted from the 21st.dev Icon Folder.", card: "tall", Demo: FolderDemo, }, { - slug: "draw-a-line", - name: "Draw a Line", - 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"], + ...componentMeta("draw-a-line")!, file: "draw-a-line.tsx", source: drawALineSource, dependencies: [], diff --git a/tests/component-seo.test.ts b/tests/component-seo.test.ts new file mode 100644 index 0000000..3e0e5a3 --- /dev/null +++ b/tests/component-seo.test.ts @@ -0,0 +1,83 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Server } from "node:http"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import * as imageApi from "../api/component-image"; +import { DEFAULT_SITE_URL } from "../shared/brand"; +import { COMPONENT_META, componentSlugFromPath } from "../shared/component-meta"; +import { componentImageVersion, componentSeoDocument } from "../shared/component-seo"; +import { robotsTxt } from "../shared/seo"; +import { shareImage } from "../server/forum-image"; +import { createAppServer } from "../server/node-server"; +import { TestStore } from "./helpers/test-store"; + +const board = new TestStore(); +vi.mock("../server/db", () => ({ getStore: () => board })); +vi.mock("../server/community-store", () => ({ getCommunityStore: () => null })); + +let server: Server; +let base: string; +let directory: string; + +beforeEach(async () => { + directory = mkdtempSync(path.join(tmpdir(), "opencircle-component-seo-")); + writeFileSync(path.join(directory, "index.html"), readFileSync(new URL("../index.html", import.meta.url), "utf8")); + server = createAppServer(directory); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No HTTP test port"); + base = `http://127.0.0.1:${address.port}`; +}); + +afterEach(async () => { + server.closeAllConnections(); + await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); + rmSync(directory, { recursive: true, force: true }); +}); + +it("recognises only the library's own component addresses", () => { + expect(componentSlugFromPath("/components/draw-a-line")).toBe("draw-a-line"); + for (const path of ["/components", "/components/", "/components/missing", "/components/draw-a-line/extra", "/components/../admin"]) + expect(componentSlugFromPath(path)).toBeNull(); +}); + +it("points each component's share card at its own image", () => { + const component = COMPONENT_META.find((entry) => entry.slug === "draw-a-line")!; + const document = componentSeoDocument(component); + expect(document.title).toBe("Draw a Line · Components · OpenCircle"); + expect(document.url).toBe(`${DEFAULT_SITE_URL}/components/draw-a-line`); + expect(document.image?.url).toBe(`${DEFAULT_SITE_URL}/api/component-image?slug=draw-a-line&v=${componentImageVersion(component)}`); + expect(componentImageVersion({ ...component, description: "Changed" })).not.toBe(componentImageVersion(component)); +}); + +it.each(COMPONENT_META)("serves $slug with its own title and share card", async ({ slug, name }) => { + const response = await fetch(`${base}/components/${slug}`); + const html = await response.text(); + expect(response.status).toBe(200); + expect(html).toContain(`${name} · Components · OpenCircle`); + expect(html).toContain(``); + expect(html).toContain(`content="${DEFAULT_SITE_URL}/api/component-image?slug=${slug}&v=`); + expect((await fetch(`${base}/api/component-image?slug=${slug}`)).status).toBe(200); +}); + +it("keeps the generic card for a component that does not exist", async () => { + const unknown = await (await fetch(`${base}/components/missing`)).text(); + expect(unknown).not.toContain("/api/component-image"); +}); + +it("renders a PNG card for a component and rejects anything else", async () => { + const response = await fetch(`${base}/api/component-image?slug=draw-a-line`); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("image/png"); + expect(Buffer.from(await response.arrayBuffer()).subarray(1, 4).toString()).toBe("PNG"); + for (const slug of ["missing", "../../etc", ""]) expect((await fetch(`${base}/api/component-image?${new URLSearchParams({ slug })}`)).status).toBe(404); + expect((await imageApi.HEAD(new Request(`${base}/api/component-image?slug=icon-folder`, { method: "HEAD" }))).status).toBe(200); + expect(robotsTxt(DEFAULT_SITE_URL)).toContain("Allow: /api/component-image"); +}); + +it("fits a very long component name on the card", async () => { + const name = "An Extremely Long Component Name That Keeps Going Past Any Sensible Width For A Share Card"; + const bytes = await shareImage("component:long-name", { label: "Component", title: name, description: "x ".repeat(200), author: "#one #two #three #four #five", category: "Motion" }); + expect(bytes.subarray(1, 4).toString()).toBe("PNG"); +}); diff --git a/tests/forum-meta.test.tsx b/tests/forum-meta.test.tsx index 29ec671..87231c8 100644 --- a/tests/forum-meta.test.tsx +++ b/tests/forum-meta.test.tsx @@ -38,8 +38,8 @@ it("uses the published public preview for client navigation and resets the image expect(fetcher).toHaveBeenCalledWith(`/api/forum-preview?id=${first}`, expect.objectContaining({ credentials: "omit", cache: "no-store", signal: expect.any(AbortSignal) })); await userEvent.setup().click(screen.getByRole("link", { name: "Tools" })); expect(document.title).toBe("Developer tools · OpenCircle"); - expect(meta("og:image")).toBe("https://opencircle.cc/og.png"); - expect(meta("twitter:image")).toBe("https://opencircle.cc/og.png"); + expect(meta("og:image")).toMatch(/^https:\/\/opencircle\.cc\/api\/page-image\?path=%2Ftools&v=/); + expect(meta("twitter:image")).toBe(meta("og:image")); }); it("preserves server-rendered thread metadata while fetching and ignores a late response after navigation", async () => { @@ -51,7 +51,7 @@ it("preserves server-rendered thread metadata while fetching and ignores a late await userEvent.setup().click(screen.getByRole("link", { name: "Community" })); await act(async () => { finish(Response.json(preview)); }); expect(document.title).toBe("Community · OpenCircle"); - expect(meta("og:image")).toBe("https://opencircle.cc/og.png"); + expect(meta("og:image")).toBe("https://opencircle.cc/api/home-image"); }); it("preserves existing event titles and covers when the event page loads", () => { diff --git a/tests/page-image.test.ts b/tests/page-image.test.ts new file mode 100644 index 0000000..b0c0bb0 --- /dev/null +++ b/tests/page-image.test.ts @@ -0,0 +1,87 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Server } from "node:http"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { DEFAULT_SITE_URL } from "../shared/brand"; +import { COMPONENT_META } from "../shared/component-meta"; +import { SEO_PAGES, seoDocument } from "../shared/seo"; +import { homeCard, homeCardKey } from "../server/home-image"; +import { createAppServer } from "../server/node-server"; +import { TestStore } from "./helpers/test-store"; + +const board = new TestStore(); +vi.mock("../server/db", () => ({ getStore: () => board })); +const members = [1, 2, 3, 4].map((rank) => ({ rank, login: `member${rank}`, nickname: `Member ${rank}`, avatarUrl: "https://example.com/avatar.png", score: 100 - rank })); +vi.mock("../server/community-store", () => ({ getCommunityStore: () => null })); + +let server: Server; +let base: string; +let directory: string; + +beforeEach(async () => { + await board.setBoard({ members } as never); + directory = mkdtempSync(path.join(tmpdir(), "opencircle-page-image-")); + writeFileSync(path.join(directory, "index.html"), readFileSync(new URL("../index.html", import.meta.url), "utf8")); + server = createAppServer(directory); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No HTTP test port"); + base = `http://127.0.0.1:${address.port}`; +}); + +afterEach(async () => { + server.closeAllConnections(); + await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); + rmSync(directory, { recursive: true, force: true }); +}); + +const png = async (response: Response) => Buffer.from(await response.arrayBuffer()).subarray(1, 4).toString(); + +it("gives every indexed page except home its own card, and private pages none", () => { + for (const page of SEO_PAGES.filter((entry) => entry.index && entry.path !== "/")) + expect(seoDocument(page.path).image?.url).toContain(`${DEFAULT_SITE_URL}/api/page-image?path=${encodeURIComponent(page.path)}&v=`); + for (const page of SEO_PAGES.filter((entry) => !entry.index)) expect(seoDocument(page.path).image).toBeUndefined(); + expect(seoDocument("/").image).toBeUndefined(); + expect(seoDocument("/nowhere").image).toBeUndefined(); +}); + +it("renders page cards and rejects paths that have none", async () => { + const tools = await fetch(`${base}/api/page-image?path=/tools`); + expect([tools.status, await png(tools)]).toEqual([200, "PNG"]); + for (const value of ["/", "/admin", "/nowhere", "../etc"]) expect((await fetch(`${base}/api/page-image?${new URLSearchParams({ path: value })}`)).status).toBe(404); + expect(await (await fetch(`${base}/tools`)).text()).toContain(`${DEFAULT_SITE_URL}/api/page-image?path=%2Ftools&v=`); +}); + +it("picks the top three members for the home card", () => { + const card = homeCard({ members: [members[3], members[1], members[0], members[2]] as never }); + expect(card.seats.map((seat) => seat.rank)).toEqual([1, 2, 3]); + expect(homeCardKey(card)).not.toBe(homeCardKey(homeCard({ members: [members[0]] as never }))); +}); + +it("renders the home podium even when avatars cannot be loaded", async () => { + const response = await fetch(`${base}/api/home-image`); + expect([response.status, await png(response)]).toEqual([200, "PNG"]); + const home = await (await fetch(`${base}/`)).text(); + expect(home).toContain(`${DEFAULT_SITE_URL}/api/home-image?v=`); + expect(home).toContain("OpenCircle leaderboard: 1. Member 1, 2. Member 2, 3. Member 3"); + const community = await (await fetch(`${base}/community`)).text(); + expect(community).toContain(`${DEFAULT_SITE_URL}/api/home-image?v=`); +}); + +it("points every page at a card that renders", async () => { + const paths = ["/", "/community", "/repositories", "/tools", "/how-it-works", "/blog", "/components", ...COMPONENT_META.map(({ slug }) => `/components/${slug}`)]; + for (const route of paths) { + const html = await (await fetch(`${base}${route}`)).text(); + const image = / { + await board.setBoard(null as never); + expect((await fetch(`${base}/api/home-image`)).status).toBe(503); + expect(await (await fetch(`${base}/`)).text()).toContain(`${DEFAULT_SITE_URL}/og.png`); +});