From 20b7aacc1ed05c3db59fae41e652b8cdc763df2c Mon Sep 17 00:00:00 2001 From: Kirill Mokevnin Date: Sat, 21 Nov 2026 10:05:48 -0500 Subject: [PATCH] fix: keep chapter descriptions after hydration The VitePress client rewrote meta description to the empty frontmatter description, falling back to the site's, so every rendered page showed the same English text. A markdown-it plugin now writes the description into the frontmatter; the table of contents takes its locale home's. Also give each og:locale:alternate tag an id, since VitePress kept only one meta per key. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- book/.vitepress/config.mjs | 2 + book/.vitepress/seo.mjs | 95 ++++++++++++++++++++----- tests/seo.test.mjs | 139 ++++++++++++++++++++++++++----------- 4 files changed, 181 insertions(+), 59 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d0c5a20..a76a900 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,7 +21,9 @@ Operating guide for agents (and humans) working in this repository. ## SEO and link previews -- `book/.vitepress/seo.mjs` adds per-page head tags in VitePress's `transformHead`: `meta description` from the chapter text, canonical, `hreflang` and Open Graph/Twitter tags. `sitemap.xml` is VitePress's own, with an x-default alternate added. +- `book/.vitepress/seo.mjs` adds per-page head tags in VitePress's `transformHead`: `meta description`, canonical, `hreflang` and Open Graph/Twitter tags. `sitemap.xml` is VitePress's own, with an x-default alternate added. +- The description is written into the page's frontmatter by a markdown-it plugin while the page renders, not computed in `transformHead`: the VitePress client rewrites `meta description` to the frontmatter description (or the site's) on hydration. A `description:` in a page's frontmatter overrides it. A locale page with no prose (the table of contents) takes its locale home page's description. +- VitePress keeps one `meta` per key (its `id`, else its first attribute besides `content`), so a repeated meta such as `og:locale:alternate` needs a distinct `id` on each tag. - The public URL, base path and preview image live in `book/.vitepress/config.mjs`; change `BASE_URL` and `base` there when the site moves to its own domain. - The description is the first paragraph of a pattern's intent section, or an anti-pattern's problem section; other pages use their first paragraph, skipping an all-italic note. The section heading ids per locale are `descriptionSections` in the same config: add the id there when a new chapter kind opens differently. That paragraph should state the chapter's point on its own. - Preview cards are `book/assets/og/.png`, rendered from `book/.vitepress/og-card.html`; the command to rerender one is at the top of that file. diff --git a/book/.vitepress/config.mjs b/book/.vitepress/config.mjs index 2843e69..e9c5dd8 100644 --- a/book/.vitepress/config.mjs +++ b/book/.vitepress/config.mjs @@ -182,6 +182,7 @@ export default defineConfig({ anchor: { slugify: (text) => slugid(text.trim()) }, config: (md) => { md.use(mermaidMarkdown); + md.use(seo.markdown); const linkOpen = md.renderer.rules.link_open; md.renderer.rules.link_open = (tokens, index, options, env, self) => { const token = tokens[index]; @@ -209,6 +210,7 @@ export default defineConfig({ transformItems: seo.sitemapItems }, + transformPageData: seo.transformPageData, transformHead: seo.transformHead, // Shared files (preview cards, chapter samples) keep their plain URLs under diff --git a/book/.vitepress/seo.mjs b/book/.vitepress/seo.mjs index a34edce..eb4f2d7 100644 --- a/book/.vitepress/seo.mjs +++ b/book/.vitepress/seo.mjs @@ -4,8 +4,16 @@ // the chapter itself, canonical and hreflang links, and Open Graph and Twitter // card tags. The sitemap is VitePress's own; `sitemapItems` only adds the // x-default alternate and keeps the language picker out of the locale groups. +// +// The description lives in the page's frontmatter, filled while the Markdown +// renders, because the VitePress client rewrites to +// the frontmatter description (or the site's) as soon as the page hydrates. + +import fs from 'node:fs'; +import path from 'node:path'; import * as cheerio from 'cheerio'; +import { createMarkdownRenderer } from 'vitepress'; const DESCRIPTION_LENGTH = 160; @@ -17,7 +25,8 @@ const OG_LOCALES = { ru: 'ru_RU', en: 'en_US', es: 'es_ES' }; * @typedef {object} SeoOptions * @property {string} baseUrl public URL of the site root, ending in "/" * @property {string} siteName - * @property {string} siteDescription stands in on the language picker + * @property {string} siteDescription stands in when a page and its locale's + * home page have no prose to describe them * @property {string[]} locales * @property {string} defaultLocale the x-default and the picker's language * @property {string} image preview card path under baseUrl; "{locale}" is replaced @@ -48,13 +57,13 @@ export function truncate(text) { * problem). Other pages use their first paragraph, skipping an all-italic note * such as a tool chapter's "checked on" line. * - * @param {string} html the page's rendered content + * @param {string} html the page's rendered Markdown * @param {string[]} sections heading ids, most preferred first * @returns {string} */ export function describe(html, sections) { - const $ = cheerio.load(html); - const content = $('.vp-doc > div').first(); + const $ = cheerio.load(html, null, false); + const content = $.root(); /** @param {import('cheerio').Cheerio} paragraphs */ const firstProse = (paragraphs) => @@ -125,8 +134,56 @@ export function createSeo(options) { Object.entries(tags).map(([name, content]) => ['meta', { [key]: name, content }]); return { + /** + * markdown-it plugin: describe each page from its rendered content, unless + * its frontmatter already has a description. + * + * @param {import('vitepress').MarkdownRenderer} md + */ + markdown(md) { + const render = md.renderer.render.bind(md.renderer); + md.renderer.render = (tokens, markdownOptions, env) => { + const html = render(tokens, markdownOptions, env); + env.frontmatter ??= {}; + if (!env.frontmatter.description) { + const description = describe(html, options.descriptionSections); + if (description) { + env.frontmatter.description = description; + } + } + return html; + }; + }, + + /** + * A locale page with no prose of its own (the table of contents) takes the + * description of the locale's home page. + * + * @type {NonNullable} + */ + async transformPageData(pageData, { siteConfig }) { + const [locale] = pageData.relativePath.split('/'); + const home = `${locale}/index.md`; + if (pageData.description || !locales.includes(locale) || pageData.relativePath === home) { + return; + } + const source = siteConfig.rewrites.inv[home] || home; + const file = path.join(siteConfig.srcDir, source); + const md = await createMarkdownRenderer( + siteConfig.srcDir, + siteConfig.markdown, + siteConfig.site.base, + siteConfig.logger + ); + /** @type {import('vitepress').MarkdownEnv} */ + const env = { path: file, relativePath: home, cleanUrls: siteConfig.cleanUrls }; + await md.renderAsync(fs.readFileSync(file, 'utf8'), env); + const description = env.frontmatter?.description; + return description ? { description } : undefined; + }, + /** @type {(context: import('vitepress').TransformContext) => import('vitepress').HeadConfig[]} */ - transformHead({ page, siteConfig, pageData, content }) { + transformHead({ page, siteConfig, pageData }) { if (page === '404.md') { return []; } @@ -138,9 +195,7 @@ export function createSeo(options) { const alternates = alternatesFor(siteConfig).get(slug) || []; const url = baseUrl + pathFor(page); const title = isPicker ? options.siteName : pageData.title; - const description = - describe(content, options.descriptionSections) || - (isPicker ? truncate(options.siteDescription) : ''); + const description = pageData.description || truncate(options.siteDescription); const image = baseUrl + options.image.replace('{locale}', locale); /** @type {import('vitepress').HeadConfig[]} */ @@ -162,28 +217,32 @@ export function createSeo(options) { 'og:site_name': options.siteName, 'og:title': title, 'og:url': url, - 'og:locale': OG_LOCALES[locale] || locale + 'og:locale': OG_LOCALES[locale] || locale, + 'og:description': description, + 'og:image': image, + 'og:image:alt': options.siteName, + 'og:image:width': String(options.imageWidth), + 'og:image:height': String(options.imageHeight) }; - if (description) { - og['og:description'] = description; - } - og['og:image'] = image; - og['og:image:alt'] = options.siteName; - og['og:image:width'] = String(options.imageWidth); - og['og:image:height'] = String(options.imageHeight); return [ - // Replaces the site-wide description VitePress would otherwise emit. + // Replaces the tag VitePress emits, which falls back to the site description. ['meta', { name: 'description', content: description }], ...links, ...meta(og, 'property'), + // VitePress keeps one meta per key (its id, else its first attribute + // besides content), so repeated og:locale:alternate tags each need an id. ...alternates .filter((alternate) => alternate !== locale) .map( (alternate) => /** @type {import('vitepress').HeadConfig} */ ([ 'meta', - { property: 'og:locale:alternate', content: OG_LOCALES[alternate] || alternate } + { + id: `og-locale-alternate-${alternate}`, + property: 'og:locale:alternate', + content: OG_LOCALES[alternate] || alternate + } ]) ), ...meta({ 'twitter:card': 'summary_large_image' }, 'name') diff --git a/tests/seo.test.mjs b/tests/seo.test.mjs index 4c434c8..7d014ef 100644 --- a/tests/seo.test.mjs +++ b/tests/seo.test.mjs @@ -3,21 +3,54 @@ import { test } from 'node:test'; import { createSeo, describe, truncate } from '../book/.vitepress/seo.mjs'; -/** @param {string} body */ -const page = (body) => `
${body}
`; +const newSeo = () => + createSeo({ + baseUrl: 'https://example.org/book/', + siteName: 'Book', + siteDescription: 'About the book', + locales: ['ru', 'en', 'es'], + defaultLocale: 'en', + image: 'assets/og/{locale}.png', + imageWidth: 1200, + imageHeight: 630, + descriptionSections: ['назначение'] + }); + +/** + * @param {string} page + * @param {string[]} pages + * @param {Record} pageData + */ +const headFor = (page, pages, pageData) => + // The page list is read once per instance, so each case gets its own. + newSeo().transformHead( + /** @type {any} */ ({ + page, + siteConfig: { pages, rewrites: { map: { 'ru/README.md': 'ru/index.md' } } }, + pageData: { title: 'T', ...pageData } + }) + ); + +/** + * @param {import('vitepress').HeadConfig[]} head + * @param {Record} attributes + */ +const find = (head, attributes) => + head.find(([, attrs]) => + Object.entries(attributes).every(([key, value]) => attrs[key] === value) + )?.[1]; test('the description is the first paragraph of the preferred section', () => { - const html = page( + const html = '

Title

Lead.

' + - '

Problem

The problem.

' + - '

Intent

A note.

The intent.

' - ); + '

Problem

The problem.

' + + '

Intent

A note.

The intent.

'; assert.equal(describe(html, ['intent', 'problem']), 'The intent.'); assert.equal(describe(html, ['propósito', 'problem']), 'The problem.'); }); test('without a listed section the description skips an all-italic note', () => { - const html = page('

Tool

Checked on 2026-11-01.

What it is.

'); + const html = '

Tool

Checked on 2026-11-01.

What it is.

'; assert.equal(describe(html, ['intent']), 'What it is.'); }); @@ -28,42 +61,68 @@ test('a long description is cut on a word boundary', () => { assert.match(result, /word…$/); }); -test('head tags carry canonical, hreflang and x-default links', () => { - const seo = createSeo({ - baseUrl: 'https://example.org/book/', - siteName: 'Book', - siteDescription: 'About the book', - locales: ['ru', 'en', 'es'], - defaultLocale: 'en', - image: 'assets/og/{locale}.png', - imageWidth: 1200, - imageHeight: 630, - descriptionSections: ['назначение'] - }); - const siteConfig = /** @type {any} */ ({ - pages: ['ru/grilling.md', 'en/grilling.md', 'ru/README.md'], - rewrites: { map: { 'ru/README.md': 'ru/index.md' } } +test('the markdown plugin puts the description into the frontmatter', () => { + const html = '

Гриллинг

Назначение

Суть.

'; + const md = /** @type {any} */ ({ renderer: { render: () => html } }); + newSeo().markdown(md); + + /** @type {Record} */ + const env = {}; + assert.equal(md.renderer.render([], {}, env), html); + assert.equal(env.frontmatter.description, 'Суть.'); + + const written = { frontmatter: { description: 'Written by hand.' } }; + md.renderer.render([], {}, written); + assert.equal(written.frontmatter.description, 'Written by hand.'); +}); + +test('head tags carry the description, canonical, hreflang and x-default links', () => { + const head = headFor('ru/grilling.md', ['ru/grilling.md', 'en/grilling.md', 'ru/README.md'], { + description: 'Суть.' }); - const head = seo.transformHead( - /** @type {any} */ ({ - page: 'ru/grilling.md', - siteConfig, - pageData: { title: 'Гриллинг' }, - content: page('

Гриллинг

Назначение

Суть.

') - }) - ); - const find = (/** @type {Record} */ attributes) => - head.find(([, attrs]) => - Object.entries(attributes).every(([key, value]) => attrs[key] === value) - )?.[1]; - assert.equal(find({ name: 'description' })?.content, 'Суть.'); - assert.equal(find({ rel: 'canonical' })?.href, 'https://example.org/book/ru/grilling.html'); - assert.equal(find({ hreflang: 'en' })?.href, 'https://example.org/book/en/grilling.html'); - assert.equal(find({ hreflang: 'x-default' })?.href, 'https://example.org/book/en/grilling.html'); - assert.equal(find({ hreflang: 'es' }), undefined); + assert.equal(find(head, { name: 'description' })?.content, 'Суть.'); + assert.equal(find(head, { property: 'og:description' })?.content, 'Суть.'); + assert.equal(find(head, { rel: 'canonical' })?.href, 'https://example.org/book/ru/grilling.html'); + assert.equal(find(head, { hreflang: 'en' })?.href, 'https://example.org/book/en/grilling.html'); assert.equal( - find({ property: 'og:image' })?.content, + find(head, { hreflang: 'x-default' })?.href, + 'https://example.org/book/en/grilling.html' + ); + assert.equal(find(head, { hreflang: 'es' }), undefined); + assert.equal( + find(head, { property: 'og:image' })?.content, 'https://example.org/book/assets/og/ru.png' ); }); + +test('a page with no description falls back to the site description', () => { + const head = headFor('ru/SUMMARY.md', ['ru/SUMMARY.md'], { description: '' }); + assert.equal(find(head, { name: 'description' })?.content, 'About the book'); +}); + +// VitePress's mergeHead keeps one meta per key: its id, else its first +// attribute other than content. +/** @param {import('vitepress').HeadConfig} tag */ +const headKey = ([type, attrs]) => { + if (attrs.id) { + return `id=${attrs.id}`; + } + if (type === 'meta') { + const name = Object.keys(attrs).find((key) => key !== 'content'); + return name && `${name}=${attrs[name]}`; + } + return undefined; +}; + +test('every locale alternate survives VitePress head deduplication', () => { + const head = headFor('ru/grilling.md', ['ru/grilling.md', 'en/grilling.md', 'es/grilling.md'], { + description: 'Суть.' + }); + const keys = head.map(headKey).filter(Boolean); + assert.deepEqual(keys, [...new Set(keys)]); + const alternates = head + .filter(([, attrs]) => attrs.property === 'og:locale:alternate') + .map(([, attrs]) => attrs.content); + assert.deepEqual(alternates, ['en_US', 'es_ES']); +});