Repository navigation
Avoid duplicate rendered titles across Astro docs #78696
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+288
−1
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5dd913c
Deduplicate rendered docs titles and document sandbox commands
pelikhan cc8cf84
Merge branch 'main' into pelikhan/smart-docs-titles
pelikhan 353d7ed
Merge remote-tracking branch 'origin/main' into pelikhan/smart-docs-t…
gh-aw-bot 49c548d
Fix title deduplication edge cases
gh-aw-bot 8fdef96
Harden title deduplication review regressions
pelikhan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| // @ts-check | ||
| import { rehypeHeadingIds } from "@astrojs/markdown-remark"; | ||
|
|
||
| /** | ||
| * Keep Starlight's page title instead of a matching opening Markdown h1. | ||
| * @type {import('@astrojs/markdown-remark').RehypePlugin} | ||
| */ | ||
| export default function rehypeDeduplicateTitle() { | ||
| const addHeadingIds = rehypeHeadingIds(); | ||
| if (typeof addHeadingIds !== "function") { | ||
| throw new TypeError("Astro's heading ID plugin must return a transformer"); | ||
| } | ||
|
|
||
| return (tree, file) => { | ||
| const frontmatter = file.data.astro?.frontmatter; | ||
| const title = frontmatter?.hero?.title ?? frontmatter?.title; | ||
| if (typeof title !== "string" || !title.trim() || isLandingPage(file.path)) return; | ||
|
|
||
| const heading = tree.children.find(isContent); | ||
| if (heading?.type !== "element" || heading.tagName !== "h1") return; | ||
| const text = headingText(heading); | ||
| if (text === null || normalizeTitle(text) !== normalizeTitle(title)) return; | ||
|
|
||
| // Generate IDs before removing the heading to preserve existing deep links | ||
| // and slug suffixes on subsequent headings with the same text. | ||
| addHeadingIds(tree, file, error => { | ||
| if (error) throw error; | ||
| }); | ||
| heading.tagName = "span"; | ||
| heading.children = []; | ||
| }; | ||
| } | ||
|
|
||
| /** @param {import('unist').Node} node */ | ||
| function isContent(node) { | ||
| if (node.type === "comment" || node.type === "mdxjsEsm" || isCommentExpression(node)) return false; | ||
| if ("value" in node && typeof node.value === "string") { | ||
| if (node.type === "text" && !node.value.trim()) return false; | ||
|
pelikhan marked this conversation as resolved.
Resolved
|
||
| if (node.type === "raw" && /^\s*<!--[\s\S]*-->\s*$/.test(node.value)) return false; | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| /** @param {string | undefined} filePath */ | ||
| function isLandingPage(filePath) { | ||
| return typeof filePath === "string" && /(?:^|[/\\])src[/\\]content[/\\]docs[/\\]index\.mdx?$/.test(filePath); | ||
| } | ||
|
|
||
| /** @param {import('unist').Node} node */ | ||
| function isCommentExpression(node) { | ||
| if (node.type !== "mdxFlowExpression" || !node.data || !("estree" in node.data)) return false; | ||
| const program = node.data.estree; | ||
| return typeof program === "object" && program !== null && "body" in program && Array.isArray(program.body) && program.body.length === 0; | ||
| } | ||
|
|
||
| /** | ||
| * Compare visible text, but keep headings containing images or expressions. | ||
| * @param {import('hast').Nodes} node | ||
| * @returns {string | null} | ||
| */ | ||
| function headingText(node) { | ||
| if (node.type === "text") return node.value; | ||
| if (node.type !== "element" || node.tagName === "img") return null; | ||
| if (node.tagName === "br") return " "; | ||
| const children = node.children.map(headingText); | ||
| return children.includes(null) ? null : children.join(""); | ||
| } | ||
|
|
||
| /** @param {string} title */ | ||
| function normalizeTitle(title) { | ||
| return title.normalize("NFC").trim().replace(/\s+/g, " ").toLowerCase(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import assert from "node:assert/strict"; | ||
| import { test } from "node:test"; | ||
| import { fileURLToPath } from "node:url"; | ||
| import { compile } from "@mdx-js/mdx"; | ||
| import rehypeDeduplicateTitle from "./deduplicateTitle.js"; | ||
|
|
||
| async function transform(value, path = "page.mdx", title = "Page Title") { | ||
| let result; | ||
| await compile( | ||
| { | ||
| value, | ||
| path: fileURLToPath(new URL(`../../content/docs/${path}`, import.meta.url)), | ||
| data: { astro: { frontmatter: { title } } }, | ||
| }, | ||
| { | ||
| rehypePlugins: [ | ||
| rehypeDeduplicateTitle, | ||
| () => tree => { | ||
| result = tree; | ||
| }, | ||
| ], | ||
| } | ||
| ); | ||
| return result.children.find(node => node.type === "element"); | ||
| } | ||
|
|
||
| for (const extension of ["md", "mdx"]) { | ||
| test(`${extension}: the landing page retains its matching Markdown title`, async () => { | ||
| const heading = await transform("# Home", `index.${extension}`, "Home"); | ||
| assert.equal(heading.tagName, "h1"); | ||
| }); | ||
|
|
||
| test(`${extension}: a nested index still deduplicates its matching title`, async () => { | ||
| const heading = await transform("# Page Title", `guide/index.${extension}`); | ||
| assert.equal(heading.tagName, "span"); | ||
| }); | ||
| } | ||
|
|
||
| for (const expression of ["{/* Introductory comment */}", "{/* First comment */ /* Second comment */}", "{// Introductory comment\n}"]) { | ||
| test(`comment-only MDX expressions do not precede the title: ${expression}`, async () => { | ||
| const heading = await transform(`${expression}\n\n# Page Title`); | ||
| assert.equal(heading.tagName, "span"); | ||
| }); | ||
| } | ||
|
|
||
| for (const expression of ['{"Visible introduction"}', '{/* Before */ "Visible introduction" /* After */}', "{/* Before */ <p>Visible introduction</p> /* After */}"]) { | ||
| test(`renderable MDX expressions keep a later matching title: ${expression}`, async () => { | ||
| const heading = await transform(`${expression}\n\n# Page Title`); | ||
| assert.equal(heading.tagName, "h1"); | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| import assert from "node:assert/strict"; | ||
| import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; | ||
| import { join } from "node:path"; | ||
| import { after, before, test } from "node:test"; | ||
| import { fileURLToPath } from "node:url"; | ||
| import { build } from "astro"; | ||
|
|
||
| const docsRoot = fileURLToPath(new URL("../", import.meta.url)); | ||
| let root; | ||
|
|
||
| const cases = [ | ||
| { | ||
| name: "matching", | ||
| body: "<!-- Introductory comment -->\n\n# Page Title\n\nContent.\n\n| Column |\n| --- |\n| Cell |\n\n## Page Title", | ||
| headings: 1, | ||
| anchor: "page-title", | ||
| section: "page-title-1", | ||
| }, | ||
| { | ||
| name: "formatted", | ||
| title: "A Smart Title & Links", | ||
| body: "# A **smart** `Title` & [Links](#details)\n\n## Details", | ||
| headings: 1, | ||
| anchor: "a-smart-title--links", | ||
| }, | ||
| { name: "distinct", body: "# A different title", headings: 2 }, | ||
| { name: "later", body: "Introduction.\n\n# Page Title", headings: 2 }, | ||
| { name: "section", body: "## Page Title", headings: 1, section: "page-title" }, | ||
| { name: "code", body: "```md\n# Page Title\n```\n\n# Page Title", headings: 2 }, | ||
| { name: "no-heading", body: "Content without a heading.", headings: 1 }, | ||
| { name: "image", body: "# Page Title ", headings: 2 }, | ||
| { | ||
| name: "hero", | ||
| extra: 'hero:\n title: "Hero Title"\n', | ||
| body: "# Hero Title", | ||
| headings: 1, | ||
| anchor: "hero-title", | ||
| }, | ||
| { | ||
| name: "distinct-hero", | ||
| extra: 'hero:\n title: "Hero Title"\n', | ||
| body: "# Page Title", | ||
| headings: 2, | ||
| }, | ||
| ]; | ||
|
|
||
| before(async () => { | ||
| await mkdir(join(docsRoot, ".astro"), { recursive: true }); | ||
| root = await mkdtemp(join(docsRoot, ".astro/page-titles-")); | ||
| const content = join(root, "src/content/docs"); | ||
| await mkdir(content, { recursive: true }); | ||
|
pelikhan marked this conversation as resolved.
Resolved
|
||
| await writeFile( | ||
| join(root, "astro.config.mjs"), | ||
| ` | ||
| import { defineConfig } from 'astro/config'; | ||
| import starlight from '@astrojs/starlight'; | ||
| import productionConfig from ${JSON.stringify(join(docsRoot, "astro.config.mjs"))}; | ||
| export default defineConfig({ | ||
| site: 'https://github.github.com', | ||
| base: '/gh-aw/', | ||
| markdown: productionConfig.markdown, | ||
| integrations: [starlight({ | ||
| title: 'Docs', | ||
| components: { PageTitle: ${JSON.stringify(join(docsRoot, "src/components/PageTitle.astro"))} }, | ||
| })], | ||
| }); | ||
| ` | ||
| ); | ||
| await writeFile( | ||
| join(root, "src/content.config.ts"), | ||
| ` | ||
| import { defineCollection } from 'astro:content'; | ||
| import { docsLoader } from '@astrojs/starlight/loaders'; | ||
| import { docsSchema } from '@astrojs/starlight/schema'; | ||
| export const collections = { docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }) }; | ||
| ` | ||
| ); | ||
| await writeFile(join(content, "index.md"), "---\ntitle: Home\n---\n# Home\n"); | ||
| for (const extension of ["md", "mdx"]) { | ||
| for (const scenario of cases) { | ||
| const imports = extension === "mdx" ? "import { Card } from '@astrojs/starlight/components';\n\n" : ""; | ||
| const body = extension === "mdx" && scenario.name === "matching" ? scenario.body.replace("<!-- Introductory comment -->\n\n", "{/* Introductory comment */}\n\n") : scenario.body; | ||
| await writeFile(join(content, `${scenario.name}-${extension}.${extension}`), `---\ntitle: ${JSON.stringify(scenario.title ?? "Page Title")}\n${scenario.extra ?? ""}---\n${imports}${body}\n`); | ||
| } | ||
| await writeFile(join(content, "expression.mdx"), '---\ntitle: Page Title\n---\n# Page Title {"details"}\n'); | ||
| } | ||
| await writeFile(join(content, "unified-agent-session-specification.md"), await readFile(join(docsRoot, "src/content/docs/specs/unified-agent-session-specification.md"), "utf8")); | ||
| await build({ root, logLevel: "silent" }); | ||
| }); | ||
|
|
||
| after(async () => { | ||
| if (root) await rm(root, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| for (const extension of ["md", "mdx"]) { | ||
| for (const scenario of cases) { | ||
| test(`${extension}: ${scenario.name} keeps only redundant opening titles out of the output`, async () => { | ||
| const html = await readFile(join(root, "dist", `${scenario.name}-${extension}`, "index.html"), "utf8"); | ||
| assert.equal([...html.matchAll(/<h1\b/g)].length, scenario.headings); | ||
| assert.match(html, /<h1 id="_top"/); | ||
| if (scenario.anchor) { | ||
| assert.ok(html.includes(`<span id="${scenario.anchor}"></span>`), "original title anchor is preserved"); | ||
| assert.ok(!html.includes(`href="#${scenario.anchor}"`), "duplicate title is not in the table of contents"); | ||
| } | ||
| if (scenario.name === "matching") { | ||
| assert.match(html, /class="table-scroll-wrapper"/); | ||
| assert.match(html, /<td data-label="Column">Cell<\/td>/); | ||
| } | ||
| if (scenario.section) assert.ok(html.includes(`id="${scenario.section}"`), "section heading keeps its original slug"); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| test("the unified session specification renders its title once", async () => { | ||
| const html = await readFile(join(root, "dist/unified-agent-session-specification/index.html"), "utf8"); | ||
| assert.equal([...html.matchAll(/<h1\b/g)].length, 1); | ||
| assert.match(html, /<h1 id="_top"[^>]*>Unified Agent Session Specification<\/h1>/); | ||
| assert.match(html, /<span id="unified-agent-session-specification"><\/span>/); | ||
| }); | ||
|
|
||
| test("the landing page keeps its own title", async () => { | ||
| const html = await readFile(join(root, "dist/index.html"), "utf8"); | ||
| assert.equal([...html.matchAll(/<h1\b/g)].length, 1); | ||
| assert.match(html, /<h1 id="home">Home<\/h1>/); | ||
| }); | ||
|
|
||
| test("headings with MDX expressions keep their dynamic content", async () => { | ||
| const html = await readFile(join(root, "dist/expression/index.html"), "utf8"); | ||
| assert.equal([...html.matchAll(/<h1\b/g)].length, 2); | ||
| assert.match(html, /Page Title details<\/h1>/); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.