page.mdx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. ### Component Props (via defineRegistry)
  80. ```tsx
  81. interface ComponentContext<P> {
  82. props: P; // Typed props from catalog
  83. children?: React.ReactNode; // Rendered children (for slot components)
  84. emit: (event: string) => void; // Emit a named event (always defined)
  85. on: (event: string) => EventHandle; // Get event handle with metadata
  86. loading?: boolean;
  87. bindings?: Record<string, string>; // State paths from $bindState/$bindItem expressions
  88. }
  89. interface EventHandle {
  90. emit: () => void; // Fire the event
  91. shouldPreventDefault: boolean; // Whether any binding requested preventDefault
  92. bound: boolean; // Whether any handler is bound
  93. }
  94. ```
  95. Use `emit("press")` for simple event firing. Use `on("click")` when you need to check metadata like `shouldPreventDefault`:
  96. ```tsx
  97. Link: ({ props, on }) => {
  98. const click = on("click");
  99. return (
  100. <a
  101. href={props.href}
  102. onClick={(e) => {
  103. if (click.shouldPreventDefault) e.preventDefault();
  104. click.emit();
  105. }}
  106. >
  107. {props.label}
  108. </a>
  109. );
  110. },
  111. ```
  112. ### BaseComponentProps
  113. Catalog-agnostic base type for building reusable component libraries (e.g. `@json-render/shadcn`) that are not tied to a specific catalog:
  114. ```typescript
  115. import type { BaseComponentProps } from "@json-render/react";
  116. const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) => (
  117. <div>{props.title}{children}</div>
  118. );
  119. ```
  120. ## Hooks
  121. ### useUIStream
  122. ```typescript
  123. const {
  124. spec, // Spec | null - current UI state
  125. isStreaming, // boolean - true while streaming
  126. error, // Error | null
  127. send, // (prompt: string, context?: Record<string, unknown>) => Promise<void>
  128. clear, // () => void - reset spec and error
  129. } = useUIStream({
  130. api: string, // API endpoint URL
  131. onComplete?: (spec: Spec) => void, // Called when streaming completes
  132. onError?: (error: Error) => void, // Called when an error occurs
  133. });
  134. ```
  135. ### useStateStore
  136. ```typescript
  137. const {
  138. state, // StateModel (Record<string, unknown>)
  139. get, // (path: string) => unknown
  140. set, // (path: string, value: unknown) => void
  141. update, // (updates: Record<string, unknown>) => void
  142. } = useStateStore();
  143. ```
  144. ### useStateValue
  145. ```typescript
  146. const value = useStateValue(path: string);
  147. ```
  148. ### useStateBinding (deprecated)
  149. > **Deprecated.** Use `useBoundProp` with `$bindState` expressions instead.
  150. ```typescript
  151. const [value, setValue] = useStateBinding(path: string);
  152. ```
  153. ### useActions
  154. ```typescript
  155. const { execute } = useActions();
  156. // execute(binding: ActionBinding) => Promise<void>
  157. ```
  158. ### useAction
  159. ```typescript
  160. const { execute, isLoading } = useAction(binding: ActionBinding);
  161. // execute() => Promise<void>
  162. ```
  163. ### useIsVisible
  164. ```typescript
  165. const isVisible = useIsVisible(condition?: VisibilityCondition);
  166. ```
  167. ### useFieldValidation
  168. ```typescript
  169. const {
  170. state, // FieldValidationState
  171. validate, // () => ValidationResult
  172. touch, // () => void
  173. clear, // () => void
  174. errors, // string[]
  175. isValid, // boolean
  176. } = useFieldValidation(path: string, config?: ValidationConfig);
  177. ```
  178. `ValidationConfig` is `{ checks?: ValidationCheck[], validateOn?: 'change' | 'blur' | 'submit' }`.
  179. ### useBoundProp
  180. Two-way binding helper for `$bindState` / `$bindItem` expressions. Returns `[value, setValue]` where `setValue` writes back to the bound state path.
  181. ```typescript
  182. const [value, setValue] = useBoundProp<T>(
  183. propValue: T | undefined, // The already-resolved prop value
  184. bindingPath: string | undefined // From bindings?.value
  185. );
  186. ```
  187. Use inside registry components:
  188. ```tsx
  189. const Input: ComponentRenderer = ({ props, bindings }) => {
  190. const [value, setValue] = useBoundProp<string>(props.value, bindings?.value);
  191. return <input value={value ?? ""} onChange={(e) => setValue(e.target.value)} />;
  192. };
  193. ```
  194. ### Chat Hooks
  195. Two hooks are available for chat + GenUI, depending on your setup:
  196. - **`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.
  197. - **`useJsonRenderMessage`** -- Extracts spec + text from an AI SDK `UIMessage.parts` array. Use with the Vercel AI SDK's `useChat` for full AI SDK integration.
  198. ### useChatUI
  199. Hook for chat + GenUI experiences. Manages a multi-turn conversation where each assistant message can contain both text and a json-render UI spec.
  200. ```typescript
  201. const {
  202. messages, // ChatMessage[] - all messages in the conversation
  203. isStreaming, // boolean - true while streaming
  204. error, // Error | null
  205. send, // (text: string) => Promise<void>
  206. clear, // () => void - reset conversation
  207. } = useChatUI({
  208. api: string, // API endpoint
  209. onComplete?: (message: ChatMessage) => void, // Called when streaming completes
  210. onError?: (error: Error) => void, // Called on error
  211. });
  212. interface ChatMessage {
  213. id: string;
  214. role: "user" | "assistant";
  215. text: string;
  216. spec: Spec | null;
  217. }
  218. ```
  219. ### useJsonRenderMessage
  220. Extract a spec and text content from an AI SDK message's `parts` array. Designed for integration with Vercel AI SDK's `useChat`.
  221. ```typescript
  222. const { spec, text, hasSpec } = useJsonRenderMessage(parts: DataPart[]);
  223. // spec: Spec | null - compiled from JSONL patches in data parts
  224. // text: string - concatenated text parts
  225. // hasSpec: boolean - true when spec is non-null
  226. ```
  227. ### buildSpecFromParts / getTextFromParts
  228. Standalone utilities for extracting spec and text from AI SDK message parts (non-hook versions):
  229. ```typescript
  230. import { buildSpecFromParts, getTextFromParts } from '@json-render/react';
  231. const spec = buildSpecFromParts(message.parts); // Spec | null
  232. const text = getTextFromParts(message.parts); // string
  233. ```