Skip to content

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

TypeScript

fix(markdown): prevent raw ** flash during streaming + fix fade-in animation (#2286)

Cindy Zhang1ce4fe8979ba
diff --git a/packages/core/src/Markdown/XDSMarkdown.tsx b/packages/core/src/Markdown/XDSMarkdown.tsx
index 3267262fea..973ff0dec5 100644
--- a/packages/core/src/Markdown/XDSMarkdown.tsx
+++ b/packages/core/src/Markdown/XDSMarkdown.tsx
@@ -39,7 +39,9 @@ import {XDSTableHeader} from '../Table/XDSTableHeader';
import {XDSTableBody} from '../Table/XDSTableBody';
import {xdsClassName, mergeProps} from '../utils';
import {useXDSStreamingText} from '../hooks/useXDSStreamingText';
+import {computeBoundaries, computeSegments} from './streaming';
import type {XDSBaseProps} from '../XDSBaseProps';
+import {useXDSTheme} from '../theme/useXDSTheme';
import {XDSCitation} from '../Citation/XDSCitation';
import type {XDSCitationSource} from '../Citation/XDSCitation';
import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
@@ -373,16 +375,27 @@ const styles = stylex.create({
// ---------------------------------------------------------------------------
// Streaming fade-in animation
+
+// Parse a CSS duration string (e.g. "175ms", "0.15s") to milliseconds.
+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 streamingStyles = stylex.create({
fadeIn: {
- // Resting state is fully visible — safe fallback if animation doesn't fire.
- // @starting-style declares the entry state (opacity: 0) so the browser
- // transitions from invisible to visible when the element first mounts.
opacity: 1,
transitionProperty: 'opacity',
- transitionDuration: durationVars['--duration-fast-max'],
+ transitionDuration: durationVars['--duration-medium'],
transitionTimingFunction: easeVars['--ease-standard'],
'@starting-style': {
opacity: 0,
@@ -398,8 +411,11 @@ const streamingStyles = stylex.create({
interface StreamingCursor {
/** Characters visited so far in this render pass */
offset: number;
- /** Character position where "new" content begins */
- boundary: number;
+ /** Recent boundary positions (up to 3), oldest first.
+ * Text before boundaries[0] is fully visible (no animation).
+ * Text between boundaries[i] and boundaries[i+1] gets its own fade span.
+ * Text after the last boundary is the newest chunk. */
+ boundaries: number[];
/** Whether streaming fade is active */
active: boolean;
}
@@ -612,6 +628,7 @@ function applyInlinePlugins(
* If the entire string is old, returns it as-is. If partially new, splits
* into [old, <span fade>new</span>]. If entirely new, wraps the whole thing.
*/
+/** Check if a cursor offset is in the "new" (animating) region */
function wrapTextWithFade(
content: string,
cursor: StreamingCursor,
@@ -623,30 +640,29 @@ function wrapTextWithFade(
if (!cursor.active) {
return content;
}
- if (startOffset >= cursor.boundary) {
- // Entirely new text
- return (
- <span
- key={`fade-${key}-${startOffset}`}
- {...stylex.props(streamingStyles.fadeIn)}>
- {content}
- </span>
- );
- }
- if (startOffset + content.length <= cursor.boundary) {
- // Entirely old text
+
+ const segments = computeSegments(
+ content,
+ startOffset,
+ cursor.boundaries,
+ key,
+ );
+
+ if (segments == null) {
return content;
}
- // Split: some old, some new
- const splitAt = cursor.boundary - startOffset;
- return (
- <Fragment key={`fade-${key}-split`}>
- {content.slice(0, splitAt)}
- <span {...stylex.props(streamingStyles.fadeIn)}>
- {content.slice(splitAt)}
+
+ const nodes = segments.map(seg =>
+ seg.fading ? (
+ <span key={seg.key} {...stylex.props(streamingStyles.fadeIn)}>
+ {seg.text}
</span>
- </Fragment>
+ ) : (
+ <span key={seg.key}>{seg.text}</span>
+ ),
);
+
+ return <span key={`wrap-${key}`}>{nodes}</span>;
}
/**
@@ -695,24 +711,11 @@ function renderInline(
wrapTextWithFade(seg.content, cursor, `${index}-seg-${i}`),
);
} else {
- // Plugin segment — advance cursor by matchLength, apply fade if new
- const startOffset = cursor.offset;
+ // Plugin segment — advance cursor by matchLength
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>,
- );
- }
+ result.push(
+ <Fragment key={`plugin-${index}-${i}`}>{seg.element}</Fragment>,
+ );
}
}
return <Fragment key={index}>{result}</Fragment>;
@@ -773,7 +776,6 @@ function renderInline(
);
case 'code': {
// Track code content length for cursor but don't split inside code
- const startOffset = cursor.offset;
cursor.offset += node.content.length;
const InlineCodeComp = components?.inlineCode;
const codeEl = InlineCodeComp ? (
@@ -781,15 +783,6 @@ function renderInline(
) : (
<XDSCode key={index}>{node.content}</XDSCode>
);
- if (cursor.active && startOffset >= cursor.boundary) {
- return (
- <span
- key={`fade-code-${index}-${startOffset}`}
- {...stylex.props(streamingStyles.fadeIn)}>
- {codeEl}
- </span>
- );
- }
return codeEl;
}
case 'link': {
@@ -900,7 +893,6 @@ function renderInline(
const source = citationCtx.sources[node.sourceId] ?? {
title: node.sourceId,
};
- const isNew = cursor.active && cursor.offset >= cursor.boundary;
const citVariant = citationCtx.style === 'number' ? 'number' : 'label';
const CitationComp = components?.citation;
const chip = CitationComp ? (
@@ -919,15 +911,7 @@ function renderInline(
/>
);
- return isNew ? (
- <span
- key={`fade-cite-${index}`}
- {...stylex.props(streamingStyles.fadeIn)}>
- {chip}
- </span>
- ) : (
- chip
- );
+ return chip;
}
}
}
@@ -1233,9 +1217,6 @@ function renderBlock(
item.children.length === 1 &&
firstChild?.type === 'paragraph';
- const itemIsNew =
- cursor.active && cursor.offset >= cursor.boundary;
-
const label = isInline ? (
<>
{firstChild.children.map((c, j) =>
@@ -1273,16 +1254,13 @@ function renderBlock(
</>
);
- const checkboxItem = (
+ return (
<XDSCheckboxListItem
- key={itemIsNew ? `fade-task-${i}` : i}
+ key={i}
value={`task-${i}`}
label={label}
- xstyle={itemIsNew ? streamingStyles.fadeIn : undefined}
/>
);
-
- return checkboxItem;
})}
</XDSCheckboxList>
</div>
@@ -1315,9 +1293,6 @@ function renderBlock(
// Check if this entire list item is "new" — if so, fade the
// whole item as a block instead of fading individual text spans.
- const itemTextLen = countBlockTextLength(item.children);
- const itemIsNew =
- cursor.active && cursor.offset >= cursor.boundary;
const label = isInline ? (
<>
@@ -1356,16 +1331,6 @@ function renderBlock(
</>
);
- if (itemIsNew) {
- return (
- <XDSListItem
- key={`fade-li-${i}-${cursor.offset - itemTextLen}`}
- label={label}
- xstyle={streamingStyles.fadeIn}
- />
- );
- }
-
return <XDSListItem key={i} label={label} />;
})}
</XDSList>
@@ -1421,8 +1386,6 @@ function renderBlock(
</XDSTableHeader>
<XDSTableBody>
{node.rows.map((row, i) => {
- const rowIsNew =
- cursor.active && cursor.offset >= cursor.boundary;
const cells = row.map((cell, j) => (
<XDSTableCell
key={j}
@@ -1444,13 +1407,7 @@ function renderBlock(
)}
</XDSTableCell>
));
- return (
- <XDSTableRow
- key={rowIsNew ? `fade-row-${i}` : i}
- {...(rowIsNew ? stylex.props(streamingStyles.fadeIn) : {})}>
- {cells}
- </XDSTableRow>
- );
+ return <XDSTableRow key={i}>{cells}</XDSTableRow>;
})}
</XDSTableBody>
</XDSTable>
@@ -1551,15 +1508,11 @@ export function XDSMarkdown({
const incrementalStateRef = useRef<IncrementalState>(
createIncrementalState(),
);
- // Track how much text content was rendered on the previous pass.
- // Everything beyond this boundary is "new" and gets the fade-in animation.
- const prevTextLenRef = useRef(0);
const blocks = useMemo(() => {
if (isStreaming) {
if (smoothedText === '') {
incrementalStateRef.current = createIncrementalState();
- prevTextLenRef.current = 0;
return [];
}
const input = trimStreamingArtifacts(smoothedText);
@@ -1572,11 +1525,34 @@ export function XDSMarkdown({
return parseMarkdown(children, sourceIds);
}, [smoothedText, children, isStreaming, sourceIds]);
- // Build the streaming cursor for this render pass.
- // The boundary is where "old" text ends and "new" text begins.
+ // Track recent boundaries for stacked fade-in animation.
+ // The number of spans needed = ceil(animationDuration / tickInterval).
+ // useXDSStreamingText ticks every ~tickMs, and the fade runs for
+ // --duration-fast-max. We compute the span count dynamically so the
+ // oldest span has just finished animating when it gets evicted.
+ const {token} = useXDSTheme();
+ const maxSpans = useMemo(() => {
+ const duration = parseDuration(token('--duration-fast-max')) ?? 230;
+ const tick = parseDuration(token('--duration-fast-min'));
+ // Tick interval mirrors useXDSStreamingText's timing: base / 10
+ const tickMs = tick != null ? Math.max(4, Math.round(tick / 10)) : 50;
+ return Math.min(Math.ceil(duration / tickMs), 12);
+ }, [token]);
+
+ const prevBlocksRef = useRef<BlockNode[]>([]);
+ const boundariesRef = useRef<number[]>([]);
+ const smoothedLen = smoothedText.length;
+ const boundaries = useMemo(() => {
+ void smoothedLen; // dep trigger
+ const prevLen = countBlockTextLength(prevBlocksRef.current);
+ const next = computeBoundaries(boundariesRef.current, prevLen, maxSpans);
+ boundariesRef.current = next;
+ return next;
+ }, [smoothedLen, maxSpans]);
+
const cursor: StreamingCursor = {
offset: 0,
- boundary: prevTextLenRef.current,
+ boundaries,
active: isStreaming,
};
@@ -1621,9 +1597,10 @@ export function XDSMarkdown({
</div>
);
- // After rendering, update the boundary for the next pass.
- // cursor.offset now holds the total character count of the rendered tree.
- prevTextLenRef.current = cursor.offset;
+ // Store current blocks for next render's boundary calculation.
+ // This ref write is safe under StrictMode: both invocations produce the same
+ // blocks (same smoothedText → same useMemo result), so both write the same value.
+ prevBlocksRef.current = blocks;
return rendered;
}
diff --git a/packages/core/src/Markdown/incremental.test.ts b/packages/core/src/Markdown/incremental.test.ts
index fe3b76c448..3ba5d2a694 100644
--- a/packages/core/src/Markdown/incremental.test.ts
+++ b/packages/core/src/Markdown/incremental.test.ts
@@ -177,17 +177,17 @@ describe('trimStreamingArtifacts', () => {
expect(trimStreamingArtifacts('Hello ***')).toBe('Hello ');
});
- it('keeps unclosed mid-line bold as plain text', () => {
- // Mid-line ** with content after → kept as-is. The parser renders
- // it as plain text, which is better than hiding content.
- expect(trimStreamingArtifacts('Hello **bold')).toBe('Hello **bold');
- expect(trimStreamingArtifacts('Hello **bo')).toBe('Hello **bo');
+ it('auto-closes unclosed mid-line bold', () => {
+ // Mid-line ** with content after but no closer → append closing **
+ // so text renders bold immediately during streaming
+ expect(trimStreamingArtifacts('Hello **bold')).toBe('Hello **bold**');
+ expect(trimStreamingArtifacts('Hello **bo')).toBe('Hello **bo**');
// Trailing ** with no content → still trimmed
expect(trimStreamingArtifacts('Hello **')).toBe('Hello ');
});
- it('keeps unclosed mid-line italic as plain text', () => {
- expect(trimStreamingArtifacts('Hello *ital')).toBe('Hello *ital');
+ it('auto-closes unclosed mid-line italic', () => {
+ expect(trimStreamingArtifacts('Hello *ital')).toBe('Hello *ital*');
expect(trimStreamingArtifacts('Hello *')).toBe('Hello ');
});
@@ -197,9 +197,9 @@ describe('trimStreamingArtifacts', () => {
);
});
- it('keeps unclosed bold after closed bold as plain text', () => {
+ it('auto-closes unclosed bold after closed bold', () => {
expect(trimStreamingArtifacts('Hello **done** and **open')).toBe(
- 'Hello **done** and **open',
+ 'Hello **done** and **open**',
);
});
@@ -459,6 +459,15 @@ describe('streaming end-to-end: no raw syntax visible', () => {
);
});
+ it('never shows raw ** during bold streaming', () => {
+ const text = 'Hello **bold text** and more';
+ const {visibleTexts} = streamCharByChar(text);
+ for (const visible of visibleTexts) {
+ // Raw ** should never appear in visible text
+ expect(visible).not.toContain('**');
+ }
+ });
+
it('never shows raw * during italic streaming', () => {
const text = 'Hello *italic text* and more';
const {visibleTexts} = streamCharByChar(text);
diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.ts
index 4280bc4ee6..e6c02958fe 100644
--- a/packages/core/src/Markdown/parser.ts
+++ b/packages/core/src/Markdown/parser.ts
@@ -774,6 +774,62 @@ export function trimStreamingArtifacts(input: string): string {
}
}
+ // Check for unclosed bold/italic mid-line: e.g. "Hello **bold" or "Hello *ital"
+ // Instead of trimming (hiding content), auto-close the markers so the text
+ // renders with formatting immediately as it streams in.
+ {
+ let searchFrom = 0;
+ const markers: Array<{pos: number; len: number}> = [];
+ while (searchFrom < tail.length) {
+ const idx = tail.indexOf('*', searchFrom);
+ if (idx === -1) {
+ break;
+ }
+ // Determine marker length (* or ** or ***)
+ let markerLen = 1;
+ while (idx + markerLen < tail.length && tail[idx + markerLen] === '*') {
+ markerLen++;
+ }
+ if (markerLen > 3) {
+ // 4+ stars — not standard markdown emphasis, skip
+ searchFrom = idx + markerLen;
+ continue;
+ }
+ markers.push({pos: idx, len: markerLen});
+ searchFrom = idx + markerLen;
+ }
+ // Pair markers greedily. Unpaired openers get auto-closed.
+ const paired = new Set<number>();
+ for (let i = 0; i < markers.length; i++) {
+ if (paired.has(i)) {
+ continue;
+ }
+ for (let j = i + 1; j < markers.length; j++) {
+ if (paired.has(j)) {
+ continue;
+ }
+ if (markers[j].len === markers[i].len) {
+ paired.add(i);
+ paired.add(j);
+ break;
+ }
+ }
+ }
+ // Append closing markers for each unpaired opener (in reverse order)
+ for (let i = markers.length - 1; i >= 0; i--) {
+ if (!paired.has(i)) {
+ const marker = markers[i];
+ // Only close if there's actual content after the opener
+ if (marker.pos + marker.len < tail.length) {
+ tail = tail + '*'.repeat(marker.len);
+ } else {
+ // Trailing marker with no content — trim it
+ tail = tail.slice(0, marker.pos);
+ }
+ }
+ }
+ }
+
// Find trailing unclosed strikethrough (~~)
if (tail.length >= 2 && tail.endsWith('~~')) {
// Check if there's an opener before these closing ~~
diff --git a/packages/core/src/Markdown/streaming.test.ts b/packages/core/src/Markdown/streaming.test.ts
new file mode 100644
index 0000000000..eb37cb9de9
--- /dev/null
+++ b/packages/core/src/Markdown/streaming.test.ts
@@ -0,0 +1,148 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {computeBoundaries, computeSegments} from './streaming';
+
+describe('computeBoundaries', () => {
+ it('pushes a new boundary when text grows', () => {
+ expect(computeBoundaries([], 10, 5)).toEqual([10]);
+ expect(computeBoundaries([10], 20, 5)).toEqual([10, 20]);
+ expect(computeBoundaries([10, 20], 30, 5)).toEqual([10, 20, 30]);
+ });
+
+ it('does not push when text has not grown', () => {
+ const prev = [10, 20];
+ expect(computeBoundaries(prev, 20, 5)).toBe(prev);
+ expect(computeBoundaries(prev, 15, 5)).toBe(prev);
+ });
+
+ it('evicts oldest boundaries when exceeding maxSpans', () => {
+ expect(computeBoundaries([10, 20, 30], 40, 3)).toEqual([20, 30, 40]);
+ expect(computeBoundaries([10, 20, 30, 40], 50, 3)).toEqual([30, 40, 50]);
+ });
+
+ it('handles maxSpans of 1', () => {
+ expect(computeBoundaries([10], 20, 1)).toEqual([20]);
+ });
+
+ it('returns same reference when nothing changes', () => {
+ const prev = [5, 10, 15];
+ const result = computeBoundaries(prev, 10, 5);
+ expect(result).toBe(prev);
+ });
+});
+
+describe('computeSegments', () => {
+ it('returns null when no boundaries', () => {
+ expect(computeSegments('Hello world', 0, [], 0)).toBeNull();
+ });
+
+ it('returns null when text is entirely before oldest boundary', () => {
+ expect(computeSegments('Hello', 0, [10, 20], 0)).toBeNull();
+ });
+
+ it('splits text at boundary into settled + fading', () => {
+ const result = computeSegments('Hello world', 0, [5], 0);
+ expect(result).toEqual([
+ {key: 'settled-0', text: 'Hello', fading: false},
+ {key: 'fade-0-b5', text: ' world', fading: true},
+ ]);
+ });
+
+ it('splits across multiple boundaries', () => {
+ const result = computeSegments('Hello beautiful world', 0, [5, 15], 0);
+ expect(result).toEqual([
+ {key: 'settled-0', text: 'Hello', fading: false},
+ {key: 'fade-0-b5', text: ' beautiful', fading: true},
+ {key: 'fade-0-b15', text: ' world', fading: true},
+ ]);
+ });
+
+ it('handles text starting after the oldest boundary', () => {
+ // Text node starts at offset 10, boundaries at [5, 15]
+ const result = computeSegments('world!', 10, [5, 15], 1);
+ expect(result).toEqual([
+ {key: 'fade-1-b5', text: 'world', fading: true},
+ {key: 'fade-1-b15', text: '!', fading: true},
+ ]);
+ });
+
+ it('produces stable keys across renders as text grows', () => {
+ // Simulate streaming: text grows tick by tick
+ // Tick 1: "Hel" with boundaries [0]
+ const r1 = computeSegments('Hel', 0, [0], 0);
+ expect(r1).toEqual([{key: 'fade-0-b0', text: 'Hel', fading: true}]);
+
+ // Tick 2: "Hello" with boundaries [0, 3]
+ const r2 = computeSegments('Hello', 0, [0, 3], 0);
+ expect(r2).toEqual([
+ {key: 'fade-0-b0', text: 'Hel', fading: true},
+ {key: 'fade-0-b3', text: 'lo', fading: true},
+ ]);
+
+ // Key 'fade-0-b0' is the SAME across tick 1 and tick 2
+ expect(r1![0].key).toBe(r2![0].key);
+
+ // Tick 3: "Hello wo" with boundaries [0, 3, 5]
+ const r3 = computeSegments('Hello wo', 0, [0, 3, 5], 0);
+ expect(r3).toEqual([
+ {key: 'fade-0-b0', text: 'Hel', fading: true},
+ {key: 'fade-0-b3', text: 'lo', fading: true},
+ {key: 'fade-0-b5', text: ' wo', fading: true},
+ ]);
+
+ // All previous keys preserved
+ expect(r2![0].key).toBe(r3![0].key);
+ expect(r2![1].key).toBe(r3![1].key);
+ });
+
+ it('graduated text gets stable settled key', () => {
+ // When boundary [0] gets evicted, its text merges into settled
+ // boundaries = [3, 5, 8] — text before 3 is settled
+ const r = computeSegments('Hello world', 0, [3, 5, 8], 0);
+ expect(r![0]).toEqual({key: 'settled-0', text: 'Hel', fading: false});
+
+ // If boundaries shift to [5, 8, 10] — more text settles but key stays the same
+ const r2 = computeSegments('Hello world', 0, [5, 8, 10], 0);
+ expect(r2![0]).toEqual({key: 'settled-0', text: 'Hello', fading: false});
+ expect(r2![0].key).toBe(r![0].key); // Same key — no remount
+ });
+
+ it('boundary span key never changes as content grows inside it', () => {
+ // Last boundary's span grows each tick but keeps the same key
+ const r1 = computeSegments('AB', 0, [0], 0);
+ const r2 = computeSegments('ABCD', 0, [0], 0);
+ const r3 = computeSegments('ABCDEF', 0, [0], 0);
+
+ expect(r1![0].key).toBe('fade-0-b0');
+ expect(r2![0].key).toBe('fade-0-b0');
+ expect(r3![0].key).toBe('fade-0-b0');
+
+ // Content grows but key is stable
+ expect(r1![0].text).toBe('AB');
+ expect(r2![0].text).toBe('ABCD');
+ expect(r3![0].text).toBe('ABCDEF');
+ });
+
+ it('evicted boundary text merges into settled without key collision', () => {
+ // Step 1: boundaries = [0, 5, 10]
+ const r1 = computeSegments('Hello World!!!', 0, [0, 5, 10], 0);
+ expect(r1!.map(s => s.key)).toEqual([
+ 'fade-0-b0',
+ 'fade-0-b5',
+ 'fade-0-b10',
+ ]);
+
+ // Step 2: boundary 0 evicted → boundaries = [5, 10, 14]
+ const r2 = computeSegments('Hello World!!!', 0, [5, 10, 14], 0);
+ expect(r2!.map(s => s.key)).toEqual([
+ 'settled-0',
+ 'fade-0-b5',
+ 'fade-0-b10',
+ ]);
+
+ // 'fade-0-b5' and 'fade-0-b10' kept their keys — no remount
+ expect(r1![1].key).toBe(r2![1].key);
+ expect(r1![2].key).toBe(r2![2].key);
+ });
+});
diff --git a/packages/core/src/Markdown/streaming.ts b/packages/core/src/Markdown/streaming.ts
new file mode 100644
index 0000000000..08da3cc270
--- /dev/null
+++ b/packages/core/src/Markdown/streaming.ts
@@ -0,0 +1,130 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file streaming.ts
+ * @input Boundary tracking and segment splitting for streaming fade-in animation
+ * @output Exports computeBoundaries, computeSegments, and StreamingCursor type
+ * @position Utility module; pure logic extracted from XDSMarkdown for testability
+ */
+
+/**
+ * A segment of text produced by splitting at boundary positions.
+ * Each segment either "settled" (fully visible) or "fading" (has an animation).
+ */
+export interface TextSegment {
+ /** Stable key for React reconciliation. Never changes for a segment's lifetime. */
+ key: string;
+ /** The text content of this segment */
+ text: string;
+ /** Whether this segment should have the fade-in animation */
+ fading: boolean;
+}
+
+/**
+ * Compute the updated boundaries ring buffer given a new rendered text length.
+ *
+ * Each time the rendered text grows, we push the previous length as a new boundary.
+ * The ring buffer is capped at `maxSpans` entries. Evicted boundaries' text becomes
+ * "settled" (fully visible, no animation).
+ *
+ * @param prevBoundaries - The current boundaries array
+ * @param prevRenderedLen - The rendered text length from the previous render
+ * @param maxSpans - Maximum number of concurrent animating spans
+ * @returns Updated boundaries array (new reference only if changed)
+ */
+export function computeBoundaries(
+ prevBoundaries: number[],
+ prevRenderedLen: number,
+ maxSpans: number,
+): number[] {
+ // Only push if the boundary actually advanced
+ if (
+ prevBoundaries.length === 0 ||
+ prevRenderedLen > prevBoundaries[prevBoundaries.length - 1]
+ ) {
+ const next = [...prevBoundaries, prevRenderedLen];
+ while (next.length > maxSpans) {
+ next.shift();
+ }
+ return next;
+ }
+ return prevBoundaries;
+}
+
+/**
+ * Split a text node into segments based on boundary positions.
+ *
+ * Each boundary defines the start of a fade span. The span covers from that
+ * boundary to the next boundary (or end of text for the last boundary).
+ * Text before the oldest boundary is "settled" (no animation).
+ *
+ * Key stability guarantees:
+ * - Settled text always gets key `settled-{nodeKey}`
+ * - Each fade span gets key `fade-{nodeKey}-b{boundaryValue}`
+ * - A span's key never changes once created — it stays the same until evicted
+ * - When a boundary is evicted, its text merges into the settled segment
+ *
+ * @param content - The full text content of the node
+ * @param startOffset - The cursor offset where this node starts
+ * @param boundaries - The current boundaries array
+ * @param nodeKey - The React key for this text node (usually its index)
+ * @returns Array of segments, or null if no splitting needed (all settled)
+ */
+export function computeSegments(
+ content: string,
+ startOffset: number,
+ boundaries: number[],
+ nodeKey: string | number,
+): TextSegment[] | null {
+ const endOffset = startOffset + content.length;
+
+ if (boundaries.length === 0) {
+ return null;
+ }
+
+ const oldestBoundary = boundaries[0];
+
+ // Entirely before the oldest boundary — fully settled
+ if (endOffset <= oldestBoundary) {
+ return null;
+ }
+
+ const segments: TextSegment[] = [];
+ let pos = startOffset;
+
+ // Text before the oldest boundary — settled
+ if (pos < oldestBoundary && oldestBoundary < endOffset) {
+ segments.push({
+ key: `settled-${nodeKey}`,
+ text: content.slice(0, oldestBoundary - startOffset),
+ fading: false,
+ });
+ pos = oldestBoundary;
+ }
+
+ // Each boundary gets a span
+ for (let i = 0; i < boundaries.length; i++) {
+ const bStart = boundaries[i];
+ const bEnd = i + 1 < boundaries.length ? boundaries[i + 1] : endOffset;
+
+ if (bStart >= endOffset || bEnd <= pos) {
+ continue;
+ }
+
+ const clampedStart = Math.max(bStart, pos);
+ const clampedEnd = Math.min(bEnd, endOffset);
+
+ if (clampedStart >= clampedEnd) {
+ continue;
+ }
+
+ segments.push({
+ key: `fade-${nodeKey}-b${bStart}`,
+ text: content.slice(clampedStart - startOffset, clampedEnd - startOffset),
+ fading: true,
+ });
+ pos = clampedEnd;
+ }
+
+ return segments.length > 0 ? segments : null;
+}
diff --git a/packages/core/src/hooks/useXDSStreamingText.test.ts b/packages/core/src/hooks/useXDSStreamingText.test.ts
index d09266d8dd..b7731ea84f 100644
--- a/packages/core/src/hooks/useXDSStreamingText.test.ts
+++ b/packages/core/src/hooks/useXDSStreamingText.test.ts
@@ -13,7 +13,7 @@ describe('useXDSStreamingText', () => {
rafCallbacks = [];
originalRAF = globalThis.requestAnimationFrame;
originalCAF = globalThis.cancelAnimationFrame;
- globalThis.requestAnimationFrame = vi.fn((cb) => {
+ globalThis.requestAnimationFrame = vi.fn(cb => {
rafCallbacks.push(cb);
return rafCallbacks.length;
}) as unknown as typeof requestAnimationFrame;
@@ -57,9 +57,7 @@ describe('useXDSStreamingText', () => {
});
it('starts with empty string when streaming', () => {
- const {result} = renderHook(() =>
- useXDSStreamingText('Hello world', true),
- );
+ const {result} = renderHook(() => useXDSStreamingText('Hello world', true));
expect(result.current).toBe('');
});
@@ -111,10 +109,9 @@ describe('useXDSStreamingText', () => {
});
it('advances monotonically without stalls or backwards jumps', () => {
- const targetText = 'Hello **world**, this is `code` and [a link](http://example.com).';
- const {result} = renderHook(() =>
- useXDSStreamingText(targetText, true),
- );
+ const targetText =
+ 'Hello **world**, this is `code` and [a link](http://example.com).';
+ const {result} = renderHook(() => useXDSStreamingText(targetText, true));
expect(result.current).toBe('');
@@ -141,10 +138,9 @@ describe('useXDSStreamingText', () => {
it('does not stall on markdown syntax characters', () => {
// Text with lots of markdown syntax that previously caused stalls
- const targetText = '- **bold** and *italic* with `code` and [link](url) and ~~strike~~';
- const {result} = renderHook(() =>
- useXDSStreamingText(targetText, true),
- );
+ const targetText =
+ '- **bold** and *italic* with `code` and [link](url) and ~~strike~~';
+ const {result} = renderHook(() => useXDSStreamingText(targetText, true));
// Fire enough frames to drain the entire text
for (let i = 0; i < 100; i++) {
@@ -158,5 +154,4 @@ describe('useXDSStreamingText', () => {
// (or close to it — the hook drains charsPerTick per tickMs)
expect(result.current.length).toBeGreaterThan(targetText.length * 0.5);
});
-
});