page.mdx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import { pageMetadata } from "@/lib/page-metadata"
  2. export const metadata = pageMetadata("docs/api/react")
  3. # @json-render/react
  4. React components, providers, and hooks.
  5. ## Providers
  6. ### StateProvider
  7. ```tsx
  8. <StateProvider initialState={object} onStateChange={fn}>
  9. {children}
  10. </StateProvider>
  11. ```
  12. <table>
  13. <thead>
  14. <tr>
  15. <th>Prop</th>
  16. <th>Type</th>
  17. <th>Description</th>
  18. </tr>
  19. </thead>
  20. <tbody>
  21. <tr>
  22. <td><code>store</code></td>
  23. <td><code>StateStore</code></td>
  24. <td>External store (controlled mode). When provided, <code>initialState</code> and <code>onStateChange</code> are ignored.</td>
  25. </tr>
  26. <tr>
  27. <td><code>initialState</code></td>
  28. <td><code>Record&lt;string, unknown&gt;</code></td>
  29. <td>Initial state model (uncontrolled mode).</td>
  30. </tr>
  31. <tr>
  32. <td><code>onStateChange</code></td>
  33. <td><code>{'(changes: Array<{ path: string; value: unknown }>) => void'}</code></td>
  34. <td>Callback when state changes (uncontrolled mode). Called once per <code>set</code> or <code>update</code> with all changed entries.</td>
  35. </tr>
  36. </tbody>
  37. </table>
  38. #### External Store (Controlled Mode)
  39. Pass a `StateStore` to bypass the internal state and wire json-render to any state management library:
  40. ```tsx
  41. import { createStateStore, type StateStore } from "@json-render/react";
  42. const store = createStateStore({ count: 0 });
  43. <StateProvider store={store}>
  44. {children}
  45. </StateProvider>
  46. // Mutate from anywhere — React re-renders automatically:
  47. store.set("/count", 1);
  48. ```
  49. The `store` prop is also available on `JSONUIProvider` and `createRenderer`.
  50. ### ActionProvider
  51. ```tsx
  52. <ActionProvider handlers={Record<string, ActionHandler>}>
  53. {children}
  54. </ActionProvider>
  55. type ActionHandler = (params: Record<string, unknown>) => void | Promise<void>;
  56. ```
  57. ### VisibilityProvider
  58. ```tsx
  59. <VisibilityProvider>
  60. {children}
  61. </VisibilityProvider>
  62. ```
  63. `VisibilityProvider` reads state from the parent `StateProvider` automatically. Conditions in specs use the `VisibilityCondition` format with `$state` paths (e.g. `{ "$state": "/path" }`, `{ "$state": "/path", "eq": value }`). See [visibility](/docs/visibility) for the full syntax.
  64. ### ValidationProvider
  65. ```tsx
  66. <ValidationProvider customFunctions={Record<string, ValidationFunction>}>
  67. {children}
  68. </ValidationProvider>
  69. type ValidationFunction = (value: unknown, args?: object) => boolean | Promise<boolean>;
  70. ```
  71. ## defineRegistry
  72. Create a type-safe component registry from a catalog. Components receive `props`, `children`, `emit`, `on`, and `loading` with catalog-inferred types.
  73. When the catalog declares actions, the `actions` field is required. When the catalog has no actions (e.g. `actions: {}`), the field is optional.
  74. ```tsx
  75. import { defineRegistry } from '@json-render/react';
  76. const { registry } = defineRegistry(catalog, {
  77. components: {
  78. Card: ({ props, children }) => <div>{props.title}{children}</div>,
  79. Button: ({ props, emit }) => (
  80. <button onClick={() => emit("press")}>
  81. {props.label}
  82. </button>
  83. ),
  84. },
  85. });
  86. // Pass to <Renderer>
  87. <Renderer spec={spec} registry={registry} />
  88. ```
  89. ## Components
  90. ### Renderer
  91. ```tsx
  92. <Renderer
  93. spec={Spec} // The UI spec to render
  94. registry={Registry} // Component registry (from defineRegistry)
  95. loading={boolean} // Optional loading state
  96. fallback={Component} // Optional fallback for unknown types
  97. />
  98. type Registry = Record<string, React.ComponentType<ComponentRenderProps>>;
  99. ```
  100. ### JSONUIProvider
  101. Convenience wrapper that combines `StateProvider`, `VisibilityProvider`, `ValidationProvider`, and `ActionProvider`. Accepts all their props plus:
  102. <table>
  103. <thead>
  104. <tr>
  105. <th>Prop</th>
  106. <th>Type</th>
  107. <th>Description</th>
  108. </tr>
  109. </thead>
  110. <tbody>
  111. <tr>
  112. <td><code>functions</code></td>
  113. <td><code>Record&lt;string, ComputedFunction&gt;</code></td>
  114. <td>Named functions for <code>$computed</code> expressions in props</td>
  115. </tr>
  116. </tbody>
  117. </table>
  118. ```tsx
  119. <JSONUIProvider
  120. spec={spec}
  121. catalog={catalog}
  122. handlers={{ submit: async () => { /* ... */ } }}
  123. functions={{ fullName: (args) => `${args.first} ${args.last}` }}
  124. >
  125. <Renderer spec={spec} registry={registry} />
  126. </JSONUIProvider>
  127. ```
  128. The `functions` prop is also available on `createRenderer`.
  129. ### Component Props (via defineRegistry)
  130. ```tsx
  131. interface ComponentContext<P> {
  132. props: P; // Typed props from catalog
  133. children?: React.ReactNode; // Rendered children (for slot components)
  134. emit: (event: string) => void; // Emit a named event (always defined)
  135. on: (event: string) => EventHandle; // Get event handle with metadata
  136. loading?: boolean;
  137. bindings?: Record<string, string>; // State paths from $bindState/$bindItem expressions
  138. }
  139. interface EventHandle {
  140. emit: () => void; // Fire the event
  141. shouldPreventDefault: boolean; // Whether any binding requested preventDefault
  142. bound: boolean; // Whether any handler is bound
  143. }
  144. ```
  145. Use `emit("press")` for simple event firing. Use `on("click")` when you need to check metadata like `shouldPreventDefault`:
  146. ```tsx
  147. Link: ({ props, on }) => {
  148. const click = on("click");
  149. return (
  150. <a
  151. href={props.href}
  152. onClick={(e) => {
  153. if (click.shouldPreventDefault) e.preventDefault();
  154. click.emit();
  155. }}
  156. >
  157. {props.label}
  158. </a>
  159. );
  160. },
  161. ```
  162. ### BaseComponentProps
  163. Catalog-agnostic base type for building reusable component libraries (e.g. `@json-render/shadcn`) that are not tied to a specific catalog:
  164. ```typescript
  165. import type { BaseComponentProps } from "@json-render/react";
  166. const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) => (
  167. <div>{props.title}{children}</div>
  168. );
  169. ```
  170. ## Hooks
  171. ### useUIStream
  172. ```typescript
  173. const {
  174. spec, // Spec | null - current UI state
  175. isStreaming, // boolean - true while streaming
  176. error, // Error | null
  177. send, // (prompt: string, context?: Record<string, unknown>) => Promise<void>
  178. clear, // () => void - reset spec and error
  179. } = useUIStream({
  180. api: string, // API endpoint URL
  181. onComplete?: (spec: Spec) => void, // Called when streaming completes
  182. onError?: (error: Error) => void, // Called when an error occurs
  183. });
  184. ```
  185. ### useStateStore
  186. ```typescript
  187. const {
  188. state, // StateModel (Record<string, unknown>)
  189. get, // (path: string) => unknown
  190. set, // (path: string, value: unknown) => void
  191. update, // (updates: Record<string, unknown>) => void
  192. } = useStateStore();
  193. ```
  194. ### useStateValue
  195. ```typescript
  196. const value = useStateValue(path: string);
  197. ```
  198. ### useStateBinding (deprecated)
  199. > **Deprecated.** Use `useBoundProp` with `$bindState` expressions instead.
  200. ```typescript
  201. const [value, setValue] = useStateBinding(path: string);
  202. ```
  203. ### useActions
  204. ```typescript
  205. const { execute } = useActions();
  206. // execute(binding: ActionBinding) => Promise<void>
  207. ```
  208. ### useAction
  209. ```typescript
  210. const { execute, isLoading } = useAction(binding: ActionBinding);
  211. // execute() => Promise<void>
  212. ```
  213. ### useIsVisible
  214. ```typescript
  215. const isVisible = useIsVisible(condition?: VisibilityCondition);
  216. ```
  217. ### useFieldValidation
  218. ```typescript
  219. const {
  220. state, // FieldValidationState
  221. validate, // () => ValidationResult
  222. touch, // () => void
  223. clear, // () => void
  224. errors, // string[]
  225. isValid, // boolean
  226. } = useFieldValidation(path: string, config?: ValidationConfig);
  227. ```
  228. `ValidationConfig` is `{ checks?: ValidationCheck[], validateOn?: 'change' | 'blur' | 'submit' }`.
  229. ### useOptionalValidation
  230. Non-throwing variant of `useValidation()`. Returns `null` when no `ValidationProvider` is present, instead of throwing. Useful in components that may or may not be rendered inside a validation context.
  231. ```typescript
  232. const validation = useOptionalValidation();
  233. // ValidationContextValue | null
  234. ```
  235. ### useBoundProp
  236. Two-way binding helper for `$bindState` / `$bindItem` expressions. Returns `[value, setValue]` where `setValue` writes back to the bound state path.
  237. ```typescript
  238. const [value, setValue] = useBoundProp<T>(
  239. propValue: T | undefined, // The already-resolved prop value
  240. bindingPath: string | undefined // From bindings?.value
  241. );
  242. ```
  243. Use inside registry components:
  244. ```tsx
  245. const Input: ComponentRenderer = ({ props, bindings }) => {
  246. const [value, setValue] = useBoundProp<string>(props.value, bindings?.value);
  247. return <input value={value ?? ""} onChange={(e) => setValue(e.target.value)} />;
  248. };
  249. ```
  250. ### Chat Hooks
  251. Two hooks are available for chat + GenUI, depending on your setup:
  252. - **`useChatUI`** -- Self-contained chat hook with its own message state, fetch logic, and mixed stream parsing. Use when you want a standalone chat experience without the Vercel AI SDK.
  253. - **`useJsonRenderMessage`** -- Extracts spec + text from an AI SDK `UIMessage.parts` array. Use with the Vercel AI SDK's `useChat` for full AI SDK integration.
  254. ### useChatUI
  255. Hook for chat + GenUI experiences. Manages a multi-turn conversation where each assistant message can contain both text and a json-render UI spec.
  256. ```typescript
  257. const {
  258. messages, // ChatMessage[] - all messages in the conversation
  259. isStreaming, // boolean - true while streaming
  260. error, // Error | null
  261. send, // (text: string) => Promise<void>
  262. clear, // () => void - reset conversation
  263. } = useChatUI({
  264. api: string, // API endpoint
  265. onComplete?: (message: ChatMessage) => void, // Called when streaming completes
  266. onError?: (error: Error) => void, // Called on error
  267. });
  268. interface ChatMessage {
  269. id: string;
  270. role: "user" | "assistant";
  271. text: string;
  272. spec: Spec | null;
  273. }
  274. ```
  275. ### useJsonRenderMessage
  276. Extract a spec and text content from an AI SDK message's `parts` array. Designed for integration with Vercel AI SDK's `useChat`.
  277. ```typescript
  278. const { spec, text, hasSpec } = useJsonRenderMessage(parts: DataPart[]);
  279. // spec: Spec | null - compiled from JSONL patches in data parts
  280. // text: string - concatenated text parts
  281. // hasSpec: boolean - true when spec is non-null
  282. ```
  283. ### buildSpecFromParts / getTextFromParts
  284. Standalone utilities for extracting spec and text from AI SDK message parts (non-hook versions):
  285. ```typescript
  286. import { buildSpecFromParts, getTextFromParts } from '@json-render/react';
  287. const spec = buildSpecFromParts(message.parts); // Spec | null
  288. const text = getTextFromParts(message.parts); // string
  289. ```