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
23 changes: 23 additions & 0 deletions api/component-image.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
20 changes: 20 additions & 0 deletions api/home-image.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
23 changes: 23 additions & 0 deletions api/page-image.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
3 changes: 3 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
18 changes: 18 additions & 0 deletions server/component-seo.ts
Original file line number Diff line number Diff line change
@@ -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 },
};
}
36 changes: 26 additions & 10 deletions server/forum-image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { ForumSharePreview } from "../shared/forum-seo.js";
const images = new Map<string, Promise<Buffer>>();
let fonts: Promise<Buffer[]> | undefined;
let logo: Promise<string> | 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 }
Expand All @@ -17,21 +17,41 @@ export function forumImage(preview: ForumSharePreview): Promise<Buffer> {
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<Buffer> {
return cachedImage(key, () => render(card));
}

/** Renders once per key; the few most recent images stay cached. */
export function cachedImage(key: string, make: () => Promise<Buffer>): Promise<Buffer> {
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<typeof h>, { regular, semibold }: Awaited<ReturnType<typeof cardAssets>>) {
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",
} },
Expand All @@ -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);
}
82 changes: 82 additions & 0 deletions server/home-image.ts
Original file line number Diff line number Diff line change
@@ -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<Board, "members">): 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<string | null> {
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('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#fff" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>');
const CROWN = svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 30"><path fill="${GOLD}" d="M2 8l9 7 9-13 9 13 9-7-3 17H5z"/><rect x="5" y="26" width="30" height="4" rx="1" fill="${GOLD}"/></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<Buffer> {
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,
);
});
}
34 changes: 34 additions & 0 deletions server/home-seo.ts
Original file line number Diff line number Diff line change
@@ -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<SeoDocument | null> {
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;
}
}
10 changes: 9 additions & 1 deletion server/node-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response>;
Expand Down Expand Up @@ -84,6 +89,9 @@ const routes: Record<string, Record<string, Handler | undefined>> = {
community: community as Record<string, Handler>,
tools: tools as Record<string, Handler>,
components: components as Record<string, Handler>,
"component-image": componentImage as Record<string, Handler>,
"home-image": homeImage as Record<string, Handler>,
"page-image": pageImage as Record<string, Handler>,
vote: vote as Record<string, Handler>,
"repository-stars": repositoryStars as Record<string, Handler>,
board: board as Record<string, Handler>,
Expand Down Expand Up @@ -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 };
Expand Down
14 changes: 14 additions & 0 deletions server/page-seo.ts
Original file line number Diff line number Diff line change
@@ -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: "" },
};
}
Loading