Production-ready animations, transitions, backgrounds, and scenes for Remotion
TypeScript ai-agentsclaude-codedemo-videomcpmcp-servermodel-context-protocolmotion-designproduct-demoreactremotionshadcnvideo
feat: GEO fixes — full Markdown copies, honest sitemap, page JSON-LD
kapishdima22607ff3d0d3
diff --git a/app/(home)/blog/[slug]/page.tsx b/app/(home)/blog/[slug]/page.tsxindex bb61acdb..3a9b2230 100644--- a/app/(home)/blog/[slug]/page.tsx+++ b/app/(home)/blog/[slug]/page.tsx@@ -3,7 +3,9 @@ import Link from "next/link";import { notFound } from "next/navigation";import { blog } from "@/.source/server";import { GuideVideo } from "@/components/docs/guide-video";+import { JsonLd } from "@/components/json-ld";import { blogSlug } from "@/lib/blog";+import { blogPostJsonLd } from "@/lib/structured-data";import { cn } from "@/lib/utils";import { getMDXComponents } from "@/mdx-components";import { landingButtonVariants } from "../../components/landing/ui/landing-button";@@ -78,9 +80,28 @@ export default async function BlogPostPage({ params }: PageProps) {);const headings = post.toc.filter((item) => item.depth <= 3);const MDX = post.body;+ const jsonLd = blogPostJsonLd({+ url: `/blog/${slug}`,+ title: post.title,+ description: post.description,+ date: post.date,+ image: post.videoPoster ?? `/og/blog/${slug}`,+ video:+ summary.video && summary.poster+ ? {+ name: post.title,+ description: post.description,+ contentUrl: summary.video,+ thumbnailUrl: summary.poster,+ uploadDate: post.date,+ duration: summary.duration,+ }+ : undefined,+ });return (<>+ <JsonLd data={jsonLd} /><article><header className="landing-container flex flex-col gap-5 pt-12 pb-8 md:pt-20 md:pb-12 xl:pt-28 xl:pb-14"><Linkdiff --git a/app/(home)/showcases/[slug]/page.tsx b/app/(home)/showcases/[slug]/page.tsxindex 31bbd63e..63c5545d 100644--- a/app/(home)/showcases/[slug]/page.tsx+++ b/app/(home)/showcases/[slug]/page.tsx@@ -1,6 +1,8 @@import type { Metadata } from "next";import Link from "next/link";import { notFound } from "next/navigation";+import { JsonLd } from "@/components/json-ld";+import { showcaseJsonLd } from "@/lib/structured-data";import { cn } from "@/lib/utils";import { formatDuration } from "@/lib/video-duration";import { landingButtonVariants } from "../../components/landing/ui/landing-button";@@ -8,6 +10,7 @@ import { pageHeaderButton } from "../../components/site-page/page-header";import { ShowcaseDetails } from "../components/showcase-details";import { ShowcaseVideo } from "../components/showcase-video";import { getReel } from "../lib/reel";+import type { ReelClip } from "../lib/reel-types";type PageProps = { params: Promise<{ slug: string }> };@@ -37,26 +40,39 @@ export async function generateMetadata({if (!found) return {};const { clip } = found;const title = `${clip.title} · Remocn`;+ const description = showcaseDescription(clip);return {title: clip.title,+ description,alternates: { canonical: `/showcases/${clip.slug}` },openGraph: {type: "article",url: `/showcases/${clip.slug}`,siteName: "Remocn",title,+ description,locale: "en_US",images: [{ url: clip.poster, alt: clip.title }],},twitter: {card: "summary_large_image",title,+ description,images: [clip.poster],},};}+/** One sentence: who made the video and which components it is built from. */+function showcaseDescription(clip: ReelClip): string {+ const names = clip.components.map((component) => component.name);+ const built = names.length+ ? `, built from ${names.slice(0, 4).join(", ")}${names.length > 4 ? ` and ${names.length - 4} more` : ""}`+ : "";+ return `${clip.title}: a video ${clip.author.name} made with Remocn components for Remotion${built}.`;+}+const NAV_BUTTON = cn(landingButtonVariants({ variant: "secondary" }),pageHeaderButton,@@ -67,9 +83,22 @@ export default async function ShowcasePage({ params }: PageProps) {const found = await getClip(slug);if (!found) notFound();const { clip, index, count, prev, next } = found;+ const jsonLd = showcaseJsonLd({+ url: `/showcases/${clip.slug}`,+ author: clip.author,+ video: {+ name: clip.title,+ description: showcaseDescription(clip),+ contentUrl: clip.video,+ thumbnailUrl: clip.poster,+ uploadDate: clip.iso,+ duration: clip.duration,+ },+ });return (<>+ <JsonLd data={jsonLd} /><header className="landing-container flex flex-col gap-5 pt-12 pb-8 md:pt-20 md:pb-12 xl:pt-24 xl:pb-12"><Link href="/showcases" className={cn(NAV_BUTTON, "self-start")}><span aria-hidden="true" className="text-primary">diff --git a/app/docs/[[...slug]]/page.tsx b/app/docs/[[...slug]]/page.tsxindex b608860f..2c0a4163 100644--- a/app/docs/[[...slug]]/page.tsx+++ b/app/docs/[[...slug]]/page.tsx@@ -6,6 +6,8 @@ import { getPageContext } from "@/components/docs/shell/page-context";import { PageFooter } from "@/components/docs/shell/page-footer";import { PageHeader } from "@/components/docs/shell/page-header";import { getPageLinks } from "@/components/docs/shell/page-links";+import { JsonLd } from "@/components/json-ld";+import { docsPageJsonLd, faqFromMdx } from "@/lib/structured-data";import { getMDXComponents } from "@/mdx-components";import { source } from "@/source";@@ -24,9 +26,24 @@ export default async function Page(props: {const MDX = data.body;const { crumbs, previous, next } = getPageContext(page.url);const links = params.slug?.length ? getPageLinks(page.url) : undefined;+ const raw = await (+ data as typeof data & { getText: (type: "raw") => Promise<string> }+ ).getText("raw");+ const jsonLd = docsPageJsonLd({+ url: page.url,+ title: data.title,+ description: data.description,+ crumbs,+ image: params.slug?.length+ ? `/og/docs/${params.slug.join("/")}`+ : "/hero.png",+ component: data.component,+ faq: faqFromMdx(raw),+ });return (<>+ <JsonLd data={jsonLd} /><MobilePageBar crumbs={crumbs} /><KeyboardNav previous={previous} next={next} /><div className="flex flex-1">diff --git a/app/sitemap.ts b/app/sitemap.tsindex ebcdec91..028ef6d2 100644--- a/app/sitemap.ts+++ b/app/sitemap.ts@@ -6,92 +6,72 @@ import { source } from "@/source";const SITE_URL = "https://remocn.dev";+/**+ * `lastModified` is set only where the date is real: a post, a showcase, or a+ * feed page whose newest entry dates it. Docs and static pages leave it out.+ * The image is built without `.git`, so their edit dates are unknown, and a+ * build-time "now" on every URL teaches Google and Bing to ignore lastmod for+ * the whole site.+ */export default async function sitemap(): Promise<MetadataRoute.Sitemap> {- const now = new Date();+ const showcases = await getShowcases();++ const newestPost = latest(blog.map((post) => post.date));+ const newestEntry = latest(changelog.map((entry) => entry.date));+ const newestShowcase = latest(+ showcases.map((showcase) => new Date(showcase.createdAt)),+ );const staticRoutes: MetadataRoute.Sitemap = [- {- url: SITE_URL,- lastModified: now,- changeFrequency: "weekly",- priority: 1,- },+ { url: SITE_URL, changeFrequency: "weekly", priority: 1 },{url: `${SITE_URL}/sponsors`,- lastModified: now,changeFrequency: "monthly",priority: 0.5,},{url: `${SITE_URL}/changelog`,- lastModified: now,+ lastModified: newestEntry,changeFrequency: "weekly",priority: 0.6,},{url: `${SITE_URL}/changelog/video`,- lastModified: now,+ lastModified: latest(+ changelog.filter((entry) => entry.video).map((entry) => entry.date),+ ),changeFrequency: "weekly",priority: 0.5,},{url: `${SITE_URL}/showcases`,- lastModified: now,+ lastModified: newestShowcase,changeFrequency: "weekly",priority: 0.6,},{url: `${SITE_URL}/blog`,- lastModified: now,+ lastModified: newestPost,changeFrequency: "weekly",priority: 0.6,},- {- url: `${SITE_URL}/about`,- lastModified: now,- changeFrequency: "yearly",- priority: 0.4,- },- {- url: `${SITE_URL}/contact`,- lastModified: now,- changeFrequency: "yearly",- priority: 0.4,- },- {- url: `${SITE_URL}/legal`,- lastModified: now,- changeFrequency: "yearly",- priority: 0.3,- },+ { url: `${SITE_URL}/about`, changeFrequency: "yearly", priority: 0.4 },+ { url: `${SITE_URL}/contact`, changeFrequency: "yearly", priority: 0.4 },+ { url: `${SITE_URL}/legal`, changeFrequency: "yearly", priority: 0.3 },];const docRoutes: MetadataRoute.Sitemap = source.getPages().map((page) => ({url: `${SITE_URL}${page.url}`,- lastModified: now,changeFrequency: "weekly",priority: 0.7,}));- const changelogRoutes: MetadataRoute.Sitemap = changelog.map((entry) => {- const slug = entry.info.path.replace(/\.mdx$/, "");-- return {- url: `${SITE_URL}/changelog#${slug}`,- lastModified: entry.date,- changeFrequency: "monthly",- priority: 0.4,- };- });-- const showcaseRoutes: MetadataRoute.Sitemap = (await getShowcases()).map(- (showcase) => ({- url: `${SITE_URL}/showcases/${showcase.slug}`,- lastModified: new Date(showcase.createdAt),- changeFrequency: "monthly",- priority: 0.5,- }),- );+ const showcaseRoutes: MetadataRoute.Sitemap = showcases.map((showcase) => ({+ url: `${SITE_URL}/showcases/${showcase.slug}`,+ lastModified: new Date(showcase.createdAt),+ changeFrequency: "monthly",+ priority: 0.5,+ }));const blogRoutes: MetadataRoute.Sitemap = blog.map((post) => ({url: `${SITE_URL}/blog/${blogSlug(post)}`,@@ -100,11 +80,11 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {priority: 0.5,}));- return [- ...staticRoutes,- ...docRoutes,- ...changelogRoutes,- ...showcaseRoutes,- ...blogRoutes,- ];+ return [...staticRoutes, ...docRoutes, ...showcaseRoutes, ...blogRoutes];+}++/** The newest of the dates, or undefined for an empty list. */+function latest(dates: Date[]): Date | undefined {+ if (dates.length === 0) return undefined;+ return new Date(Math.max(...dates.map((date) => date.getTime())));}diff --git a/lib/get-llm-text.ts b/lib/get-llm-text.tsindex 32d7e30c..f39ebbdf 100644--- a/lib/get-llm-text.ts+++ b/lib/get-llm-text.ts@@ -1,5 +1,14 @@import type { InferPageType } from "fumadocs-core/source";-import { mdxToMarkdown, stripFrontmatter } from "@/lib/mdx-to-markdown";+import {+ getComponentEntries,+ getEntry,+ loadDocsSource,+} from "@/components/docs/index/data";+import {+ type DocsLookup,+ mdxToMarkdown,+ stripFrontmatter,+} from "@/lib/mdx-to-markdown";import type { source } from "@/source";export const SITE_URL = "https://remocn.dev";@@ -18,7 +27,12 @@ export async function getLLMText(page: DocPage): Promise<string> {};const raw = await data.getText("raw");- const body = mdxToMarkdown(stripFrontmatter(raw), SITE_URL).trim();+ await loadDocsSource();+ const docs: DocsLookup = {+ entry: getEntry,+ componentEntries: getComponentEntries,+ };+ const body = mdxToMarkdown(stripFrontmatter(raw), SITE_URL, { docs }).trim();const facts: string[] = [];if (data.component)diff --git a/lib/mdx-to-markdown.test.ts b/lib/mdx-to-markdown.test.tsindex 59a47a14..9b99c961 100644--- a/lib/mdx-to-markdown.test.ts+++ b/lib/mdx-to-markdown.test.ts@@ -1,5 +1,10 @@import { describe, expect, test } from "bun:test";-import { mdxToMarkdown } from "./mdx-to-markdown";+import { readFileSync } from "node:fs";+import {+ type DocsLookup,+ mdxToMarkdown,+ stripFrontmatter,+} from "./mdx-to-markdown";const SITE = "https://remocn.dev";@@ -49,3 +54,128 @@ describe("mdxToMarkdown", () => {expect(mdxToMarkdown(src, SITE)).toBe(src);});});++describe("mdxToMarkdown: words carried in props", () => {+ test("a step keeps its command as a bash block", () => {+ const src = [+ '<Step n={1} title="Start from a Remotion project" command="npx create-video@latest">You need one.</Step>',+ ].join("\n");+ expect(mdxToMarkdown(src, SITE)).toBe(+ [+ "**Start from a Remotion project**",+ "",+ "You need one.",+ "",+ "```bash",+ "npx create-video@latest",+ "```",+ ].join("\n"),+ );+ });++ test("a multi-line command expression survives", () => {+ const src =+ '<Step n={2} title="Init" command={"npx shadcn@latest init\\nnpx shadcn@latest add @remocn/x"}>Run init.</Step>';+ expect(mdxToMarkdown(src, SITE)).toContain(+ "npx shadcn@latest init\nnpx shadcn@latest add @remocn/x",+ );+ });++ test("a self-closing widget with words in its props is kept", () => {+ const src =+ 'Intro.\n\n<FileFlow steps={["components.json", "components/remocn/x.tsx"]} />\n\nOutro.';+ expect(mdxToMarkdown(src, SITE)).toBe(+ "Intro.\n\n`components.json` → `components/remocn/x.tsx`\n\nOutro.",+ );+ });++ test("indented sibling widgets become separate paragraphs", () => {+ const src = [+ "<Pillars>",+ ' <Pillar title="One">First.</Pillar>',+ ' <Pillar title="Two">Second.</Pillar>',+ "</Pillars>",+ ].join("\n");+ expect(mdxToMarkdown(src, SITE).trim()).toBe(+ "**One**\n\nFirst.\n\n**Two**\n\nSecond.",+ );+ });+});++describe("mdxToMarkdown: category indexes", () => {+ const pages = {+ "/docs/transitions/whip-pan": {+ title: "Whip Pan",+ description: "Fast pan",+ },+ "/docs/transitions/zoom-blur": {+ title: "Zoom Blur",+ description: "Depth punch",+ },+ "/docs/transitions/glitch-cut": {+ title: "Glitch Cut",+ description: "RGB tear",+ },+ } as const;+ const docs: DocsLookup = {+ entry: (url) =>+ url in pages ? { url, ...pages[url as keyof typeof pages] } : undefined,+ componentEntries: () =>+ Object.entries(pages).map(([url, page]) => ({ url, ...page })),+ };++ test("lists each group's pages and the unlisted rest under More", () => {+ const src = [+ '<CategoryIndex section="/docs/transitions">',+ "",+ '<ComponentGroup items={["whip-pan", "zoom-blur"]}>',+ "",+ "## Camera",+ "",+ "</ComponentGroup>",+ "",+ "</CategoryIndex>",+ ].join("\n");+ expect(mdxToMarkdown(src, SITE, { docs })).toBe(+ [+ "## Camera",+ "",+ "- [Whip Pan](https://remocn.dev/docs/transitions/whip-pan) — Fast pan",+ "- [Zoom Blur](https://remocn.dev/docs/transitions/zoom-blur) — Depth punch",+ "",+ "## More",+ "",+ "- [Glitch Cut](https://remocn.dev/docs/transitions/glitch-cut) — RGB tear",+ ].join("\n"),+ );+ });++ test("a self-closing index is one flat list", () => {+ const out = mdxToMarkdown(+ '<CategoryIndex section="/docs/transitions" />',+ SITE,+ { docs },+ );+ expect(out).not.toContain("## More");+ expect(out.split("\n")).toHaveLength(3);+ });+});++describe("mdxToMarkdown over content/docs", () => {+ // Commands and prompts are what an agent copies from a page. Every one in+ // the MDX must reach the Markdown copy, whichever widget carries it.+ test("every command and prompt prop reaches the Markdown", () => {+ const missing: string[] = [];+ for (const file of new Bun.Glob("content/docs/**/*.mdx").scanSync()) {+ const src = readFileSync(file, "utf8");+ const out = mdxToMarkdown(stripFrontmatter(src), SITE);+ for (const match of src.matchAll(+ /\s(?:command|prompt)=(?:"([^"]+)"|\{"((?:[^"\\]|\\.)+)"\})/g,+ )) {+ const value = (match[1] ?? JSON.parse(`"${match[2]}"`)) as string;+ if (!out.includes(value)) missing.push(`${file}: ${value}`);+ }+ }+ expect(missing).toEqual([]);+ });+});diff --git a/lib/mdx-to-markdown.ts b/lib/mdx-to-markdown.tsindex c28cf6ec..93b00eb1 100644--- a/lib/mdx-to-markdown.ts+++ b/lib/mdx-to-markdown.ts@@ -198,6 +198,182 @@ function renderShaderPresets(base: string, siteUrl: string): string {.join("\n");}+/** A docs page as an index row needs: where it lives and what it is. */+export interface DocsEntry {+ url: string;+ title: string;+ description?: string;+}++/**+ * Lookups into the docs tree for the widgets that render data from it instead+ * of from their props (`CategoryIndex`). Without it those lists are skipped.+ */+export interface DocsLookup {+ entry(url: string): DocsEntry | undefined;+ /** Component pages of a section, in sidebar order. */+ componentEntries(section: string): DocsEntry[];+}++export interface MdxToMarkdownOptions {+ docs?: DocsLookup;+}++/** The `CategoryIndex` being converted: its section and the pages listed so far. */+interface CategoryContext {+ section: string;+ listed: Set<string>;+}++function renderEntryList(entries: DocsEntry[], siteUrl: string): string {+ return entries+ .map((entry) =>+ `- [${entry.title}](${siteUrl}${entry.url}) — ${entry.description ?? ""}`.trimEnd(),+ )+ .join("\n");+}++function fenced(lang: string, body: string): string {+ return [`\`\`\`${lang}`, body, "```"].join("\n");+}++function strings(value: unknown): string[] {+ return Array.isArray(value)+ ? value.filter((item): item is string => typeof item === "string")+ : [];+}++function records(value: unknown): Record<string, AttrValue>[] {+ return Array.isArray(value)+ ? value.filter(+ (item): item is Record<string, AttrValue> =>+ typeof item === "object" && item !== null && !Array.isArray(item),+ )+ : [];+}++function text(value: AttrValue | undefined): string {+ return typeof value === "string" ? value : "";+}++function absolute(href: string, siteUrl: string): string {+ return href.startsWith("/") ? siteUrl + href : href;+}++/**+ * Widgets whose words live in their props, not their children. Each returns+ * the Markdown placed around the children: `title` replaces the bold title+ * line, `before` and `after` sit on either side of the converted children.+ */+type PropText = (+ attrs: Record<string, AttrValue>,+ ctx: Context,+) => { title?: string; before?: string; after?: string };++const PROP_TEXT: Record<string, PropText> = {+ Step: (a) => ({+ after: text(a.command) && fenced("bash", text(a.command)),+ }),+ RuntimeCommand: (a) => ({+ after: text(a.command) && fenced("bash", text(a.command)),+ }),+ GuideRenderCard: (a) => ({+ before: text(a.prompt) && `Prompt:\n\n${fenced("text", text(a.prompt))}`,+ }),+ FileFlow: (a) => ({+ before: strings(a.steps)+ .map((step) => `\`${step}\``)+ .join(" → "),+ }),+ Tier: (a, { siteUrl, docs }) => ({+ title: [text(a.name), text(a.registry) && `(\`@${text(a.registry)}\`)`]+ .filter(Boolean)+ .join(" "),+ after: records(a.links)+ .map((link) => {+ const href = text(link.href);+ const label =+ text(link.label) ||+ docs?.entry(href)?.title ||+ href.split("/").pop() ||+ href;+ return `- [${label}](${absolute(href, siteUrl)})`;+ })+ .join("\n"),+ }),+ GuideFacts: (a) => ({+ before: records(a.facts)+ .map((fact) => `- **${text(fact.value)}** — ${text(fact.label)}`)+ .join("\n"),+ }),+ HowItWorks: (a) => ({+ before: records(a.steps)+ .map(+ (step, index) =>+ `${index + 1}. **${text(step.title)}** — ${text(step.body)}`,+ )+ .join("\n"),+ }),+ AgentSkillPanel: (a) => ({+ before: [+ text(a.lead),+ strings(a.steps)+ .map((step) => `- ${step}`)+ .join("\n"),+ text(a.from) &&+ text(a.to) &&+ `From “${text(a.from)}” to “${text(a.to)}”.`,+ ]+ .filter(Boolean)+ .join("\n\n"),+ }),+ ApiChips: (a) => ({+ before: [+ strings(a.uses).length &&+ `Uses ${strings(a.uses)+ .map((use) => `\`${use}\``)+ .join(", ")}.`,+ text(a.avoids) &&+ `Avoids \`${text(a.avoids)}\`${text(a.avoidsNote) ? ` ${text(a.avoidsNote)}` : ""}.`,+ ]+ .filter(Boolean)+ .join(" "),+ }),+ RuntimeRules: (a) => ({+ before: [+ strings(a.not).length &&+ `No ${strings(a.not)+ .map((rule) => `\`${rule}\``)+ .join(", ")}.`,+ text(a.only) && `Only \`${text(a.only)}\`.`,+ ]+ .filter(Boolean)+ .join(" "),+ }),+ TemplateCard: (a) => ({+ after: [+ strings(a.inside).length && `Inside: ${strings(a.inside).join(", ")}.`,+ text(a.name) &&+ fenced("bash", `npx shadcn@latest add @remocn/${text(a.name)}`),+ ]+ .filter(Boolean)+ .join("\n\n"),+ }),+ TranscriptSources: (a) => ({+ before: [+ records(a.sources)+ .map((source) => {+ const code = text(source.code) ? ` (\`${text(source.code)}\`)` : "";+ return `- **${text(source.title)}** — ${text(source.body)}${code}`;+ })+ .join("\n"),+ text(a.note),+ ]+ .filter(Boolean)+ .join("\n\n"),+ }),+};+function renderDependencies(items: unknown): string {if (!Array.isArray(items) || items.length === 0) return "";return `Requires: ${items.map((i) => `\`${String(i)}\``).join(", ")}`;@@ -264,7 +440,85 @@ export function stripFrontmatter(src: string): string {return after === -1 ? "" : src.slice(after + 1);}-export function mdxToMarkdown(src: string, siteUrl: string): string {+/** True when the line `out` ends on holds nothing but indentation. */+function atBlockStart(out: string): boolean {+ return /(^|\n)[ \t]*$/.test(out);+}++/**+ * Append a block-level piece as its own paragraph. Without the blank line a+ * widget's text would run into the previous line's paragraph.+ */+function appendBlock(out: string, block: string): string {+ if (!block) return out;+ const trimmed = out.replace(/[ \t]+$/, "");+ if (!trimmed) return block;+ if (trimmed.endsWith("\n\n")) return trimmed + block;+ return trimmed + (trimmed.endsWith("\n") ? "\n" : "\n\n") + block;+}++interface Context {+ siteUrl: string;+ docs?: DocsLookup;+ category?: CategoryContext;+}++export function mdxToMarkdown(+ src: string,+ siteUrl: string,+ options: MdxToMarkdownOptions = {},+): string {+ return convert(src, { siteUrl, docs: options.docs });+}++/** `<ComponentGroup items>`: its heading and lead, then its pages. */+function renderComponentGroup(+ attrs: Record<string, AttrValue>,+ inner: string,+ ctx: Context,+): string {+ const { docs, category } = ctx;+ if (!docs || !category) return inner;+ const entries = strings(attrs.items)+ .map((item) =>+ docs.entry(item.startsWith("/") ? item : `${category.section}/${item}`),+ )+ .filter((entry): entry is DocsEntry => Boolean(entry));+ for (const entry of entries) category.listed.add(entry.url);+ return [inner, renderEntryList(entries, ctx.siteUrl)]+ .filter(Boolean)+ .join("\n\n");+}++/**+ * `<CategoryIndex section>`: its groups, then every component page no group+ * listed (under "More" when there were groups), as the HTML index does.+ */+function renderCategoryIndex(+ attrs: Record<string, AttrValue>,+ body: string | null,+ ctx: Context,+): string {+ const section = text(attrs.section);+ if (!ctx.docs || !section) return body ? convert(body, ctx).trim() : "";+ const category: CategoryContext = { section, listed: new Set() };+ const groups = body ? convert(body, { ...ctx, category }).trim() : "";+ const rest = ctx.docs+ .componentEntries(section)+ .filter((entry) => !category.listed.has(entry.url));+ const more = rest.length+ ? [+ category.listed.size ? "## More" : "",+ renderEntryList(rest, ctx.siteUrl),+ ]+ .filter(Boolean)+ .join("\n\n")+ : "";+ return [groups, more].filter(Boolean).join("\n\n");+}++function convert(src: string, ctx: Context): string {+ const { siteUrl } = ctx;let out = "";let i = 0;@@ -317,10 +571,7 @@ export function mdxToMarkdown(src: string, siteUrl: string): string {if (CONTAINER_WIDGETS.has(tag) && !tagEnd.selfClosing) {const closeIndex = findClosingTag(src, tag, tagEnd.end);if (closeIndex !== -1) {- const inner = mdxToMarkdown(- src.slice(tagEnd.end, closeIndex),- siteUrl,- );+ const inner = convert(src.slice(tagEnd.end, closeIndex), ctx);const label = typeof attrs.title === "string" ? attrs.title : tag;out += blockquote(inner, label);i = closeIndex + `</${tag}>`.length;@@ -369,30 +620,58 @@ export function mdxToMarkdown(src: string, siteUrl: string): string {// Any other component (guide and index blocks): its markdown children// are the content, so keep those and drop the tags. A string `title`- // is kept as a bold line; self-closing ones are visual only.+ // is kept as a bold line. Widgets in PROP_TEXT also carry words in+ // their props; other self-closing ones are visual only.if (tag) {const tagEnd = findTagEnd(src, i + 1 + tag.length);- if (tagEnd?.selfClosing) {- i = tagEnd.end;- i = skipBlankAfterDrop(src, i, out);- continue;- }- if (tagEnd) {- const closeIndex = findClosingTag(src, tag, tagEnd.end);- if (closeIndex !== -1) {- const attrs = parseAttrs(- src.slice(i + 1 + tag.length, tagEnd.end - 1),- );- const inner = mdxToMarkdown(- src.slice(tagEnd.end, closeIndex),- siteUrl,- ).trim();- const title =- typeof attrs.title === "string" ? `**${attrs.title}**\n\n` : "";- out += `${title}${inner}`;- i = closeIndex + `</${tag}>`.length;+ const closeIndex =+ tagEnd && !tagEnd.selfClosing+ ? findClosingTag(src, tag, tagEnd.end)+ : -1;+ if (tagEnd && (tagEnd.selfClosing || closeIndex !== -1)) {+ const attrs = parseAttrs(+ src.slice(+ i + 1 + tag.length,+ tagEnd.end - (tagEnd.selfClosing ? 2 : 1),+ ),+ );+ const body = tagEnd.selfClosing+ ? null+ : src.slice(tagEnd.end, closeIndex);+ const next = tagEnd.selfClosing+ ? tagEnd.end+ : closeIndex + `</${tag}>`.length;++ if (tag === "CategoryIndex") {+ out = appendBlock(out, renderCategoryIndex(attrs, body, ctx));+ i = next;+ continue;+ }++ const propText = PROP_TEXT[tag]?.(attrs, ctx);+ if (tagEnd.selfClosing && !propText) {+ i = skipBlankAfterDrop(src, next, out);continue;}++ let inner = body === null ? "" : convert(body, ctx).trim();+ if (tag === "ComponentGroup") {+ inner = renderComponentGroup(attrs, inner, ctx);+ }+ const titleText =+ propText?.title ||+ (typeof attrs.title === "string" ? attrs.title : "");+ const block = [+ titleText && `**${titleText}**`,+ propText?.before,+ inner,+ propText?.after,+ ]+ .filter(Boolean)+ .join("\n\n");+ out = atBlockStart(out) ? appendBlock(out, block) : out + block;+ i = next;+ continue;}}}diff --git a/lib/structured-data.test.ts b/lib/structured-data.test.tsindex 6a4242ba..b94be7d9 100644--- a/lib/structured-data.test.ts+++ b/lib/structured-data.test.ts@@ -1,5 +1,14 @@import { describe, expect, test } from "bun:test";-import { HOME_KEYWORDS, homeJsonLd, serializeJsonLd } from "./structured-data";+import {+ blogPostJsonLd,+ docsPageJsonLd,+ faqFromMdx,+ HOME_KEYWORDS,+ homeJsonLd,+ isoDuration,+ serializeJsonLd,+ showcaseJsonLd,+} from "./structured-data";type Node = Record<string, unknown>;@@ -59,3 +68,144 @@ describe("serializeJsonLd", () => {expect(JSON.parse(out).x).toBe("</script><script>alert(1)</script>");});});++describe("docs page JSON-LD", () => {+ const doc = docsPageJsonLd({+ url: "/docs/transitions/zoom-blur",+ title: "Zoom Blur",+ description: "Depth punch-in",+ crumbs: [+ { label: "Transitions", href: "/docs/transitions" },+ { label: "Zoom Blur" },+ ],+ image: "/og/docs/transitions/zoom-blur",+ component: "zoom-blur",+ });+ const nodes = doc["@graph"] as Node[];+ const find = (type: string) => nodes.find((n) => n["@type"] === type);++ test("is a TechArticle about the component's source", () => {+ expect(find("TechArticle")).toMatchObject({+ headline: "Zoom Blur",+ url: "https://remocn.dev/docs/transitions/zoom-blur",+ image: "https://remocn.dev/og/docs/transitions/zoom-blur",+ about: {+ "@type": "SoftwareSourceCode",+ url: "https://remocn.dev/r/zoom-blur.json",+ },+ });+ });++ test("breadcrumbs run from the home page to the page itself", () => {+ const items = find("BreadcrumbList")?.itemListElement as Node[];+ expect(items.map((item) => item.item)).toEqual([+ "https://remocn.dev/",+ "https://remocn.dev/docs/transitions",+ "https://remocn.dev/docs/transitions/zoom-blur",+ ]);+ expect(items.map((item) => item.position)).toEqual([1, 2, 3]);+ });++ test("adds an FAQPage only when the page has questions", () => {+ expect(find("FAQPage")).toBeUndefined();+ const withFaq = docsPageJsonLd({+ url: "/docs/x",+ title: "X",+ crumbs: [],+ image: "/hero.png",+ faq: [{ question: "Is it free?", answer: "Yes." }],+ })["@graph"] as Node[];+ expect(withFaq.find((n) => n["@type"] === "FAQPage")).toMatchObject({+ mainEntity: [+ {+ "@type": "Question",+ name: "Is it free?",+ acceptedAnswer: { "@type": "Answer", text: "Yes." },+ },+ ],+ });+ });+});++describe("faqFromMdx", () => {+ test("reads bold questions and plain answers out of <Faq>", () => {+ const raw = [+ "Intro.",+ "",+ "<Faq>",+ "",+ "**Do I need **code**?**",+ "Not with an [agent](/docs/guides). Use `npx`.",+ "",+ "**Is it free?**",+ "MIT.",+ "",+ "</Faq>",+ ].join("\n");+ expect(faqFromMdx(raw)).toEqual([+ { question: "Do I need code?", answer: "Not with an agent. Use npx." },+ { question: "Is it free?", answer: "MIT." },+ ]);+ });++ test("returns nothing for a page without a FAQ", () => {+ expect(faqFromMdx("**Bold**\nText")).toEqual([]);+ });+});++describe("video JSON-LD", () => {+ test("ISO 8601 durations", () => {+ expect(isoDuration(33.4)).toBe("PT33S");+ expect(isoDuration(75)).toBe("PT1M15S");+ expect(isoDuration(120)).toBe("PT2M");+ });++ test("a blog post carries its video", () => {+ const post = blogPostJsonLd({+ url: "/blog/nextjs-launch-video",+ title: "Next.js",+ description: "The eclipse cut",+ date: new Date("2026-07-22T00:00:00Z"),+ image: "https://cdn.remocn.dev/posters/n.png",+ video: {+ name: "Next.js",+ description: "The eclipse cut",+ contentUrl: "https://cdn.remocn.dev/videos/n.mp4",+ thumbnailUrl: "https://cdn.remocn.dev/posters/n.png",+ uploadDate: new Date("2026-07-22T00:00:00Z"),+ duration: 33,+ },+ })["@graph"] as Node[];+ expect(post[0]).toMatchObject({+ "@type": "BlogPosting",+ datePublished: "2026-07-22T00:00:00.000Z",+ video: {+ "@type": "VideoObject",+ contentUrl: "https://cdn.remocn.dev/videos/n.mp4",+ thumbnailUrl: ["https://cdn.remocn.dev/posters/n.png"],+ uploadDate: "2026-07-22T00:00:00.000Z",+ duration: "PT33S",+ },+ });+ });++ test("a video without a known length leaves duration out", () => {+ const video = showcaseJsonLd({+ url: "/showcases/x",+ author: { name: "Ann", url: null },+ video: {+ name: "X",+ description: "d",+ contentUrl: "https://cdn.remocn.dev/x.mp4",+ thumbnailUrl: "https://cdn.remocn.dev/x.png",+ uploadDate: "2026-09-01",+ duration: null,+ },+ })["@graph"] as Node[];+ expect(video[0]).not.toHaveProperty("duration");+ expect(video[0]).toMatchObject({+ "@type": "VideoObject",+ creator: { "@type": "Person", name: "Ann" },+ });+ });+});diff --git a/lib/structured-data.ts b/lib/structured-data.tsindex 62613c7f..3b800dad 100644--- a/lib/structured-data.ts+++ b/lib/structured-data.ts@@ -92,6 +92,232 @@ export function homeJsonLd(description: string) {};}+const WEBSITE_ID = `${SITE_URL}/#website`;++/**+ * The Organization by reference, with its name and URL inline: the full node+ * lives on the home page, and Google wants an author name on every article.+ */+const ORG_REF = {+ "@type": "Organization",+ "@id": ORG_ID,+ name: "Remocn",+ url: SITE_URL,+};++function absolute(url: string): string {+ return url.startsWith("/") ? `${SITE_URL}${url}` : url;+}++/** Seconds as an ISO 8601 duration, e.g. 33.4 → "PT33S", 75 → "PT1M15S". */+export function isoDuration(seconds: number): string {+ const total = Math.max(1, Math.round(seconds));+ const minutes = Math.floor(total / 60);+ const rest = total % 60;+ return `PT${minutes ? `${minutes}M` : ""}${rest ? `${rest}S` : ""}`;+}++export type VideoInput = {+ name: string;+ description: string;+ /** The mp4 itself. */+ contentUrl: string;+ thumbnailUrl: string;+ uploadDate: Date | string;+ /** Seconds; left out when unknown. */+ duration?: number | null;+};++/**+ * A video Google can index and show in video results: name, thumbnail and+ * upload date are required, the mp4 URL lets it read the frames.+ */+export function videoObject(video: VideoInput) {+ const uploadDate =+ typeof video.uploadDate === "string"+ ? video.uploadDate+ : video.uploadDate.toISOString();+ return {+ "@type": "VideoObject",+ name: video.name,+ description: video.description,+ contentUrl: video.contentUrl,+ thumbnailUrl: [video.thumbnailUrl],+ uploadDate,+ ...(video.duration ? { duration: isoDuration(video.duration) } : {}),+ publisher: ORG_REF,+ };+}++export type Crumb = { label: string; href?: string };++/** Breadcrumbs from the site root to the page; the last one is the page. */+function breadcrumbList(url: string, crumbs: Crumb[]) {+ const trail = [{ label: "Remocn", href: "/" }, ...crumbs];+ return {+ "@type": "BreadcrumbList",+ itemListElement: trail.map((crumb, index) => ({+ "@type": "ListItem",+ position: index + 1,+ name: crumb.label,+ item: absolute(crumb.href ?? url),+ })),+ };+}++export type FaqItem = { question: string; answer: string };++/**+ * The questions of an MDX `<Faq>` block: paragraphs written as+ * `**Question?**` with the answer on the next line (see the Faq component).+ * Links keep their text and inline Markdown is dropped.+ */+export function faqFromMdx(raw: string): FaqItem[] {+ const block = /<Faq>([\s\S]*?)<\/Faq>/.exec(raw)?.[1];+ if (!block) return [];+ return block+ .split(/\n\s*\n/)+ .map((paragraph) => /^\s*\*\*(.+?)\*\*\s*\n([\s\S]+)$/.exec(paragraph))+ .filter((match): match is RegExpExecArray => Boolean(match))+ .map((match) => ({+ question: plain(match[1]),+ answer: plain(match[2]),+ }));+}++function plain(markdown: string): string {+ return markdown+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")+ .replace(/[*_`]/g, "")+ .replace(/\s+/g, " ")+ .trim();+}++export type DocsPageInput = {+ /** Path of the page, e.g. "/docs/transitions/zoom-blur". */+ url: string;+ title: string;+ description?: string;+ crumbs: Crumb[];+ image: string;+ /** Registry name, for pages that document an installable component. */+ component?: string;+ faq?: FaqItem[];+};++/**+ * JSON-LD for a docs page: the page as a TechArticle, its breadcrumb trail,+ * the component it documents as source code, and its FAQ when it has one.+ */+export function docsPageJsonLd(page: DocsPageInput) {+ const url = absolute(page.url);+ const article = {+ "@type": "TechArticle",+ "@id": `${url}#article`,+ headline: page.title,+ ...(page.description ? { description: page.description } : {}),+ url,+ mainEntityOfPage: url,+ image: absolute(page.image),+ inLanguage: "en",+ isPartOf: { "@id": WEBSITE_ID },+ publisher: ORG_REF,+ author: ORG_REF,+ ...(page.component+ ? {+ about: {+ "@type": "SoftwareSourceCode",+ name: page.title,+ codeRepository: GITHUB_URL,+ programmingLanguage: "TypeScript",+ runtimePlatform: "Remotion",+ license: "https://opensource.org/licenses/MIT",+ url: `${SITE_URL}/r/${page.component}.json`,+ },+ }+ : {}),+ };+ const graph: unknown[] = [article, breadcrumbList(page.url, page.crumbs)];+ if (page.faq?.length) {+ graph.push({+ "@type": "FAQPage",+ "@id": `${url}#faq`,+ mainEntity: page.faq.map((item) => ({+ "@type": "Question",+ name: item.question,+ acceptedAnswer: { "@type": "Answer", text: item.answer },+ })),+ });+ }+ return { "@context": "https://schema.org", "@graph": graph };+}++export type BlogPostInput = {+ url: string;+ title: string;+ description: string;+ date: Date;+ image: string;+ video?: VideoInput;+};++/** JSON-LD for a blog post, with the video it is about when it has one. */+export function blogPostJsonLd(post: BlogPostInput) {+ const url = absolute(post.url);+ return {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "BlogPosting",+ "@id": `${url}#post`,+ headline: post.title,+ description: post.description,+ url,+ mainEntityOfPage: url,+ image: absolute(post.image),+ datePublished: post.date.toISOString(),+ inLanguage: "en",+ isPartOf: { "@id": WEBSITE_ID },+ author: ORG_REF,+ publisher: ORG_REF,+ ...(post.video ? { video: videoObject(post.video) } : {}),+ },+ breadcrumbList(post.url, [+ { label: "Blog", href: "/blog" },+ { label: post.title },+ ]),+ ],+ };+}++/** JSON-LD for a showcase: the video itself, made by its author. */+export function showcaseJsonLd(showcase: {+ url: string;+ video: VideoInput;+ author: { name: string; url: string | null };+}) {+ const url = absolute(showcase.url);+ return {+ "@context": "https://schema.org",+ "@graph": [+ {+ ...videoObject(showcase.video),+ "@id": `${url}#video`,+ url,+ creator: {+ "@type": "Person",+ name: showcase.author.name,+ ...(showcase.author.url ? { url: showcase.author.url } : {}),+ },+ },+ breadcrumbList(showcase.url, [+ { label: "Showcases", href: "/showcases" },+ { label: showcase.video.name },+ ]),+ ],+ };+}+/** `JSON.stringify` safe to inline in a `<script>` (Next's JSON-LD guide). */export function serializeJsonLd(data: unknown): string {return JSON.stringify(data).replace(/</g, "\\u003c");