Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat: useXDSStreamingText + useXDSLinkify hooks (#1121)

Cindy Zhang7fdd99612878
diff --git a/apps/storybook/stories/useXDSLinkify.stories.tsx b/apps/storybook/stories/useXDSLinkify.stories.tsx
new file mode 100644
index 0000000000..272d74cfee
--- /dev/null
+++ b/apps/storybook/stories/useXDSLinkify.stories.tsx
@@ -0,0 +1,186 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {useState} from 'react';
+import {useXDSLinkify} from '@xds/core/Link';
+import {XDSText} from '@xds/core/Text';
+import {XDSStack} from '@xds/core/Stack';
+import {XDSTextInput} from '@xds/core/TextInput';
+
+// ---------------------------------------------------------------------------
+// Wrapper — hooks need a component
+// ---------------------------------------------------------------------------
+
+interface LinkifyDemoProps {
+ text: string;
+ hasBuiltins: boolean;
+ hasTaskPattern: boolean;
+ hasDiffPattern: boolean;
+}
+
+function LinkifyDemo({
+ text,
+ hasBuiltins,
+ hasTaskPattern,
+ hasDiffPattern,
+}: LinkifyDemoProps) {
+ const patterns = [];
+ if (hasTaskPattern) {
+ patterns.push({
+ pattern: /\bT(\d+)\b/g,
+ href: (m: RegExpMatchArray) => `https://tasks.example.com/${m[1]}`,
+ isExternal: true,
+ });
+ }
+ if (hasDiffPattern) {
+ patterns.push({
+ pattern: /\bD(\d+)\b/g,
+ href: (m: RegExpMatchArray) => `https://phabricator.example.com/${m[0]}`,
+ isExternal: true,
+ });
+ }
+
+ const nodes = useXDSLinkify(text, {
+ patterns: patterns.length > 0 ? patterns : undefined,
+ hasBuiltins,
+ });
+
+ return (
+ <XDSStack gap={4}>
+ <div
+ style={{
+ padding: 16,
+ borderRadius: 8,
+ background: 'var(--xds-color-bg-secondary, #f5f5f5)',
+ minHeight: 40,
+ }}>
+ <XDSText type="body">{nodes}</XDSText>
+ </div>
+ <XDSText type="detail" color="secondary">
+ {nodes.length} node{nodes.length !== 1 ? 's' : ''} rendered
+ </XDSText>
+ </XDSStack>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Meta
+// ---------------------------------------------------------------------------
+
+const meta: Meta<typeof LinkifyDemo> = {
+ title: 'Hooks/useXDSLinkify',
+ component: LinkifyDemo,
+ tags: ['autodocs'],
+ argTypes: {
+ text: {control: 'text'},
+ hasBuiltins: {control: 'boolean'},
+ hasTaskPattern: {control: 'boolean'},
+ hasDiffPattern: {control: 'boolean'},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof LinkifyDemo>;
+
+// ---------------------------------------------------------------------------
+// Stories
+// ---------------------------------------------------------------------------
+
+export const URLs: Story = {
+ args: {
+ text: 'Check out https://react.dev and also https://github.com/facebook/react for the source.',
+ hasBuiltins: true,
+ hasTaskPattern: false,
+ hasDiffPattern: false,
+ },
+};
+
+export const Emails: Story = {
+ args: {
+ text: 'Contact us at [email protected] or [email protected] for help.',
+ hasBuiltins: true,
+ hasTaskPattern: false,
+ hasDiffPattern: false,
+ },
+};
+
+export const CustomPatterns: Story = {
+ name: 'Custom patterns (T/D numbers)',
+ args: {
+ text: 'Fixed in T123456 and D789012. Also see T999.',
+ hasBuiltins: true,
+ hasTaskPattern: true,
+ hasDiffPattern: true,
+ },
+};
+
+export const MixedContent: Story = {
+ args: {
+ text: 'See T123456 for the task. The fix is in D789012. Docs at https://example.com/docs. Questions? Email [email protected].',
+ hasBuiltins: true,
+ hasTaskPattern: true,
+ hasDiffPattern: true,
+ },
+};
+
+export const PlainText: Story = {
+ name: 'Plain text (no links)',
+ args: {
+ text: 'This is just regular text with no links, emails, or patterns to match.',
+ hasBuiltins: true,
+ hasTaskPattern: false,
+ hasDiffPattern: false,
+ },
+};
+
+export const BuiltinsDisabled: Story = {
+ name: 'Builtins disabled (custom only)',
+ args: {
+ text: 'T123 is a task. https://example.com is a URL that should NOT become a link.',
+ hasBuiltins: false,
+ hasTaskPattern: true,
+ hasDiffPattern: false,
+ },
+};
+
+/** Interactive playground: type text and see it linkified in real time */
+export const Interactive: Story = {
+ render: () => {
+ const [text, setText] = useState(
+ 'Check T12345, visit https://react.dev, or email [email protected]',
+ );
+
+ const nodes = useXDSLinkify(text, {
+ patterns: [
+ {
+ pattern: /\bT(\d+)\b/g,
+ href: (m: RegExpMatchArray) => `https://tasks.example.com/${m[1]}`,
+ isExternal: true,
+ },
+ {
+ pattern: /\bD(\d+)\b/g,
+ href: (m: RegExpMatchArray) =>
+ `https://phabricator.example.com/${m[0]}`,
+ isExternal: true,
+ },
+ ],
+ });
+
+ return (
+ <XDSStack gap={4}>
+ <XDSTextInput
+ label="Input text"
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ />
+ <div
+ style={{
+ padding: 16,
+ borderRadius: 8,
+ background: 'var(--xds-color-bg-secondary, #f5f5f5)',
+ minHeight: 40,
+ }}>
+ <XDSText type="body">{nodes}</XDSText>
+ </div>
+ </XDSStack>
+ );
+ },
+};
diff --git a/apps/storybook/stories/useXDSStreamingText.stories.tsx b/apps/storybook/stories/useXDSStreamingText.stories.tsx
new file mode 100644
index 0000000000..f48ee2498b
--- /dev/null
+++ b/apps/storybook/stories/useXDSStreamingText.stories.tsx
@@ -0,0 +1,121 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {useCallback, useEffect, useRef, useState} from 'react';
+import {useXDSStreamingText} from '@xds/core/hooks';
+import {XDSText} from '@xds/core/Text';
+import {XDSButton} from '@xds/core/Button';
+import {XDSVStack} from '@xds/core/Layout';
+
+interface StreamingDemoProps {
+ text: string;
+ speed: 'natural' | 'fast' | 'instant';
+ chunkSize: number;
+ chunkIntervalMs: number;
+}
+
+function StreamingDemo({
+ text,
+ speed,
+ chunkSize,
+ chunkIntervalMs,
+}: StreamingDemoProps) {
+ const [target, setTarget] = useState('');
+ const [isStreaming, setIsStreaming] = useState(false);
+ const indexRef = useRef(0);
+ const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
+
+ const displayed = useXDSStreamingText(target, isStreaming, {speed});
+
+ const start = useCallback(() => {
+ if (timerRef.current) clearInterval(timerRef.current);
+ indexRef.current = 0;
+ setTarget('');
+ setIsStreaming(true);
+
+ timerRef.current = setInterval(() => {
+ indexRef.current = Math.min(indexRef.current + chunkSize, text.length);
+ setTarget(text.slice(0, indexRef.current));
+
+ if (indexRef.current >= text.length) {
+ if (timerRef.current) clearInterval(timerRef.current);
+ timerRef.current = null;
+ setTimeout(() => setIsStreaming(false), 200);
+ }
+ }, chunkIntervalMs);
+ }, [text, chunkSize, chunkIntervalMs]);
+
+ useEffect(() => {
+ return () => {
+ if (timerRef.current) clearInterval(timerRef.current);
+ };
+ }, []);
+
+ return (
+ <XDSVStack gap={4}>
+ <div style={{display: 'flex', gap: 8, alignItems: 'center'}}>
+ <XDSButton
+ label={isStreaming ? 'Streaming...' : 'Start'}
+ onClick={start}
+ variant={isStreaming ? 'secondary' : 'primary'}
+ isDisabled={isStreaming}
+ />
+ <XDSText type="supporting">
+ speed: {speed} · chunk: {chunkSize} chars every {chunkIntervalMs}ms
+ </XDSText>
+ </div>
+ <div
+ style={{
+ padding: 16,
+ borderRadius: 8,
+ background: 'var(--color-background-muted)',
+ minHeight: 80,
+ whiteSpace: 'pre-wrap',
+ fontFamily: 'var(--font-family-body)',
+ }}>
+ <XDSText type="body">{displayed || '\u00a0'}</XDSText>
+ </div>
+ <XDSText type="supporting">
+ {displayed.length} / {target.length} chars displayed
+ {isStreaming ? ' · streaming' : target.length > 0 ? ' · done' : ''}
+ </XDSText>
+ </XDSVStack>
+ );
+}
+
+const SAMPLE_TEXT = 'Here is how you fetch a user in TypeScript:\n\nconst response = await fetch("/api/users/" + id);\nconst user = await response.json();\n\nKey points:\n- Always check response.ok before parsing\n- Use AbortController for cancellation\n- Consider a useUser hook for React apps\n\nThis approach gives you type-safe API calls with proper error handling.';
+
+const meta: Meta<typeof StreamingDemo> = {
+ title: 'Hooks/useXDSStreamingText',
+ component: StreamingDemo,
+ tags: ['autodocs'],
+ argTypes: {
+ speed: {control: 'select', options: ['natural', 'fast', 'instant']},
+ chunkSize: {control: {type: 'range', min: 1, max: 100, step: 1}},
+ chunkIntervalMs: {control: {type: 'range', min: 10, max: 500, step: 10}},
+ text: {control: 'text'},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof StreamingDemo>;
+
+export const Natural: Story = {
+ args: {text: SAMPLE_TEXT, speed: 'natural', chunkSize: 20, chunkIntervalMs: 50},
+};
+
+export const Fast: Story = {
+ args: {text: SAMPLE_TEXT, speed: 'fast', chunkSize: 20, chunkIntervalMs: 50},
+};
+
+export const Instant: Story = {
+ args: {text: SAMPLE_TEXT, speed: 'instant', chunkSize: 20, chunkIntervalMs: 50},
+};
+
+export const BurstyChunks: Story = {
+ name: 'Bursty chunks (large backlog)',
+ args: {text: SAMPLE_TEXT, speed: 'natural', chunkSize: 80, chunkIntervalMs: 200},
+};
+
+export const SlowTrickle: Story = {
+ name: 'Slow trickle',
+ args: {text: SAMPLE_TEXT, speed: 'natural', chunkSize: 1, chunkIntervalMs: 100},
+};
diff --git a/internal/test-utils/src/setup.ts b/internal/test-utils/src/setup.ts
index 02b4237fad..18af52f747 100644
--- a/internal/test-utils/src/setup.ts
+++ b/internal/test-utils/src/setup.ts
@@ -19,3 +19,21 @@ if (typeof HTMLElement.prototype.showPopover === 'undefined') {
return false;
};
}
+
+// Polyfill for matchMedia (not supported in jsdom)
+// Used by useMediaQuery → useXDSTheme → useXDSStreamingText
+if (typeof window.matchMedia === 'undefined') {
+ Object.defineProperty(window, 'matchMedia', {
+ writable: true,
+ value: (query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ }),
+ });
+}
diff --git a/packages/core/src/Link/index.ts b/packages/core/src/Link/index.ts
index af6857823a..d108c5f21c 100644
--- a/packages/core/src/Link/index.ts
+++ b/packages/core/src/Link/index.ts
@@ -18,3 +18,6 @@ export type {XDSLinkProviderProps} from './XDSLinkProvider';
export {useXDSLinkComponent} from './useXDSLinkComponent';
export type {XDSLinkComponentType} from './types';
+
+export {useXDSLinkify} from './useXDSLinkify';
+export type {LinkifyPattern, UseXDSLinkifyOptions} from './useXDSLinkify';
diff --git a/packages/core/src/Link/useXDSLinkify.test.tsx b/packages/core/src/Link/useXDSLinkify.test.tsx
new file mode 100644
index 0000000000..7ab6047135
--- /dev/null
+++ b/packages/core/src/Link/useXDSLinkify.test.tsx
@@ -0,0 +1,144 @@
+import {describe, it, expect} from 'vitest';
+import {render} from '@testing-library/react';
+import {renderHook} from '@testing-library/react';
+import {useXDSLinkify} from './useXDSLinkify';
+
+describe('useXDSLinkify', () => {
+ it('returns plain text when no links are found', () => {
+ const {result} = renderHook(() => useXDSLinkify('Hello world'));
+ expect(result.current).toEqual(['Hello world']);
+ });
+
+ it('returns plain text for empty string', () => {
+ const {result} = renderHook(() => useXDSLinkify(''));
+ expect(result.current).toEqual(['']);
+ });
+
+ it('detects URLs', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('Visit https://example.com today'),
+ );
+ expect(result.current).toHaveLength(3);
+ expect(result.current[0]).toBe('Visit ');
+ expect(result.current[2]).toBe(' today');
+ });
+
+ it('renders URLs as XDSLink elements', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('Visit https://example.com'),
+ );
+ const {container} = render(<p>{result.current}</p>);
+ const link = container.querySelector('a');
+ expect(link?.getAttribute('href')).toBe('https://example.com');
+ });
+
+ it('detects email addresses', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('Email [email protected] for info'),
+ );
+ expect(result.current).toHaveLength(3);
+ expect(result.current[0]).toBe('Email ');
+ expect(result.current[2]).toBe(' for info');
+ });
+
+ it('renders email links with mailto:', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('Email [email protected]'),
+ );
+ const {container} = render(<p>{result.current}</p>);
+ const link = container.querySelector('a');
+ expect(link?.getAttribute('href')).toBe('mailto:[email protected]');
+ });
+
+ it('detects multiple links in one string', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('Go to https://a.com and https://b.com now'),
+ );
+ expect(result.current).toHaveLength(5);
+ expect(result.current[0]).toBe('Go to ');
+ expect(result.current[2]).toBe(' and ');
+ expect(result.current[4]).toBe(' now');
+ });
+
+ it('supports custom patterns', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('Check T1234 for details', {
+ patterns: [
+ {
+ pattern: /\bT(\d+)\b/g,
+ href: (m) => `https://tasks.example.com/${m[1]}`,
+ },
+ ],
+ }),
+ );
+ expect(result.current).toHaveLength(3);
+ expect(result.current[0]).toBe('Check ');
+ expect(result.current[2]).toBe(' for details');
+
+ const {container} = render(<p>{result.current}</p>);
+ const link = container.querySelector('a');
+ expect(link?.getAttribute('href')).toBe('https://tasks.example.com/1234');
+ expect(link?.textContent).toBe('T1234');
+ });
+
+ it('custom patterns take priority over builtins', () => {
+ // A custom pattern that matches something a URL would also match
+ const {result} = renderHook(() =>
+ useXDSLinkify('See https://example.com/T1234', {
+ patterns: [
+ {
+ pattern: /https:\/\/example\.com\/T(\d+)/g,
+ href: (m) => `https://tasks.example.com/${m[1]}`,
+ label: (m) => `T${m[1]}`,
+ },
+ ],
+ }),
+ );
+ const {container} = render(<p>{result.current}</p>);
+ const link = container.querySelector('a');
+ expect(link?.textContent).toBe('T1234');
+ expect(link?.getAttribute('href')).toBe('https://tasks.example.com/1234');
+ });
+
+ it('supports custom label function', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('See D5678 here', {
+ patterns: [
+ {
+ pattern: /\bD(\d+)\b/g,
+ href: (m) => `https://phabricator.example.com/${m[0]}`,
+ label: (m) => `Diff ${m[1]}`,
+ },
+ ],
+ }),
+ );
+ const {container} = render(<p>{result.current}</p>);
+ const link = container.querySelector('a');
+ expect(link?.textContent).toBe('Diff 5678');
+ });
+
+ it('can disable builtins', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('Visit https://example.com', {
+ hasBuiltins: false,
+ }),
+ );
+ expect(result.current).toEqual(['Visit https://example.com']);
+ });
+
+ it('handles text that starts with a link', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('https://example.com is cool'),
+ );
+ expect(result.current).toHaveLength(2);
+ expect(result.current[1]).toBe(' is cool');
+ });
+
+ it('handles text that ends with a link', () => {
+ const {result} = renderHook(() =>
+ useXDSLinkify('Visit https://example.com'),
+ );
+ expect(result.current).toHaveLength(2);
+ expect(result.current[0]).toBe('Visit ');
+ });
+});
diff --git a/packages/core/src/Link/useXDSLinkify.tsx b/packages/core/src/Link/useXDSLinkify.tsx
new file mode 100644
index 0000000000..30a892e89f
--- /dev/null
+++ b/packages/core/src/Link/useXDSLinkify.tsx
@@ -0,0 +1,248 @@
+'use client';
+
+/**
+ * @file useXDSLinkify.tsx
+ * @input Uses React, XDSLink, useXDSLinkComponent
+ * @output Exports useXDSLinkify hook for auto-detecting links in plain text
+ * @position Link utility hook; turns plain text into a mix of strings and XDSLink elements
+ *
+ * Detects URLs, email addresses, and custom patterns (e.g. T1234, D5678)
+ * in plain text and renders them as XDSLink elements that respect
+ * XDSLinkProvider for client-side routing.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Link/index.ts (exports)
+ * - /packages/core/src/Link/useXDSLinkify.test.tsx (tests)
+ */
+
+import {type ReactNode, useMemo} from 'react';
+import {XDSLink} from './XDSLink';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+/**
+ * A custom pattern for detecting linkable text.
+ */
+export interface LinkifyPattern {
+ /**
+ * Regex pattern to match. Must use the global flag (g).
+ * Capture groups can be used in `href` and `label` functions.
+ */
+ pattern: RegExp;
+
+ /**
+ * Build the link URL from a regex match.
+ */
+ href: (match: RegExpMatchArray) => string;
+
+ /**
+ * Optional: custom display text for the link.
+ * Defaults to the full matched string (match[0]).
+ */
+ label?: (match: RegExpMatchArray) => string;
+
+ /**
+ * Whether the link should open in a new tab.
+ * @default false
+ */
+ isExternal?: boolean;
+}
+
+export interface UseXDSLinkifyOptions {
+ /**
+ * Custom patterns to detect, in addition to (or replacing) built-in patterns.
+ * Patterns are matched in order; first match wins for overlapping ranges.
+ */
+ patterns?: LinkifyPattern[];
+
+ /**
+ * Whether to include built-in URL and email detection.
+ * @default true
+ */
+ hasBuiltins?: boolean;
+}
+
+// =============================================================================
+// Built-in patterns
+// =============================================================================
+
+// URL pattern: matches http(s) URLs
+const URL_PATTERN: LinkifyPattern = {
+ pattern: /https?:\/\/[^\s<>'")\]},]+/g,
+ href: (match) => match[0],
+ isExternal: true,
+};
+
+// Email pattern: matches email addresses
+const EMAIL_PATTERN: LinkifyPattern = {
+ pattern: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
+ href: (match) => `mailto:${match[0]}`,
+};
+
+const BUILTIN_PATTERNS: LinkifyPattern[] = [URL_PATTERN, EMAIL_PATTERN];
+
+// =============================================================================
+// Match processing
+// =============================================================================
+
+interface ResolvedMatch {
+ start: number;
+ end: number;
+ href: string;
+ label: string;
+ isExternal: boolean;
+}
+
+/**
+ * Find all non-overlapping matches across all patterns.
+ * Custom patterns are checked first (higher priority), then builtins.
+ * First match wins for overlapping ranges.
+ */
+function findMatches(
+ text: string,
+ patterns: LinkifyPattern[],
+): ResolvedMatch[] {
+ const allMatches: ResolvedMatch[] = [];
+
+ for (const p of patterns) {
+ // Clone the regex to reset lastIndex
+ const re = new RegExp(p.pattern.source, p.pattern.flags);
+ let match: RegExpExecArray | null;
+
+ while ((match = re.exec(text)) !== null) {
+ allMatches.push({
+ start: match.index,
+ end: match.index + match[0].length,
+ href: p.href(match),
+ label: p.label ? p.label(match) : match[0],
+ isExternal: p.isExternal ?? false,
+ });
+ }
+ }
+
+ // Sort by start position, then by earlier pattern priority (stable sort)
+ allMatches.sort((a, b) => a.start - b.start);
+
+ // Remove overlapping matches (first wins)
+ const result: ResolvedMatch[] = [];
+ let lastEnd = 0;
+ for (const m of allMatches) {
+ if (m.start >= lastEnd) {
+ result.push(m);
+ lastEnd = m.end;
+ }
+ }
+
+ return result;
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+/**
+ * Detects URLs, emails, and custom patterns in plain text and returns
+ * a ReactNode array with XDSLink elements for each match.
+ *
+ * Links render via XDSLink, respecting XDSLinkProvider for client-side routing.
+ *
+ * @example
+ * ```
+ * // Basic: auto-detect URLs and emails
+ * const nodes = useXDSLinkify('Visit https://example.com or email [email protected]');
+ * return <p>{nodes}</p>;
+ * ```
+ *
+ * @example
+ * ```
+ * // Custom patterns: task and diff references
+ * const nodes = useXDSLinkify('See T1234 and D5678', {
+ * patterns: [
+ * {
+ * pattern: /\bT(\d+)\b/g,
+ * href: (m) => `https://tasks.example.com/${m[1]}`,
+ * },
+ * {
+ * pattern: /\bD(\d+)\b/g,
+ * href: (m) => `https://phabricator.example.com/${m[0]}`,
+ * },
+ * ],
+ * });
+ * ```
+ *
+ * @example
+ * ```
+ * // With XDSMarkdown — linkify text nodes in rendered markdown
+ * <XDSMarkdown
+ * components={{
+ * p: ({children}) => <p>{useXDSLinkify(String(children))}</p>,
+ * }}
+ * >
+ * {markdown}
+ * </XDSMarkdown>
+ * ```
+ */
+export function useXDSLinkify(
+ text: string,
+ options?: UseXDSLinkifyOptions,
+): ReactNode[] {
+ const {patterns: customPatterns, hasBuiltins = true} = options ?? {};
+
+ // Build the pattern list: custom first (higher priority), then builtins
+ const allPatterns = useMemo(() => {
+ const result: LinkifyPattern[] = [];
+ if (customPatterns) {
+ result.push(...customPatterns);
+ }
+ if (hasBuiltins) {
+ result.push(...BUILTIN_PATTERNS);
+ }
+ return result;
+ }, [customPatterns, hasBuiltins]);
+
+ return useMemo(() => {
+ if (allPatterns.length === 0 || text.length === 0) {
+ return [text];
+ }
+
+ const matches = findMatches(text, allPatterns);
+ if (matches.length === 0) {
+ return [text];
+ }
+
+ const nodes: ReactNode[] = [];
+ let lastIndex = 0;
+
+ for (let i = 0; i < matches.length; i++) {
+ const m = matches[i];
+
+ // Text before this match
+ if (m.start > lastIndex) {
+ nodes.push(text.slice(lastIndex, m.start));
+ }
+
+ // The link
+ nodes.push(
+ <XDSLink
+ key={`linkify-${i}`}
+ href={m.href}
+ label={m.label}
+ isExternalLink={m.isExternal}
+ >
+ {m.label}
+ </XDSLink>,
+ );
+
+ lastIndex = m.end;
+ }
+
+ // Remaining text after the last match
+ if (lastIndex < text.length) {
+ nodes.push(text.slice(lastIndex));
+ }
+
+ return nodes;
+ }, [text, allPatterns]);
+}
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index 4e2f5482cf..74a3288c2d 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -27,3 +27,9 @@ export {useScrollLock} from './useScrollLock';
export {useEntryAnimation} from './useEntryAnimation';
export type {EntryAnimationPreset} from './useEntryAnimation';
+
+export {useXDSStreamingText} from './useXDSStreamingText';
+export type {
+ StreamingTextSpeed,
+ UseStreamingTextOptions,
+} from './useXDSStreamingText';
diff --git a/packages/core/src/hooks/useXDSStreamingText.test.ts b/packages/core/src/hooks/useXDSStreamingText.test.ts
new file mode 100644
index 0000000000..46bceb5063
--- /dev/null
+++ b/packages/core/src/hooks/useXDSStreamingText.test.ts
@@ -0,0 +1,110 @@
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {renderHook, act} from '@testing-library/react';
+import {useXDSStreamingText} from './useXDSStreamingText';
+
+describe('useXDSStreamingText', () => {
+ let rafCallbacks: Array<(time: number) => void>;
+ let originalRAF: typeof requestAnimationFrame;
+ let originalCAF: typeof cancelAnimationFrame;
+
+ beforeEach(() => {
+ rafCallbacks = [];
+ originalRAF = globalThis.requestAnimationFrame;
+ originalCAF = globalThis.cancelAnimationFrame;
+ globalThis.requestAnimationFrame = vi.fn((cb) => {
+ rafCallbacks.push(cb);
+ return rafCallbacks.length;
+ }) as unknown as typeof requestAnimationFrame;
+ globalThis.cancelAnimationFrame = vi.fn();
+
+ // Mock matchMedia for useXDSTheme → useMediaQuery
+ if (!window.matchMedia) {
+ Object.defineProperty(window, 'matchMedia', {
+ writable: true,
+ value: vi.fn().mockImplementation((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ });
+ }
+ });
+
+ afterEach(() => {
+ globalThis.requestAnimationFrame = originalRAF;
+ globalThis.cancelAnimationFrame = originalCAF;
+ });
+
+ it('returns full text when not streaming', () => {
+ const {result} = renderHook(() =>
+ useXDSStreamingText('Hello world', false),
+ );
+ expect(result.current).toBe('Hello world');
+ });
+
+ it('returns full text with instant speed', () => {
+ const {result} = renderHook(() =>
+ useXDSStreamingText('Hello world', true, {speed: 'instant'}),
+ );
+ expect(result.current).toBe('Hello world');
+ });
+
+ it('starts with empty string when streaming', () => {
+ const {result} = renderHook(() =>
+ useXDSStreamingText('Hello world', true),
+ );
+ expect(result.current).toBe('');
+ });
+
+ it('snaps to full text when streaming ends', () => {
+ const {result, rerender} = renderHook(
+ ({text, streaming}) => useXDSStreamingText(text, streaming),
+ {initialProps: {text: 'Hello world', streaming: true}},
+ );
+
+ expect(result.current).toBe('');
+
+ // Stop streaming
+ rerender({text: 'Hello world', streaming: false});
+ expect(result.current).toBe('Hello world');
+ });
+
+ it('resets when target text clears', () => {
+ const {result, rerender} = renderHook(
+ ({text, streaming}) => useXDSStreamingText(text, streaming),
+ {initialProps: {text: 'Hello', streaming: false}},
+ );
+
+ expect(result.current).toBe('Hello');
+
+ // Clear text (new message)
+ rerender({text: '', streaming: true});
+ expect(result.current).toBe('');
+ });
+
+ it('progressively reveals text through animation frames', () => {
+ const {result} = renderHook(() =>
+ useXDSStreamingText('Hello, world! This is a test.', true),
+ );
+
+ expect(result.current).toBe('');
+
+ // Fire animation frames
+ let lastLen = 0;
+ for (let i = 0; i < 20; i++) {
+ if (rafCallbacks.length > 0) {
+ const cb = rafCallbacks.pop()!;
+ act(() => cb(performance.now() + i * 20));
+ }
+ expect(result.current.length).toBeGreaterThanOrEqual(lastLen);
+ lastLen = result.current.length;
+ }
+
+ expect(result.current.length).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/core/src/hooks/useXDSStreamingText.ts b/packages/core/src/hooks/useXDSStreamingText.ts
new file mode 100644
index 0000000000..67bdab3ce5
--- /dev/null
+++ b/packages/core/src/hooks/useXDSStreamingText.ts
@@ -0,0 +1,220 @@
+'use client';
+
+/**
+ * @file useXDSStreamingText.ts
+ * @input Uses React useState, useEffect, useRef, useXDSTheme
+ * @output Exports useXDSStreamingText hook for smooth text streaming
+ * @position Core hook; smooths bursty streamed text into steady character reveal
+ *
+ * Decouples the arrival rate of streamed chunks from the display rate,
+ * draining characters at a steady pace using requestAnimationFrame.
+ * Advances on word/syntax boundaries to avoid slicing mid-markdown or
+ * mid-word, preventing visual glitches when used with markdown renderers.
+ *
+ * Animation timing derives from XDS motion tokens (via useXDSTheme) when
+ * an XDSTheme provider is present. Falls back to sensible defaults when
+ * used outside a theme provider.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/index.ts (exports)
+ * - /packages/core/src/hooks/useXDSStreamingText.test.ts (tests)
+ */
+
+import {useEffect, useMemo, useRef, useState} from 'react';
+import {useXDSTheme} from '../theme/useXDSTheme';
+
+/**
+ * Speed presets for streaming text reveal.
+ * - `'natural'` — steady character-by-character reveal (~2 chars/frame)
+ * - `'fast'` — faster reveal, scales with backlog (~4 chars/frame)
+ * - `'instant'` — no animation, returns full text immediately
+ */
+export type StreamingTextSpeed = 'natural' | 'fast' | 'instant';
+
+export interface UseStreamingTextOptions {
+ /**
+ * Speed of text reveal.
+ * @default 'natural'
+ */
+ speed?: StreamingTextSpeed;
+}
+
+// Characters that are safe word/syntax boundaries for slicing
+const BOUNDARY_PATTERN = /[\s,.;:!?)\]}>]/;
+
+// Markdown syntax markers to avoid slicing inside.
+const PARTIAL_SYNTAX_PATTERNS = [
+ /\*{1,2}$/, // partial bold/italic: * or **
+ /_{1,2}$/, // partial bold/italic: _ or __
+ /~{1,2}$/, // partial strikethrough: ~ or ~~
+ /`{1,3}$/, // partial inline code or fence
+ /\[(?:[^\]]*)$/, // unclosed link text: [text
+ /!\[(?:[^\]]*)$/, // unclosed image alt: ![alt
+ /\]\([^)]*$/, // unclosed link url: ](url
+];
+
+// Fallback values when no XDSTheme provider is present
+const FALLBACK_TICK_MS = 12;
+const FALLBACK_TICK_MS_FAST = 8;
+
+/**
+ * Parse a CSS duration string (e.g. "175ms", "0.15s") to milliseconds.
+ * Returns null if unparseable.
+ */
+function parseDuration(value: string): number | null {
+ const ms = value.match(/^([\d.]+)ms$/);
+ if (ms) return parseFloat(ms[1]);
+ const s = value.match(/^([\d.]+)s$/);
+ if (s) return parseFloat(s[1]) * 1000;
+ return null;
+}
+
+const CHARS_PER_TICK = {
+ natural: 2,
+ fast: 4,
+ instant: Infinity,
+} as const;
+
+/**
+ * Smooths bursty streamed text into a steady character-by-character reveal.
+ *
+ * Returns a string that grows steadily toward `targetText`. When `isStreaming`
+ * is false, returns the full `targetText` immediately.
+ *
+ * The hook advances on word and syntax boundaries, avoiding slices inside
+ * markdown markers like `**`, backticks, `[]()`, etc. This prevents visual
+ * glitches when the output is rendered through a markdown parser.
+ *
+ * @example
+ * ```
+ * const displayed = useXDSStreamingText(rawText, isStreaming);
+ * return <XDSMarkdown>{displayed}</XDSMarkdown>;
+ * ```
+ *
+ * @example
+ * ```
+ * const displayed = useXDSStreamingText(rawText, isStreaming, { speed: 'fast' });
+ * ```
+ */
+export function useXDSStreamingText(
+ targetText: string,
+ isStreaming: boolean,
+ options?: UseStreamingTextOptions,
+): string {
+ const speed = options?.speed ?? 'natural';
+ const charsPerTick = CHARS_PER_TICK[speed];
+
+ // Derive tick timing from XDS motion tokens when available.
+ // natural → --duration-fast-min (frame-level cadence from the theme)
+ // fast → half that, floored at 4ms (roughly 2x speed)
+ const {token} = useXDSTheme();
+ const tickMs = useMemo(() => {
+ if (speed === 'instant') return 0;
+ const base = parseDuration(token('--duration-fast-min'));
+ if (base == null) {
+ return speed === 'fast' ? FALLBACK_TICK_MS_FAST : FALLBACK_TICK_MS;
+ }
+ // Scale: use ~1/10th of the theme's fast-min duration as the per-frame tick.
+ // This maps a 130ms token to ~13ms tick (natural) or ~6.5ms tick (fast).
+ const tick = speed === 'fast' ? base / 20 : base / 10;
+ return Math.max(4, Math.round(tick));
+ }, [token, speed]);
+
+ const [displayedLen, setDisplayedLen] = useState(0);
+ const targetRef = useRef(targetText);
+ const displayedLenRef = useRef(0);
+ const lastTickRef = useRef(0);
+ const rafRef = useRef<number | null>(null);
+
+ // Keep target ref in sync
+ useEffect(() => {
+ targetRef.current = targetText;
+ }, [targetText]);
+
+ // Reset when target clears (new message)
+ const targetLen = targetText.length;
+ useEffect(() => {
+ if (targetLen === 0) {
+ displayedLenRef.current = 0;
+ setDisplayedLen(0);
+ }
+ }, [targetLen]);
+
+ // Animation loop
+ useEffect(() => {
+ if (!isStreaming || speed === 'instant') return;
+
+ function tick(now: number) {
+ const elapsed = now - lastTickRef.current;
+ if (elapsed >= tickMs) {
+ lastTickRef.current = now;
+ const target = targetRef.current;
+ const currentLen = displayedLenRef.current;
+
+ if (currentLen < target.length) {
+ // Scale chars with backlog to avoid falling behind
+ const backlog = target.length - currentLen;
+ const scaledChars =
+ backlog > 200
+ ? Math.max(charsPerTick, Math.ceil(backlog * 0.15))
+ : backlog > 80
+ ? Math.max(charsPerTick, Math.ceil(backlog * 0.08))
+ : charsPerTick;
+
+ let nextLen = Math.min(currentLen + scaledChars, target.length);
+
+ // Snap to a word/punctuation boundary
+ if (nextLen < target.length) {
+ const searchWindow = target.slice(nextLen, nextLen + 12);
+ const boundaryOffset = searchWindow.search(BOUNDARY_PATTERN);
+ if (boundaryOffset >= 0 && boundaryOffset <= 8) {
+ nextLen = nextLen + boundaryOffset + 1;
+ }
+ }
+
+ nextLen = Math.min(nextLen, target.length);
+
+ // Back up if we'd slice inside a markdown syntax marker
+ const candidate = target.slice(0, nextLen);
+ for (const pattern of PARTIAL_SYNTAX_PATTERNS) {
+ const match = candidate.match(pattern);
+ if (match && match.index != null) {
+ nextLen = match.index;
+ break;
+ }
+ }
+
+ // Never go backwards
+ nextLen = Math.max(nextLen, currentLen);
+
+ displayedLenRef.current = nextLen;
+ setDisplayedLen(nextLen);
+ }
+ }
+
+ rafRef.current = requestAnimationFrame(tick);
+ }
+
+ rafRef.current = requestAnimationFrame(tick);
+ return () => {
+ if (rafRef.current !== null) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = null;
+ }
+ };
+ }, [isStreaming, charsPerTick, tickMs, speed]);
+
+ // Snap to full text when streaming ends
+ useEffect(() => {
+ if (!isStreaming && targetText.length > 0) {
+ displayedLenRef.current = targetText.length;
+ setDisplayedLen(targetText.length);
+ }
+ }, [isStreaming, targetText.length]);
+
+ if (!isStreaming || speed === 'instant') {
+ return targetText;
+ }
+
+ return targetText.slice(0, displayedLen);
+}