An open source design system that's fully customizable and agent ready
TypeScript
fix(docsite): render code spans in link labels; auto-link component names in doc prose (#4425) (#4444)
AK3a852c19bf02
diff --git a/apps/docsite/src/__tests__/changelog-linkify.test.ts b/apps/docsite/src/__tests__/changelog-linkify.test.tsindex 08cd0662fa..ec80183539 100644--- a/apps/docsite/src/__tests__/changelog-linkify.test.ts+++ b/apps/docsite/src/__tests__/changelog-linkify.test.ts@@ -87,6 +87,47 @@ describe('linkifyComponents', () => {expect(linkifyComponents('`Button`', names)).toBe('`Button`');expect(linkifyComponents('[Button](/x)', names)).toBe('[Button](/x)');});++ it('skips a name anywhere inside a code span, not just against the ticks', () => {+ const names = ['Theme', 'Button'];+ expect(linkifyComponents('Wrap your app in `<Theme>`.', names)).toBe(+ 'Wrap your app in `<Theme>`.',+ );+ expect(linkifyComponents("`import {Button} from 'x'`", names)).toBe(+ "`import {Button} from 'x'`",+ );+ });++ it('skips a name anywhere inside an existing link, not just against the brackets', () => {+ const names = ['Button'];+ const codeLabel = '[`<Button>`](/components/Button)';+ expect(linkifyComponents(codeLabel, names)).toBe(codeLabel);+ const inHref = '[the docs](/components/Button)';+ expect(linkifyComponents(inHref, names)).toBe(inHref);+ });++ it('skips names inside fenced code blocks', () => {+ const names = ['Button'];+ const md = ['```tsx', '<Button label="Save" />', '```'].join('\n');+ expect(linkifyComponents(md, names)).toBe(md);+ });++ it('still links the prose around a skipped span', () => {+ const names = ['Button', 'Card'];+ expect(linkifyComponents('A Card wraps `<Button>` here', names)).toBe(+ 'A [Card](/components/Card) wraps `<Button>` here',+ );+ });++ it('emits a monospace label when asked, and a plain one by default', () => {+ const names = ['Button'];+ expect(linkifyComponents('Use Button', names, {monospace: true})).toBe(+ 'Use [`Button`](/components/Button)',+ );+ expect(linkifyComponents('Use Button', names)).toBe(+ 'Use [Button](/components/Button)',+ );+ });});describe('stripTitle', () => {diff --git a/apps/docsite/src/__tests__/code-linkifiers.test.ts b/apps/docsite/src/__tests__/code-linkifiers.test.tsindex 71c0e9c009..0c0e32d767 100644--- a/apps/docsite/src/__tests__/code-linkifiers.test.ts+++ b/apps/docsite/src/__tests__/code-linkifiers.test.ts@@ -51,6 +51,51 @@ describe('doc topic linkifier', () => {});});+describe('component name linkifier', () => {+ it.each([+ ['Button', '/components/Button'],+ [+ 'InternationalizationProvider',+ '/components/InternationalizationProvider',+ ],+ [+ '<InternationalizationProvider>',+ '/components/InternationalizationProvider',+ ],+ ['<Button/>', '/components/Button'],+ ['<Button />', '/components/Button'],+ [' <Popover> ', '/components/Popover'],+ // XDS-prefixed aliases map to the unprefixed page, like the changelog's+ // prose linkifier.+ ['XDSButton', '/components/Button'],+ ['<XDSButton>', '/components/Button'],+ ])('links %s', (code, href) => {+ expect(linkifyCode(code)).toBe(href);+ });++ it('links every documented component and hook name', () => {+ for (const {name} of Object.values(components).flat()) {+ expect(linkifyCode(name)).toBe(`/components/${name}`);+ }+ });++ it.each([+ // Case matters: `button` is the HTML element, `Button` the component.+ ['button'],+ ['<dialog>'],+ // A name with anything attached is a snippet, not a reference.+ ['Popover API'],+ ['<Button open>'],+ ['Button.props'],+ ['Crimson Text'],+ ['NotARealComponent'],+ ['<NotARealComponent>'],+ ['XDSNotARealComponent'],+ ])('leaves %s as plain code', code => {+ expect(linkifyCode(code)).toBeNull();+ });+});+/** Every backticked `astryx docs ...` reference in a chunk of authored data. */function docReferences(json: string): string[] {const found = [...json.matchAll(/`((?:npx )?astryx docs[^`]*)`/g)];diff --git a/apps/docsite/src/__tests__/docs-linkify.test.ts b/apps/docsite/src/__tests__/docs-linkify.test.tsnew file mode 100644index 0000000000..8bcdd4d09f--- /dev/null+++ b/apps/docsite/src/__tests__/docs-linkify.test.ts@@ -0,0 +1,95 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Unit tests for the doc-section auto-linker.+ *+ * Run: pnpm -F @astryxdesign/docsite test+ */++import {describe, it, expect} from 'vitest';+import {linkifyDocSections} from '../components/docs/docsLinkify';+import type {DocSection} from '../generated/docsRegistry';++const NAMES = ['Button', 'Card', 'Theme'];++function sectionWith(...content: DocSection['content']): DocSection[] {+ return [{title: 'Overview', content}];+}++describe('linkifyDocSections', () => {+ it('links component names in prose as monospace links', () => {+ const out = linkifyDocSections(+ sectionWith({type: 'prose', text: 'Wrap the app in Theme.'}),+ NAMES,+ );+ expect(out[0].content[0].text).toBe(+ 'Wrap the app in [`Theme`](/components/Theme).',+ );+ });++ it('links component names in list items', () => {+ const out = linkifyDocSections(+ sectionWith({type: 'list', items: ['Use Button here', 'no names here']}),+ NAMES,+ );+ expect(out[0].content[0].items).toEqual([+ 'Use [`Button`](/components/Button) here',+ 'no names here',+ ]);+ });++ it('links component names in table cells but not table headers', () => {+ const out = linkifyDocSections(+ sectionWith({+ type: 'table',+ headers: ['Button', 'Notes'],+ rows: [['Card', 'plain']],+ }),+ NAMES,+ );+ expect(out[0].content[0].headers).toEqual(['Button', 'Notes']);+ expect(out[0].content[0].rows).toEqual([+ ['[`Card`](/components/Card)', 'plain'],+ ]);+ });++ it('leaves heading and code blocks untouched', () => {+ const out = linkifyDocSections(+ sectionWith(+ {type: 'heading', text: 'Button basics', level: 3},+ {type: 'code', lang: 'tsx', code: '<Button />'},+ ),+ NAMES,+ );+ expect(out[0].content[0].text).toBe('Button basics');+ expect(out[0].content[1].code).toBe('<Button />');+ });++ it('leaves section titles untouched', () => {+ const out = linkifyDocSections(+ [{title: 'Button anatomy', content: []}],+ NAMES,+ );+ expect(out[0].title).toBe('Button anatomy');+ });++ it('does not mutate the input sections', () => {+ const input = sectionWith({type: 'prose', text: 'Use Button.'});+ const snapshot = JSON.parse(JSON.stringify(input));+ linkifyDocSections(input, NAMES);+ expect(input).toEqual(snapshot);+ });++ it('returns the input unchanged when there are no component names', () => {+ const input = sectionWith({type: 'prose', text: 'Use Button.'});+ expect(linkifyDocSections(input, [])).toEqual(input);+ });++ it('leaves names that authors already wrote as code spans alone', () => {+ const out = linkifyDocSections(+ sectionWith({type: 'prose', text: 'Wrap the app in `<Theme>`.'}),+ NAMES,+ );+ expect(out[0].content[0].text).toBe('Wrap the app in `<Theme>`.');+ });+});diff --git a/apps/docsite/src/__tests__/inline-tokens.test.ts b/apps/docsite/src/__tests__/inline-tokens.test.tsnew file mode 100644index 0000000000..52d5bae072--- /dev/null+++ b/apps/docsite/src/__tests__/inline-tokens.test.ts@@ -0,0 +1,91 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Unit tests for the inline-markdown tokenizer used by authored docs.+ *+ * Run: pnpm -F @astryxdesign/docsite test+ */++import {describe, it, expect} from 'vitest';+import {tokenizeInline} from '../components/docs/inlineTokens';++describe('tokenizeInline', () => {+ it('returns a single text token for plain prose', () => {+ expect(tokenizeInline('just words')).toEqual([+ {type: 'text', value: 'just words'},+ ]);+ });++ it('returns nothing for an empty string', () => {+ expect(tokenizeInline('')).toEqual([]);+ });++ it('splits code spans out of the surrounding text', () => {+ expect(tokenizeInline('use `light-dark()` here')).toEqual([+ {type: 'text', value: 'use '},+ {type: 'code', value: 'light-dark()'},+ {type: 'text', value: ' here'},+ ]);+ });++ it('splits links out of the surrounding text', () => {+ expect(tokenizeInline('see [Button](/components/Button) now')).toEqual([+ {type: 'text', value: 'see '},+ {+ type: 'link',+ href: '/components/Button',+ label: 'Button',+ isCodeLabel: false,+ },+ {type: 'text', value: ' now'},+ ]);+ });++ it('marks a backticked link label as a code label and unwraps it', () => {+ expect(+ tokenizeInline('[`<InternationalizationProvider>`](/components/X)'),+ ).toEqual([+ {+ type: 'link',+ href: '/components/X',+ label: '<InternationalizationProvider>',+ isCodeLabel: true,+ },+ ]);+ });++ it('only treats a label as code when the whole label is one span', () => {+ expect(tokenizeInline('[the `Button` prop](/x)')).toEqual([+ {+ type: 'link',+ href: '/x',+ label: 'the `Button` prop',+ isCodeLabel: false,+ },+ ]);+ });++ it('handles a code span adjacent to a link', () => {+ expect(tokenizeInline('`a`[`b`](/c)')).toEqual([+ {type: 'code', value: 'a'},+ {type: 'link', href: '/c', label: 'b', isCodeLabel: true},+ ]);+ });++ it('keeps an unpaired backtick as literal text', () => {+ expect(tokenizeInline('a ` b')).toEqual([{type: 'text', value: 'a ` b'}]);+ });++ it('keeps external and internal hrefs verbatim', () => {+ expect(+ tokenizeInline('[MDN](https://developer.mozilla.org/en-US/)'),+ ).toEqual([+ {+ type: 'link',+ href: 'https://developer.mozilla.org/en-US/',+ label: 'MDN',+ isCodeLabel: false,+ },+ ]);+ });+});diff --git a/apps/docsite/src/app/(docs)/docs/[topic]/page.tsx b/apps/docsite/src/app/(docs)/docs/[topic]/page.tsxindex 016bbb2453..8fcb242ae5 100644--- a/apps/docsite/src/app/(docs)/docs/[topic]/page.tsx+++ b/apps/docsite/src/app/(docs)/docs/[topic]/page.tsx@@ -14,12 +14,20 @@ import type {Metadata} from 'next';import {notFound} from 'next/navigation';import {docTopics} from '../../../../generated/docsRegistry';import {packages} from '../../../../generated/packageRegistry';+import {components} from '../../../../generated/componentRegistry';import {ReferenceDocView} from '../../../../components/docs/ReferenceDocView';import {TokensDocView} from '../../../../components/docs/TokensDocView';import {PackageStubPage} from '../../../../components/docs/PackageStubPage';import {type InstallStep} from '../../../../components/docs/PackageActions';+import {linkifyDocSections} from '../../../../components/docs/docsLinkify';import {pageMetadata} from '../../../../lib/pageMetadata';+// Every documented component and hook name, for the prose auto-linker. Same+// list the changelog passes to linkifyComponents.+const componentNames = Object.values(components)+ .flat()+ .map(c => c.name);+const TOKEN_TOPICS = new Set(['tokens','color',@@ -116,19 +124,20 @@ export default async function DocPage({if (topic) {const isTokenTopic =topic.category === 'foundations' && TOKEN_TOPICS.has(topic.topic);+ const sections = linkifyDocSections(topic.sections, componentNames);return isTokenTopic ? (<TokensDocViewtitle={topic.title}description={topic.description}- sections={topic.sections}+ sections={sections}topic={topic.topic}/>) : (<ReferenceDocViewtitle={topic.title}description={topic.description}- sections={topic.sections}+ sections={sections}/>);}diff --git a/apps/docsite/src/components/changelogLinkify.ts b/apps/docsite/src/components/changelogLinkify.tsindex 0f8ac3a284..2da6016961 100644--- a/apps/docsite/src/components/changelogLinkify.ts+++ b/apps/docsite/src/components/changelogLinkify.ts@@ -1,10 +1,14 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * Pure markdown post-processors for the changelog view. Each turns a raw- * pattern in the rendered CHANGELOG text into a markdown link before it is- * handed to <Markdown>. Kept side-effect-free and colocated so they can be- * unit tested without rendering the component.+ * Pure markdown post-processors. Each turns a raw pattern in authored markdown+ * into a markdown link before it is handed to a renderer. Kept side-effect-free+ * so they can be unit tested without rendering the component.+ *+ * `linkifyPRs` / `linkifyContributors` / `stripTitle` are changelog-specific.+ * `linkifyComponents` is shared: the changelog runs it over CHANGELOG text+ * before <Markdown>, and the docs pages run it over `.doc.mjs` prose before+ * renderInlineMarkdown (see docs/docsLinkify.ts).*/import {GITHUB_REPO} from '../constants';@@ -33,8 +37,36 @@ export function linkifyContributors(markdown: string): string {);}+/**+ * Spans the component linkifier copies through verbatim: fenced blocks, inline+ * code spans, and existing markdown links. Whatever sits inside one of those is+ * already deliberate authoring, so rewriting it would either double-link it or+ * splice link syntax into a literal. In the changelog this doubles as the+ * author's opt-out — backticking a name suppresses its auto-link. On the docs+ * site, InlineCode still resolves an exact-name code span to its page+ * (codeLinkifiers.ts); this pass stays out of the span either way.+ *+ * Adjacency lookarounds alone are not enough: they miss `<Theme>` and+ * `packages/core/src/Icon/x.tsx`, where the name is inside the span but not+ * touching its delimiters.+ */+const OPAQUE_SPAN = /```[\s\S]*?```|`[^`]+`|\[[^\]]*\]\([^)]*\)/g;++export interface LinkifyComponentsOptions {+ /**+ * Emit a backticked label — `` [`Button`](/components/Button) `` — so the+ * auto-link renders as monospace. Off by default; the changelog wants plain+ * prose labels.+ */+ monospace?: boolean;+}+/** Link bare component names (e.g. `Button`, `XDSButton`) to their doc page. */-export function linkifyComponents(markdown: string, names: string[]): string {+export function linkifyComponents(+ markdown: string,+ names: string[],+ options?: LinkifyComponentsOptions,+): string {if (names.length === 0) {return markdown;}@@ -52,13 +84,23 @@ export function linkifyComponents(markdown: string, names: string[]): string {'g',);- return markdown.replace(pattern, match => {- const href = nameToHref.get(match);- if (!href) {- return match;- }- return '[' + match + '](' + href + ')';- });+ const linkify = (text: string): string =>+ text.replace(pattern, match => {+ const href = nameToHref.get(match);+ if (!href) {+ return match;+ }+ const label = options?.monospace === true ? '`' + match + '`' : match;+ return '[' + label + '](' + href + ')';+ });++ let out = '';+ let lastIndex = 0;+ for (const span of markdown.matchAll(OPAQUE_SPAN)) {+ out += linkify(markdown.slice(lastIndex, span.index)) + span[0];+ lastIndex = span.index + span[0].length;+ }+ return out + linkify(markdown.slice(lastIndex));}/** Strip the leading `# Title` line (the package name h1) from a changelog. */diff --git a/apps/docsite/src/components/codeLinkifiers.ts b/apps/docsite/src/components/codeLinkifiers.tsindex b0b2ede3ee..0340cfe9c9 100644--- a/apps/docsite/src/components/codeLinkifiers.ts+++ b/apps/docsite/src/components/codeLinkifiers.ts@@ -11,13 +11,16 @@* Docs prose cites sibling topics as the literal CLI command — "Semantic* tokens, not hardcoded values (see `astryx docs tokens`)". That is what an* agent should type, so it stays copy-pasteable code; linkifying it gives a- * human somewhere to click.+ * human somewhere to click. Component mentions work the same way: authors+ * write `<InternationalizationProvider>` as literal code, and the span+ * resolves to that component's doc page.** To teach the site a new kind of cross-reference, write a CodeLinkifier and* append it to LINKIFIERS.*/import {docTopics} from '../generated/docsRegistry';+import {components} from '../generated/componentRegistry';/** Returns an href for a code span it recognizes, or null to pass. */type CodeLinkifier = (code: string) => string | null;@@ -45,7 +48,36 @@ const docTopic: CodeLinkifier = code => {return KNOWN_TOPICS.has(topic) ? `/docs/${topic}` : null;};-const LINKIFIERS: CodeLinkifier[] = [docTopic];+/** Every documented component and hook name; each has a /components page. */+const KNOWN_COMPONENTS = new Set(+ Object.values(components)+ .flat()+ .map(c => c.name),+);++/**+ * `Button`, `<InternationalizationProvider>`, `<Button />` -> the component's+ * doc page.+ *+ * A span has to be exactly one documented name — bare, or as a lone JSX tag —+ * so snippets like `<Button open>` and phrases that merely contain a name stay+ * plain code. Case-sensitive on purpose: `button` is the HTML element,+ * `Button` the component. XDS-prefixed aliases resolve to the unprefixed page,+ * matching the prose linkifier (changelogLinkify's linkifyComponents).+ */+const componentName: CodeLinkifier = code => {+ const jsx = /^<([A-Z][A-Za-z\d]*)\s*\/?>$/.exec(code);+ const name = jsx != null ? jsx[1] : code;+ if (KNOWN_COMPONENTS.has(name)) {+ return `/components/${name}`;+ }+ if (name.startsWith('XDS') && KNOWN_COMPONENTS.has(name.slice(3))) {+ return `/components/${name.slice(3)}`;+ }+ return null;+};++const LINKIFIERS: CodeLinkifier[] = [docTopic, componentName];/** Resolve an inline code span to a docs href, or null to leave it alone. */export function linkifyCode(code: string): string | null {diff --git a/apps/docsite/src/components/docs/docsLinkify.ts b/apps/docsite/src/components/docs/docsLinkify.tsnew file mode 100644index 0000000000..746058f9af--- /dev/null+++ b/apps/docsite/src/components/docs/docsLinkify.ts@@ -0,0 +1,56 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Auto-links bare component and hook names in authored `.doc.mjs` prose to+ * their doc pages, reusing the changelog's `linkifyComponents` so both surfaces+ * share one linkifier and one mental model. Runs on the server, before the+ * sections reach renderInlineMarkdown, so nothing extra ships to the client.+ *+ * Labels are emitted as code spans, giving the monospace API references the+ * docs want; renderInlineMarkdown renders that shape as a monospace link.+ *+ * Code spans and existing links are opaque to this pass. A backticked mention+ * is InlineCode's territory — it links the span only when the whole span is a+ * documented name (see codeLinkifiers.ts). An explicit link renders as+ * written, which is the author's override for both layers.+ */++import {linkifyComponents} from '../changelogLinkify';+import type {ContentBlock, DocSection} from '../../generated/docsRegistry';++function linkifyBlock(block: ContentBlock, names: string[]): ContentBlock {+ const linkify = (text: string) =>+ linkifyComponents(text, names, {monospace: true});++ switch (block.type) {+ case 'prose':+ return block.text == null ? block : {...block, text: linkify(block.text)};+ case 'list':+ return block.items == null+ ? block+ : {...block, items: block.items.map(linkify)};+ case 'table':+ // Column headers render as raw labels, not inline markdown — cells only.+ return block.rows == null+ ? block+ : {...block, rows: block.rows.map(row => row.map(linkify))};+ default:+ // Headings and code blocks render verbatim; anything else is untouched.+ return block;+ }+}++/** Auto-link component names across a topic's sections. Never mutates input. */+export function linkifyDocSections(+ sections: DocSection[],+ componentNames: string[],+): DocSection[] {+ if (componentNames.length === 0) {+ return sections;+ }++ return sections.map(section => ({+ ...section,+ content: section.content.map(block => linkifyBlock(block, componentNames)),+ }));+}diff --git a/apps/docsite/src/components/docs/inlineMarkdown.tsx b/apps/docsite/src/components/docs/inlineMarkdown.tsxindex fe93b15c5f..8f1f10f75d 100644--- a/apps/docsite/src/components/docs/inlineMarkdown.tsx+++ b/apps/docsite/src/components/docs/inlineMarkdown.tsx@@ -4,9 +4,11 @@import {Fragment, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';+import {Code} from '@astryxdesign/core/CodeBlock';import {InlineCode} from '../InlineCode';+import {tokenizeInline, type InlineToken} from './inlineTokens';-const TOKEN = /(`([^`]+)`|\[([^\]]+)\]\(([^)]+)\))/g;+type LinkToken = Extract<InlineToken, {type: 'link'}>;const styles = stylex.create({link: {@@ -29,43 +31,37 @@ const styles = stylex.create({},});-function renderLink(label: string, href: string, key: number): ReactNode {- const isExternal = /^https?:\/\//.test(href);+function renderLink(token: LinkToken): ReactNode {+ const isExternal = /^https?:\/\//.test(token.href);return (<a- key={key}- href={href}+ href={token.href}rel={isExternal ? 'noreferrer' : undefined}target={isExternal ? '_blank' : undefined}{...stylex.props(styles.link)}>- {label}+ {token.isCodeLabel ? (+ // color="inherit" keeps the link's accent color on the code span;+ // Code's default `primary` would read as body text inside the anchor.+ <Code color="inherit">{token.label}</Code>+ ) : (+ token.label+ )}</a>);}-// Render a small inline markdown subset for authored docs: code spans and links.+// Render a small inline markdown subset for authored docs: code spans, links,+// and a code span used as a whole link label ([`Name`](href)).export function renderInlineMarkdown(text: string) {- const nodes: ReactNode[] = [];- let lastIndex = 0;- let match;- while ((match = TOKEN.exec(text)) !== null) {- if (match.index > lastIndex) {- nodes.push(text.slice(lastIndex, match.index));- }-- const code = match[2];- const linkLabel = match[3];- const linkHref = match[4];- if (code != null) {- nodes.push(<InlineCode key={match.index}>{code}</InlineCode>);- } else if (linkLabel != null && linkHref != null) {- nodes.push(renderLink(linkLabel, linkHref, match.index));- }-- lastIndex = match.index + match[0].length;- }- if (lastIndex < text.length) {- nodes.push(text.slice(lastIndex));- }- return nodes.map((node, i) => <Fragment key={i}>{node}</Fragment>);+ return tokenizeInline(text).map((token, i) => (+ <Fragment key={i}>+ {token.type === 'code' ? (+ <InlineCode>{token.value}</InlineCode>+ ) : token.type === 'link' ? (+ renderLink(token)+ ) : (+ token.value+ )}+ </Fragment>+ ));}diff --git a/apps/docsite/src/components/docs/inlineTokens.ts b/apps/docsite/src/components/docs/inlineTokens.tsnew file mode 100644index 0000000000..48f7b4f47c--- /dev/null+++ b/apps/docsite/src/components/docs/inlineTokens.ts@@ -0,0 +1,63 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * The parse half of the inline-markdown subset authored docs may use: code+ * spans, links, and a code span used as a whole link label. Split out of+ * inlineMarkdown.tsx so it carries no React or StyleX and can be unit tested+ * directly (the docsite suite runs in plain node, without the StyleX+ * transform).+ *+ * Deliberately not a markdown parser. Nesting beyond "the label is one code+ * span" stays literal, matching what doc authors actually write.+ */++/** One piece of an authored inline string. */+export type InlineToken =+ | {type: 'text'; value: string}+ | {type: 'code'; value: string}+ | {+ type: 'link';+ href: string;+ /** Label text, with the backticks stripped when `isCodeLabel` is true. */+ label: string;+ /** True when the entire label was a single code span. */+ isCodeLabel: boolean;+ };++const TOKEN = /`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)/g;++/** A link label that is entirely one code span, e.g. [`<Theme>`](/x). */+const CODE_LABEL = /^`([^`]+)`$/;++/** Split an authored inline string into text, code, and link tokens. */+export function tokenizeInline(text: string): InlineToken[] {+ const tokens: InlineToken[] = [];+ let lastIndex = 0;++ for (const match of text.matchAll(TOKEN)) {+ if (match.index > lastIndex) {+ tokens.push({type: 'text', value: text.slice(lastIndex, match.index)});+ }++ const [whole, code, linkLabel, linkHref] = match;+ if (code != null) {+ tokens.push({type: 'code', value: code});+ } else if (linkLabel != null && linkHref != null) {+ const codeLabel = CODE_LABEL.exec(linkLabel);+ tokens.push({+ type: 'link',+ href: linkHref,+ label: codeLabel != null ? codeLabel[1] : linkLabel,+ isCodeLabel: codeLabel != null,+ });+ }++ lastIndex = match.index + whole.length;+ }++ if (lastIndex < text.length) {+ tokens.push({type: 'text', value: text.slice(lastIndex)});+ }++ return tokens;+}diff --git a/packages/cli/assets/docs/browser-support.doc.mjs b/packages/cli/assets/docs/browser-support.doc.mjsindex 878e922e27..b5f922e558 100644--- a/packages/cli/assets/docs/browser-support.doc.mjs+++ b/packages/cli/assets/docs/browser-support.doc.mjs@@ -15,7 +15,7 @@ export const docs = {content: [{type: 'prose',- text: 'Astryx is built on modern web platform features: the Popover API, CSS anchor positioning, and CSS `light-dark()`. These let components stay small, accessible, and dependency-free, but they also set a floor on which browsers render everything correctly.',+ text: 'Astryx is built on modern web platform features: the [`Popover`](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API) API, CSS anchor positioning, and CSS `light-dark()`. These let components stay small, accessible, and dependency-free, but they also set a floor on which browsers render everything correctly.',},{type: 'prose',@@ -73,7 +73,7 @@ export const docs = {'Baseline 2026: the tightest requirement.',],[- 'Popover API',+ '[`Popover`](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API) API','Opens, stacks, and light-dismisses layered surfaces via the top layer.','Baseline 2025.',],@@ -86,7 +86,7 @@ export const docs = {},{type: 'prose',- text: 'The gap that matters is between Tier 1 and Tier 2: the Popover API and `light-dark()` reached wide availability well before anchor positioning. So in Tier 2 browsers, layered surfaces open and dismiss correctly; they just are not positioned. This is the one feature most consumers will need to reason about.',+ text: 'The gap that matters is between Tier 1 and Tier 2: the [`Popover`](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API) API and `light-dark()` reached wide availability well before anchor positioning. So in Tier 2 browsers, layered surfaces open and dismiss correctly; they just are not positioned. This is the one feature most consumers will need to reason about.',},],},@@ -112,7 +112,7 @@ export const docs = {},{type: 'prose',- text: 'If your product does not use any of these, it has no anchor-positioning requirement at all; it needs only `light-dark()` (Tier 2 and up) for correct theme colors. Layout, typography, forms, buttons, cards, tables, and navigation all work down to Tier 2 with no special handling.',+ text: 'If your product does not use any of these, it has no anchor-positioning requirement at all; it needs only `light-dark()` (Tier 2 and up) for correct theme colors. Page layout, typography, forms, buttons, cards, tables, and navigation all work down to Tier 2 with no special handling.',},],},@@ -123,7 +123,7 @@ export const docs = {type: 'list',style: 'do',items: [- 'Components never throw on missing platform APIs. Where a browser lacks the Popover API, layers fall back to plain visibility instead of crashing.',+ 'Components never throw on missing platform APIs. Where a browser lacks the [`Popover`](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API) API, layers fall back to plain visibility instead of crashing.','Tier 1 and Tier 2 are officially supported and tested.','Non-layered components render correctly down to Tier 2.',],@@ -192,7 +192,7 @@ const hasLightDark = CSS.supports('color', 'light-dark(#000, #fff)');`,},{type: 'prose',- text: 'This is not an arbitrary window: Baseline − 2 is close to where anchor positioning stops being available while the Popover API and `light-dark()` still are, so the tier boundary tracks a real capability edge, not a guessed date. The version floors above are reviewed and advanced roughly once a year as new Baseline years land. Always feature-detect rather than hardcoding version numbers, so your app adapts automatically as the platform moves.',+ text: 'This is not an arbitrary window: Baseline − 2 is close to where anchor positioning stops being available while the [`Popover`](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API) API and `light-dark()` still are, so the tier boundary tracks a real capability edge, not a guessed date. The version floors above are reviewed and advanced roughly once a year as new Baseline years land. Always feature-detect rather than hardcoding version numbers, so your app adapts automatically as the platform moves.',},],},diff --git a/packages/cli/assets/docs/icons.doc.mjs b/packages/cli/assets/docs/icons.doc.mjsindex b1925a81f6..c3558c6fbe 100644--- a/packages/cli/assets/docs/icons.doc.mjs+++ b/packages/cli/assets/docs/icons.doc.mjs@@ -114,9 +114,9 @@ export const brandTheme = defineTheme({type: 'list',style: 'ordered',items: [- 'Add the name to IconName type in packages/core/src/Icon/globalIconRegistry.tsx',- 'Add the default SVG to packages/core/src/Icon/defaultIcons.tsx',- 'Add a row to the Available Names table in packages/cli/docs/icons.doc.mjs',+ 'Add the name to IconName type in `packages/core/src/Icon/globalIconRegistry.tsx`',+ 'Add the default SVG to `packages/core/src/Icon/defaultIcons.tsx`',+ 'Add a row to the Available Names table in `packages/cli/assets/docs/icons.doc.mjs`',],},],diff --git a/packages/cli/assets/docs/illustrations.doc.mjs b/packages/cli/assets/docs/illustrations.doc.mjsindex f246a8ea4e..63b210c846 100644--- a/packages/cli/assets/docs/illustrations.doc.mjs+++ b/packages/cli/assets/docs/illustrations.doc.mjs@@ -40,7 +40,7 @@ export const docs = {'Keep illustrations consistent in style across the product.','Use simple, flat illustrations that work in both light and dark mode.','Size illustrations proportionally to the container, typically 120\u2013240px.',- 'Center illustrations with supporting text below.',+ 'Place illustrations centered with supporting text below.',],},{@@ -59,7 +59,7 @@ export const docs = {content: [{type: 'prose',- text: 'Center illustrations inside Center with supporting text stacked below. Typical illustration sizes range from 120px for inline empty states to 240px for full-page onboarding screens. Always pair the illustration with a heading and optional body text to explain what the user should do next.',+ text: 'Place illustrations inside Center with supporting text stacked below. Typical illustration sizes range from 120px for inline empty states to 240px for full-page onboarding screens. Always pair the illustration with a heading and optional body text to explain what the user should do next.',},{type: 'code',diff --git a/packages/cli/assets/docs/internationalization.doc.mjs b/packages/cli/assets/docs/internationalization.doc.mjsindex 304812d283..28a34480a9 100644--- a/packages/cli/assets/docs/internationalization.doc.mjs+++ b/packages/cli/assets/docs/internationalization.doc.mjs@@ -300,7 +300,7 @@ export default function App() {content: [{type: 'prose',- text: 'Astryx generates a `pseudo` locale that wraps every string in `⟦…⟧` and replaces letters with accented look-alikes. Switch to it in development to catch hardcoded astryx strings and layout issues caused by longer text.',+ text: 'Astryx generates a `pseudo` locale that wraps every string in `⟦…⟧` and replaces letters with accented look-alikes. Turn it on in development to catch hardcoded astryx strings and layout issues caused by longer text.',},{type: 'code',diff --git a/packages/cli/assets/docs/migration.doc.mjs b/packages/cli/assets/docs/migration.doc.mjsindex 2f3d7a97a8..d022b96644 100644--- a/packages/cli/assets/docs/migration.doc.mjs+++ b/packages/cli/assets/docs/migration.doc.mjs@@ -350,7 +350,7 @@ if (getComputedStyle(button).paddingInline === '0px') {'Run the app in light and dark mode and check that surfaces, borders, text, icons, hover states, focus rings, and status colors flow together.','Open the command palette from the shell, type into it, select items by keyboard, and confirm focus returns to the trigger.','Check the SideNav at collapsed, expanded, active, hover, nested, and mobile states.',- 'Verify settings popovers and dialogs in jsdom and in a real browser because native dialog and Popover APIs may need test shims.',+ 'Verify settings popovers and dialogs in jsdom and in a real browser because the native dialog and [`Popover`](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API) APIs may need test shims.','Search for leftover hardcoded Tailwind colors, arbitrary hex values, and one-off hover colors after each route migration.','Run component tests, build, and at least one browser screenshot pass for each migrated route.',],diff --git a/packages/cli/assets/docs/principles.doc.mjs b/packages/cli/assets/docs/principles.doc.mjsindex 41faef50af..c568db41c3 100644--- a/packages/cli/assets/docs/principles.doc.mjs+++ b/packages/cli/assets/docs/principles.doc.mjs@@ -39,7 +39,7 @@ export const docs = {style: 'ordered',items: ['Use components for everything they cover',- 'Layout is frame-first: pick the shell and budget regions before writing content (see \`astryx docs layout\`)',+ 'Page layout is frame-first: pick the shell and budget regions before writing content (see \`astryx docs layout\`)','Dense data renders as rows (Table, List/Item), edge-to-edge with dividers; Card is for widgets, galleries, and settings groups','StyleX or Tailwind for custom styling; both are first-class (see \`astryx docs styling\`)','Semantic tokens, not hardcoded values (see \`astryx docs tokens\`)',diff --git a/packages/cli/assets/docs/styling-libraries.doc.mjs b/packages/cli/assets/docs/styling-libraries.doc.mjsindex b97c5adae5..3fe409af1d 100644--- a/packages/cli/assets/docs/styling-libraries.doc.mjs+++ b/packages/cli/assets/docs/styling-libraries.doc.mjs@@ -56,7 +56,7 @@ export const docs = {'`@astryxdesign/core/tailwind-theme.css`',],[- 'Token resolver APIs',+ 'Design token resolver APIs','JavaScript needs token values for charts, canvas, SVG, or config objects',"`resolveThemeToken(theme, '--color-data-categorical-blue', {mode})`",],diff --git a/packages/cli/assets/docs/styling.doc.mjs b/packages/cli/assets/docs/styling.doc.mjsindex 2281541349..c76948322d 100644--- a/packages/cli/assets/docs/styling.doc.mjs+++ b/packages/cli/assets/docs/styling.doc.mjs@@ -22,10 +22,10 @@ export const docs = {type: 'table',headers: ['Approach', 'Use for', 'Example'],rows: [- ['StyleX', 'Component-specific overrides, reusable styles, pseudo-classes, and typed tokens', 'const styles = stylex.create(...); <Button xstyle={styles.save} />'],- ['Tailwind utilities', 'Layout, wrappers, and utility styling', 'className="flex gap-3 p-4"'],- ['className', 'Integrating with external CSS or Tailwind on components', 'className="my-card shadow-lg"'],- ['Styling-library token aliases', 'Keeping Panda, Chakra, MUI, Emotion, styled-components, UnoCSS, CSS Modules, or Sass in sync with the system', "colors.surface = 'var(--color-background-surface)'"],+ ['StyleX', 'Component-specific overrides, reusable styles, pseudo-classes, and typed tokens', '`const styles = stylex.create(...); <Button xstyle={styles.save} />`'],+ ['Tailwind utilities', 'Page layout, wrappers, and utility styling', '`className="flex gap-3 p-4"`'],+ ['className', 'Integrating with external CSS or Tailwind on components', '`className="my-card shadow-lg"`'],+ ['Styling-library token aliases', 'Keeping Panda, Chakra, MUI, Emotion, styled-components, UnoCSS, CSS Modules, or Sass in sync with the system', "`colors.surface = 'var(--color-background-surface)'`"],],},{diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjsindex a7bc2294f2..f2b8e509c3 100644--- a/packages/cli/assets/docs/theme.doc.mjs+++ b/packages/cli/assets/docs/theme.doc.mjs@@ -106,7 +106,7 @@ function App() {['Y2K',"import {y2kTheme} from '@astryxdesign/theme-y2k'",- 'Playful Y2K pop; periwinkle body, holographic accents, Poppins + Crimson Text.',+ 'Playful Y2K pop; periwinkle body, holographic accents, Poppins + `Crimson Text`.',],],},@@ -510,7 +510,7 @@ import './themes/ocean.css';content: [{type: 'prose',- text: 'Wrap different sections in separate <Theme> providers.',+ text: 'Wrap different sections in separate [`<Theme>`](/components/Theme) providers.',},{type: 'code',@@ -606,7 +606,7 @@ function ChartConfig() {},{type: 'prose',- text: 'Prefer CSS variables, StyleX token imports, xstyle, or className for ordinary styling. To change the theme or mode, manage state at the app level and pass it to <Theme>.',+ text: 'Prefer CSS variables, StyleX token imports, xstyle, or className for ordinary styling. To change the theme or mode, manage state at the app level and pass it to `<Theme>`.',},{type: 'prose',diff --git a/packages/cli/assets/docs/typography.doc.mjs b/packages/cli/assets/docs/typography.doc.mjsindex 4701741424..9b8516566b 100644--- a/packages/cli/assets/docs/typography.doc.mjs+++ b/packages/cli/assets/docs/typography.doc.mjs@@ -122,7 +122,7 @@ export const docs = {},{type: 'prose',- text: 'Display text often needs heading semantics for accessibility. Use the type prop on Heading to apply display styling while preserving the correct HTML element: <Heading level={1} type="display-1"> gives you display-1 styling with an <h1> tag, so screen readers see the correct document outline.',+ text: 'Display text often needs heading semantics for accessibility. Use the type prop on Heading to apply display styling while preserving the correct HTML element: `<Heading level={1} type="display-1">` gives you display-1 styling with an `<h1>` tag, so screen readers see the correct document outline.',},],},@@ -205,7 +205,7 @@ const denseTheme = defineTheme({items: ['Use Heading for document headings and Text for everything else; they apply the full type scale automatically.','Adjust typography holistically: change base and ratio in defineTheme to shift the entire ramp (e.g. { base: 16, ratio: 1.25 } for editorial, { base: 12, ratio: 1.125 } for dense UI).',- 'Use display types with as="h1" (or h2/h3) when display text is a page heading; this preserves accessibility while giving you display-level sizing. Or better, use <Heading level={1} type="display-1"> which handles both semantics and styling.',+ 'Use display types with as="h1" (or h2/h3) when display text is a page heading; this preserves accessibility while giving you display-level sizing. Or better, use `<Heading level={1} type="display-1">` which handles both semantics and styling.','Let line-height snap to the 4px grid via the type scale; expandTypeScale computes leading automatically from base and ratio.','Use the supporting type for secondary information: timestamps, helper text, metadata, captions.','Use accessibilityLevel on Heading when the visual hierarchy doesn\u0027t match the document outline (e.g. sidebar or card headings).',diff --git a/packages/core/src/Avatar/Avatar.doc.mjs b/packages/core/src/Avatar/Avatar.doc.mjsindex 9d0b110330..5dfbedf669 100644--- a/packages/core/src/Avatar/Avatar.doc.mjs+++ b/packages/core/src/Avatar/Avatar.doc.mjs@@ -93,7 +93,7 @@ export const docs = {name: 'as',type: 'ElementType',description:- 'Custom link component used when `href` is set (e.g. Next.js `Link`). Overrides the provider-level LinkProvider default. Only applies with `href`.',+ 'Custom link component used when `href` is set (e.g. `next/link`). Overrides the provider-level LinkProvider default. Only applies with `href`.',},{name: 'target',