An open source design system that's fully customizable and agent ready
TypeScript
fix(core): render Markdown heading ids so Outline links scroll (#4173) (#4765)
Jiun Shin6bd4a757835a
diff --git a/.changeset/render-generated-id-attributes-on-markdown-headi-qcnn.md b/.changeset/render-generated-id-attributes-on-markdown-headi-qcnn.mdnew file mode 100644index 0000000000..83bb625ade--- /dev/null+++ b/.changeset/render-generated-id-attributes-on-markdown-headi-qcnn.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Render generated id attributes on Markdown headings so Outline hash links scroll to their target. Heading slugs now come from parser helpers shared with parseOutlineFromMarkdown, and the components.heading override receives the generated id.+@jiunshinndiff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjsindex 52dd698804..153128c5f1 100644--- a/packages/core/src/Markdown/Markdown.doc.mjs+++ b/packages/core/src/Markdown/Markdown.doc.mjs@@ -169,6 +169,7 @@ export const docs = {{ guidance: true, description: 'Set headingLevelStart to match the page hierarchy, e.g. start at 3 if the markdown sits inside an h2 section.' },{ guidance: true, description: 'Use contentWidth to keep prose at a readable line length in wide layouts.' },{ guidance: true, description: 'Use inlinePlugins for custom shorthand patterns like issue refs, diff refs, and mentions instead of preprocessing the markdown string.' },+ { guidance: true, description: 'Pair with Outline and useOutlineFromMarkdown for section navigation: headings render generated id attributes that match the outline item ids, so hash links scroll to their target.' },{ guidance: false, description: 'Use Markdown for hand-authored layouts; use Text and Heading directly when you control the content.' },],},@@ -381,6 +382,7 @@ export const docsZh = {{ guidance: true, description: 'Set headingLevelStart to match the page hierarchy, e.g. start at 3 if the markdown sits inside an h2 section.' },{ guidance: true, description: 'Use contentWidth to keep prose at a readable line length in wide layouts.' },{ guidance: true, description: 'Use inlinePlugins for custom shorthand patterns like issue refs, diff refs, and mentions instead of preprocessing the markdown string.' },+ { guidance: true, description: 'Pair with Outline and useOutlineFromMarkdown for section navigation: headings render generated id attributes that match the outline item ids, so hash links scroll to their target.' },{ guidance: false, description: 'Use Markdown for hand-authored layouts; use Text and Heading directly when you control the content.' },],},@@ -396,6 +398,7 @@ export const docsDense = {{ guidance: true, description: 'Set headingLevelStart to match the page hierarchy, e.g. start at 3 if the markdown sits inside an h2 section.' },{ guidance: true, description: 'Use contentWidth to keep prose at a readable line length in wide layouts.' },{ guidance: true, description: 'Use inlinePlugins for custom shorthand patterns (issue refs, diff refs, mentions) instead of preprocessing the markdown string.' },+ { guidance: true, description: 'Headings render id attributes matching useOutlineFromMarkdown ids; pair with Outline for hash navigation.' },{ guidance: false, description: 'Use Markdown for hand-authored layouts; use Text and Heading directly when you control the content.' },],},diff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsxindex 1a36daf0c5..54974fb9ec 100644--- a/packages/core/src/Markdown/Markdown.test.tsx+++ b/packages/core/src/Markdown/Markdown.test.tsx@@ -5,6 +5,7 @@ import {render, screen, fireEvent} from '@testing-library/react';import type {ReactNode} from 'react';import {Markdown} from './Markdown';import type {MarkdownInlinePlugin} from './Markdown';+import {parseOutlineFromMarkdown} from '../Outline/parseOutlineFromMarkdown';describe('Markdown', () => {it('renders with role="document"', () => {@@ -23,6 +24,83 @@ describe('Markdown', () => {expect(screen.getByText('Heading 2').tagName).toBe('H2');});+ describe('heading ids', () => {+ // Outline's documented contract: an outline item id "should match the+ // target heading element id". Markdown renders the ids that+ // useOutlineFromMarkdown derives, so hash navigation resolves.+ it('renders generated id attributes on headings', () => {+ render(<Markdown>{'# Overview\n\ncontent\n\n# Installation'}</Markdown>);+ expect(screen.getByText('Overview')).toHaveAttribute('id', 'overview');+ expect(screen.getByText('Installation')).toHaveAttribute(+ 'id',+ 'installation',+ );+ });++ it('disambiguates duplicate headings with numeric suffixes', () => {+ render(<Markdown>{'# Setup\n\n# Setup\n\n# Setup'}</Markdown>);+ const ids = screen.getAllByText('Setup').map(el => el.id);+ expect(ids).toEqual(['setup', 'setup-1', 'setup-2']);+ });++ it('renders ids matching parseOutlineFromMarkdown for the same source', () => {+ // Parity invariant: every id the outline derives must resolve to a+ // rendered heading with that exact id — including slugified formatting,+ // duplicate numbering, the empty-slug fallback, and code-fence decoys.+ const source = [+ '# **Bold** and _italic_ text',+ '## Setup',+ '## Setup',+ '### !!!',+ '```',+ '# not a heading',+ '```',+ '## The `useState` hook',+ ].join('\n\n');+ const {container} = render(<Markdown>{source}</Markdown>);+ const outline = parseOutlineFromMarkdown(source);+ expect(outline.length).toBe(5);+ for (const item of outline) {+ const target = container.querySelector(`[id="${item.id}"]`);+ expect(target, `no rendered heading with id "${item.id}"`).not.toBe(+ null,+ );+ expect(target!.tagName).toMatch(/^H[1-6]$/);+ expect(target!.textContent?.trim()).toBe(item.label);+ }+ });++ it('passes the generated id to a custom heading component', () => {+ const received: (string | undefined)[] = [];+ render(+ <Markdown+ components={{+ heading: ({children, id}: {children: ReactNode; id?: string}) => {+ received.push(id);+ return <h2 id={id}>{children}</h2>;+ },+ }}>+ {'# Overview\n\n# Overview'}+ </Markdown>,+ );+ expect(received).toEqual(['overview', 'overview-1']);+ });++ it('does not assign ids to headings nested inside blockquotes', () => {+ // parseOutlineFromMarkdown only lists top-level headings. If nested+ // headings consumed slugs too, duplicate numbering would drift and+ // outline links would land on the wrong heading.+ const source = '> # Quoted\n\n# Quoted';+ const {container} = render(<Markdown>{source}</Markdown>);+ const outline = parseOutlineFromMarkdown(source);+ expect(outline.map(i => i.id)).toEqual(['quoted']);+ const [nested, topLevel] = screen.getAllByText('Quoted');+ expect(container.querySelector('blockquote')).toContainElement(nested);+ expect(nested).not.toHaveAttribute('id');+ expect(topLevel).toHaveAttribute('id', 'quoted');+ });+ });+it('renders paragraphs as block <div> (never <p>) for composition safety', () => {render(<Markdown>{'Hello world'}</Markdown>);// Markdown paragraphs render as <div> so block-level inline contentdiff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex a6f850b7e2..ea918b4946 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -53,6 +53,9 @@ import {parseMarkdownIncremental,createIncrementalState,trimStreamingArtifacts,+ inlineText,+ slugify,+ uniqueSlug,} from './parser';import type {BlockNode, InlineNode, IncrementalState} from './parser';import {themeProps} from '../utils/themeProps';@@ -108,6 +111,14 @@ export interface MarkdownComponents {heading?: React.ComponentType<{level: 1 | 2 | 3 | 4 | 5 | 6;children: React.ReactNode;+ /**+ * Generated slug for this heading, matching the ids produced by+ * useOutlineFromMarkdown / parseOutlineFromMarkdown. Render it as the+ * element's `id` to keep Outline hash navigation working. Undefined for+ * headings nested inside blockquotes or list items (the outline only+ * lists top-level headings).+ */+ id?: string;}>;paragraph?: React.ComponentType<{children: React.ReactNode}>;image?: React.ComponentType<{src: string; alt: string}>;@@ -1045,6 +1056,7 @@ function renderBlock(inlinePlugins: MarkdownInlinePlugin[] | undefined,components: Partial<MarkdownComponents> | undefined,t: TranslatorFn,+ headingIdMap?: ReadonlyMap<BlockNode, string>,): SyncReactNode {const blockAlignMargin = BLOCK_ALIGN_MARGIN[contentAlign];const blockAlignStyle =@@ -1071,10 +1083,15 @@ function renderBlock(components,),);+ // Only top-level headings get an id: the map is built from the same+ // traversal parseOutlineFromMarkdown uses (which skips headings nested+ // in blockquotes / list items), so rendered ids and outline ids stay+ // identical — including duplicate-slug numbering.+ const headingId = headingIdMap?.get(node);const HeadingComp = components?.heading;if (HeadingComp) {return (- <HeadingComp key={index} level={level}>+ <HeadingComp key={index} level={level} id={headingId}>{headingChildren}</HeadingComp>);@@ -1083,6 +1100,7 @@ function renderBlock(return (<Tagkey={index}+ id={headingId}{...mergeProps(themeProps('markdown-heading', {density, level}),stylex.props(@@ -1652,6 +1670,27 @@ export function Markdown({return parseMarkdown(children, parseOptions);}, [display, smoothedText, children, isStreaming, parseOptions]);+ // Assign each top-level heading the slug that parseOutlineFromMarkdown+ // would derive for it, so Outline hash links built from the same source+ // always find a matching DOM id. Mirrors that function's traversal exactly:+ // top-level blocks only, one shared duplicate-numbering sequence.+ // NOTE: must stay above the `display === 'inline'` early return below —+ // hooks cannot be conditional.+ const headingIdMap = useMemo(() => {+ if (display === 'inline' || blocks.length === 0) {+ return undefined;+ }+ const map = new Map<BlockNode, string>();+ const counts = new Map<string, number>();+ for (const block of blocks) {+ if (block.type === 'heading') {+ const label = inlineText(block.children).trim();+ map.set(block, uniqueSlug(slugify(label), counts));+ }+ }+ return map;+ }, [display, blocks]);+const inlineNodes = useMemo(() => {if (display !== 'inline') {return [];@@ -1765,6 +1804,7 @@ export function Markdown({inlinePlugins,components,t,+ headingIdMap,),)}</div>diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.tsindex d4bd05799c..3ed553d7aa 100644--- a/packages/core/src/Markdown/parser.ts+++ b/packages/core/src/Markdown/parser.ts@@ -3,8 +3,10 @@/*** @file parser.ts* @input Markdown string- * @output Array of MarkdownNode AST nodes- * @position Core parser; consumed by Markdown.tsx+ * @output Array of MarkdownNode AST nodes; heading slug helpers+ * (inlineText, slugify, uniqueSlug) shared by Markdown rendering and+ * Outline's parseOutlineFromMarkdown+ * @position Core parser; consumed by Markdown.tsx and Outline*/// ---------------------------------------------------------------------------@@ -1815,3 +1817,59 @@ export function parseMarkdownIncremental(return mergeSettledBlocks(settledBlocks, unsettledBlocks);}++// ---------------------------------------------------------------------------+// Heading slugs+// ---------------------------------------------------------------------------+// Single source of truth for the heading id contract: Markdown renders these+// slugs as `id` attributes on h1–h6, and Outline's parseOutlineFromMarkdown+// derives its item ids from the same functions, so outline hash links always+// resolve to a rendered heading by construction.++/** Flatten inline nodes into their plain text content. */+export function inlineText(nodes: InlineNode[]): string {+ return nodes+ .map(node => {+ switch (node.type) {+ case 'text':+ case 'code':+ return node.content;+ case 'bold':+ case 'italic':+ case 'strikethrough':+ case 'link':+ return inlineText(node.children);+ case 'image':+ return node.alt;+ case 'citation':+ case 'break':+ return '';+ }+ })+ .join('');+}++/** Turn heading text into a URL-safe slug (lowercase, hyphen-separated). */+export function slugify(value: string): string {+ return value+ .trim()+ .toLowerCase()+ .replace(/['"]/g, '')+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+}++/**+ * Disambiguate repeated slugs with a numeric suffix (`setup`, `setup-1`, …).+ * Empty slugs fall back to `section`. The caller owns the counts map so one+ * document shares a single numbering sequence.+ */+export function uniqueSlug(+ baseSlug: string,+ counts: Map<string, number>,+): string {+ const fallbackSlug = baseSlug || 'section';+ const count = counts.get(fallbackSlug) ?? 0;+ counts.set(fallbackSlug, count + 1);+ return count === 0 ? fallbackSlug : `${fallbackSlug}-${count}`;+}diff --git a/packages/core/src/Outline/Outline.doc.mjs b/packages/core/src/Outline/Outline.doc.mjsindex 39c4ed3b43..96c59ac80e 100644--- a/packages/core/src/Outline/Outline.doc.mjs+++ b/packages/core/src/Outline/Outline.doc.mjs@@ -166,6 +166,8 @@ import {Outline, useOutlineFromMarkdown} from '@astryxdesign/core/Outline';function MarkdownOutline({markdown}) {// Derives {id, label, level} items from headings in the source.+ // The Markdown component renders the same generated ids on its+ // headings, so outline links scroll without any extra wiring.const items = useOutlineFromMarkdown(markdown);return <Outline items={items} />;}diff --git a/packages/core/src/Outline/parseOutlineFromMarkdown.ts b/packages/core/src/Outline/parseOutlineFromMarkdown.tsindex 22591286b2..5d4e02aae0 100644--- a/packages/core/src/Outline/parseOutlineFromMarkdown.ts+++ b/packages/core/src/Outline/parseOutlineFromMarkdown.ts@@ -2,7 +2,8 @@/*** @file parseOutlineFromMarkdown.ts- * @input Uses Markdown parser internals and OutlineItem type+ * @input Uses Markdown parser internals (parseMarkdown + heading slug+ * helpers) and OutlineItem type* @output Exports parseOutlineFromMarkdown for extracting heading outlines from Markdown* @position Pure utility; consumed by useOutlineFromMarkdown and public exports*@@ -11,52 +12,21 @@* - /packages/core/src/Outline/index.ts*/-import {parseMarkdown, type InlineNode} from '../Markdown/parser';+import {+ parseMarkdown,+ inlineText,+ slugify,+ uniqueSlug,+} from '../Markdown/parser';import type {OutlineItem} from './types';-function inlineText(nodes: InlineNode[]): string {- return nodes- .map(node => {- switch (node.type) {- case 'text':- case 'code':- return node.content;- case 'bold':- case 'italic':- case 'strikethrough':- case 'link':- return inlineText(node.children);- case 'image':- return node.alt;- case 'citation':- case 'break':- return '';- }- })- .join('');-}--function slugify(value: string): string {- return value- .trim()- .toLowerCase()- .replace(/['"]/g, '')- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-+|-+$/g, '');-}--function uniqueSlug(baseSlug: string, counts: Map<string, number>): string {- const fallbackSlug = baseSlug || 'section';- const count = counts.get(fallbackSlug) ?? 0;- counts.set(fallbackSlug, count + 1);- return count === 0 ? fallbackSlug : `${fallbackSlug}-${count}`;-}-/*** Extract heading items from a Markdown string.** Uses Markdown's parser so fenced code blocks, tables, lists, and inline* formatting are interpreted consistently with rendered Markdown output.+ * Ids come from the parser's shared slug helpers, so they always match the+ * `id` attributes Markdown renders on its headings.*/export function parseOutlineFromMarkdown(markdown: string): OutlineItem[] {const counts = new Map<string, number>();