An open source design system that's fully customizable and agent ready
TypeScript
fix(core): respect prefers-reduced-motion in streaming text (#3730)
Baraa Hamodid6796f8fabef
diff --git a/.changeset/streaming-reduced-motion.md b/.changeset/streaming-reduced-motion.mdnew file mode 100644index 0000000000..be4a0b92cc--- /dev/null+++ b/.changeset/streaming-reduced-motion.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Markdown/useStreamingText: streaming text now respects `prefers-reduced-motion` — the per-character reveal snaps to the full text and the entry fade is disabled for users who prefer reduced motion, matching the convention already used by Spinner, Skeleton, ProgressBar, and Chat. (#3730)+@bhamodidiff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex f4cdba9330..ccbba0d3d2 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -425,7 +425,14 @@ const streamingStyles = stylex.create({fadeIn: {opacity: 1,transitionProperty: 'opacity',- transitionDuration: durationVars['--duration-medium'],+ // Collapse the entry fade to an instant swap under reduced motion. The+ // 0s duration makes the @starting-style opacity jump non-animated (the+ // media query can't nest inside @starting-style), mirroring the+ // conditional-duration form in Spinner (Spinner.tsx).+ transitionDuration: {+ default: durationVars['--duration-medium'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },transitionTimingFunction: easeVars['--ease-standard'],'@starting-style': {opacity: 0,@@ -1049,12 +1056,7 @@ function renderBlock(switch (node.type) {case 'heading': {const level = Math.min(node.level + headingLevelStart - 1, 6) as- | 1- | 2- | 3- | 4- | 5- | 6;+ 1 | 2 | 3 | 4 | 5 | 6;const headingChildren = node.children.map((c, i) =>renderInline(c,diff --git a/packages/core/src/hooks/useStreamingText.test.ts b/packages/core/src/hooks/useStreamingText.test.tsindex 528bb42e59..70e13eb1b4 100644--- a/packages/core/src/hooks/useStreamingText.test.ts+++ b/packages/core/src/hooks/useStreamingText.test.ts@@ -8,6 +8,10 @@ describe('useStreamingText', () => {let rafCallbacks: ((time: number) => void)[];let originalRAF: typeof requestAnimationFrame;let originalCAF: typeof cancelAnimationFrame;+ let originalMatchMedia: typeof window.matchMedia | undefined;+ // Toggled per-test to drive the reduced-motion media query. Reset in+ // beforeEach so the preference never leaks between tests.+ let prefersReducedMotion: boolean;beforeEach(() => {rafCallbacks = [];@@ -19,33 +23,44 @@ describe('useStreamingText', () => {});globalThis.cancelAnimationFrame = vi.fn();- // Mock matchMedia for useTheme → 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(),- })),- });- }+ // Mock matchMedia for useTheme → useMediaQuery and the hook's own+ // reduced-motion read. Only the reduced-motion query reflects+ // `prefersReducedMotion`; theme media queries always report no match.+ prefersReducedMotion = false;+ originalMatchMedia = window.matchMedia;+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ writable: true,+ value: vi.fn().mockImplementation((query: string) => ({+ matches: query.includes('prefers-reduced-motion')+ ? prefersReducedMotion+ : 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;+ // Restore matchMedia so the mock never leaks into other suites. jsdom+ // has no matchMedia by default, so drop the property when there was none.+ if (originalMatchMedia === undefined) {+ // @ts-expect-error jsdom leaves matchMedia undefined by default+ delete window.matchMedia;+ } else {+ window.matchMedia = originalMatchMedia;+ }});it('returns full text when not streaming', () => {- const {result} = renderHook(() =>- useStreamingText('Hello world', false),- );+ const {result} = renderHook(() => useStreamingText('Hello world', false));expect(result.current).toBe('Hello world');});@@ -56,6 +71,26 @@ describe('useStreamingText', () => {expect(result.current).toBe('Hello world');});+ it('snaps to full text immediately when reduced motion is preferred', () => {+ prefersReducedMotion = true;+ const {result} = renderHook(() => useStreamingText('Hello world', true));+ expect(result.current).toBe('Hello world');+ });++ it('keeps snapping to the full text on updates when reduced motion is preferred', () => {+ prefersReducedMotion = true;+ const {result, rerender} = renderHook(+ ({text}) => useStreamingText(text, true),+ {initialProps: {text: 'Hello'}},+ );++ expect(result.current).toBe('Hello');++ // A later chunk arrives — it should appear in full, not reveal char-by-char.+ rerender({text: 'Hello world'});+ expect(result.current).toBe('Hello world');+ });+it('starts with empty string when streaming', () => {const {result} = renderHook(() => useStreamingText('Hello world', true));expect(result.current).toBe('');diff --git a/packages/core/src/hooks/useStreamingText.ts b/packages/core/src/hooks/useStreamingText.tsindex 8f13ec0731..02c069f33a 100644--- a/packages/core/src/hooks/useStreamingText.ts+++ b/packages/core/src/hooks/useStreamingText.ts@@ -4,7 +4,7 @@/*** @file useStreamingText.ts- * @input Uses React useState, useEffect, useRef, useTheme+ * @input Uses React useState, useEffect, useRef, useMediaQuery, useTheme* @output Exports useStreamingText hook for smooth text streaming* @position Core hook; smooths bursty streamed text into steady character reveal*@@ -23,6 +23,7 @@*/import {useEffect, useMemo, useRef, useState} from 'react';+import {useMediaQuery} from './useMediaQuery';import {useTheme} from '../theme/useTheme';/**@@ -71,7 +72,9 @@ const CHARS_PER_TICK = {* 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.+ * is false, returns the full `targetText` immediately. When the user prefers+ * 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@@ -143,9 +146,17 @@ export function useStreamingText(}}+ // Respect the user's reduced-motion preference — skip the progressive+ // reveal and snap straight to the full text. Uses the package's SSR-safe+ // useMediaQuery (useMediaQuery.ts) so the read stays in sync if the+ // preference changes mid-stream.+ const prefersReducedMotion = useMediaQuery(+ '(prefers-reduced-motion: reduce)',+ );+// Animation loopuseEffect(() => {- if (!isStreaming || speed === 'instant') {+ if (!isStreaming || speed === 'instant' || prefersReducedMotion) {return;}@@ -174,9 +185,9 @@ export function useStreamingText(rafRef.current = null;}};- }, [isStreaming, charsPerTick, tickMs, speed]);+ }, [isStreaming, charsPerTick, tickMs, speed, prefersReducedMotion]);- if (!isStreaming || speed === 'instant') {+ if (!isStreaming || speed === 'instant' || prefersReducedMotion) {return targetText;}