page.mdx 9.2 KB

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