Skip to content

Commit 23a976b

Browse files
authored
feat(docs): give docs pages an SEO title, Open Graph, and structured data (#186)
Fixes #166 generateMetadata returned four fields, so all 79 English pages and every translation shipped a title tag built from the short navigational noun, no share card, and no structured data. This adds the mechanism for all three and authors no content. An optional seoTitle frontmatter field lets a page declare a title tag separate from its H1; generateMetadata prefers it and falls back to title, so the sidebar, breadcrumb and H1 keep the short noun. Built from pageSchema.shape.title rather than a fresh zod import, because zod is a peer dependency of fumadocs-core and does not resolve from apps/docs. .trim().min(1) rejects an empty value at build time, which is what earns the plain ?? fallback in the consumer. Open Graph and Twitter now point at the 1200x630 card that the OG route was already generating for every page and that nothing referenced. JSON-LD emits BreadcrumbList and TechArticle, rendered from the page component because the Metadata API has no channel for a script element. TechArticle deliberately carries no publisher or author: those are entity-level claims and issue #171 has not settled which entity this site speaks for. The share card's site= string said "ObjectStack Protocol", a different product. Both use sites now read one exported SITE_NAME constant. Verified from prerendered HTML: 79 of 79 English pages keep their existing title tag, and removing the schema extension turns type-check red with TS2339 naming the field, proving page.data.seoTitle resolves against the generated collection type rather than any.
1 parent c243ad7 commit 23a976b

4 files changed

Lines changed: 236 additions & 34 deletions

File tree

Lines changed: 190 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { source } from '@/lib/source';
1+
import { SITE_NAME, getPageImage, source } from '@/lib/source';
22
import type { Metadata } from 'next';
33
import { DocsBody, DocsDescription, DocsPage, DocsTitle } from 'fumadocs-ui/layouts/docs/page';
44
import { notFound } from 'next/navigation';
@@ -9,7 +9,118 @@ import { File, Folder, Files } from 'fumadocs-ui/components/files';
99
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
1010
import { LLMCopyButton, ViewOptions } from '@/components/ai/page-actions';
1111
import { gitConfig } from '@/lib/layout.shared';
12-
import { languageAlternates, localeUrl, translatedLocales } from '@/lib/seo';
12+
import { SITE_URL, languageAlternates, localeUrl, translatedLocales } from '@/lib/seo';
13+
import type { InferPageType } from 'fumadocs-core/source';
14+
15+
/**
16+
* The page type the loader actually produces, frontmatter schema included.
17+
*
18+
* Deliberately inferred rather than hand-written: a structural annotation like
19+
* `{ data: { seoTitle?: string } }` would type-check whether or not the schema
20+
* extension in `source.config.ts` ever reached the generated collection types,
21+
* which is exactly the thing that has to be true for `seoTitle` to arrive.
22+
* Inferring it means `tsc` fails if the field is not really there.
23+
*/
24+
type DocsPageData = InferPageType<typeof source>;
25+
26+
/** Logical, locale-independent path of a docs page, e.g. `docs/build/interface/views`. */
27+
function docsPath(slugs: string[]): string {
28+
return ['docs', ...slugs].join('/');
29+
}
30+
31+
/**
32+
* The string the `<title>` tag should carry. A page may declare `seoTitle` when
33+
* its H1 noun is too short to match anything a reader would search for; most
34+
* pages declare nothing and fall back to `title`, rendering byte-identically to
35+
* before this field existed. `??` is safe rather than lax because the schema
36+
* rejects an empty or whitespace-only `seoTitle` at build time.
37+
*/
38+
function seoTitleOf(page: DocsPageData): string {
39+
return page.data.seoTitle ?? page.data.title;
40+
}
41+
42+
/** Absolute URL of the generated 1200x630 share card for a page. */
43+
function shareCardUrl(page: DocsPageData): string {
44+
return `${SITE_URL}${getPageImage(page).url}`;
45+
}
46+
47+
/**
48+
* Open Graph wants `language_TERRITORY`. Our locale tags carry no territory
49+
* (`en`, `zh-Hans`, `ja`, …), so the honest mapping is the tag with the
50+
* separator swapped — the same one the marketing site emits, which keeps
51+
* og:locale consistent across the two properties.
52+
*/
53+
function ogLocale(lang: string): string {
54+
return lang.replace('-', '_');
55+
}
56+
57+
/** `record-access` -> `Record access`, for a path segment with no page to name it. */
58+
function humanizeSegment(segment: string): string {
59+
const spaced = segment.replace(/-/g, ' ');
60+
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
61+
}
62+
63+
/**
64+
* Serialize a JSON-LD node for injection into a `<script>` tag.
65+
*
66+
* Every `<` is rewritten to the six-character JSON escape backslash-u-0-0-3-c,
67+
* which parses back to the same character but cannot be read as markup. Without
68+
* it a closing script tag inside a title or description would end the block
69+
* early and drop the rest of the JSON into the document as markup.
70+
*/
71+
function jsonLdHtml(value: Record<string, unknown>): string {
72+
return JSON.stringify(value).replace(/</g, '\\u003c');
73+
}
74+
75+
/**
76+
* `BreadcrumbList` over the page's own ancestry: the docs root, then every
77+
* prefix of its slugs. Each crumb is named by the page that actually sits at
78+
* that path so the name matches what a reader sees in the sidebar; a folder
79+
* with no index page falls back to its humanized segment.
80+
*/
81+
function breadcrumbListLd(lang: string, slugs: string[]): Record<string, unknown> {
82+
const trails = [[] as string[], ...slugs.map((_, i) => slugs.slice(0, i + 1))];
83+
84+
return {
85+
'@context': 'https://schema.org',
86+
'@type': 'BreadcrumbList',
87+
itemListElement: trails.map((trail, index) => ({
88+
'@type': 'ListItem',
89+
position: index + 1,
90+
name:
91+
source.getPage(trail, lang)?.data.title ??
92+
humanizeSegment(trail[trail.length - 1] ?? 'docs'),
93+
item: localeUrl(lang, docsPath(trail)),
94+
})),
95+
};
96+
}
97+
98+
/**
99+
* `TechArticle` for a docs page.
100+
*
101+
* Deliberately carries no `publisher`/`author`: those are entity-level claims
102+
* about the organization, and which entity this site speaks for is the open
103+
* question on the positioning card. A TechArticle without them is valid; a
104+
* TechArticle asserting the wrong entity would have to be retracted.
105+
*/
106+
function techArticleLd(args: {
107+
lang: string;
108+
title: string;
109+
description?: string;
110+
url: string;
111+
image: string;
112+
}): Record<string, unknown> {
113+
return {
114+
'@context': 'https://schema.org',
115+
'@type': 'TechArticle',
116+
headline: args.title,
117+
...(args.description ? { description: args.description } : {}),
118+
url: args.url,
119+
image: args.image,
120+
inLanguage: args.lang,
121+
isAccessibleForFree: true,
122+
};
123+
}
13124

14125
export default async function Page(props: {
15126
params: Promise<{ lang: string; slug?: string[] }>;
@@ -20,33 +131,58 @@ export default async function Page(props: {
20131

21132
const MDX = page.data.body;
22133

134+
// Structured data. Emitted from the page rather than from `generateMetadata`,
135+
// which can only produce meta/link elements — the Metadata API has no channel
136+
// for a JSON-LD script. Google reads `application/ld+json` from either the
137+
// head or the body, so rendering it here is a supported placement, not a
138+
// workaround.
139+
const jsonLd = [
140+
breadcrumbListLd(params.lang, page.slugs),
141+
techArticleLd({
142+
lang: params.lang,
143+
title: seoTitleOf(page),
144+
description: page.data.description,
145+
url: localeUrl(params.lang, docsPath(page.slugs)),
146+
image: shareCardUrl(page),
147+
}),
148+
];
149+
23150
return (
24-
<DocsPage toc={page.data.toc} full={page.data.full}>
25-
<DocsTitle>{page.data.title}</DocsTitle>
26-
<DocsDescription className="mb-0">{page.data.description}</DocsDescription>
27-
<div className="flex flex-row gap-2 items-center border-b pb-6">
28-
<LLMCopyButton markdownUrl={`${page.url}.mdx`} />
29-
<ViewOptions
30-
markdownUrl={`${page.url}.mdx`}
31-
githubUrl={`https://github.com/${gitConfig.user}/${gitConfig.repo}/blob/${gitConfig.branch}/content/docs/${page.path}`}
151+
<>
152+
{jsonLd.map((item) => (
153+
<script
154+
key={item['@type'] as string}
155+
type="application/ld+json"
156+
dangerouslySetInnerHTML={{ __html: jsonLdHtml(item) }}
32157
/>
33-
</div>
34-
<DocsBody>
35-
<MDX
36-
components={getMDXComponents({
37-
a: createRelativeLink(source, page),
38-
Step,
39-
Steps,
40-
File,
41-
Folder,
42-
Files,
43-
FileTree: Files,
44-
Tab,
45-
Tabs,
46-
})}
47-
/>
48-
</DocsBody>
49-
</DocsPage>
158+
))}
159+
<DocsPage toc={page.data.toc} full={page.data.full}>
160+
<DocsTitle>{page.data.title}</DocsTitle>
161+
<DocsDescription className="mb-0">{page.data.description}</DocsDescription>
162+
<div className="flex flex-row gap-2 items-center border-b pb-6">
163+
<LLMCopyButton markdownUrl={`${page.url}.mdx`} />
164+
<ViewOptions
165+
markdownUrl={`${page.url}.mdx`}
166+
githubUrl={`https://github.com/${gitConfig.user}/${gitConfig.repo}/blob/${gitConfig.branch}/content/docs/${page.path}`}
167+
/>
168+
</div>
169+
<DocsBody>
170+
<MDX
171+
components={getMDXComponents({
172+
a: createRelativeLink(source, page),
173+
Step,
174+
Steps,
175+
File,
176+
Folder,
177+
Files,
178+
FileTree: Files,
179+
Tab,
180+
Tabs,
181+
})}
182+
/>
183+
</DocsBody>
184+
</DocsPage>
185+
</>
50186
);
51187
}
52188

@@ -62,17 +198,40 @@ export async function generateMetadata(props: {
62198
if (!page) notFound();
63199

64200
// Logical path is locale-independent; reconstruct each locale URL from slugs.
65-
const path = ['docs', ...page.slugs].join('/');
201+
const path = docsPath(page.slugs);
202+
const canonical = localeUrl(params.lang, path);
203+
const title = seoTitleOf(page);
204+
const description = page.data.description;
205+
const image = shareCardUrl(page);
66206

67207
return {
68-
title: page.data.title,
69-
description: page.data.description,
208+
title,
209+
description,
70210
alternates: {
71-
canonical: localeUrl(params.lang, path),
211+
canonical,
72212
// Only the locales that really have this page. The cluster is keyed by
73213
// the logical path, not by params.lang, so every page in it advertises
74214
// the same reciprocal set.
75215
languages: languageAlternates(path, translatedLocales(page.slugs)),
76216
},
217+
openGraph: {
218+
type: 'article',
219+
url: canonical,
220+
siteName: SITE_NAME,
221+
// Set explicitly rather than inherited: the root layout's `%s | ObjectOS`
222+
// template belongs on the title tag, where the brand suffix helps. Here
223+
// `siteName` already carries the brand, so repeating it would render
224+
// "Views | ObjectOS — ObjectOS" in a share preview.
225+
title,
226+
description,
227+
locale: ogLocale(params.lang),
228+
images: [{ url: image, width: 1200, height: 630, alt: title }],
229+
},
230+
twitter: {
231+
card: 'summary_large_image',
232+
title,
233+
description,
234+
images: [image],
235+
},
77236
};
78237
}

‎apps/docs/app/og/docs/[...slug]/route.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { getPageImage, source } from '@/lib/source';
1+
import { SITE_NAME, getPageImage, source } from '@/lib/source';
22
import { notFound } from 'next/navigation';
33
import { ImageResponse } from 'next/og';
44
import { generate as DefaultImage } from 'fumadocs-ui/og';
@@ -17,7 +17,7 @@ export async function GET(
1717
<DefaultImage
1818
title={page.data.title}
1919
description={page.data.description}
20-
site="ObjectStack Protocol"
20+
site={SITE_NAME}
2121
/>,
2222
{
2323
width: 1200,

‎apps/docs/lib/source.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,20 @@ export const source = loader({
1010
plugins: [lucideIconsPlugin()],
1111
});
1212

13+
/**
14+
* The product name, as it should appear to a reader — in `og:site_name`, on the
15+
* generated share card, anywhere the brand is spelled out.
16+
*
17+
* It is a constant rather than a literal at each use site because the two use
18+
* sites had already drifted: the share-card generator was passing "ObjectStack
19+
* Protocol", a different product, while the metadata said "ObjectOS". One
20+
* exported string is what stops the next consumer from inventing a fourth
21+
* spelling. It lives here, next to `getPageImage`, because `lib/seo.ts` — the
22+
* other plausible home — imports this module, and putting it there would make
23+
* the dependency circular.
24+
*/
25+
export const SITE_NAME = 'ObjectOS';
26+
1327
export function getPageImage(page: InferPageType<typeof source>) {
1428
const segments = [...page.slugs, 'image.png'];
1529

‎apps/docs/source.config.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,36 @@ import path from 'node:path';
55
export const docs = defineDocs({
66
dir: path.resolve(process.cwd(), '../../content/docs'),
77
docs: {
8-
schema: pageSchema,
8+
schema: pageSchema.extend({
9+
/**
10+
* Optional SEO title: what the `<title>` tag should say, when that is not
11+
* what the H1 and the sidebar should say.
12+
*
13+
* `title` stays the short navigational noun ("Views") because it is what
14+
* renders in the sidebar, the breadcrumb and the H1. That same noun makes
15+
* a title tag carrying no query term at all, so a page may declare a
16+
* longer, keyword-bearing `seoTitle` here and `generateMetadata` prefers
17+
* it. Declaring nothing is the norm: the fallback is `title`, so a page
18+
* that says nothing renders exactly what it rendered before.
19+
*
20+
* Extending is not optional bookkeeping — the base `pageSchema` is a Zod
21+
* object with the default "strip" behaviour, so a `seoTitle:` in
22+
* frontmatter that is not declared here is silently dropped at parse time
23+
* rather than reaching `page.data`.
24+
*
25+
* Built from `pageSchema.shape.title` rather than a fresh `z.string()`
26+
* because `zod` is a *peer* dependency of fumadocs-core and is not
27+
* resolvable from this workspace — `require.resolve('zod')` fails in
28+
* `apps/docs`. Reusing the shape keeps the field's type identical to
29+
* `title`'s without adding a dependency to declare it.
30+
*
31+
* `.trim().min(1)` is deliberate: an empty or whitespace-only `seoTitle`
32+
* is an authoring mistake, and rejecting it at build time is what lets
33+
* the consumer use a plain `??` fallback instead of a tolerant one that
34+
* would quietly paper over the empty string.
35+
*/
36+
seoTitle: pageSchema.shape.title.trim().min(1).optional(),
37+
}),
938
postprocess: {
1039
includeProcessedMarkdown: true,
1140
},

0 commit comments

Comments
 (0)