page.mdx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. export const metadata = { title: "Registry" }
  2. # Registry
  3. A registry maps your [catalog](/docs/catalog) definitions to platform-specific implementations. The catalog defines *what* AI can generate — the registry provides the *how*.
  4. What a registry contains depends on the schema you use. Each package defines its own schema, which determines the shape of both the catalog and the registry.
  5. - **`@json-render/react`** — Components (React elements) and action handlers
  6. - **`@json-render/react-native`** — Components (React Native elements) and action handlers
  7. - **`@json-render/remotion`** — Clip components, transitions, and effects
  8. ## @json-render/react
  9. ### defineRegistry
  10. Use `defineRegistry` to create a type-safe registry from your catalog. Pass your components, actions, or both:
  11. ```tsx
  12. import { defineRegistry } from '@json-render/react';
  13. import { myCatalog } from './catalog';
  14. export const { registry, handlers, executeAction } = defineRegistry(myCatalog, {
  15. components: {
  16. Card: ({ props, children }) => (
  17. <div className="card">
  18. <h2>{props.title}</h2>
  19. {props.description && <p>{props.description}</p>}
  20. {children}
  21. </div>
  22. ),
  23. Button: ({ props, emit }) => (
  24. <button onClick={() => emit("press")}>
  25. {props.label}
  26. </button>
  27. ),
  28. },
  29. actions: {
  30. submit_form: async (params, setState) => {
  31. const res = await fetch('/api/submit', {
  32. method: 'POST',
  33. body: JSON.stringify(params),
  34. });
  35. const result = await res.json();
  36. setState((prev) => ({ ...prev, formResult: result }));
  37. },
  38. export_data: async (params) => {
  39. const blob = await generateExport(params.format);
  40. downloadBlob(blob, `export.${params.format}`);
  41. },
  42. },
  43. });
  44. ```
  45. The returned object contains:
  46. - `registry` — component registry for `<Renderer />`
  47. - `handlers` — factory for ActionProvider-compatible handlers
  48. - `executeAction` — imperative action dispatch (for use outside the React tree)
  49. ### Component Props
  50. Each component receives a `ComponentContext` object:
  51. ```typescript
  52. interface ComponentContext {
  53. props: T; // Type-safe props from your catalog
  54. children?: React.ReactNode; // Rendered children (for slot components)
  55. emit: (event: string) => void; // Emit a named event (e.g. "press")
  56. loading?: boolean; // Whether the renderer is in a loading state
  57. bindings?: Record<string, string>; // State paths from $bindState/$bindItem expressions
  58. }
  59. ```
  60. Props are automatically inferred from your catalog, so `props.title` is typed as `string` if your catalog defines it that way.
  61. #### Using `bindings` for two-way binding
  62. When a spec uses `{ "$bindState": "/path" }` or `{ "$bindItem": "field" }` on a prop, the renderer resolves the **value** into `props` and provides the **write-back path** in `bindings`. Use the `useBoundProp` hook to wire both together:
  63. ```tsx
  64. import { useBoundProp, defineRegistry } from '@json-render/react';
  65. // Inside your registry:
  66. TextInput: ({ props, bindings }) => {
  67. const [value, setValue] = useBoundProp<string>(props.value, bindings?.value);
  68. return (
  69. <input
  70. value={value ?? ""}
  71. onChange={(e) => setValue(e.target.value)}
  72. />
  73. );
  74. },
  75. ```
  76. `useBoundProp` returns `[resolvedValue, setter]`. The setter writes to the bound state path. If no binding exists (the prop is a literal), the setter is a no-op.
  77. ### Action Handlers
  78. Instead of AI generating arbitrary code, it declares *intent* by name. Your application provides the implementation. This is a core guardrail.
  79. Actions are declared in your [catalog](/docs/catalog). The `@json-render/react` schema supports an `actions` key where you define what operations AI can trigger:
  80. ```typescript
  81. import { defineCatalog } from '@json-render/core';
  82. import { schema } from '@json-render/react';
  83. import { z } from 'zod';
  84. const catalog = defineCatalog(schema, {
  85. components: { /* ... */ },
  86. actions: {
  87. submit_form: {
  88. params: z.object({
  89. formId: z.string(),
  90. }),
  91. description: 'Submit a form',
  92. },
  93. export_data: {
  94. params: z.object({
  95. format: z.enum(['csv', 'pdf', 'json']),
  96. }),
  97. },
  98. navigate: {
  99. params: z.object({
  100. url: z.string(),
  101. }),
  102. },
  103. },
  104. });
  105. ```
  106. Action handlers receive `(params, setState, state)` and are defined inside `defineRegistry`:
  107. ```tsx
  108. export const { handlers, executeAction } = defineRegistry(catalog, {
  109. actions: {
  110. submit_form: async (params, setState) => {
  111. const response = await fetch('/api/submit', {
  112. method: 'POST',
  113. body: JSON.stringify({ formId: params.formId }),
  114. });
  115. const result = await response.json();
  116. setState((prev) => ({ ...prev, formResult: result }));
  117. },
  118. export_data: async (params) => {
  119. const blob = await generateExport(params.format);
  120. downloadBlob(blob, `export.${params.format}`);
  121. },
  122. navigate: (params) => {
  123. window.location.href = params.url;
  124. },
  125. },
  126. });
  127. ```
  128. ### Data Binding
  129. Most data binding is handled automatically by the renderer — `$state`, `$item`, and `$index` expressions in props are resolved before your component receives them. See the [Data Binding](/docs/data-binding) guide for the full reference.
  130. For two-way binding (form inputs), use `{ "$bindState": "/path" }` on the natural value prop (or `{ "$bindItem": "field" }` inside repeat scopes). The renderer provides a `bindings` map with the state path for each bound prop. Use `useBoundProp` to get `[value, setValue]`:
  131. ```tsx
  132. import { useBoundProp } from '@json-render/react';
  133. // Inside defineRegistry components:
  134. Input: ({ props, bindings }) => {
  135. const [value, setValue] = useBoundProp<string>(
  136. props.value,
  137. bindings?.value
  138. );
  139. return (
  140. <input
  141. value={value ?? ''}
  142. onChange={(e) => setValue(e.target.value)}
  143. placeholder={props.placeholder}
  144. />
  145. );
  146. },
  147. ```
  148. For read-only state access (e.g. displaying a value from state), use `$state` expressions in props — they are resolved before the component receives them. For custom logic, use `useStateStore` and `getByPath` from `@json-render/core`.
  149. ### Using the Renderer
  150. Wire everything together with providers and the `<Renderer />` component:
  151. ```tsx
  152. import { useMemo, useRef } from 'react';
  153. import {
  154. Renderer,
  155. StateProvider,
  156. VisibilityProvider,
  157. ActionProvider,
  158. } from '@json-render/react';
  159. import { registry, handlers } from './registry';
  160. function App({ spec, state, setState }) {
  161. const stateRef = useRef(state);
  162. const setStateRef = useRef(setState);
  163. stateRef.current = state;
  164. setStateRef.current = setState;
  165. const actionHandlers = useMemo(
  166. () => handlers(() => setStateRef.current, () => stateRef.current),
  167. [],
  168. );
  169. return (
  170. <StateProvider initialState={state}>
  171. <VisibilityProvider>
  172. <ActionProvider handlers={actionHandlers}>
  173. <Renderer spec={spec} registry={registry} />
  174. </ActionProvider>
  175. </VisibilityProvider>
  176. </StateProvider>
  177. );
  178. }
  179. ```
  180. ## @json-render/react-native
  181. `@json-render/react-native` uses the same `defineRegistry` API. The only difference is that components return React Native elements instead of HTML:
  182. ```tsx
  183. import { defineRegistry } from '@json-render/react-native';
  184. import { View, Text, Pressable } from 'react-native';
  185. export const { registry } = defineRegistry(catalog, {
  186. components: {
  187. Card: ({ props, children }) => (
  188. <View style={styles.card}>
  189. <Text style={styles.title}>{props.title}</Text>
  190. {children}
  191. </View>
  192. ),
  193. Button: ({ props, emit }) => (
  194. <Pressable onPress={() => emit("press")}>
  195. <Text>{props.label}</Text>
  196. </Pressable>
  197. ),
  198. },
  199. });
  200. ```
  201. See the [@json-render/react-native API reference](/docs/api/react-native) for the full API.
  202. ## @json-render/remotion
  203. `@json-render/remotion` takes a different approach. Instead of `defineRegistry`, it uses a plain component registry with built-in standard components for video production:
  204. ```tsx
  205. import { Renderer, standardComponents } from '@json-render/remotion';
  206. // Use the standard components directly
  207. <Renderer spec={timelineSpec} components={standardComponents} />
  208. // Or extend with your own
  209. const components = {
  210. ...standardComponents,
  211. CustomSlide: ({ clip }) => <AbsoluteFill>{/* ... */}</AbsoluteFill>,
  212. };
  213. ```
  214. The Remotion schema also supports `transitions` and `effects` in the catalog rather than actions.
  215. See the [@json-render/remotion API reference](/docs/api/remotion) for the full API.
  216. ## Next
  217. Learn about [data binding](/docs/data-binding) for dynamic values.