An open source design system that's fully customizable and agent ready
TypeScript
feat(Markdown): add inlinePlugins prop for custom text pattern rendering (#1917)
nynexman44643aad4358e95f
diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsxindex 372060bbad..d293299541 100644--- a/apps/storybook/stories/Markdown.stories.tsx+++ b/apps/storybook/stories/Markdown.stories.tsx@@ -328,3 +328,80 @@ export const ContentAlignCenter: Story = {</div>),};++export const InlinePlugins: Story = {+ name: 'Inline Plugins',+ render: () => {+ const inlinePlugins = [+ {+ // JIRA-style ticket references: PROJ-123, BUG-456, etc.+ pattern: /\b([A-Z][A-Z0-9]+-\d+)\b/g,+ render: (match: RegExpMatchArray, key: string) => (+ <a+ key={key}+ href={`https://issues.example.com/browse/${match[1]}`}+ style={{+ color: 'var(--color-text-accent, #0066FF)',+ textDecoration: 'none',+ fontWeight: 600,+ }}+ >+ {match[0]}+ </a>+ ),+ },+ {+ // GitHub-style issue references: #123, #456, etc.+ pattern: /#(\d+)/g,+ render: (match: RegExpMatchArray, key: string) => (+ <a+ key={key}+ href={`https://github.com/org/repo/issues/${match[1]}`}+ style={{+ color: 'var(--color-text-accent, #0066FF)',+ textDecoration: 'none',+ fontWeight: 600,+ }}+ >+ {match[0]}+ </a>+ ),+ },+ ];++ const markdown = [+ '## Release Notes — v2.1.0',+ '',+ 'This release fixes several issues reported in PROJ-42 and introduces',+ 'the inline plugins feature requested in #1873.',+ '',+ '### Bug Fixes',+ '',+ '- Fixed crash in streaming mode (BUG-789)',+ '- Resolved memory leak in chat components (PROJ-101)',+ '- **Bold context**: Plugin works inside **PROJ-55 formatting**',+ '',+ '### Code Example (not linkified)',+ '',+ '```typescript',+ '// PROJ-999 and BUG-888 should NOT become links inside code blocks',+ 'const ticketId = "PROJ-999";',+ '```',+ '',+ 'Inline code is also safe: `PROJ-999` stays as plain text.',+ '',+ '### Migration Guide',+ '',+ 'See PROJ-200 for the full pattern. Also check [the docs](/docs/markdown)',+ 'for usage alongside regular markdown links.',+ ].join('\n');++ return (+ <div style={{maxWidth: 680}}>+ <XDSMarkdown inlinePlugins={inlinePlugins} density="compact" headingLevelStart={2}>+ {markdown}+ </XDSMarkdown>+ </div>+ );+ },+};diff --git a/packages/core/src/Markdown/XDSMarkdown.test.tsx b/packages/core/src/Markdown/XDSMarkdown.test.tsxindex 6263b302f8..c59cd57198 100644--- a/packages/core/src/Markdown/XDSMarkdown.test.tsx+++ b/packages/core/src/Markdown/XDSMarkdown.test.tsx@@ -1,6 +1,7 @@import {describe, it, expect, vi} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';import {XDSMarkdown} from './XDSMarkdown';+import type {MarkdownInlinePlugin} from './XDSMarkdown';describe('XDSMarkdown', () => {it('renders with role="document"', () => {@@ -200,3 +201,186 @@ describe('XDSMarkdown', () => {expect(links[1].getAttribute('href')).toBe('/page');});});++// ---------------------------------------------------------------------------+// inlinePlugins+// ---------------------------------------------------------------------------++// Helper: creates a plugin that turns JIRA-style ticket refs (PROJ-123) into links+function createTicketPlugin(): MarkdownInlinePlugin {+ return {+ pattern: /\b([A-Z][A-Z0-9]+-\d+)\b/g,+ render: (match, key) => (+ <a key={key} href={`https://issues.example.com/browse/${match[1]}`} data-testid="ticket-link">+ {match[0]}+ </a>+ ),+ };+}++// Helper: creates a plugin that turns X-numbers (X12345) into links+function createXRefPlugin(): MarkdownInlinePlugin {+ return {+ pattern: /\bX(\d+)\b/g,+ render: (match, key) => (+ <a key={key} href={`https://xref.example.com/${match[1]}`} data-testid="xref-link">+ {match[0]}+ </a>+ ),+ };+}++describe('inlinePlugins', () => {+ it('transforms text patterns into custom elements', () => {+ const ticketPlugin = createTicketPlugin();+ const {container} = render(+ <XDSMarkdown inlinePlugins={[ticketPlugin]}>+ {'Check out PROJ-123 for details'}+ </XDSMarkdown>,+ );+ const link = container.querySelector('[data-testid="ticket-link"]');+ expect(link).toBeInTheDocument();+ expect(link!.getAttribute('href')).toBe('https://issues.example.com/browse/PROJ-123');+ expect(link!.textContent).toBe('PROJ-123');+ });++ it('supports multiple plugins', () => {+ const {container} = render(+ <XDSMarkdown inlinePlugins={[createTicketPlugin(), createXRefPlugin()]}>+ {'See PROJ-123 and X99999'}+ </XDSMarkdown>,+ );+ const ticketLink = container.querySelector('[data-testid="ticket-link"]');+ const xrefLink = container.querySelector('[data-testid="xref-link"]');+ expect(ticketLink).toBeInTheDocument();+ expect(ticketLink!.getAttribute('href')).toBe('https://issues.example.com/browse/PROJ-123');+ expect(xrefLink).toBeInTheDocument();+ expect(xrefLink!.getAttribute('href')).toBe('https://xref.example.com/99999');+ });++ it('does not transform patterns inside fenced code blocks', () => {+ const {container} = render(+ <XDSMarkdown inlinePlugins={[createTicketPlugin()]}>+ {'```\nPROJ-123\n```'}+ </XDSMarkdown>,+ );+ const link = container.querySelector('[data-testid="ticket-link"]');+ expect(link).toBeNull();+ expect(container.textContent).toContain('PROJ-123');+ });++ it('does not transform patterns inside inline code', () => {+ const {container} = render(+ <XDSMarkdown inlinePlugins={[createTicketPlugin()]}>+ {'Use `PROJ-123` in your code'}+ </XDSMarkdown>,+ );+ const link = container.querySelector('[data-testid="ticket-link"]');+ expect(link).toBeNull();+ expect(container.textContent).toContain('PROJ-123');+ });++ it('works alongside regular markdown links', () => {+ const {container} = render(+ <XDSMarkdown inlinePlugins={[createTicketPlugin()]}>+ {'Visit [example](https://example.com) and check PROJ-123'}+ </XDSMarkdown>,+ );+ const ticketLink = container.querySelector('[data-testid="ticket-link"]');+ expect(ticketLink).toBeInTheDocument();+ const mdLink = container.querySelector('a[href="https://example.com"]');+ expect(mdLink).toBeInTheDocument();+ expect(mdLink!.textContent).toBe('example');+ });++ it('first plugin wins for overlapping patterns', () => {+ const narrowPlugin: MarkdownInlinePlugin = {+ pattern: /PROJ-\d+/g,+ render: (match, key) => (+ <span key={key} data-testid="narrow-match">{match[0]}</span>+ ),+ };+ const broadPlugin: MarkdownInlinePlugin = {+ pattern: /[A-Z]+-\d+/g,+ render: (match, key) => (+ <span key={key} data-testid="broad-match">{match[0]}</span>+ ),+ };+ const {container} = render(+ <XDSMarkdown inlinePlugins={[narrowPlugin, broadPlugin]}>+ {'Check PROJ-123'}+ </XDSMarkdown>,+ );+ expect(container.querySelector('[data-testid="narrow-match"]')).toBeInTheDocument();+ expect(container.querySelector('[data-testid="broad-match"]')).toBeNull();+ });++ it('skips matches when getEndIndex returns false', () => {+ const plugin: MarkdownInlinePlugin = {+ pattern: /\b([A-Z]+-\d+)\b/g,+ getEndIndex: () => false,+ render: (match, key) => (+ <a key={key} data-testid="ticket-link">{match[0]}</a>+ ),+ };+ const {container} = render(+ <XDSMarkdown inlinePlugins={[plugin]}>+ {'Check PROJ-123 for details'}+ </XDSMarkdown>,+ );+ const link = container.querySelector('[data-testid="ticket-link"]');+ expect(link).toBeNull();+ expect(container.textContent).toContain('PROJ-123');+ });++ it('uses getEndIndex to adjust match boundaries', () => {+ const plugin: MarkdownInlinePlugin = {+ pattern: /TAG:/g,+ getEndIndex: (text, match) => {+ const afterMatch = text.slice(match.index! + match[0].length);+ const wordMatch = afterMatch.match(/^(\S+)/);+ if (wordMatch) {+ return match.index! + match[0].length + wordMatch[1].length;+ }+ return match.index! + match[0].length;+ },+ render: (match, key) => {+ return <span key={key} data-testid="tag-match">{match[0]}</span>;+ },+ };+ const {container} = render(+ <XDSMarkdown inlinePlugins={[plugin]}>+ {'See TAG:important here'}+ </XDSMarkdown>,+ );+ const tag = container.querySelector('[data-testid="tag-match"]');+ expect(tag).toBeInTheDocument();+ expect(container.textContent).toContain('here');+ });++ it('renders identically when no inlinePlugins are provided', () => {+ const withPlugins = render(+ <XDSMarkdown inlinePlugins={[]}>+ {'Hello **world** and `code`'}+ </XDSMarkdown>,+ );+ const withoutPlugins = render(+ <XDSMarkdown>+ {'Hello **world** and `code`'}+ </XDSMarkdown>,+ );+ expect(withPlugins.container.textContent).toBe(withoutPlugins.container.textContent);+ });++ it('transforms patterns inside bold/italic text', () => {+ const {container} = render(+ <XDSMarkdown inlinePlugins={[createTicketPlugin()]}>+ {'**PROJ-123**'}+ </XDSMarkdown>,+ );+ const link = container.querySelector('[data-testid="ticket-link"]');+ expect(link).toBeInTheDocument();+ expect(link!.textContent).toBe('PROJ-123');+ expect(link!.closest('strong')).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Markdown/XDSMarkdown.tsx b/packages/core/src/Markdown/XDSMarkdown.tsxindex 363cac2749..1b3b208cb0 100644--- a/packages/core/src/Markdown/XDSMarkdown.tsx+++ b/packages/core/src/Markdown/XDSMarkdown.tsx@@ -44,6 +44,31 @@ import type {BlockNode, InlineNode, IncrementalState} from './parser';// Props// ---------------------------------------------------------------------------+/**+ * A plugin that transforms text patterns into custom React elements+ * inside XDSMarkdown. Applied to parsed text nodes only — code blocks,+ * inline code, and other non-prose contexts are unaffected.+ *+ * Follows Lexical's TextMatchTransformer architecture:+ * - `pattern` for initial regex matching+ * - `getEndIndex` for programmatic boundary refinement+ * - `render` for producing the replacement element+ */+export interface MarkdownInlinePlugin {+ /** Regex with global flag. Matched against text nodes only. */+ pattern: RegExp;++ /**+ * Optional: refine the match boundary after the regex hits.+ * Return the end index, or false to reject the match.+ * Default: match.index + match[0].length+ */+ getEndIndex?: (text: string, match: RegExpMatchArray) => number | false;++ /** Render the match as a React element. */+ render: (match: RegExpMatchArray, key: string) => React.ReactNode;+}+/*** A citation source referenced inline in the markdown via `[id]` or `【id】`.* When `sources` is provided, bracket content matching a source key is rendered@@ -106,6 +131,13 @@ export interface XDSMarkdownProps {* @default 'start'*/contentAlign?: 'start' | 'center';+ /**+ * Plugins that transform text patterns into custom React elements.+ * Applied to text nodes after parsing — code blocks and inline code+ * are unaffected. Patterns are matched in order; first match wins+ * for overlapping ranges.+ */+ inlinePlugins?: MarkdownInlinePlugin[];xstyle?: StyleXStyles;className?: string;style?: React.CSSProperties;@@ -542,6 +574,109 @@ function sanitizeUrl(url: string): string | null {return trimmed;}+// ---------------------------------------------------------------------------+// Inline plugin matching+// ---------------------------------------------------------------------------++type InlinePluginSegment =+ | {type: 'text'; content: string}+ | {type: 'plugin'; element: React.ReactNode; matchLength: number};++/**+ * Find all plugin matches in a text string and split it into segments+ * of plain text and plugin-rendered elements.+ *+ * Algorithm mirrors `findMatches` in `useXDSLinkify`:+ * 1. Run each plugin's regex against the text+ * 2. Check getEndIndex if provided (default: match.index + match[0].length)+ * 3. If getEndIndex returns false, skip the match+ * 4. Collect all non-overlapping matches, sorted by start (first match wins)+ * 5. Split into text/plugin segments+ */+function applyInlinePlugins(+ text: string,+ plugins: MarkdownInlinePlugin[],+): InlinePluginSegment[] {+ interface RawMatch {+ start: number;+ end: number;+ match: RegExpMatchArray;+ plugin: MarkdownInlinePlugin;+ }++ const allMatches: RawMatch[] = [];++ for (const plugin of plugins) {+ // Reset lastIndex instead of cloning — avoids allocation per call.+ // Safe because text nodes are processed sequentially (no interleaving).+ plugin.pattern.lastIndex = 0;+ let m: RegExpExecArray | null;++ while ((m = plugin.pattern.exec(text)) !== null) {+ let end: number;+ if (plugin.getEndIndex) {+ const result = plugin.getEndIndex(text, m);+ if (result === false) continue;+ end = result;+ } else {+ end = m.index + m[0].length;+ }++ allMatches.push({+ start: m.index,+ end,+ match: m,+ plugin,+ });+ }+ }++ // Sort by start position (stable sort preserves plugin order for same position)+ allMatches.sort((a, b) => a.start - b.start);++ // Remove overlapping matches (first wins)+ const resolved: RawMatch[] = [];+ let lastEnd = 0;+ for (const m of allMatches) {+ if (m.start >= lastEnd) {+ resolved.push(m);+ lastEnd = m.end;+ }+ }++ if (resolved.length === 0) {+ return [{type: 'text', content: text}];+ }++ const segments: InlinePluginSegment[] = [];+ let cursor = 0;++ for (let i = 0; i < resolved.length; i++) {+ const m = resolved[i];++ // Text before this match+ if (m.start > cursor) {+ segments.push({type: 'text', content: text.slice(cursor, m.start)});+ }++ // Plugin element+ segments.push({+ type: 'plugin',+ element: m.plugin.render(m.match, `plugin-${i}`),+ matchLength: m.end - m.start,+ });++ cursor = m.end;+ }++ // Remaining text+ if (cursor < text.length) {+ segments.push({type: 'text', content: text.slice(cursor)});+ }++ return segments;+}+// ---------------------------------------------------------------------------// Inline renderer// ---------------------------------------------------------------------------@@ -614,15 +749,50 @@ function renderInline(cursor: StreamingCursor,citationCtx: CitationContext | null,linkComponent: XDSLinkComponentType = 'a',+ inlinePlugins?: MarkdownInlinePlugin[],): React.ReactNode {switch (node.type) {- case 'text':+ case 'text': {+ if (inlinePlugins && inlinePlugins.length > 0) {+ const segments = applyInlinePlugins(node.content, inlinePlugins);+ // If no plugin matched, fall through to the normal path+ // O(1) guard: applyInlinePlugins returns a single text segment when+ // nothing matched — skip the plugin path entirely in that case.+ if (!(segments.length === 1 && segments[0].type === 'text')) {+ const result: React.ReactNode[] = [];+ for (let i = 0; i < segments.length; i++) {+ const seg = segments[i];+ if (seg.type === 'text') {+ result.push(wrapTextWithFade(seg.content, cursor, `${index}-seg-${i}`));+ } else {+ // Plugin segment — advance cursor by matchLength, apply fade if new+ const startOffset = cursor.offset;+ cursor.offset += seg.matchLength;+ if (cursor.active && startOffset >= cursor.boundary) {+ result.push(+ <span+ key={`fade-plugin-${index}-${i}-${startOffset}`}+ {...stylex.props(streamingStyles.fadeIn)}>+ {seg.element}+ </span>,+ );+ } else {+ result.push(+ <Fragment key={`plugin-${index}-${i}`}>{seg.element}</Fragment>,+ );+ }+ }+ }+ return <Fragment key={index}>{result}</Fragment>;+ }+ }return wrapTextWithFade(node.content, cursor, index);+ }case 'bold':return (<strong key={index} {...stylex.props(styles.bold)}>{node.children.map((c, i) =>- renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</strong>);@@ -630,7 +800,7 @@ function renderInline(return (<em key={index}>{node.children.map((c, i) =>- renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</em>);@@ -638,7 +808,7 @@ function renderInline(return (<del key={index} {...stylex.props(styles.strikethrough)}>{node.children.map((c, i) =>- renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</del>);@@ -664,7 +834,7 @@ function renderInline(return (<span key={index}>{node.children.map((c, i) =>- renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</span>);@@ -692,7 +862,7 @@ function renderInline(: {})}{...stylex.props(styles.link)}>{node.children.map((c, i) =>- renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</LinkTag>);@@ -843,6 +1013,7 @@ function renderBlock(contentWidthValue: string | null,contentAlign: 'start' | 'center',linkComponent: XDSLinkComponentType = 'a',+ inlinePlugins?: MarkdownInlinePlugin[],): React.ReactNode {const spacing = getElementSpacing(node, density);const isFirst = index === 0;@@ -875,7 +1046,7 @@ function renderBlock(isLast && styles.noMarginBlockEnd,)}>{node.children.map((c, i) =>- renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</Tag>);@@ -896,7 +1067,7 @@ function renderBlock(isLast && styles.noMarginBlockEnd,)}>{node.children.map((c, i) =>- renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, i, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</p>);@@ -957,6 +1128,7 @@ function renderBlock(contentWidthValue,contentAlign,linkComponent,+ inlinePlugins,),)}</blockquote>@@ -1000,7 +1172,7 @@ function renderBlock(const label = isInline ? (<>{firstChild.children.map((c, j) =>- renderInline(c, j, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, j, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</>) : (@@ -1018,6 +1190,7 @@ function renderBlock(contentWidthValue,contentAlign,linkComponent,+ inlinePlugins,),)}</>@@ -1080,7 +1253,7 @@ function renderBlock(const label = isInline ? (<>{firstChild.children.map((c, j) =>- renderInline(c, j, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, j, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</>) : (@@ -1098,6 +1271,7 @@ function renderBlock(contentWidthValue,contentAlign,linkComponent,+ inlinePlugins,),)}</>@@ -1156,7 +1330,7 @@ function renderBlock(alignStyle(node.alignments[i]),)}>{h.children.map((c, j) =>- renderInline(c, j, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, j, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</th>))}@@ -1174,7 +1348,7 @@ function renderBlock(alignStyle(node.alignments[j]),)}>{cell.children.map((c, k) =>- renderInline(c, k, onLinkClick, cursor, citationCtx, linkComponent),+ renderInline(c, k, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins),)}</td>));@@ -1259,6 +1433,7 @@ export function XDSMarkdown({citationStyle = 'label',contentWidth = 680,contentAlign = 'start',+ inlinePlugins,xstyle,className,style,@@ -1339,6 +1514,7 @@ export function XDSMarkdown({: null,contentAlign,LinkComponent,+ inlinePlugins,),)}</div>diff --git a/packages/core/src/Markdown/index.ts b/packages/core/src/Markdown/index.tsindex 0c7c57637f..d61a6832d7 100644--- a/packages/core/src/Markdown/index.ts+++ b/packages/core/src/Markdown/index.ts@@ -7,7 +7,7 @@*/export {XDSMarkdown} from './XDSMarkdown';-export type {XDSMarkdownProps, XDSMarkdownSource} from './XDSMarkdown';+export type {XDSMarkdownProps, XDSMarkdownSource, MarkdownInlinePlugin} from './XDSMarkdown';export {parseMarkdown,