page.mdx 9.9 KB

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