Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

streamingServerComponents.tsx

164 lines5.4 KB

1import { createServerFn } from '@tanstack/react-start'
2import { createCompositeComponent } from '@tanstack/react-start/rsc'
3import { serverBox, serverBadge, serverHeader, timestamp } from './serverStyles'
4​
5// ============================================================================
6// STREAMING: Notification components streamed via ReadableStream or AsyncGenerator
7// Used by: rsc-stream-readable.tsx, rsc-stream-generator.tsx, rsc-stream-loader.tsx
8// ============================================================================
9​
10type NotificationData = {
11 id: string
12 title: string
13 message: string
14 timestamp: number
15 source: string
17​
18function generateNotification(index: number): NotificationData {
19 const sources = ['System', 'User', 'API', 'Database', 'Security', 'Analytics']
20 const messages = [
21 'New user registration completed successfully',
22 'Database backup finished without errors',
23 'API rate limit approaching threshold',
24 'Security scan detected no vulnerabilities',
25 'Weekly analytics report is ready',
26 'Server maintenance scheduled for tonight',
27 'New feature deployment completed',
28 'Cache invalidation triggered',
29 ]
30​
31 return {
32 id: `notif_${index}_${Math.random().toString(36).slice(2, 8)}`,
33 title: `Notification ${index + 1}`,
34 message: messages[index % messages.length],
35 timestamp: Date.now(),
36 source: sources[index % sources.length],
37 }
39​
40async function createNotificationRSC(notification: NotificationData) {
41 return createCompositeComponent(
42 (props: { renderActions?: (data: { id: string }) => React.ReactNode }) => {
43 return (
44 <div style={serverBox} data-testid={`notification-${notification.id}`}>
45 <div style={serverHeader}>
46 <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
47 <span style={serverBadge}>SERVER COMPONENT</span>
48 <span
49 style={{
50 fontSize: '11px',
51 color: '#0c4a6e',
52 fontWeight: 'bold',
53 }}
54 >
55 {notification.source}
56 </span>
57 </div>
58 <span
59 style={timestamp}
60 data-testid={`timestamp-${notification.id}`}
61 >
62 {new Date(notification.timestamp).toLocaleTimeString()}
63 </span>
64 </div>
65​
66 <div style={{ flex: 1 }}>
67 <h3
68 style={{ margin: '0 0 4px 0', color: '#0c4a6e' }}
69 data-testid={`title-${notification.id}`}
70 >
71 {notification.title}
72 </h3>
73 <p
74 style={{ margin: 0, fontSize: '14px', color: '#64748b' }}
75 data-testid={`message-${notification.id}`}
76 >
77 {notification.message}
78 </p>
79 <div
80 style={{
81 marginTop: '8px',
82 fontSize: '11px',
83 color: '#94a3b8',
84 }}
85 data-testid={`id-${notification.id}`}
86 >
87 ID: {notification.id}
88 </div>
89 </div>
90​
91 {/* Client slot for interactive actions */}
92 {props.renderActions?.({ id: notification.id })}
93 </div>
94 )
95 },
96 )
98​
99/**
100 * Streams notification RSCs using ReadableStream pattern.
101 * First `initialCount` notifications arrive immediately (batched),
102 * then `streamCount` more stream in with delays.
103 */
104export const streamNotificationsReadable = createServerFn({ method: 'GET' })
105 .validator(
106 (data: { initialCount: number; streamCount: number; delayMs: number }) =>
107 data,
108 )
109 .handler(async ({ data }) => {
110 const { initialCount, streamCount, delayMs } = data
111​
112 // Return a typed ReadableStream of server components
113 const stream = new ReadableStream({
114 async start(controller) {
115 // Send initial batch immediately
116 for (let i = 0; i < initialCount; i++) {
117 const notification = generateNotification(i)
118 const rsc = await createNotificationRSC(notification)
119 controller.enqueue(rsc)
120 }
121​
122 // Stream remaining with delays
123 for (let i = 0; i < streamCount; i++) {
124 await new Promise((resolve) => setTimeout(resolve, delayMs))
125 const notification = generateNotification(initialCount + i)
126 const rsc = await createNotificationRSC(notification)
127 controller.enqueue(rsc)
128 }
129​
130 controller.close()
131 },
132 })
133​
134 return stream
135 })
136​
137/**
138 * Streams notification RSCs using async generator pattern.
139 * First `initialCount` notifications arrive immediately (batched),
140 * then `streamCount` more stream in with delays.
141 */
142export const streamNotificationsGenerator = createServerFn({ method: 'GET' })
143 .validator(
144 (data: { initialCount: number; streamCount: number; delayMs: number }) =>
145 data,
146 )
147 .handler(async function* ({ data }) {
148 const { initialCount, streamCount, delayMs } = data
149​
150 // Yield initial batch immediately
151 for (let i = 0; i < initialCount; i++) {
152 const notification = generateNotification(i)
153 const rsc = await createNotificationRSC(notification)
154 yield rsc
155 }
156​
157 // Stream remaining with delays
158 for (let i = 0; i < streamCount; i++) {
159 await new Promise((resolve) => setTimeout(resolve, delayMs))
160 const notification = generateNotification(initialCount + i)
161 const rsc = await createNotificationRSC(notification)
162 yield rsc
163 }
164 })