@xmachines/json-render-react 0.19.0-xm.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +543 -0
- package/dist/chunk-WYDS23XB.mjs +87 -0
- package/dist/chunk-WYDS23XB.mjs.map +1 -0
- package/dist/index.d.mts +762 -0
- package/dist/index.d.ts +762 -0
- package/dist/index.js +1916 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1832 -0
- package/dist/index.mjs.map +1 -0
- package/dist/schema.d.mts +102 -0
- package/dist/schema.d.ts +102 -0
- package/dist/schema.js +112 -0
- package/dist/schema.js.map +1 -0
- package/dist/schema.mjs +9 -0
- package/dist/schema.mjs.map +1 -0
- package/package.json +66 -0
package/README.md
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
# @xmachines/json-render-react
|
|
2
|
+
|
|
3
|
+
React renderer for json-render. Turn JSON specs into React components with data binding, visibility, and actions.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @xmachines/json-render-react @xmachines/json-render-core zod
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
### 1. Create a Catalog
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { defineCatalog } from "@xmachines/json-render-core";
|
|
17
|
+
import { schema } from "@xmachines/json-render-react/schema";
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
|
|
20
|
+
export const catalog = defineCatalog(schema, {
|
|
21
|
+
components: {
|
|
22
|
+
Card: {
|
|
23
|
+
props: z.object({
|
|
24
|
+
title: z.string(),
|
|
25
|
+
description: z.string().nullable(),
|
|
26
|
+
}),
|
|
27
|
+
description: "A card container",
|
|
28
|
+
},
|
|
29
|
+
Button: {
|
|
30
|
+
props: z.object({
|
|
31
|
+
label: z.string(),
|
|
32
|
+
action: z.string(),
|
|
33
|
+
}),
|
|
34
|
+
description: "A clickable button",
|
|
35
|
+
},
|
|
36
|
+
Input: {
|
|
37
|
+
props: z.object({
|
|
38
|
+
value: z.union([z.string(), z.record(z.unknown())]).nullable(),
|
|
39
|
+
label: z.string(),
|
|
40
|
+
placeholder: z.string().nullable(),
|
|
41
|
+
}),
|
|
42
|
+
description: "Text input field with optional value binding",
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
actions: {
|
|
46
|
+
submit: { description: "Submit the form" },
|
|
47
|
+
cancel: { description: "Cancel and close" },
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### 2. Define Component Implementations
|
|
53
|
+
|
|
54
|
+
`defineRegistry` conditionally requires the `actions` field only when the catalog declares actions. Catalogs with `actions: {}` can omit it entirely.
|
|
55
|
+
|
|
56
|
+
```tsx
|
|
57
|
+
import { defineRegistry, useBoundProp } from "@xmachines/json-render-react";
|
|
58
|
+
import { catalog } from "./catalog";
|
|
59
|
+
|
|
60
|
+
export const { registry } = defineRegistry(catalog, {
|
|
61
|
+
components: {
|
|
62
|
+
Card: ({ props, children }) => (
|
|
63
|
+
<div className="card">
|
|
64
|
+
<h3>{props.title}</h3>
|
|
65
|
+
{props.description && <p>{props.description}</p>}
|
|
66
|
+
{children}
|
|
67
|
+
</div>
|
|
68
|
+
),
|
|
69
|
+
Button: ({ props, emit }) => (
|
|
70
|
+
<button onClick={() => emit("press")}>
|
|
71
|
+
{props.label}
|
|
72
|
+
</button>
|
|
73
|
+
),
|
|
74
|
+
Input: ({ props, bindings }) => {
|
|
75
|
+
const [value, setValue] = useBoundProp(props.value, bindings?.value);
|
|
76
|
+
return (
|
|
77
|
+
<label>
|
|
78
|
+
{props.label}
|
|
79
|
+
<input
|
|
80
|
+
placeholder={props.placeholder ?? ""}
|
|
81
|
+
value={value ?? ""}
|
|
82
|
+
onChange={(e) => setValue(e.target.value)}
|
|
83
|
+
/>
|
|
84
|
+
</label>
|
|
85
|
+
);
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### 3. Render Specs
|
|
92
|
+
|
|
93
|
+
```tsx
|
|
94
|
+
import { Renderer, StateProvider, ActionProvider } from "@xmachines/json-render-react";
|
|
95
|
+
import { registry } from "./registry";
|
|
96
|
+
|
|
97
|
+
function App({ spec }) {
|
|
98
|
+
return (
|
|
99
|
+
<StateProvider initialState={{ form: { name: "" } }}>
|
|
100
|
+
<ActionProvider handlers={{
|
|
101
|
+
submit: () => console.log("Submit"),
|
|
102
|
+
}}>
|
|
103
|
+
<Renderer spec={spec} registry={registry} />
|
|
104
|
+
</ActionProvider>
|
|
105
|
+
</StateProvider>
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Spec Format
|
|
111
|
+
|
|
112
|
+
The React renderer uses a flat element map format:
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
interface Spec {
|
|
116
|
+
root: string; // Key of the root element
|
|
117
|
+
elements: Record<string, UIElement>; // Flat map of elements by key
|
|
118
|
+
state?: Record<string, unknown>; // Optional initial state
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface UIElement {
|
|
122
|
+
type: string; // Component name from catalog
|
|
123
|
+
props: Record<string, unknown>; // Component props
|
|
124
|
+
children?: string[]; // Keys of child elements
|
|
125
|
+
visible?: VisibilityCondition; // Visibility condition
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Example spec:
|
|
130
|
+
|
|
131
|
+
```json
|
|
132
|
+
{
|
|
133
|
+
"root": "card-1",
|
|
134
|
+
"elements": {
|
|
135
|
+
"card-1": {
|
|
136
|
+
"type": "Card",
|
|
137
|
+
"props": { "title": "Welcome" },
|
|
138
|
+
"children": ["input-1", "btn-1"]
|
|
139
|
+
},
|
|
140
|
+
"input-1": {
|
|
141
|
+
"type": "Input",
|
|
142
|
+
"props": {
|
|
143
|
+
"value": { "$bindState": "/form/name" },
|
|
144
|
+
"label": "Name",
|
|
145
|
+
"placeholder": "Enter name"
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
"btn-1": {
|
|
149
|
+
"type": "Button",
|
|
150
|
+
"props": { "label": "Submit" },
|
|
151
|
+
"children": []
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Contexts
|
|
158
|
+
|
|
159
|
+
### StateProvider
|
|
160
|
+
|
|
161
|
+
Share data across components with JSON Pointer paths:
|
|
162
|
+
|
|
163
|
+
```tsx
|
|
164
|
+
<StateProvider initialState={{ user: { name: "John" } }}>
|
|
165
|
+
{children}
|
|
166
|
+
</StateProvider>
|
|
167
|
+
|
|
168
|
+
// In components:
|
|
169
|
+
const { state, get, set } = useStateStore();
|
|
170
|
+
const name = get("/user/name"); // "John"
|
|
171
|
+
set("/user/age", 25);
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
#### External Store (Controlled Mode)
|
|
175
|
+
|
|
176
|
+
For full control over state, pass a `StateStore` to bypass the internal state and wire json-render to any state management library (Redux, Zustand, XState, etc.):
|
|
177
|
+
|
|
178
|
+
```tsx
|
|
179
|
+
import { createStateStore, type StateStore } from "@xmachines/json-render-react";
|
|
180
|
+
|
|
181
|
+
// Option 1: Use the built-in store outside of React
|
|
182
|
+
const store = createStateStore({ count: 0 });
|
|
183
|
+
|
|
184
|
+
<StateProvider store={store}>
|
|
185
|
+
{children}
|
|
186
|
+
</StateProvider>
|
|
187
|
+
|
|
188
|
+
// Mutate from anywhere — React will re-render automatically:
|
|
189
|
+
store.set("/count", 1);
|
|
190
|
+
|
|
191
|
+
// Option 2: Implement the StateStore interface with your own backend
|
|
192
|
+
const zustandStore: StateStore = {
|
|
193
|
+
get: (path) => getByPath(useStore.getState(), path),
|
|
194
|
+
set: (path, value) => useStore.setState(prev => { /* ... */ }),
|
|
195
|
+
update: (updates) => useStore.setState(prev => { /* ... */ }),
|
|
196
|
+
getSnapshot: () => useStore.getState(),
|
|
197
|
+
subscribe: (listener) => useStore.subscribe(listener),
|
|
198
|
+
};
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
When `store` is provided, `initialState` and `onStateChange` are ignored. The store is the single source of truth. The same `store` prop is available on `createRenderer`, `JSONUIProvider`, and `StateProvider`.
|
|
202
|
+
|
|
203
|
+
### ActionProvider
|
|
204
|
+
|
|
205
|
+
Handle actions from components:
|
|
206
|
+
|
|
207
|
+
```tsx
|
|
208
|
+
<ActionProvider
|
|
209
|
+
handlers={{
|
|
210
|
+
submit: (params) => handleSubmit(params),
|
|
211
|
+
cancel: () => handleCancel(),
|
|
212
|
+
}}
|
|
213
|
+
>
|
|
214
|
+
{children}
|
|
215
|
+
</ActionProvider>
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### VisibilityProvider
|
|
219
|
+
|
|
220
|
+
Control element visibility based on data:
|
|
221
|
+
|
|
222
|
+
```tsx
|
|
223
|
+
<VisibilityProvider>
|
|
224
|
+
{children}
|
|
225
|
+
</VisibilityProvider>
|
|
226
|
+
|
|
227
|
+
// Elements can use visibility conditions:
|
|
228
|
+
{
|
|
229
|
+
"type": "Alert",
|
|
230
|
+
"props": { "message": "Error!" },
|
|
231
|
+
"visible": { "$state": "/form/hasError" }
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### ValidationProvider
|
|
236
|
+
|
|
237
|
+
Add field validation:
|
|
238
|
+
|
|
239
|
+
```tsx
|
|
240
|
+
<ValidationProvider>
|
|
241
|
+
{children}
|
|
242
|
+
</ValidationProvider>
|
|
243
|
+
|
|
244
|
+
// Use validation hooks:
|
|
245
|
+
const { errors, validate } = useFieldValidation("/form/email", {
|
|
246
|
+
checks: [
|
|
247
|
+
{ type: "required", message: "Email required" },
|
|
248
|
+
{ type: "email", message: "Invalid email" },
|
|
249
|
+
],
|
|
250
|
+
});
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
## Hooks
|
|
254
|
+
|
|
255
|
+
| Hook | Purpose |
|
|
256
|
+
|------|---------|
|
|
257
|
+
| `useStateStore()` | Access state context (`state`, `get`, `set`, `update`) |
|
|
258
|
+
| `useStateValue(path)` | Get single value from state |
|
|
259
|
+
| `useStateBinding(path)` | Two-way data binding (returns `[value, setValue]`) |
|
|
260
|
+
| `useIsVisible(condition)` | Check if a visibility condition is met |
|
|
261
|
+
| `useActions()` | Access action context |
|
|
262
|
+
| `useAction(name)` | Get a single action dispatch function |
|
|
263
|
+
| `useFieldValidation(path, config)` | Field validation state |
|
|
264
|
+
| `useOptionalValidation()` | Non-throwing validation context (returns `null` if no provider) |
|
|
265
|
+
| `useUIStream(options)` | Stream specs from an API endpoint |
|
|
266
|
+
|
|
267
|
+
## Visibility Conditions
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
// Truthiness check
|
|
271
|
+
{ "$state": "/user/isAdmin" }
|
|
272
|
+
|
|
273
|
+
// Auth state (use state path)
|
|
274
|
+
{ "$state": "/auth/isSignedIn" }
|
|
275
|
+
|
|
276
|
+
// Comparisons (flat style)
|
|
277
|
+
{ "$state": "/status", "eq": "active" }
|
|
278
|
+
{ "$state": "/count", "gt": 10 }
|
|
279
|
+
|
|
280
|
+
// Negation
|
|
281
|
+
{ "$state": "/maintenance", "not": true }
|
|
282
|
+
|
|
283
|
+
// Multiple conditions (implicit AND)
|
|
284
|
+
[
|
|
285
|
+
{ "$state": "/feature/enabled" },
|
|
286
|
+
{ "$state": "/maintenance", "not": true }
|
|
287
|
+
]
|
|
288
|
+
|
|
289
|
+
// Always / never
|
|
290
|
+
true // always visible
|
|
291
|
+
false // never visible
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
TypeScript helpers from `@xmachines/json-render-core`:
|
|
295
|
+
|
|
296
|
+
```typescript
|
|
297
|
+
import { visibility } from "@xmachines/json-render-core";
|
|
298
|
+
|
|
299
|
+
visibility.when("/path") // { $state: "/path" }
|
|
300
|
+
visibility.unless("/path") // { $state: "/path", not: true }
|
|
301
|
+
visibility.eq("/path", val) // { $state: "/path", eq: val }
|
|
302
|
+
visibility.neq("/path", val) // { $state: "/path", neq: val }
|
|
303
|
+
visibility.and(cond1, cond2) // { $and: [cond1, cond2] }
|
|
304
|
+
visibility.always // true
|
|
305
|
+
visibility.never // false
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
## Dynamic Prop Expressions
|
|
309
|
+
|
|
310
|
+
Any prop value can use data-driven expressions that resolve at render time. The renderer resolves these transparently before passing props to components.
|
|
311
|
+
|
|
312
|
+
```json
|
|
313
|
+
{
|
|
314
|
+
"type": "Badge",
|
|
315
|
+
"props": {
|
|
316
|
+
"label": { "$state": "/user/role" },
|
|
317
|
+
"color": {
|
|
318
|
+
"$cond": { "$state": "/user/role", "eq": "admin" },
|
|
319
|
+
"$then": "red",
|
|
320
|
+
"$else": "gray"
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
For two-way binding, use `{ "$bindState": "/path" }` on the natural value prop (e.g. `value`, `checked`, `pressed`). Inside repeat scopes, use `{ "$bindItem": "field" }` instead. Components receive resolved `bindings` with the state path for each bound prop; use `useBoundProp(props.value, bindings?.value)` to get `[value, setValue]`.
|
|
327
|
+
|
|
328
|
+
### `$template` and `$computed`
|
|
329
|
+
|
|
330
|
+
```json
|
|
331
|
+
{
|
|
332
|
+
"label": { "$template": "Hello, ${/user/name}!" },
|
|
333
|
+
"fullName": {
|
|
334
|
+
"$computed": "fullName",
|
|
335
|
+
"args": {
|
|
336
|
+
"first": { "$state": "/form/firstName" },
|
|
337
|
+
"last": { "$state": "/form/lastName" }
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
Register functions via the `functions` prop on `JSONUIProvider` or `createRenderer`:
|
|
344
|
+
|
|
345
|
+
```tsx
|
|
346
|
+
<JSONUIProvider
|
|
347
|
+
spec={spec}
|
|
348
|
+
catalog={catalog}
|
|
349
|
+
functions={{ fullName: (args) => `${args.first} ${args.last}` }}
|
|
350
|
+
>
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
See [@xmachines/json-render-core](../core/README.md) for full expression syntax.
|
|
354
|
+
|
|
355
|
+
## State Watchers
|
|
356
|
+
|
|
357
|
+
Elements can declare a `watch` field to trigger actions when state values change:
|
|
358
|
+
|
|
359
|
+
```json
|
|
360
|
+
{
|
|
361
|
+
"type": "Select",
|
|
362
|
+
"props": {
|
|
363
|
+
"label": "Country",
|
|
364
|
+
"value": { "$bindState": "/form/country" },
|
|
365
|
+
"options": ["US", "Canada", "UK"]
|
|
366
|
+
},
|
|
367
|
+
"watch": {
|
|
368
|
+
"/form/country": {
|
|
369
|
+
"action": "loadCities",
|
|
370
|
+
"params": { "country": { "$state": "/form/country" } }
|
|
371
|
+
}
|
|
372
|
+
},
|
|
373
|
+
"children": []
|
|
374
|
+
}
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
`watch` is a top-level field on elements (sibling of `type`/`props`/`children`), not inside `props`. Watchers only fire on value changes, not on initial render.
|
|
378
|
+
|
|
379
|
+
## Built-in Actions
|
|
380
|
+
|
|
381
|
+
The `setState`, `pushState`, `removeState`, and `validateForm` actions are built into the React schema and handled automatically by `ActionProvider`. They are injected into AI prompts without needing to be declared in your catalog's `actions`:
|
|
382
|
+
|
|
383
|
+
```json
|
|
384
|
+
{
|
|
385
|
+
"type": "Button",
|
|
386
|
+
"props": { "label": "Switch Tab" },
|
|
387
|
+
"on": {
|
|
388
|
+
"press": {
|
|
389
|
+
"action": "setState",
|
|
390
|
+
"params": { "statePath": "/activeTab", "value": "settings" }
|
|
391
|
+
}
|
|
392
|
+
},
|
|
393
|
+
"children": []
|
|
394
|
+
}
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
### `validateForm`
|
|
398
|
+
|
|
399
|
+
Validate all registered form fields at once and write the result to state:
|
|
400
|
+
|
|
401
|
+
```json
|
|
402
|
+
{
|
|
403
|
+
"type": "Button",
|
|
404
|
+
"props": { "label": "Submit" },
|
|
405
|
+
"on": {
|
|
406
|
+
"press": [
|
|
407
|
+
{ "action": "validateForm", "params": { "statePath": "/formResult" } },
|
|
408
|
+
{ "action": "submitForm" }
|
|
409
|
+
]
|
|
410
|
+
},
|
|
411
|
+
"children": []
|
|
412
|
+
}
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
Writes `{ valid: boolean, errors: Record<string, string[]> }` to the specified state path (defaults to `/formValidation`).
|
|
416
|
+
|
|
417
|
+
## Component Props
|
|
418
|
+
|
|
419
|
+
When using `defineRegistry`, components receive these props:
|
|
420
|
+
|
|
421
|
+
```typescript
|
|
422
|
+
interface ComponentContext<P> {
|
|
423
|
+
props: P; // Typed props from the catalog (expressions resolved)
|
|
424
|
+
children?: React.ReactNode; // Rendered children
|
|
425
|
+
emit: (event: string) => void; // Emit a named event (always defined)
|
|
426
|
+
on: (event: string) => EventHandle; // Get event handle with metadata
|
|
427
|
+
loading?: boolean; // Whether the parent is loading
|
|
428
|
+
bindings?: Record<string, string>; // State paths for $bindState/$bindItem expressions (e.g. bindings.value)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
interface EventHandle {
|
|
432
|
+
emit: () => void; // Fire the event
|
|
433
|
+
shouldPreventDefault: boolean; // Whether any binding requested preventDefault
|
|
434
|
+
bound: boolean; // Whether any handler is bound
|
|
435
|
+
}
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
Use `emit("press")` for simple event firing. Use `on("click")` when you need to check metadata like `shouldPreventDefault` or `bound`:
|
|
439
|
+
|
|
440
|
+
```tsx
|
|
441
|
+
Link: ({ props, on }) => {
|
|
442
|
+
const click = on("click");
|
|
443
|
+
return (
|
|
444
|
+
<a
|
|
445
|
+
href={props.href}
|
|
446
|
+
onClick={(e) => {
|
|
447
|
+
if (click.shouldPreventDefault) e.preventDefault();
|
|
448
|
+
click.emit();
|
|
449
|
+
}}
|
|
450
|
+
>
|
|
451
|
+
{props.label}
|
|
452
|
+
</a>
|
|
453
|
+
);
|
|
454
|
+
},
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
Use `bindings?.value`, `bindings?.checked`, etc. with `useBoundProp()` for two-way bound form components.
|
|
458
|
+
|
|
459
|
+
### `BaseComponentProps`
|
|
460
|
+
|
|
461
|
+
For building reusable component libraries that are not tied to a specific catalog (e.g. `@xmachines/json-render-shadcn`), use the catalog-agnostic `BaseComponentProps` type:
|
|
462
|
+
|
|
463
|
+
```typescript
|
|
464
|
+
import type { BaseComponentProps } from "@xmachines/json-render-react";
|
|
465
|
+
|
|
466
|
+
const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) => (
|
|
467
|
+
<div>{props.title}{children}</div>
|
|
468
|
+
);
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
## Generate AI Prompts
|
|
472
|
+
|
|
473
|
+
```typescript
|
|
474
|
+
const systemPrompt = catalog.prompt();
|
|
475
|
+
// Returns detailed prompt with component/action descriptions
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
## Full Example
|
|
479
|
+
|
|
480
|
+
```tsx
|
|
481
|
+
import { defineCatalog } from "@xmachines/json-render-core";
|
|
482
|
+
import { schema } from "@xmachines/json-render-react/schema";
|
|
483
|
+
import { defineRegistry, Renderer } from "@xmachines/json-render-react";
|
|
484
|
+
import { z } from "zod";
|
|
485
|
+
|
|
486
|
+
const catalog = defineCatalog(schema, {
|
|
487
|
+
components: {
|
|
488
|
+
Greeting: {
|
|
489
|
+
props: z.object({ name: z.string() }),
|
|
490
|
+
description: "Displays a greeting",
|
|
491
|
+
},
|
|
492
|
+
},
|
|
493
|
+
actions: {},
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
const { registry } = defineRegistry(catalog, {
|
|
497
|
+
components: {
|
|
498
|
+
Greeting: ({ props }) => <h1>Hello, {props.name}!</h1>,
|
|
499
|
+
},
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
const spec = {
|
|
503
|
+
root: "greeting-1",
|
|
504
|
+
elements: {
|
|
505
|
+
"greeting-1": {
|
|
506
|
+
type: "Greeting",
|
|
507
|
+
props: { name: "World" },
|
|
508
|
+
children: [],
|
|
509
|
+
},
|
|
510
|
+
},
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
function App() {
|
|
514
|
+
return <Renderer spec={spec} registry={registry} />;
|
|
515
|
+
}
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
## Key Exports
|
|
519
|
+
|
|
520
|
+
| Export | Purpose |
|
|
521
|
+
|--------|---------|
|
|
522
|
+
| `defineRegistry` | Create a type-safe component registry from a catalog |
|
|
523
|
+
| `Renderer` | Render a spec using a registry |
|
|
524
|
+
| `schema` | Element tree schema (includes built-in actions: `setState`, `pushState`, `removeState`, `validateForm`) |
|
|
525
|
+
| `useStateStore` | Access state context |
|
|
526
|
+
| `useStateValue` | Get single value from state |
|
|
527
|
+
| `useBoundProp` | Two-way binding for `$bindState`/`$bindItem` expressions |
|
|
528
|
+
| `useActions` | Access actions context |
|
|
529
|
+
| `useAction` | Get a single action dispatch function |
|
|
530
|
+
| `useUIStream` | Stream specs from an API endpoint |
|
|
531
|
+
| `createStateStore` | Create a framework-agnostic in-memory `StateStore` |
|
|
532
|
+
|
|
533
|
+
### Types
|
|
534
|
+
|
|
535
|
+
| Export | Purpose |
|
|
536
|
+
|--------|---------|
|
|
537
|
+
| `ComponentContext` | Typed component render function context (catalog-aware) |
|
|
538
|
+
| `BaseComponentProps` | Catalog-agnostic base type for reusable component libraries |
|
|
539
|
+
| `EventHandle` | Event handle with `emit()`, `shouldPreventDefault`, `bound` |
|
|
540
|
+
| `ComponentFn` | Component render function type |
|
|
541
|
+
| `SetState` | State setter type |
|
|
542
|
+
| `StateModel` | State model type |
|
|
543
|
+
| `StateStore` | Interface for plugging in external state management |
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// src/schema.ts
|
|
2
|
+
import { defineSchema } from "@xmachines/json-render-core";
|
|
3
|
+
var schema = defineSchema(
|
|
4
|
+
(s) => ({
|
|
5
|
+
// What the AI-generated SPEC looks like
|
|
6
|
+
spec: s.object({
|
|
7
|
+
/** Root element key */
|
|
8
|
+
root: s.string(),
|
|
9
|
+
/** Flat map of elements by key */
|
|
10
|
+
elements: s.record(
|
|
11
|
+
s.object({
|
|
12
|
+
/** Component type from catalog */
|
|
13
|
+
type: s.ref("catalog.components"),
|
|
14
|
+
/** Component props */
|
|
15
|
+
props: s.propsOf("catalog.components"),
|
|
16
|
+
/** Child element keys (flat reference) */
|
|
17
|
+
children: s.array(s.string()),
|
|
18
|
+
/** Visibility condition */
|
|
19
|
+
visible: s.any()
|
|
20
|
+
})
|
|
21
|
+
)
|
|
22
|
+
}),
|
|
23
|
+
// What the CATALOG must provide
|
|
24
|
+
catalog: s.object({
|
|
25
|
+
/** Component definitions */
|
|
26
|
+
components: s.map({
|
|
27
|
+
/** Zod schema for component props */
|
|
28
|
+
props: s.zod(),
|
|
29
|
+
/** Slots for this component. Use ['default'] for children, or named slots like ['header', 'footer'] */
|
|
30
|
+
slots: s.array(s.string()),
|
|
31
|
+
/** Description for AI generation hints */
|
|
32
|
+
description: s.string(),
|
|
33
|
+
/** Example prop values used in prompt examples (auto-generated from Zod schema if omitted) */
|
|
34
|
+
example: s.any()
|
|
35
|
+
}),
|
|
36
|
+
/** Action definitions (optional) */
|
|
37
|
+
actions: s.map({
|
|
38
|
+
/** Zod schema for action params */
|
|
39
|
+
params: s.zod(),
|
|
40
|
+
/** Description for AI generation hints */
|
|
41
|
+
description: s.string()
|
|
42
|
+
})
|
|
43
|
+
})
|
|
44
|
+
}),
|
|
45
|
+
{
|
|
46
|
+
builtInActions: [
|
|
47
|
+
{
|
|
48
|
+
name: "setState",
|
|
49
|
+
description: "Update a value in the state model at the given statePath. Params: { statePath: string, value: any }"
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: "pushState",
|
|
53
|
+
description: 'Append an item to an array in state. Params: { statePath: string, value: any, clearStatePath?: string }. Value can contain {"$state":"/path"} refs and "$id" for auto IDs.'
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: "removeState",
|
|
57
|
+
description: "Remove an item from an array in state by index. Params: { statePath: string, index: number }"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
name: "validateForm",
|
|
61
|
+
description: "Validate all registered form fields and write the result to state. Params: { statePath?: string }. Defaults to /formValidation. Result: { valid: boolean, errors: Record<string, string[]> }."
|
|
62
|
+
}
|
|
63
|
+
],
|
|
64
|
+
defaultRules: [
|
|
65
|
+
// Element integrity
|
|
66
|
+
"CRITICAL INTEGRITY CHECK: Before outputting ANY element that references children, you MUST have already output (or will output) each child as its own element. If an element has children: ['a', 'b'], then elements 'a' and 'b' MUST exist. A missing child element causes that entire branch of the UI to be invisible.",
|
|
67
|
+
"SELF-CHECK: After generating all elements, mentally walk the tree from root. Every key in every children array must resolve to a defined element. If you find a gap, output the missing element immediately.",
|
|
68
|
+
// Field placement
|
|
69
|
+
'CRITICAL: The "visible" field goes on the ELEMENT object, NOT inside "props". Correct: {"type":"<ComponentName>","props":{},"visible":{"$state":"/tab","eq":"home"},"children":[...]}.',
|
|
70
|
+
'CRITICAL: The "on" field goes on the ELEMENT object, NOT inside "props". Use on.press, on.change, on.submit etc. NEVER put action/actionParams inside props.',
|
|
71
|
+
// State and data
|
|
72
|
+
"When the user asks for a UI that displays data (e.g. blog posts, products, users), ALWAYS include a state field with realistic sample data. The state field is a top-level field on the spec (sibling of root/elements).",
|
|
73
|
+
'When building repeating content backed by a state array (e.g. posts, products, items), use the "repeat" field on a container element. Example: { "type": "<ContainerComponent>", "props": {}, "repeat": { "statePath": "/posts", "key": "id" }, "children": ["post-card"] }. Replace <ContainerComponent> with an appropriate component from the AVAILABLE COMPONENTS list. Inside repeated children, use { "$item": "field" } to read a field from the current item, and { "$index": true } for the current array index. For two-way binding to an item field use { "$bindItem": "completed" }. Do NOT hardcode individual elements for each array item.',
|
|
74
|
+
// Design quality
|
|
75
|
+
"Design with visual hierarchy: use container components to group content, heading components for section titles, proper spacing, and status indicators. ONLY use components from the AVAILABLE COMPONENTS list.",
|
|
76
|
+
"For data-rich UIs, use multi-column layout components if available. For forms and single-column content, use vertical layout components. ONLY use components from the AVAILABLE COMPONENTS list.",
|
|
77
|
+
"Always include realistic, professional-looking sample data. For blogs include 3-4 posts with varied titles, authors, dates, categories. For products include names, prices, images. Never leave data empty."
|
|
78
|
+
]
|
|
79
|
+
}
|
|
80
|
+
);
|
|
81
|
+
var elementTreeSchema = schema;
|
|
82
|
+
|
|
83
|
+
export {
|
|
84
|
+
schema,
|
|
85
|
+
elementTreeSchema
|
|
86
|
+
};
|
|
87
|
+
//# sourceMappingURL=chunk-WYDS23XB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts"],"sourcesContent":["import { defineSchema } from \"@xmachines/json-render-core\";\n\n/**\n * The schema for @xmachines/json-render-react\n *\n * Defines:\n * - Spec: A flat tree of elements with keys, types, props, and children references\n * - Catalog: Components with props schemas, and optional actions\n */\nexport const schema = defineSchema(\n (s) => ({\n // What the AI-generated SPEC looks like\n spec: s.object({\n /** Root element key */\n root: s.string(),\n /** Flat map of elements by key */\n elements: s.record(\n s.object({\n /** Component type from catalog */\n type: s.ref(\"catalog.components\"),\n /** Component props */\n props: s.propsOf(\"catalog.components\"),\n /** Child element keys (flat reference) */\n children: s.array(s.string()),\n /** Visibility condition */\n visible: s.any(),\n }),\n ),\n }),\n\n // What the CATALOG must provide\n catalog: s.object({\n /** Component definitions */\n components: s.map({\n /** Zod schema for component props */\n props: s.zod(),\n /** Slots for this component. Use ['default'] for children, or named slots like ['header', 'footer'] */\n slots: s.array(s.string()),\n /** Description for AI generation hints */\n description: s.string(),\n /** Example prop values used in prompt examples (auto-generated from Zod schema if omitted) */\n example: s.any(),\n }),\n /** Action definitions (optional) */\n actions: s.map({\n /** Zod schema for action params */\n params: s.zod(),\n /** Description for AI generation hints */\n description: s.string(),\n }),\n }),\n }),\n {\n builtInActions: [\n {\n name: \"setState\",\n description:\n \"Update a value in the state model at the given statePath. Params: { statePath: string, value: any }\",\n },\n {\n name: \"pushState\",\n description:\n 'Append an item to an array in state. Params: { statePath: string, value: any, clearStatePath?: string }. Value can contain {\"$state\":\"/path\"} refs and \"$id\" for auto IDs.',\n },\n {\n name: \"removeState\",\n description:\n \"Remove an item from an array in state by index. Params: { statePath: string, index: number }\",\n },\n {\n name: \"validateForm\",\n description:\n \"Validate all registered form fields and write the result to state. Params: { statePath?: string }. Defaults to /formValidation. Result: { valid: boolean, errors: Record<string, string[]> }.\",\n },\n ],\n defaultRules: [\n // Element integrity\n \"CRITICAL INTEGRITY CHECK: Before outputting ANY element that references children, you MUST have already output (or will output) each child as its own element. If an element has children: ['a', 'b'], then elements 'a' and 'b' MUST exist. A missing child element causes that entire branch of the UI to be invisible.\",\n \"SELF-CHECK: After generating all elements, mentally walk the tree from root. Every key in every children array must resolve to a defined element. If you find a gap, output the missing element immediately.\",\n\n // Field placement\n 'CRITICAL: The \"visible\" field goes on the ELEMENT object, NOT inside \"props\". Correct: {\"type\":\"<ComponentName>\",\"props\":{},\"visible\":{\"$state\":\"/tab\",\"eq\":\"home\"},\"children\":[...]}.',\n 'CRITICAL: The \"on\" field goes on the ELEMENT object, NOT inside \"props\". Use on.press, on.change, on.submit etc. NEVER put action/actionParams inside props.',\n\n // State and data\n \"When the user asks for a UI that displays data (e.g. blog posts, products, users), ALWAYS include a state field with realistic sample data. The state field is a top-level field on the spec (sibling of root/elements).\",\n 'When building repeating content backed by a state array (e.g. posts, products, items), use the \"repeat\" field on a container element. Example: { \"type\": \"<ContainerComponent>\", \"props\": {}, \"repeat\": { \"statePath\": \"/posts\", \"key\": \"id\" }, \"children\": [\"post-card\"] }. Replace <ContainerComponent> with an appropriate component from the AVAILABLE COMPONENTS list. Inside repeated children, use { \"$item\": \"field\" } to read a field from the current item, and { \"$index\": true } for the current array index. For two-way binding to an item field use { \"$bindItem\": \"completed\" }. Do NOT hardcode individual elements for each array item.',\n\n // Design quality\n \"Design with visual hierarchy: use container components to group content, heading components for section titles, proper spacing, and status indicators. ONLY use components from the AVAILABLE COMPONENTS list.\",\n \"For data-rich UIs, use multi-column layout components if available. For forms and single-column content, use vertical layout components. ONLY use components from the AVAILABLE COMPONENTS list.\",\n \"Always include realistic, professional-looking sample data. For blogs include 3-4 posts with varied titles, authors, dates, categories. For products include names, prices, images. Never leave data empty.\",\n ],\n },\n);\n\n/**\n * Type for the React schema\n */\nexport type ReactSchema = typeof schema;\n\n/**\n * Infer the spec type from a catalog\n */\nexport type ReactSpec<TCatalog> = typeof schema extends {\n createCatalog: (catalog: TCatalog) => { _specType: infer S };\n}\n ? S\n : never;\n\n// Backward compatibility aliases\n/** @deprecated Use `schema` instead */\nexport const elementTreeSchema = schema;\n/** @deprecated Use `ReactSchema` instead */\nexport type ElementTreeSchema = ReactSchema;\n/** @deprecated Use `ReactSpec` instead */\nexport type ElementTreeSpec<T> = ReactSpec<T>;\n"],"mappings":";AAAA,SAAS,oBAAoB;AAStB,IAAM,SAAS;AAAA,EACpB,CAAC,OAAO;AAAA;AAAA,IAEN,MAAM,EAAE,OAAO;AAAA;AAAA,MAEb,MAAM,EAAE,OAAO;AAAA;AAAA,MAEf,UAAU,EAAE;AAAA,QACV,EAAE,OAAO;AAAA;AAAA,UAEP,MAAM,EAAE,IAAI,oBAAoB;AAAA;AAAA,UAEhC,OAAO,EAAE,QAAQ,oBAAoB;AAAA;AAAA,UAErC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA;AAAA,UAE5B,SAAS,EAAE,IAAI;AAAA,QACjB,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA;AAAA,IAGD,SAAS,EAAE,OAAO;AAAA;AAAA,MAEhB,YAAY,EAAE,IAAI;AAAA;AAAA,QAEhB,OAAO,EAAE,IAAI;AAAA;AAAA,QAEb,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA;AAAA,QAEzB,aAAa,EAAE,OAAO;AAAA;AAAA,QAEtB,SAAS,EAAE,IAAI;AAAA,MACjB,CAAC;AAAA;AAAA,MAED,SAAS,EAAE,IAAI;AAAA;AAAA,QAEb,QAAQ,EAAE,IAAI;AAAA;AAAA,QAEd,aAAa,EAAE,OAAO;AAAA,MACxB,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AAAA,EACA;AAAA,IACE,gBAAgB;AAAA,MACd;AAAA,QACE,MAAM;AAAA,QACN,aACE;AAAA,MACJ;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,aACE;AAAA,MACJ;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,aACE;AAAA,MACJ;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,aACE;AAAA,MACJ;AAAA,IACF;AAAA,IACA,cAAc;AAAA;AAAA,MAEZ;AAAA,MACA;AAAA;AAAA,MAGA;AAAA,MACA;AAAA;AAAA,MAGA;AAAA,MACA;AAAA;AAAA,MAGA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAkBO,IAAM,oBAAoB;","names":[]}
|