page.tsx 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import { Code } from "@/components/code";
  2. export const metadata = {
  3. title: "Streaming | json-render",
  4. };
  5. export default function StreamingPage() {
  6. return (
  7. <article>
  8. <h1 className="text-3xl font-bold mb-4">Streaming</h1>
  9. <p className="text-muted-foreground mb-8">
  10. Progressively render UI as AI generates it.
  11. </p>
  12. <h2 className="text-xl font-semibold mt-12 mb-4">SpecStream Format</h2>
  13. <p className="text-sm text-muted-foreground mb-4">
  14. json-render uses <strong>SpecStream</strong>, a JSONL-based streaming
  15. format where each line is a JSON patch operation that progressively
  16. builds your spec:
  17. </p>
  18. <Code lang="json">{`{"op":"set","path":"/root","value":"root"}
  19. {"op":"set","path":"/elements/root","value":{"type":"Card","props":{"title":"Dashboard"},"children":["metric-1","metric-2"]}}
  20. {"op":"set","path":"/elements/metric-1","value":{"type":"Metric","props":{"label":"Revenue"}}}
  21. {"op":"set","path":"/elements/metric-2","value":{"type":"Metric","props":{"label":"Users"}}}`}</Code>
  22. <h2 className="text-xl font-semibold mt-12 mb-4">useUIStream Hook</h2>
  23. <p className="text-sm text-muted-foreground mb-4">
  24. The hook handles parsing and state management:
  25. </p>
  26. <Code lang="tsx">{`import { useUIStream } from '@json-render/react';
  27. function App() {
  28. const {
  29. spec, // Current UI spec state
  30. isStreaming, // True while streaming
  31. error, // Any error that occurred
  32. send, // Function to start generation
  33. clear, // Function to reset spec and error
  34. } = useUIStream({
  35. api: '/api/generate',
  36. onComplete: (spec) => {}, // Optional: called when streaming completes
  37. onError: (error) => {}, // Optional: called when an error occurs
  38. });
  39. }`}</Code>
  40. <h2 className="text-xl font-semibold mt-12 mb-4">Patch Operations</h2>
  41. <p className="text-sm text-muted-foreground mb-4">
  42. Supported operations:
  43. </p>
  44. <ul className="list-disc list-inside text-sm text-muted-foreground space-y-2 mb-4">
  45. <li>
  46. <code className="text-foreground">set</code> — Set the value at a path
  47. (creates if needed)
  48. </li>
  49. <li>
  50. <code className="text-foreground">add</code> — Add to an array at a
  51. path
  52. </li>
  53. <li>
  54. <code className="text-foreground">replace</code> — Replace value at a
  55. path
  56. </li>
  57. <li>
  58. <code className="text-foreground">remove</code> — Remove value at a
  59. path
  60. </li>
  61. </ul>
  62. <h2 className="text-xl font-semibold mt-12 mb-4">Path Format</h2>
  63. <p className="text-sm text-muted-foreground mb-4">
  64. Paths use a key-based format for elements:
  65. </p>
  66. <Code lang="bash">{`/root -> Root element
  67. /root/children -> Children of root
  68. /elements/card-1 -> Element with key "card-1"
  69. /elements/card-1/children -> Children of card-1`}</Code>
  70. <h2 className="text-xl font-semibold mt-12 mb-4">Server-Side Setup</h2>
  71. <p className="text-sm text-muted-foreground mb-4">
  72. Ensure your API route streams properly:
  73. </p>
  74. <Code lang="typescript">{`import { streamText } from 'ai';
  75. import { catalog } from '@/lib/catalog';
  76. export async function POST(req: Request) {
  77. const { prompt } = await req.json();
  78. const result = streamText({
  79. model: 'anthropic/claude-haiku-4.5',
  80. system: catalog.prompt(),
  81. prompt,
  82. });
  83. // Return as a streaming response
  84. return result.toTextStreamResponse();
  85. }`}</Code>
  86. <h2 className="text-xl font-semibold mt-12 mb-4">
  87. Progressive Rendering
  88. </h2>
  89. <p className="text-sm text-muted-foreground mb-4">
  90. The Renderer automatically updates as the spec changes:
  91. </p>
  92. <Code lang="tsx">{`function App() {
  93. const { spec, isStreaming } = useUIStream({ api: '/api/generate' });
  94. return (
  95. <div>
  96. {isStreaming && <LoadingIndicator />}
  97. <Renderer spec={spec} registry={registry} loading={isStreaming} />
  98. </div>
  99. );
  100. }`}</Code>
  101. <h2 className="text-xl font-semibold mt-12 mb-4">Aborting Streams</h2>
  102. <p className="text-sm text-muted-foreground mb-4">
  103. Calling <code className="text-foreground">send</code> again
  104. automatically aborts the previous request. Use{" "}
  105. <code className="text-foreground">clear</code> to reset the spec and
  106. error state:
  107. </p>
  108. <Code lang="tsx">{`function App() {
  109. const { isStreaming, send, clear } = useUIStream({
  110. api: '/api/generate',
  111. });
  112. return (
  113. <div>
  114. <button onClick={() => send('Create dashboard')}>
  115. Generate
  116. </button>
  117. <button onClick={clear}>Reset</button>
  118. </div>
  119. );
  120. }`}</Code>
  121. <h2 className="text-xl font-semibold mt-12 mb-4">
  122. Low-Level SpecStream API
  123. </h2>
  124. <p className="text-sm text-muted-foreground mb-4">
  125. For custom streaming implementations, use the SpecStream compiler
  126. directly:
  127. </p>
  128. <Code lang="typescript">{`import { createSpecStreamCompiler } from '@json-render/core';
  129. // Create a compiler for your spec type
  130. const compiler = createSpecStreamCompiler<MySpec>();
  131. // Process streaming chunks from AI
  132. async function processStream(reader: ReadableStreamDefaultReader) {
  133. while (true) {
  134. const { done, value } = await reader.read();
  135. if (done) break;
  136. const { result, newPatches } = compiler.push(value);
  137. if (newPatches.length > 0) {
  138. // Update UI with partial result
  139. setSpec(result);
  140. }
  141. }
  142. // Get final compiled result
  143. return compiler.getResult();
  144. }`}</Code>
  145. <h3 className="text-lg font-semibold mt-8 mb-4">One-Shot Compilation</h3>
  146. <p className="text-sm text-muted-foreground mb-4">
  147. For non-streaming scenarios, compile entire SpecStream at once:
  148. </p>
  149. <Code lang="typescript">{`import { compileSpecStream } from '@json-render/core';
  150. const jsonl = \`{"op":"set","path":"/root","value":{"type":"Card"}}
  151. {"op":"set","path":"/root/props","value":{"title":"Hello"}}\`;
  152. const spec = compileSpecStream<MySpec>(jsonl);
  153. // { root: { type: "Card", props: { title: "Hello" } } }`}</Code>
  154. </article>
  155. );
  156. }