An open source design system that's fully customizable and agent ready
TypeScript
fix(hooks): snap useStreamingText's rendered slice to a grapheme boundary (#4866)
Ojas Mutreja5ec28b6a7728
diff --git a/.changeset/streaming-text-grapheme-boundary.md b/.changeset/streaming-text-grapheme-boundary.mdnew file mode 100644index 0000000000..9a254d9936--- /dev/null+++ b/.changeset/streaming-text-grapheme-boundary.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `useStreamingText` no longer renders a broken glyph (a lone surrogate, or a partial ZWJ emoji sequence) for one frame when its fixed-code-unit reveal cadence happens to land inside a surrogate pair or multi-codepoint emoji. The rendered slice now snaps back to the nearest grapheme cluster boundary via `Intl.Segmenter` (with a surrogate-pair-safe fallback where it's unavailable); the reveal cadence itself is unchanged. Also corrected the hook's doc comment, which inaccurately described the cadence as advancing on word/syntax boundaries — it always advanced by fixed code units.++@HelloOjasMutrejadiff --git a/packages/core/src/hooks/useStreamingText.test.ts b/packages/core/src/hooks/useStreamingText.test.tsindex 70e13eb1b4..1fe1630099 100644--- a/packages/core/src/hooks/useStreamingText.test.ts+++ b/packages/core/src/hooks/useStreamingText.test.ts@@ -2,7 +2,7 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {renderHook, act} from '@testing-library/react';-import {useStreamingText} from './useStreamingText';+import {snapToGraphemeBoundary, useStreamingText} from './useStreamingText';describe('useStreamingText', () => {let rafCallbacks: ((time: number) => void)[];@@ -189,4 +189,49 @@ describe('useStreamingText', () => {// (or close to it — the hook drains charsPerTick per tickMs)expect(result.current.length).toBeGreaterThan(targetText.length * 0.5);});++ it('never reveals a tick boundary landing mid-surrogate-pair or mid-ZWJ-emoji-sequence (#4779)', () => {+ // natural speed advances 10 UTF-16 code units per tick. 9 ASCII chars+ // (indices 0-8) followed by a 4-person ZWJ family emoji (indices 9-19,+ // one grapheme cluster, 11 code units) means the first tick's raw+ // boundary (index 10) lands one code unit into the family emoji's first+ // surrogate pair -- exactly the failure case from the issue.+ const family = '\u{1F468}\u{1F469}\u{1F467}\u{1F466}';+ const targetText = 'a'.repeat(9) + family + 'end';+ const {result} = renderHook(() => useStreamingText(targetText, true));++ expect(rafCallbacks.length).toBeGreaterThan(0);+ const cb = rafCallbacks.pop()!;+ act(() => cb(performance.now() + 20));++ // Without the fix this would be 'a'.repeat(9) + a lone high surrogate+ // (renders as U+FFFD). With the fix, the whole not-yet-complete family+ // cluster is held back rather than rendering a broken glyph.+ expect(result.current).toBe('a'.repeat(9));+ });+});++describe('snapToGraphemeBoundary', () => {+ it('does not split a surrogate pair', () => {+ const text = 'a\u{1F389}b'; // 🎉 is a surrogate pair: indices 1 (high) and 2 (low)+ expect(snapToGraphemeBoundary(text, 2)).toBe(1);+ expect(snapToGraphemeBoundary(text, 1)).toBe(1);+ });++ it('does not split a ZWJ emoji sequence', () => {+ const family = '\u{1F468}\u{1F469}\u{1F467}\u{1F466}';+ const text = 'x' + family + 'y';+ const familyStart = 1;+ const familyEnd = 1 + family.length;+ for (let offset = familyStart + 1; offset < familyEnd; offset++) {+ expect(snapToGraphemeBoundary(text, offset)).toBe(familyStart);+ }+ });++ it('leaves boundary offsets (start, end, plain-ASCII midpoints) unchanged', () => {+ const text = 'hello';+ expect(snapToGraphemeBoundary(text, 0)).toBe(0);+ expect(snapToGraphemeBoundary(text, 5)).toBe(5);+ expect(snapToGraphemeBoundary(text, 3)).toBe(3);+ });});diff --git a/packages/core/src/hooks/useStreamingText.ts b/packages/core/src/hooks/useStreamingText.tsindex 02c069f33a..55b441e1a2 100644--- a/packages/core/src/hooks/useStreamingText.ts+++ b/packages/core/src/hooks/useStreamingText.ts@@ -9,9 +9,12 @@* @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.+ * draining characters at a steady pace using requestAnimationFrame. The+ * reveal cadence advances by a fixed number of UTF-16 code units per tick;+ * the rendered slice is then snapped back to the nearest grapheme cluster+ * boundary (see snapToGraphemeBoundary) so a tick landing inside a+ * surrogate pair, flag sequence, or ZWJ emoji doesn't render a lone+ * surrogate or a partial glyph for one frame.** Animation timing derives from Astryx motion tokens (via useTheme) when* an Theme provider is present. Falls back to sensible defaults when@@ -68,6 +71,43 @@ const CHARS_PER_TICK = {instant: Infinity,} as const;+// Reuse a single segmenter when the runtime supports Intl.Segmenter.+// Granularity is fixed and locale doesn't affect grapheme-cluster+// boundaries, so one instance is safe to share across calls.+const graphemeSegmenter =+ typeof Intl.Segmenter === 'function'+ ? new Intl.Segmenter(undefined, {granularity: 'grapheme'})+ : null;++function isLowSurrogate(codeUnit: number): boolean {+ return codeUnit >= 0xdc00 && codeUnit <= 0xdfff;+}++/**+ * Snap a UTF-16 code-unit offset down to the start of the grapheme cluster+ * it falls inside, so slicing `text` at the returned offset never splits a+ * surrogate pair, flag sequence, or ZWJ emoji mid-glyph. Offsets at the+ * start/end of the string are returned unchanged (nothing to snap).+ *+ * Falls back to snapping off a lone low surrogate when `Intl.Segmenter` is+ * unavailable — narrower than full grapheme-cluster awareness (a ZWJ+ * sequence or flag pair can still split in that path), but it's what's+ * achievable without a full grapheme-aware dependency, and it's strictly+ * better than the unguarded default of never checking at all.+ */+export function snapToGraphemeBoundary(text: string, offset: number): number {+ if (offset <= 0 || offset >= text.length) {+ return offset;+ }+ if (graphemeSegmenter) {+ // `containing` only returns undefined for an out-of-range index; offset+ // is already guarded to [1, text.length - 1] above, so this is always+ // defined at runtime — the `??` is to satisfy the type, which is wider.+ return graphemeSegmenter.segment(text).containing(offset)?.index ?? offset;+ }+ return isLowSurrogate(text.charCodeAt(offset)) ? offset - 1 : offset;+}+/*** Smooths bursty streamed text into a steady character-by-character reveal.*@@ -76,9 +116,11 @@ const CHARS_PER_TICK = {* reduced motion, the progressive reveal is skipped entirely and the full* `targetText` is returned 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.+ * The reveal cadence itself advances by a fixed number of UTF-16 code units+ * per tick, not on word or markdown-syntax boundaries — but the rendered+ * slice is always snapped back to the nearest grapheme cluster boundary, so+ * a tick landing mid-surrogate-pair or mid-emoji-sequence never renders a+ * broken glyph.** @example* ```@@ -191,5 +233,5 @@ export function useStreamingText(return targetText;}- return targetText.slice(0, displayedLen);+ return targetText.slice(0, snapToGraphemeBoundary(targetText, displayedLen));}