page.mdx 6.7 KB

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