Skip to content

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

TypeScript

docs(useStreamingText): make the example actually stream (#9975)

Sleep8hc44f02ec2581
diff --git a/.changeset/hook-example-use-streaming-text.md b/.changeset/hook-example-use-streaming-text.md
new file mode 100644
index 0000000000..f775ebaf90
--- /dev/null
+++ b/.changeset/hook-example-use-streaming-text.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] Fix the `useStreamingText — Streaming Response` example block: it passed `isStreaming` as `false`, so the streaming reveal it exists to show never ran. The block is now a chat-style reply card with a Regenerate button that streams the response in bursts — the hook reveals it steadily while streaming and snaps to the full text when it ends.
+
+@LetMeSleep8h
diff --git a/packages/cli/api/template/use-streaming-text-hook-usage.test.tsx b/packages/cli/api/template/use-streaming-text-hook-usage.test.tsx
new file mode 100644
index 0000000000..a154683be5
--- /dev/null
+++ b/packages/cli/api/template/use-streaming-text-hook-usage.test.tsx
@@ -0,0 +1,107 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useStreamingText example shows the hook's reveal: clicking Regenerate
+ * starts a bursty fake stream, the displayed text grows steadily while
+ * streaming, and the full text is shown once the stream ends.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import UseStreamingTextHookUsage from '../../assets/templates/blocks/components/Hooks/useStreamingTextHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const FULL_TEXT =
+ 'Astryx hooks keep behavior reusable while components keep visuals consistent. Streaming text arrives in bursts; the hook smooths it into a steady reveal.';
+
+let root: Root | null = null;
+let container: HTMLElement;
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'matchMedia',
+ (query: string) =>
+ ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ }) as unknown as MediaQueryList,
+ );
+ vi.useFakeTimers();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+const FIRST_CHUNK = 'Astryx hooks keep behavior reusable ';
+
+// The reply is the text element right after the "Assistant response" heading.
+const replyText = () => {
+ const heading = Array.from(container.querySelectorAll('*')).find(
+ el => el.children.length === 0 && el.textContent === 'Assistant response',
+ );
+ return heading?.nextElementSibling?.textContent ?? '';
+};
+
+const pressRegenerate = () => {
+ const button = Array.from(container.querySelectorAll('button')).find(
+ b => b.textContent === 'Regenerate' || b.textContent === 'Streaming…',
+ );
+ act(() => button?.click());
+};
+
+describe('useStreamingTextHookUsage example', () => {
+ it('reveals text progressively while streaming and snaps to full when done', () => {
+ root = createRoot(container);
+ act(() => root!.render(<UseStreamingTextHookUsage />));
+ // Before Regenerate: nothing has streamed.
+ expect(replyText()).toBe('');
+
+ pressRegenerate();
+
+ // The first chunk lands at 350 ms. A few frames later the hook has revealed
+ // only part of it; without the hook the whole chunk would show at once.
+ act(() => vi.advanceTimersByTime(350));
+ act(() => vi.advanceTimersByTime(50));
+ const partial = replyText();
+ expect(partial.length).toBeGreaterThan(0);
+ expect(partial.length).toBeLessThan(FIRST_CHUNK.length);
+ expect(FIRST_CHUNK.startsWith(partial)).toBe(true);
+
+ // After the last chunk the stream ends and the full text shows at once.
+ act(() => vi.advanceTimersByTime(350 * 4 + 100));
+ expect(replyText()).toBe(FULL_TEXT);
+ });
+
+ it('restarts cleanly when Regenerate is pressed mid-stream', () => {
+ root = createRoot(container);
+ act(() => root!.render(<UseStreamingTextHookUsage />));
+ pressRegenerate();
+ act(() => vi.advanceTimersByTime(800));
+ pressRegenerate();
+ act(() => vi.advanceTimersByTime(350 * 4 + 100));
+ // One stream, in order: no repeated or interleaved chunks.
+ expect(replyText()).toBe(FULL_TEXT);
+ expect(
+ Array.from(container.querySelectorAll('button')).some(
+ b => b.textContent === 'Regenerate',
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.doc.mjs
index 85bc5a1cbb..92ee98f1c2 100644
--- a/packages/cli/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.doc.mjs
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.doc.mjs
@@ -7,8 +7,8 @@ export const doc = {
name: 'useStreamingText — Streaming Response',
displayName: 'useStreamingText — Streaming Response',
description:
- 'Smooth bursty generated text into a steady reveal with useStreamingText.',
+ 'A chat-style reply card: while the response streams in bursts, useStreamingText reveals it steadily character by character; when streaming ends the full text snaps into place. Regenerate replays the stream.',
isReady: true,
aspectRatio: 4 / 3,
- componentsUsed: ['Card', 'Text', 'Layout'],
+ componentsUsed: ['Button', 'Card', 'Text', 'Layout'],
};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.tsx
index ee8660053a..0cb4c3ca7c 100644
--- a/packages/cli/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.tsx
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.tsx
@@ -2,29 +2,85 @@
'use client';
+import {useCallback, useEffect, useRef, useState} from 'react';
import {useStreamingText} from '@astryxdesign/core/hooks';
+import {Button} from '@astryxdesign/core/Button';
import {Card} from '@astryxdesign/core/Card';
-import {VStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/Layout';
+
+const CHUNKS = [
+ 'Astryx hooks keep behavior reusable ',
+ 'while components keep visuals consistent. ',
+ 'Streaming text arrives in bursts; ',
+ 'the hook smooths it into a steady reveal.',
+];
-const response =
- 'Astryx hooks keep behavior reusable while components keep visuals consistent.';
+// A fake stream: chunks land in bursts, the way a model streams tokens.
+// Starting again stops the stream in progress, and the last chunk ends it.
+function useFakeStream(onChunk: (chunk: string) => void, onEnd: () => void) {
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const start = useCallback(() => {
+ if (timer.current) {
+ clearTimeout(timer.current);
+ }
+ let index = 0;
+ const tick = () => {
+ onChunk(CHUNKS[index]);
+ index += 1;
+ if (index < CHUNKS.length) {
+ timer.current = setTimeout(tick, 350);
+ } else {
+ timer.current = null;
+ onEnd();
+ }
+ };
+ timer.current = setTimeout(tick, 350);
+ }, [onChunk, onEnd]);
+ useEffect(
+ () => () => {
+ if (timer.current) {
+ clearTimeout(timer.current);
+ }
+ },
+ [],
+ );
+ return start;
+}
export default function UseStreamingTextHookUsage() {
- const displayedText = useStreamingText(response, false, {
- speed: 'fast',
- });
+ const [target, setTarget] = useState('');
+ const [isStreaming, setIsStreaming] = useState(false);
+
+ const appendChunk = useCallback((chunk: string) => {
+ setTarget(previous => previous + chunk);
+ }, []);
+ // When the last chunk has landed, end the stream so the hook snaps to the
+ // full text.
+ const endStream = useCallback(() => setIsStreaming(false), []);
+ const startStream = useFakeStream(appendChunk, endStream);
+
+ const regenerate = useCallback(() => {
+ setTarget('');
+ setIsStreaming(true);
+ startStream();
+ }, [startStream]);
+
+ const displayedText = useStreamingText(target, isStreaming, {speed: 'fast'});
return (
<Card width={420} padding={4}>
- <VStack gap={2}>
+ <VStack gap={3}>
<Text type="body" weight="bold">
Assistant response
</Text>
<Text type="body">{displayedText}</Text>
- <Text type="supporting" color="secondary">
- Complete
- </Text>
+ <Button
+ label={isStreaming ? 'Streaming…' : 'Regenerate'}
+ variant="secondary"
+ size="sm"
+ onClick={regenerate}
+ />
</VStack>
</Card>
);