page.mdx 7.9 KB

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