page.mdx 8.0 KB

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