mirror of
https://github.com/vercel-labs/json-render.git
synced 2026-10-03 20:38:21 +08:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f34f0713ae | ||
|
|
9d3dfc8917 |
@@ -650,7 +650,7 @@ interface UIElement {
|
||||
children?: string[]; // Keys of child elements
|
||||
visible?: VisibilityCondition;
|
||||
on?: Record<string, ActionBinding | ActionBinding[]>; // Event bindings
|
||||
repeat?: { statePath: string; key?: string }; // Repeat for arrays
|
||||
repeat?: { statePath: string | { $item: string }; key?: string }; // Repeat for arrays
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ The `repeat` field on an element renders its children once per item in a state a
|
||||
}
|
||||
```
|
||||
|
||||
- `repeat.statePath` — JSON Pointer to the state array
|
||||
- `repeat.statePath`: root JSON Pointer to the state array, or `{ "$item": "field" }` for an array on the enclosing repeat item
|
||||
- `repeat.key` — field name on each item to use as a stable key for rendering
|
||||
|
||||
Inside `todo-item`, `{ "$item": "title" }` reads the `title` field from whichever array item is currently being rendered. `{ "$index": true }` would return `0` for the first item, `1` for the second, and so on.
|
||||
|
||||
@@ -556,7 +556,7 @@ console.log(formatSpecIssues(issues));
|
||||
const { spec: fixed, fixes, fixDetails } = autoFixSpec(spec);
|
||||
```
|
||||
|
||||
`validateSpec` checks structure beyond the catalog schema: missing or dangling `children` references, malformed `visible` conditions (anything outside the documented forms evaluates to hidden at runtime, so it is rejected with code `invalid_visible`), `repeat` containers with no children (`repeat_without_children`), and `repeat.statePath` values that do not reference an array in the spec's own `state` (`repeat_state_mismatch`).
|
||||
`validateSpec` checks structure beyond the catalog schema: missing or dangling `children` references, malformed `visible` conditions (anything outside the documented forms evaluates to hidden at runtime, so it is rejected with code `invalid_visible`), `repeat` containers with no children (`repeat_without_children`), relative repeat paths outside an enclosing repeat (`repeat_item_outside_scope`), and `repeat.statePath` values that do not reference an array in the spec's own `state` (`repeat_state_mismatch`).
|
||||
|
||||
`autoFixSpec` distinguishes lossless fixes (relocating `visible`/`on`/`repeat`/`watch` out of `props`) from lossy ones (pruning `children` references to elements that were never defined). Each entry in `fixDetails` carries `{ message, lossy }`. Callers with a repair loop should apply lossless fixes immediately and prefer re-prompting over lossy fixes, passing `{ lossy: false }` to withhold pruning until retries are exhausted:
|
||||
|
||||
|
||||
@@ -4,8 +4,28 @@ import {
|
||||
executeAction,
|
||||
interpolateString,
|
||||
actionBinding,
|
||||
ActionOnSuccessSchema,
|
||||
ActionOnErrorSchema,
|
||||
} from "./actions";
|
||||
|
||||
describe("onSuccess/onError schemas", () => {
|
||||
it("keeps params on the onSuccess action form", () => {
|
||||
const parsed = ActionOnSuccessSchema.parse({
|
||||
action: "toast",
|
||||
params: { message: "Saved" },
|
||||
});
|
||||
expect(parsed).toEqual({ action: "toast", params: { message: "Saved" } });
|
||||
});
|
||||
|
||||
it("keeps params on the onError action form", () => {
|
||||
const parsed = ActionOnErrorSchema.parse({
|
||||
action: "toast",
|
||||
params: { message: "Failed" },
|
||||
});
|
||||
expect(parsed).toEqual({ action: "toast", params: { message: "Failed" } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("interpolateString", () => {
|
||||
it("interpolates ${path} expressions", () => {
|
||||
const data = { user: { name: "Alice" }, count: 5 };
|
||||
@@ -161,7 +181,27 @@ describe("executeAction", () => {
|
||||
executeAction: executeActionFn,
|
||||
});
|
||||
|
||||
expect(executeActionFn).toHaveBeenCalledWith("followUp");
|
||||
expect(executeActionFn).toHaveBeenCalledWith({ action: "followUp" });
|
||||
});
|
||||
|
||||
it("handles onSuccess with action and params", async () => {
|
||||
const executeActionFn = vi.fn();
|
||||
|
||||
await executeAction({
|
||||
action: {
|
||||
action: "save",
|
||||
params: {},
|
||||
onSuccess: { action: "toast", params: { message: "Saved" } },
|
||||
},
|
||||
handler: vi.fn().mockResolvedValue(undefined),
|
||||
setState: vi.fn(),
|
||||
executeAction: executeActionFn,
|
||||
});
|
||||
|
||||
expect(executeActionFn).toHaveBeenCalledWith({
|
||||
action: "toast",
|
||||
params: { message: "Saved" },
|
||||
});
|
||||
});
|
||||
|
||||
it("handles onError with set", async () => {
|
||||
@@ -196,7 +236,28 @@ describe("executeAction", () => {
|
||||
executeAction: executeActionFn,
|
||||
});
|
||||
|
||||
expect(executeActionFn).toHaveBeenCalledWith("handleError");
|
||||
expect(executeActionFn).toHaveBeenCalledWith({ action: "handleError" });
|
||||
});
|
||||
|
||||
it("handles onError with action and params", async () => {
|
||||
const executeActionFn = vi.fn();
|
||||
const error = new Error("Failed");
|
||||
|
||||
await executeAction({
|
||||
action: {
|
||||
action: "save",
|
||||
params: {},
|
||||
onError: { action: "toast", params: { message: "Save failed" } },
|
||||
},
|
||||
handler: vi.fn().mockRejectedValue(error),
|
||||
setState: vi.fn(),
|
||||
executeAction: executeActionFn,
|
||||
});
|
||||
|
||||
expect(executeActionFn).toHaveBeenCalledWith({
|
||||
action: "toast",
|
||||
params: { message: "Save failed" },
|
||||
});
|
||||
});
|
||||
|
||||
it("re-throws error when no onError handler", async () => {
|
||||
|
||||
@@ -19,14 +19,14 @@ export interface ActionConfirm {
|
||||
export type ActionOnSuccess =
|
||||
| { navigate: string }
|
||||
| { set: Record<string, unknown> }
|
||||
| { action: string };
|
||||
| { action: string; params?: Record<string, DynamicValue> };
|
||||
|
||||
/**
|
||||
* Action error handler
|
||||
*/
|
||||
export type ActionOnError =
|
||||
| { set: Record<string, unknown> }
|
||||
| { action: string };
|
||||
| { action: string; params?: Record<string, DynamicValue> };
|
||||
|
||||
/**
|
||||
* Action binding — maps an event to an action invocation.
|
||||
@@ -73,7 +73,10 @@ export const ActionConfirmSchema = z.object({
|
||||
export const ActionOnSuccessSchema = z.union([
|
||||
z.object({ navigate: z.string() }),
|
||||
z.object({ set: z.record(z.string(), z.unknown()) }),
|
||||
z.object({ action: z.string() }),
|
||||
z.object({
|
||||
action: z.string(),
|
||||
params: z.record(z.string(), DynamicValueSchema).optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -81,7 +84,10 @@ export const ActionOnSuccessSchema = z.union([
|
||||
*/
|
||||
export const ActionOnErrorSchema = z.union([
|
||||
z.object({ set: z.record(z.string(), z.unknown()) }),
|
||||
z.object({ action: z.string() }),
|
||||
z.object({
|
||||
action: z.string(),
|
||||
params: z.record(z.string(), DynamicValueSchema).optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -190,7 +196,7 @@ export interface ActionExecutionContext {
|
||||
/** Function to navigate */
|
||||
navigate?: (path: string) => void;
|
||||
/** Function to execute another action */
|
||||
executeAction?: (name: string) => Promise<void>;
|
||||
executeAction?: (binding: ActionBinding) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -213,7 +219,7 @@ export async function executeAction(
|
||||
setState(path, value);
|
||||
}
|
||||
} else if ("action" in action.onSuccess && executeAction) {
|
||||
await executeAction(action.onSuccess.action);
|
||||
await executeAction(action.onSuccess);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -229,7 +235,7 @@ export async function executeAction(
|
||||
setState(path, resolvedValue);
|
||||
}
|
||||
} else if ("action" in action.onError && executeAction) {
|
||||
await executeAction(action.onError.action);
|
||||
await executeAction(action.onError);
|
||||
}
|
||||
} else {
|
||||
throw error;
|
||||
|
||||
@@ -4,6 +4,7 @@ export type {
|
||||
DynamicString,
|
||||
DynamicNumber,
|
||||
DynamicBoolean,
|
||||
RepeatStatePath,
|
||||
UIElement,
|
||||
FlatElement,
|
||||
Spec,
|
||||
@@ -38,6 +39,8 @@ export {
|
||||
DynamicBooleanSchema,
|
||||
resolveDynamicValue,
|
||||
getByPath,
|
||||
resolveRepeatStatePath,
|
||||
resolveRepeatItemStatePath,
|
||||
setByPath,
|
||||
addByPath,
|
||||
removeByPath,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Schema, SchemaType } from "./schema";
|
||||
import { schema as imageSchema } from "../../image/src/schema";
|
||||
import { schema as inkSchema } from "../../ink/src/schema";
|
||||
import { schema as reactEmailSchema } from "../../react-email/src/schema";
|
||||
import { schema as reactNativeSchema } from "../../react-native/src/schema";
|
||||
import { schema as reactPdfSchema } from "../../react-pdf/src/schema";
|
||||
import { schema as reactSchema } from "../../react/src/schema";
|
||||
import { schema as solidSchema } from "../../solid/src/schema";
|
||||
import { schema as svelteSchema } from "../../svelte/src/schema";
|
||||
import { schema as vueSchema } from "../../vue/src/schema";
|
||||
|
||||
const schemas: Record<string, Schema> = {
|
||||
image: imageSchema,
|
||||
ink: inkSchema,
|
||||
react: reactSchema,
|
||||
"react-email": reactEmailSchema,
|
||||
"react-native": reactNativeSchema,
|
||||
"react-pdf": reactPdfSchema,
|
||||
solid: solidSchema,
|
||||
svelte: svelteSchema,
|
||||
vue: vueSchema,
|
||||
};
|
||||
|
||||
describe("renderer schema repeat parity", () => {
|
||||
it.each(Object.entries(schemas))(
|
||||
"%s declares repeat as an optional element field",
|
||||
(_name, schema) => {
|
||||
const spec = schema.definition.spec as SchemaType<
|
||||
"object",
|
||||
Record<string, SchemaType>
|
||||
>;
|
||||
const elements = spec.inner?.elements as SchemaType<
|
||||
"record",
|
||||
SchemaType<"object", Record<string, SchemaType>>
|
||||
>;
|
||||
const repeat = elements.inner?.inner?.repeat;
|
||||
|
||||
expect(repeat?.kind).toBe("any");
|
||||
expect(repeat?.optional).toBe(true);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -762,6 +762,9 @@ Note: state patches appear right after the elements that use them, so the UI fil
|
||||
lines.push(
|
||||
'The element itself renders once (as the container), and its children are expanded once per array item. "statePath" is the state array path. "key" is an optional field name on each item for stable React keys.',
|
||||
);
|
||||
lines.push(
|
||||
'For nested lists, an inner repeat can read an array from the enclosing item with { "statePath": { "$item": "field" } }. This form is valid only inside another repeat. Use an empty field to repeat over the enclosing item itself.',
|
||||
);
|
||||
lines.push(
|
||||
`Example: ${JSON.stringify({ type: comp1, props: comp1Props, repeat: { statePath: "/todos", key: "id" }, children: ["todo-item"] })}`,
|
||||
);
|
||||
|
||||
@@ -236,6 +236,203 @@ describe("repeat validation", () => {
|
||||
});
|
||||
expect(runtimeState.valid).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a nested repeat relative to the enclosing item", () => {
|
||||
const result = validateSpec({
|
||||
root: "groups",
|
||||
state: {
|
||||
groups: [{ subitems: [{ label: "a" }] }],
|
||||
},
|
||||
elements: {
|
||||
groups: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: "/groups" },
|
||||
children: ["subitems"],
|
||||
},
|
||||
subitems: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "subitems" } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: { type: "Text", props: {}, children: [] },
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.issues).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("rejects a relative repeat outside repeat scope", () => {
|
||||
const result = validateSpec({
|
||||
root: "items",
|
||||
state: { items: [{ label: "root" }] },
|
||||
elements: {
|
||||
items: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "items" } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: { type: "Text", props: {}, children: [] },
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(
|
||||
result.issues.some((issue) => issue.code === "repeat_item_outside_scope"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts relative repeat structure when the outer sample array is empty", () => {
|
||||
const result = validateSpec({
|
||||
root: "groups",
|
||||
state: { groups: [] },
|
||||
elements: {
|
||||
groups: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: "/groups" },
|
||||
children: ["subitems"],
|
||||
},
|
||||
subitems: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "subitems" } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: { type: "Text", props: {}, children: [] },
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a nested relative repeat that does not resolve to an array", () => {
|
||||
const result = validateSpec({
|
||||
root: "groups",
|
||||
state: { groups: [{ subitems: { label: "a" } }] },
|
||||
elements: {
|
||||
groups: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: "/groups" },
|
||||
children: ["subitems"],
|
||||
},
|
||||
subitems: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "/subitems" } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: { type: "Text", props: {}, children: [] },
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(
|
||||
result.issues.some((issue) => issue.code === "repeat_state_mismatch"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not duplicate repeat issues for the same structural context", () => {
|
||||
const result = validateSpec({
|
||||
root: "root",
|
||||
state: { items: [] },
|
||||
elements: {
|
||||
root: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
children: ["left", "right"],
|
||||
},
|
||||
left: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
children: ["shared"],
|
||||
},
|
||||
right: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
children: ["shared"],
|
||||
},
|
||||
shared: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "items" } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: { type: "Text", props: {}, children: [] },
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
result.issues.filter(
|
||||
(issue) => issue.code === "repeat_item_outside_scope",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("validates a reused repeat separately inside and outside scope", () => {
|
||||
const result = validateSpec({
|
||||
root: "root",
|
||||
state: { groups: [{ items: [] }] },
|
||||
elements: {
|
||||
root: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
children: ["groups", "shared"],
|
||||
},
|
||||
groups: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: "/groups" },
|
||||
children: ["shared"],
|
||||
},
|
||||
shared: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "items" } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: { type: "Text", props: {}, children: [] },
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
result.issues.filter(
|
||||
(issue) => issue.code === "repeat_item_outside_scope",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
result.issues.filter((issue) => issue.code === "repeat_state_mismatch"),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("terminates repeat validation for cyclic child graphs", () => {
|
||||
const result = validateSpec({
|
||||
root: "groups",
|
||||
state: { groups: [{ items: [] }] },
|
||||
elements: {
|
||||
groups: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: "/groups" },
|
||||
children: ["items"],
|
||||
},
|
||||
items: {
|
||||
type: "Stack",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "items" } },
|
||||
children: ["groups"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
result.issues.filter((issue) => issue.code === "repeat_state_mismatch"),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("visible condition validation", () => {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { Spec, UIElement } from "./types";
|
||||
import { getByPath } from "./types";
|
||||
import {
|
||||
getByPath,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
} from "./types";
|
||||
import { VisibilityConditionStrictSchema } from "./visibility";
|
||||
|
||||
// =============================================================================
|
||||
@@ -28,6 +32,7 @@ export interface SpecIssue {
|
||||
| "missing_child"
|
||||
| "invalid_visible"
|
||||
| "repeat_without_children"
|
||||
| "repeat_item_outside_scope"
|
||||
| "repeat_state_mismatch"
|
||||
| "visible_in_props"
|
||||
| "orphaned_element"
|
||||
@@ -138,17 +143,6 @@ export function validateSpec(
|
||||
code: "repeat_without_children",
|
||||
});
|
||||
}
|
||||
if (spec.state !== undefined) {
|
||||
const value = getByPath(spec.state, element.repeat.statePath);
|
||||
if (!Array.isArray(value)) {
|
||||
issues.push({
|
||||
severity: "error",
|
||||
message: `Element "${key}" repeats over "${element.repeat.statePath}" but state${value === undefined ? " has no value there" : ` has a ${typeof value} there`}. Repeat statePath must reference an array in state; add sample items to state at that path.`,
|
||||
elementKey: key,
|
||||
code: "repeat_state_mismatch",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3b. Malformed visible condition. Unrecognized shapes silently evaluate
|
||||
@@ -207,6 +201,88 @@ export function validateSpec(
|
||||
}
|
||||
}
|
||||
|
||||
const repeatValidatedKeys = new Set<string>();
|
||||
const repeatValidatedContexts = new Set<string>();
|
||||
const validateRepeatPaths = (
|
||||
key: string,
|
||||
repeatBasePath: string | undefined,
|
||||
sampleAvailable: boolean,
|
||||
ancestors: Set<string>,
|
||||
) => {
|
||||
if (ancestors.has(key)) return;
|
||||
const element = spec.elements[key];
|
||||
if (!element) return;
|
||||
repeatValidatedKeys.add(key);
|
||||
const contextKey = `${key}\u0000${repeatBasePath ?? ""}\u0000${sampleAvailable}`;
|
||||
if (repeatValidatedContexts.has(contextKey)) return;
|
||||
repeatValidatedContexts.add(contextKey);
|
||||
|
||||
let childRepeatBasePath = repeatBasePath;
|
||||
let childSampleAvailable = sampleAvailable;
|
||||
|
||||
if (element.repeat !== undefined) {
|
||||
const statePath = resolveRepeatStatePath(
|
||||
element.repeat.statePath,
|
||||
repeatBasePath,
|
||||
);
|
||||
const displayPath =
|
||||
typeof element.repeat.statePath === "string"
|
||||
? element.repeat.statePath
|
||||
: JSON.stringify(element.repeat.statePath);
|
||||
|
||||
if (statePath === undefined) {
|
||||
issues.push({
|
||||
severity: "error",
|
||||
message: `Element "${key}" uses relative repeat statePath ${displayPath} outside a repeat scope.`,
|
||||
elementKey: key,
|
||||
code: "repeat_item_outside_scope",
|
||||
});
|
||||
childRepeatBasePath = undefined;
|
||||
childSampleAvailable = false;
|
||||
} else {
|
||||
const canCheckSample =
|
||||
spec.state !== undefined &&
|
||||
(typeof element.repeat.statePath === "string" || sampleAvailable);
|
||||
const value = canCheckSample
|
||||
? getByPath(spec.state, statePath)
|
||||
: undefined;
|
||||
|
||||
if (canCheckSample && !Array.isArray(value)) {
|
||||
issues.push({
|
||||
severity: "error",
|
||||
message: `Element "${key}" repeats over "${statePath}" but state${value === undefined ? " has no value there" : ` has a ${typeof value} there`}. Repeat statePath must reference an array in state; add sample items to state at that path.`,
|
||||
elementKey: key,
|
||||
code: "repeat_state_mismatch",
|
||||
});
|
||||
}
|
||||
|
||||
childRepeatBasePath = resolveRepeatItemStatePath(statePath, 0);
|
||||
childSampleAvailable =
|
||||
canCheckSample && Array.isArray(value) && value.length > 0;
|
||||
}
|
||||
}
|
||||
|
||||
const nextAncestors = new Set(ancestors);
|
||||
nextAncestors.add(key);
|
||||
for (const childKey of element.children ?? []) {
|
||||
validateRepeatPaths(
|
||||
childKey,
|
||||
childRepeatBasePath,
|
||||
childSampleAvailable,
|
||||
nextAncestors,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if (spec.elements[spec.root]) {
|
||||
validateRepeatPaths(spec.root, undefined, true, new Set());
|
||||
}
|
||||
for (const key of Object.keys(spec.elements)) {
|
||||
if (!repeatValidatedKeys.has(key)) {
|
||||
validateRepeatPaths(key, undefined, true, new Set());
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Orphaned elements (optional)
|
||||
if (checkOrphans) {
|
||||
const reachable = new Set<string>();
|
||||
|
||||
@@ -2,6 +2,8 @@ import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
resolveDynamicValue,
|
||||
getByPath,
|
||||
resolveRepeatStatePath,
|
||||
resolveRepeatItemStatePath,
|
||||
setByPath,
|
||||
addByPath,
|
||||
removeByPath,
|
||||
@@ -58,6 +60,41 @@ describe("getByPath", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveRepeatStatePath", () => {
|
||||
it("preserves string paths exactly", () => {
|
||||
expect(resolveRepeatStatePath("/items")).toBe("/items");
|
||||
expect(resolveRepeatStatePath("items")).toBe("items");
|
||||
});
|
||||
|
||||
it("resolves $item paths against the enclosing item path", () => {
|
||||
expect(resolveRepeatStatePath({ $item: "subitems" }, "/groups/0")).toBe(
|
||||
"/groups/0/subitems",
|
||||
);
|
||||
expect(resolveRepeatStatePath({ $item: "/subitems" }, "/groups/0")).toBe(
|
||||
"/groups/0/subitems",
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves an empty $item path to the enclosing item", () => {
|
||||
expect(resolveRepeatStatePath({ $item: "" }, "/groups/0")).toBe(
|
||||
"/groups/0",
|
||||
);
|
||||
expect(resolveRepeatStatePath({ $item: "/" }, "/groups/0")).toBe(
|
||||
"/groups/0",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not resolve $item outside repeat scope", () => {
|
||||
expect(resolveRepeatStatePath({ $item: "items" })).toBeUndefined();
|
||||
});
|
||||
|
||||
it("builds item paths without duplicate root separators", () => {
|
||||
expect(resolveRepeatItemStatePath("/items", 2)).toBe("/items/2");
|
||||
expect(resolveRepeatItemStatePath("/", 2)).toBe("/2");
|
||||
expect(resolveRepeatItemStatePath("items", 2)).toBe("items/2");
|
||||
});
|
||||
});
|
||||
|
||||
describe("setByPath", () => {
|
||||
it("sets value at existing path", () => {
|
||||
const data: Record<string, unknown> = { user: { name: "John" } };
|
||||
|
||||
@@ -50,6 +50,8 @@ export const DynamicBooleanSchema = z.union([
|
||||
z.object({ $state: z.string() }),
|
||||
]);
|
||||
|
||||
export type RepeatStatePath = string | { $item: string };
|
||||
|
||||
/**
|
||||
* Base UI element structure for v2
|
||||
*/
|
||||
@@ -68,7 +70,7 @@ export interface UIElement<
|
||||
/** Event bindings — maps event names to action bindings */
|
||||
on?: Record<string, ActionBinding | ActionBinding[]>;
|
||||
/** Repeat children once per item in a state array */
|
||||
repeat?: { statePath: string; key?: string };
|
||||
repeat?: { statePath: RepeatStatePath; key?: string };
|
||||
/**
|
||||
* State watchers — maps JSON Pointer state paths to action bindings.
|
||||
* When the value at a watched path changes, the bound actions fire.
|
||||
@@ -307,6 +309,40 @@ export function getByPath(obj: unknown, path: string): unknown {
|
||||
return current;
|
||||
}
|
||||
|
||||
export function resolveRepeatStatePath(
|
||||
statePath: RepeatStatePath,
|
||||
repeatBasePath?: string | null,
|
||||
): string | undefined {
|
||||
if (typeof statePath === "string") {
|
||||
return statePath;
|
||||
}
|
||||
|
||||
if (repeatBasePath == null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (statePath.$item === "" || statePath.$item === "/") {
|
||||
return repeatBasePath;
|
||||
}
|
||||
|
||||
return joinStatePath(repeatBasePath, statePath.$item);
|
||||
}
|
||||
|
||||
export function resolveRepeatItemStatePath(
|
||||
statePath: string,
|
||||
index: number,
|
||||
): string {
|
||||
return joinStatePath(statePath, String(index));
|
||||
}
|
||||
|
||||
function joinStatePath(basePath: string, childPath: string): string {
|
||||
const child = childPath.startsWith("/") ? childPath.slice(1) : childPath;
|
||||
if (basePath === "" || basePath === "/") {
|
||||
return `/${child}`;
|
||||
}
|
||||
return `${basePath}/${child}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string is a numeric index
|
||||
*/
|
||||
|
||||
@@ -156,6 +156,8 @@ const png = await renderToPng(spec, { fonts });
|
||||
|
||||
## Server-Safe Import
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
Import schema and catalog definitions without pulling in React or Satori:
|
||||
|
||||
```typescript
|
||||
|
||||
@@ -3,6 +3,8 @@ import satori, { type SatoriOptions } from "satori";
|
||||
import type { Spec, UIElement } from "@json-render/core";
|
||||
import {
|
||||
resolveElementProps,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
type PropResolutionContext,
|
||||
@@ -60,21 +62,25 @@ function renderElement(
|
||||
if (!Component) return null;
|
||||
|
||||
if (resolvedElement.repeat) {
|
||||
const repeat = resolvedElement.repeat;
|
||||
const statePath = resolveRepeatStatePath(repeat.statePath, repeatBasePath);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render/image] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const items =
|
||||
(getByPath(stateModel, resolvedElement.repeat.statePath) as
|
||||
| unknown[]
|
||||
| undefined) ?? [];
|
||||
(getByPath(stateModel, statePath) as unknown[] | undefined) ?? [];
|
||||
|
||||
const fragments = items.map((item, index) => {
|
||||
const key =
|
||||
resolvedElement.repeat!.key && typeof item === "object" && item !== null
|
||||
? String(
|
||||
(item as Record<string, unknown>)[resolvedElement.repeat!.key!] ??
|
||||
index,
|
||||
)
|
||||
repeat.key && typeof item === "object" && item !== null
|
||||
? String((item as Record<string, unknown>)[repeat.key!] ?? index)
|
||||
: String(index);
|
||||
|
||||
const childPath = `${resolvedElement.repeat!.statePath}/${index}`;
|
||||
const childPath = resolveRepeatItemStatePath(statePath, index);
|
||||
const children = resolvedElement.children?.map((childKey) =>
|
||||
renderElement(
|
||||
childKey,
|
||||
@@ -206,6 +212,5 @@ export async function renderToPng(
|
||||
|
||||
const resvg = new Resvg(svg);
|
||||
const pngData = resvg.render();
|
||||
const png = pngData.asPng();
|
||||
return new Uint8Array(png.buffer, png.byteOffset, png.byteLength);
|
||||
return pngData.asPng();
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ export const schema = defineSchema(
|
||||
props: s.propsOf("catalog.components"),
|
||||
children: s.array(s.string()),
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
|
||||
@@ -110,6 +110,8 @@ const { spec, send, isStreaming } = useUIStream({ api: "/api/generate" });
|
||||
|
||||
## Key Exports
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
| Export | Purpose |
|
||||
|--------|---------|
|
||||
| `createRenderer` | Create an all-in-one renderer component from a catalog |
|
||||
|
||||
@@ -280,9 +280,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate: navigateRef.current,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
resolveElementProps,
|
||||
resolveBindings,
|
||||
resolveActionParam,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
type PropResolutionContext,
|
||||
@@ -320,8 +322,18 @@ function RepeatChildren({
|
||||
fallback?: ComponentRenderer;
|
||||
}) {
|
||||
const { state } = useStateStore();
|
||||
const parentScope = useRepeatScope();
|
||||
const repeat = element.repeat!;
|
||||
const statePath = repeat.statePath;
|
||||
const statePath = resolveRepeatStatePath(
|
||||
repeat.statePath,
|
||||
parentScope?.basePath,
|
||||
);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render/ink] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = getByPath(state, statePath);
|
||||
const items = Array.isArray(raw) ? raw : [];
|
||||
@@ -341,7 +353,7 @@ function RepeatChildren({
|
||||
key={key}
|
||||
item={itemValue}
|
||||
index={index}
|
||||
basePath={`${statePath}/${index}`}
|
||||
basePath={resolveRepeatItemStatePath(statePath, index)}
|
||||
>
|
||||
{element.children?.map((childKey) => {
|
||||
const childElement = spec.elements[childKey];
|
||||
|
||||
@@ -23,6 +23,8 @@ export const schema = defineSchema(
|
||||
children: s.array(s.string()),
|
||||
/** Visibility condition */
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
/** Repeat children from a state array */
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
@@ -76,7 +78,7 @@ export const schema = defineSchema(
|
||||
'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.',
|
||||
// State and data
|
||||
"When the user asks for a UI that displays data (e.g. logs, tasks, metrics), ALWAYS include a state field with realistic sample data. The state field is a top-level field on the spec (sibling of root/elements).",
|
||||
'When building repeating content backed by a state array, use the "repeat" field on a container element. Example: { "type": "Box", "props": { "flexDirection": "column" }, "repeat": { "statePath": "/items", "key": "id" }, "children": ["item-row"] }. Inside repeated children, use { "$item": "field" } to read a field from the current item, and { "$index": true } for the current array index.',
|
||||
'When building repeating content backed by a state array, use the "repeat" field on a container element. Example: { "type": "Box", "props": { "flexDirection": "column" }, "repeat": { "statePath": "/items", "key": "id" }, "children": ["item-row"] }. For a nested list stored on the enclosing item, use "repeat": { "statePath": { "$item": "children" }, "key": "id" }. The $item statePath form is valid only inside another repeat. Inside repeated children, use { "$item": "field" } to read from the current item and { "$index": true } for the current index.',
|
||||
// Terminal UI design
|
||||
"This UI renders in a terminal using Ink. Use Box for layout (flexDirection, padding, gap), Text for text content. Keep designs compact and readable in monospace.",
|
||||
"Terminal UIs have limited width (~80-120 columns). Prefer vertical layouts (flexDirection: column) for main structure. Use horizontal layouts (flexDirection: row) for inline elements like badges, key-value pairs, and table rows.",
|
||||
|
||||
@@ -128,6 +128,8 @@ Both accept an optional second argument with:
|
||||
- `includeStandard` — Include built-in standard components (default: `true`)
|
||||
- `state` — Initial state for `$state` / `$cond` dynamic prop resolution
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
## Server-Safe Import
|
||||
|
||||
Import schema and catalog definitions without pulling in React or `@react-email/components`:
|
||||
|
||||
@@ -174,9 +174,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -196,9 +195,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { render } from "@react-email/render";
|
||||
import type { Spec, UIElement } from "@json-render/core";
|
||||
import {
|
||||
resolveElementProps,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
type PropResolutionContext,
|
||||
@@ -57,12 +59,18 @@ function renderElement(
|
||||
if (!Component) return null;
|
||||
|
||||
if (resolvedElement.repeat) {
|
||||
const repeat = resolvedElement.repeat;
|
||||
const statePath = resolveRepeatStatePath(repeat.statePath, repeatBasePath);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render/react-email] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const items =
|
||||
(getByPath(stateModel, resolvedElement.repeat.statePath) as
|
||||
| unknown[]
|
||||
| undefined) ?? [];
|
||||
(getByPath(stateModel, statePath) as unknown[] | undefined) ?? [];
|
||||
|
||||
const repeat = resolvedElement.repeat!;
|
||||
const fragments = items.map((item, index) => {
|
||||
const repeatKey = repeat.key;
|
||||
const key =
|
||||
@@ -70,7 +78,7 @@ function renderElement(
|
||||
? String((item as Record<string, unknown>)[repeatKey] ?? index)
|
||||
: String(index);
|
||||
|
||||
const childPath = `${repeat.statePath}/${index}`;
|
||||
const childPath = resolveRepeatItemStatePath(statePath, index);
|
||||
const children = resolvedElement.children?.map((childKey) =>
|
||||
renderElement(
|
||||
childKey,
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
resolveElementProps,
|
||||
resolveBindings,
|
||||
resolveActionParam,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
type PropResolutionContext,
|
||||
@@ -248,8 +250,18 @@ function RepeatChildren({
|
||||
fallback?: ComponentRenderer;
|
||||
}) {
|
||||
const { state } = useStateStore();
|
||||
const parentScope = useRepeatScope();
|
||||
const repeat = element.repeat!;
|
||||
const statePath = repeat.statePath;
|
||||
const statePath = resolveRepeatStatePath(
|
||||
repeat.statePath,
|
||||
parentScope?.basePath,
|
||||
);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render/react-email] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const items = (getByPath(state, statePath) as unknown[] | undefined) ?? [];
|
||||
|
||||
@@ -268,7 +280,7 @@ function RepeatChildren({
|
||||
key={key}
|
||||
item={itemValue}
|
||||
index={index}
|
||||
basePath={`${statePath}/${index}`}
|
||||
basePath={resolveRepeatItemStatePath(statePath, index)}
|
||||
>
|
||||
{element.children?.map((childKey) => {
|
||||
const childElement = spec.elements[childKey];
|
||||
|
||||
@@ -19,6 +19,7 @@ export const schema = defineSchema(
|
||||
props: s.propsOf("catalog.components"),
|
||||
children: s.array(s.string()),
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
|
||||
@@ -236,6 +236,8 @@ When `store` is provided, `initialState` and `onStateChange` are ignored. The st
|
||||
|
||||
## Hooks
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
| Hook | Purpose |
|
||||
|------|---------|
|
||||
| `useStateStore()` | Access state context (`state`, `get`, `set`, `update`) |
|
||||
|
||||
@@ -262,9 +262,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -285,9 +284,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
resolveElementProps,
|
||||
resolveBindings,
|
||||
resolveActionParam,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
type PropResolutionContext,
|
||||
@@ -300,8 +302,18 @@ function RepeatChildren({
|
||||
fallback?: ComponentRenderer;
|
||||
}) {
|
||||
const { state } = useStateStore();
|
||||
const parentScope = useRepeatScope();
|
||||
const repeat = element.repeat!;
|
||||
const statePath = repeat.statePath;
|
||||
const statePath = resolveRepeatStatePath(
|
||||
repeat.statePath,
|
||||
parentScope?.basePath,
|
||||
);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render/react-native] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const items = (getByPath(state, statePath) as unknown[] | undefined) ?? [];
|
||||
|
||||
@@ -321,7 +333,7 @@ function RepeatChildren({
|
||||
key={key}
|
||||
item={itemValue}
|
||||
index={index}
|
||||
basePath={`${statePath}/${index}`}
|
||||
basePath={resolveRepeatItemStatePath(statePath, index)}
|
||||
>
|
||||
{element.children?.map((childKey) => {
|
||||
const childElement = spec.elements[childKey];
|
||||
|
||||
@@ -24,6 +24,8 @@ export const schema = defineSchema(
|
||||
children: s.array(s.string()),
|
||||
/** Visibility condition */
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
/** Repeat children from a state array */
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
@@ -60,7 +62,7 @@ export const schema = defineSchema(
|
||||
"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.",
|
||||
"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.",
|
||||
'REQUIRED FIELDS: Every element MUST include a "children" array. Leaf elements (text, badges, inputs, images) use an empty array: "children": []. Omitting "children" fails validation.',
|
||||
'When building repeating content backed by a state array (e.g. todos, posts, cart items), use the "repeat" field on a container element from the AVAILABLE COMPONENTS list. Example: { "type": "<ContainerComponent>", "props": { "gap": 8 }, "repeat": { "statePath": "/todos", "key": "id" }, "children": ["todo-item"] }. 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.',
|
||||
'When building repeating content backed by a state array (e.g. todos, posts, cart items), use the "repeat" field on a container element from the AVAILABLE COMPONENTS list. Example: { "type": "<ContainerComponent>", "props": { "gap": 8 }, "repeat": { "statePath": "/todos", "key": "id" }, "children": ["todo-item"] }. For a nested list stored on the enclosing item, use "repeat": { "statePath": { "$item": "comments" }, "key": "id" }. The $item statePath form is valid only inside another repeat. 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.',
|
||||
|
||||
// Visible field placement
|
||||
'CRITICAL: The "visible" field goes on the ELEMENT object, NOT inside "props". Correct: {"type":"<ComponentName>","props":{},"visible":{"$state":"/activeTab","eq":"home"},"children":[...]}. WRONG: {"type":"<ComponentName>","props":{},"visible":{...},"children":[...]} with visible inside props.',
|
||||
|
||||
@@ -154,6 +154,8 @@ All render functions accept an optional second argument with:
|
||||
- `state` - Initial state for `$state` / `$cond` dynamic prop resolution
|
||||
- `handlers` - Action handlers
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
## External Store (Controlled Mode)
|
||||
|
||||
For full control over state, pass a `StateStore` to `StateProvider`, `JSONUIProvider`, or `createRenderer`. When `store` is provided, `initialState` and `onStateChange` are ignored and the store is the single source of truth:
|
||||
|
||||
@@ -176,9 +176,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -198,9 +197,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
import type { Spec, UIElement } from "@json-render/core";
|
||||
import {
|
||||
resolveElementProps,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
type PropResolutionContext,
|
||||
@@ -61,21 +63,25 @@ function renderElement(
|
||||
if (!Component) return null;
|
||||
|
||||
if (resolvedElement.repeat) {
|
||||
const repeat = resolvedElement.repeat;
|
||||
const statePath = resolveRepeatStatePath(repeat.statePath, repeatBasePath);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render/react-pdf] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const items =
|
||||
(getByPath(stateModel, resolvedElement.repeat.statePath) as
|
||||
| unknown[]
|
||||
| undefined) ?? [];
|
||||
(getByPath(stateModel, statePath) as unknown[] | undefined) ?? [];
|
||||
|
||||
const fragments = items.map((item, index) => {
|
||||
const key =
|
||||
resolvedElement.repeat!.key && typeof item === "object" && item !== null
|
||||
? String(
|
||||
(item as Record<string, unknown>)[resolvedElement.repeat!.key!] ??
|
||||
index,
|
||||
)
|
||||
repeat.key && typeof item === "object" && item !== null
|
||||
? String((item as Record<string, unknown>)[repeat.key!] ?? index)
|
||||
: String(index);
|
||||
|
||||
const childPath = `${resolvedElement.repeat!.statePath}/${index}`;
|
||||
const childPath = resolveRepeatItemStatePath(statePath, index);
|
||||
const children = resolvedElement.children?.map((childKey) =>
|
||||
renderElement(
|
||||
childKey,
|
||||
@@ -153,8 +159,7 @@ export async function renderToBuffer(
|
||||
options?: RenderOptions,
|
||||
): Promise<Uint8Array> {
|
||||
const document = buildDocument(spec, options);
|
||||
const buffer = await pdfRenderToBuffer(document as any);
|
||||
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
||||
return pdfRenderToBuffer(document as any);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,7 +168,7 @@ export async function renderToBuffer(
|
||||
export async function renderToStream(
|
||||
spec: Spec,
|
||||
options?: RenderOptions,
|
||||
): Promise<NodeJS.ReadableStream> {
|
||||
): Promise<ReadableStream> {
|
||||
const document = buildDocument(spec, options);
|
||||
return pdfRenderToStream(document as any);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
resolveElementProps,
|
||||
resolveBindings,
|
||||
resolveActionParam,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
type PropResolutionContext,
|
||||
@@ -256,8 +258,18 @@ function RepeatChildren({
|
||||
fallback?: ComponentRenderer;
|
||||
}) {
|
||||
const { state } = useStateStore();
|
||||
const parentScope = useRepeatScope();
|
||||
const repeat = element.repeat!;
|
||||
const statePath = repeat.statePath;
|
||||
const statePath = resolveRepeatStatePath(
|
||||
repeat.statePath,
|
||||
parentScope?.basePath,
|
||||
);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render/react-pdf] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const items = (getByPath(state, statePath) as unknown[] | undefined) ?? [];
|
||||
|
||||
@@ -276,7 +288,7 @@ function RepeatChildren({
|
||||
key={key}
|
||||
item={itemValue}
|
||||
index={index}
|
||||
basePath={`${statePath}/${index}`}
|
||||
basePath={resolveRepeatItemStatePath(statePath, index)}
|
||||
>
|
||||
{element.children?.map((childKey) => {
|
||||
const childElement = spec.elements[childKey];
|
||||
|
||||
@@ -19,6 +19,7 @@ export const schema = defineSchema(
|
||||
props: s.propsOf("catalog.components"),
|
||||
children: s.array(s.string()),
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
|
||||
@@ -519,6 +519,8 @@ function App() {
|
||||
|
||||
## Key Exports
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
| Export | Purpose |
|
||||
|--------|---------|
|
||||
| `defineRegistry` | Create a type-safe component registry from a catalog |
|
||||
|
||||
@@ -195,4 +195,46 @@ describe("chained actions: live $state resolution (#141)", () => {
|
||||
expect(state.counter).toBe(42);
|
||||
expect(state.counterCopy).toBe(42);
|
||||
});
|
||||
|
||||
it("forwards params to a named onSuccess action (#301)", async () => {
|
||||
let receivedParams: Record<string, unknown> | undefined;
|
||||
const handlers = {
|
||||
save: async () => {},
|
||||
toast: async (params: Record<string, unknown>) => {
|
||||
receivedParams = params;
|
||||
},
|
||||
};
|
||||
|
||||
const spec: Spec = {
|
||||
root: "main",
|
||||
elements: {
|
||||
main: {
|
||||
type: "Button",
|
||||
props: { label: "Save" },
|
||||
on: {
|
||||
press: {
|
||||
action: "save",
|
||||
onSuccess: { action: "toast", params: { message: "Saved!" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<JSONUIProvider registry={registry} handlers={handlers}>
|
||||
<Renderer spec={spec} registry={registry} />
|
||||
</JSONUIProvider>
|
||||
);
|
||||
}
|
||||
|
||||
render(<App />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByTestId("btn"));
|
||||
});
|
||||
|
||||
expect(receivedParams).toEqual({ message: "Saved!" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -309,9 +309,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -332,9 +331,8 @@ export function ActionProvider({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import React from "react";
|
||||
import { Renderer } from "./renderer";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import type { Spec } from "@json-render/core";
|
||||
import {
|
||||
JSONUIProvider,
|
||||
Renderer,
|
||||
type ComponentRenderProps,
|
||||
} from "./renderer";
|
||||
|
||||
describe("Renderer", () => {
|
||||
it("renders null for null spec", () => {
|
||||
@@ -40,4 +46,97 @@ describe("Renderer", () => {
|
||||
});
|
||||
expect(element.props.fallback).toBe(Fallback);
|
||||
});
|
||||
|
||||
it.each(["subitems", "/subitems"])(
|
||||
"resolves nested repeat statePath %s from parent $item scope",
|
||||
(itemPath) => {
|
||||
function Group({ children }: ComponentRenderProps) {
|
||||
return <div>{children}</div>;
|
||||
}
|
||||
|
||||
function Text({ element }: ComponentRenderProps<{ text: unknown }>) {
|
||||
return (
|
||||
<span data-testid="item-text">{String(element.props.text)}</span>
|
||||
);
|
||||
}
|
||||
|
||||
const spec: Spec = {
|
||||
root: "groups",
|
||||
state: {
|
||||
groups: [
|
||||
{ subitems: [{ label: "a1" }, { label: "a2" }] },
|
||||
{ subitems: [{ label: "b1" }] },
|
||||
],
|
||||
},
|
||||
elements: {
|
||||
groups: {
|
||||
type: "Group",
|
||||
props: {},
|
||||
repeat: { statePath: "/groups" },
|
||||
children: ["subitems"],
|
||||
},
|
||||
subitems: {
|
||||
type: "Group",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: itemPath } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: {
|
||||
type: "Text",
|
||||
props: { text: { $item: "label" } },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
render(
|
||||
<JSONUIProvider registry={{ Group, Text }} initialState={spec.state}>
|
||||
<Renderer spec={spec} registry={{ Group, Text }} />
|
||||
</JSONUIProvider>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getAllByTestId("item-text").map((el) => el.textContent),
|
||||
).toEqual(["a1", "a2", "b1"]);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not fall back to root state for $item outside repeat scope", () => {
|
||||
function Group({ children }: ComponentRenderProps) {
|
||||
return <div>{children}</div>;
|
||||
}
|
||||
|
||||
function Text({ element }: ComponentRenderProps<{ text: unknown }>) {
|
||||
return <span data-testid="item-text">{String(element.props.text)}</span>;
|
||||
}
|
||||
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const spec: Spec = {
|
||||
root: "items",
|
||||
state: { items: [{ label: "must-not-render" }] },
|
||||
elements: {
|
||||
items: {
|
||||
type: "Group",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "items" } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: {
|
||||
type: "Text",
|
||||
props: { text: { $item: "label" } },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const { queryAllByTestId } = render(
|
||||
<JSONUIProvider registry={{ Group, Text }} initialState={spec.state}>
|
||||
<Renderer spec={spec} registry={{ Group, Text }} />
|
||||
</JSONUIProvider>,
|
||||
);
|
||||
|
||||
expect(queryAllByTestId("item-text")).toHaveLength(0);
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
"[json-render] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
warn.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
resolveElementProps,
|
||||
resolveBindings,
|
||||
resolveActionParam,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
splitRepeatVisibility,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
@@ -483,8 +485,18 @@ function RepeatChildren({
|
||||
}) {
|
||||
const { state } = useStateStore();
|
||||
const { ctx } = useVisibility();
|
||||
const parentScope = useRepeatScope();
|
||||
const repeat = element.repeat!;
|
||||
const statePath = repeat.statePath;
|
||||
const statePath = resolveRepeatStatePath(
|
||||
repeat.statePath,
|
||||
parentScope?.basePath,
|
||||
);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const items = (getByPath(state, statePath) as unknown[] | undefined) ?? [];
|
||||
|
||||
@@ -519,7 +531,7 @@ function RepeatChildren({
|
||||
key={key}
|
||||
item={itemValue}
|
||||
index={index}
|
||||
basePath={`${statePath}/${index}`}
|
||||
basePath={resolveRepeatItemStatePath(statePath, index)}
|
||||
>
|
||||
{element.children?.map((childKey) => {
|
||||
const childElement = spec.elements[childKey];
|
||||
|
||||
@@ -24,6 +24,8 @@ export const schema = defineSchema(
|
||||
children: s.array(s.string()),
|
||||
/** Visibility condition */
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
/** Repeat children from a state array */
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
@@ -86,7 +88,7 @@ export const schema = defineSchema(
|
||||
|
||||
// State and data
|
||||
"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).",
|
||||
'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.',
|
||||
'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"] }. For a nested list stored on the enclosing item, use "repeat": { "statePath": { "$item": "comments" }, "key": "id" }. The $item statePath form is valid only inside another repeat. 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.',
|
||||
|
||||
// Design quality
|
||||
"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.",
|
||||
|
||||
@@ -227,6 +227,8 @@ await stream.send("Build me a dashboard");
|
||||
|
||||
## Differences from `@json-render/react`
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
Most APIs are intentionally aligned, but there are runtime behavior differences due to Solid:
|
||||
|
||||
- Solid components run once, then update via signals.
|
||||
|
||||
@@ -239,9 +239,8 @@ export function ActionProvider(props: ParentProps<ActionProviderProps>) {
|
||||
handler,
|
||||
setState: set,
|
||||
navigate: props.navigate,
|
||||
executeAction: async (name: string) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -261,9 +260,8 @@ export function ActionProvider(props: ParentProps<ActionProviderProps>) {
|
||||
handler,
|
||||
setState: set,
|
||||
navigate: props.navigate,
|
||||
executeAction: async (name: string) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -26,6 +26,8 @@ import {
|
||||
resolveElementProps,
|
||||
resolveBindings,
|
||||
resolveActionParam,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
isDevtoolsActive,
|
||||
@@ -427,10 +429,25 @@ interface RepeatChildrenProps {
|
||||
function RepeatChildren(props: RepeatChildrenProps) {
|
||||
const stateStore = useStateStore();
|
||||
const repeat = () => props.element.repeat!;
|
||||
const statePath = () => repeat().statePath;
|
||||
const parentScope = useRepeatScope();
|
||||
const statePath = () => {
|
||||
const resolved = resolveRepeatStatePath(
|
||||
repeat().statePath,
|
||||
parentScope?.basePath,
|
||||
);
|
||||
if (resolved === undefined) {
|
||||
console.warn(
|
||||
"[json-render/solid] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
}
|
||||
return resolved;
|
||||
};
|
||||
|
||||
const items = () =>
|
||||
(getByPath(stateStore.state, statePath()) as unknown[] | undefined) ?? [];
|
||||
statePath() === undefined
|
||||
? []
|
||||
: ((getByPath(stateStore.state, statePath()!) as unknown[] | undefined) ??
|
||||
[]);
|
||||
|
||||
return (
|
||||
<For each={items()}>
|
||||
@@ -446,7 +463,7 @@ function RepeatChildren(props: RepeatChildrenProps) {
|
||||
<RepeatScopeProvider
|
||||
item={itemValue}
|
||||
index={index()}
|
||||
basePath={`${statePath()}/${index()}`}
|
||||
basePath={resolveRepeatItemStatePath(statePath()!, index())}
|
||||
>
|
||||
<For each={props.element.children ?? []}>
|
||||
{(childKey) => {
|
||||
|
||||
@@ -24,6 +24,8 @@ export const schema = defineSchema(
|
||||
children: s.array(s.string()),
|
||||
/** Visibility condition */
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
/** Repeat children from a state array */
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
@@ -85,7 +87,7 @@ export const schema = defineSchema(
|
||||
|
||||
// State and data
|
||||
"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).",
|
||||
'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.',
|
||||
'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"] }. For a nested list stored on the enclosing item, use "repeat": { "statePath": { "$item": "comments" }, "key": "id" }. The $item statePath form is valid only inside another repeat. 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.',
|
||||
|
||||
// Design quality
|
||||
"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.",
|
||||
|
||||
@@ -148,6 +148,8 @@ const chat = createChatUI({ endpoint: "/api/chat" });
|
||||
|
||||
## Documentation
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
Full API reference: [json-render.dev/docs/api/svelte](https://json-render.dev/docs/api/svelte).
|
||||
|
||||
## License
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
<script lang="ts">
|
||||
import type { Spec, UIElement } from "@json-render/core";
|
||||
import { getByPath } from "@json-render/core";
|
||||
import {
|
||||
getByPath,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
} from "@json-render/core";
|
||||
import type { ComponentRegistry, ComponentRenderer } from "./renderer.js";
|
||||
import { getStateContext } from "./contexts/StateProvider.svelte";
|
||||
import RepeatScopeProvider from "./contexts/RepeatScopeProvider.svelte";
|
||||
import RepeatScopeProvider, {
|
||||
getRepeatScope,
|
||||
} from "./contexts/RepeatScopeProvider.svelte";
|
||||
import ElementRenderer from "./ElementRenderer.svelte";
|
||||
|
||||
interface Props {
|
||||
@@ -17,17 +23,30 @@
|
||||
let { element, spec, registry, loading = false, fallback }: Props = $props();
|
||||
|
||||
const stateCtx = getStateContext();
|
||||
const parentScope = getRepeatScope();
|
||||
|
||||
let statePath = $derived.by(() => {
|
||||
const resolved = resolveRepeatStatePath(
|
||||
element.repeat!.statePath,
|
||||
parentScope?.basePath,
|
||||
);
|
||||
if (resolved === undefined) {
|
||||
console.warn(
|
||||
"[json-render/svelte] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
}
|
||||
return resolved;
|
||||
});
|
||||
|
||||
// Get items from state
|
||||
let items = $derived(
|
||||
(getByPath(stateCtx.state, element.repeat!.statePath) as
|
||||
| unknown[]
|
||||
| undefined) ?? [],
|
||||
statePath === undefined
|
||||
? []
|
||||
: ((getByPath(stateCtx.state, statePath) as unknown[] | undefined) ?? []),
|
||||
);
|
||||
</script>
|
||||
|
||||
{#each items as itemValue, index (element.repeat?.key && typeof itemValue === "object" && itemValue !== null ? String((itemValue as any)[element.repeat.key] ?? index) : String(index))}
|
||||
{@const basePath = `${element.repeat!.statePath}/${index}`}
|
||||
{@const basePath = resolveRepeatItemStatePath(statePath!, index)}
|
||||
|
||||
{#if element.children}
|
||||
<RepeatScopeProvider item={itemValue} {index} {basePath}>
|
||||
|
||||
@@ -304,9 +304,8 @@
|
||||
handler,
|
||||
setState: stateCtx.set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: CoreActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -322,9 +321,8 @@
|
||||
handler,
|
||||
setState: stateCtx.set,
|
||||
navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: CoreActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -179,6 +179,56 @@ describe("createActionContext", () => {
|
||||
})(),
|
||||
);
|
||||
|
||||
it(
|
||||
"forwards params to a named onSuccess action (#301)",
|
||||
(() => {
|
||||
const toast = vi.fn().mockResolvedValue(undefined);
|
||||
return component(
|
||||
async () => {
|
||||
const actionCtx = getActionContext();
|
||||
|
||||
await actionCtx.execute({
|
||||
action: "save",
|
||||
onSuccess: { action: "toast", params: { message: "Saved" } },
|
||||
});
|
||||
|
||||
expect(toast).toHaveBeenCalledWith({ message: "Saved" });
|
||||
},
|
||||
{
|
||||
handlers: {
|
||||
save: vi.fn().mockResolvedValue(undefined),
|
||||
toast,
|
||||
},
|
||||
},
|
||||
);
|
||||
})(),
|
||||
);
|
||||
|
||||
it(
|
||||
"forwards params to a named onError action (#301)",
|
||||
(() => {
|
||||
const toast = vi.fn().mockResolvedValue(undefined);
|
||||
return component(
|
||||
async () => {
|
||||
const actionCtx = getActionContext();
|
||||
|
||||
await actionCtx.execute({
|
||||
action: "save",
|
||||
onError: { action: "toast", params: { message: "Failed" } },
|
||||
});
|
||||
|
||||
expect(toast).toHaveBeenCalledWith({ message: "Failed" });
|
||||
},
|
||||
{
|
||||
handlers: {
|
||||
save: vi.fn().mockRejectedValue(new Error("boom")),
|
||||
toast,
|
||||
},
|
||||
},
|
||||
);
|
||||
})(),
|
||||
);
|
||||
|
||||
it(
|
||||
"warns when no handler registered",
|
||||
component(async () => {
|
||||
|
||||
@@ -191,4 +191,42 @@ describe("Renderer", () => {
|
||||
expect(texts).toHaveLength(1);
|
||||
expect(texts[0]?.textContent).toBe("I exist");
|
||||
});
|
||||
|
||||
it("renders nested repeats from the enclosing item", () => {
|
||||
const spec: Spec = {
|
||||
root: "groups",
|
||||
state: {
|
||||
groups: [
|
||||
{ subitems: [{ label: "a1" }, { label: "a2" }] },
|
||||
{ subitems: [{ label: "b1" }] },
|
||||
],
|
||||
},
|
||||
elements: {
|
||||
groups: {
|
||||
type: "Container",
|
||||
props: {},
|
||||
repeat: { statePath: "/groups" },
|
||||
children: ["subitems"],
|
||||
},
|
||||
subitems: {
|
||||
type: "Container",
|
||||
props: {},
|
||||
repeat: { statePath: { $item: "/subitems" } },
|
||||
children: ["label"],
|
||||
},
|
||||
label: {
|
||||
type: "Text",
|
||||
props: { text: { $item: "label" } },
|
||||
children: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const { container } = mountRenderer(spec);
|
||||
expect(
|
||||
Array.from(container.querySelectorAll(".test-text")).map(
|
||||
(element) => element.textContent,
|
||||
),
|
||||
).toEqual(["a1", "a2", "b1"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,6 +24,8 @@ export const schema = defineSchema(
|
||||
children: s.array(s.string()),
|
||||
/** Visibility condition */
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
/** Repeat children from a state array */
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
@@ -85,7 +87,7 @@ export const schema = defineSchema(
|
||||
|
||||
// State and data
|
||||
"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).",
|
||||
'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.',
|
||||
'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"] }. For a nested list stored on the enclosing item, use "repeat": { "statePath": { "$item": "comments" }, "key": "id" }. The $item statePath form is valid only inside another repeat. 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.',
|
||||
|
||||
// Design quality
|
||||
"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.",
|
||||
|
||||
@@ -488,6 +488,8 @@ const spec = {
|
||||
|
||||
## Differences from `@json-render/react`
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` to iterate an array on the enclosing repeat item.
|
||||
|
||||
| API | React | Vue | Note |
|
||||
|-----|-------|-----|------|
|
||||
| `useStateStore().state` | `StateModel` | `ShallowRef<StateModel>` | Vue reactivity; use `state.value` |
|
||||
|
||||
@@ -287,9 +287,8 @@ export const ActionProvider = defineComponent({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate: props.navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
@@ -310,9 +309,8 @@ export const ActionProvider = defineComponent({
|
||||
handler,
|
||||
setState: set,
|
||||
navigate: props.navigate,
|
||||
executeAction: async (name) => {
|
||||
const subBinding: ActionBinding = { action: name };
|
||||
await execute(subBinding);
|
||||
executeAction: async (binding) => {
|
||||
await execute(binding);
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -28,6 +28,8 @@ import {
|
||||
resolveElementProps,
|
||||
resolveBindings,
|
||||
resolveActionParam,
|
||||
resolveRepeatItemStatePath,
|
||||
resolveRepeatStatePath,
|
||||
evaluateVisibility,
|
||||
getByPath,
|
||||
createDirectiveRegistry,
|
||||
@@ -487,11 +489,21 @@ const RepeatChildren = defineComponent({
|
||||
},
|
||||
setup(props) {
|
||||
const { state } = useStateStore();
|
||||
const parentScope = useRepeatScope();
|
||||
|
||||
return () => {
|
||||
const repeat = props.element.repeat;
|
||||
if (!repeat?.statePath) return null;
|
||||
const statePath = repeat.statePath;
|
||||
const statePath = resolveRepeatStatePath(
|
||||
repeat.statePath,
|
||||
parentScope?.basePath,
|
||||
);
|
||||
if (statePath === undefined) {
|
||||
console.warn(
|
||||
"[json-render/vue] $item in repeat.statePath used outside of a repeat scope",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const raw = getByPath(state.value, statePath);
|
||||
const items = Array.isArray(raw) ? (raw as unknown[]) : [];
|
||||
|
||||
@@ -505,7 +517,12 @@ const RepeatChildren = defineComponent({
|
||||
|
||||
return h(
|
||||
RepeatScopeProvider,
|
||||
{ key, item: itemValue, index, basePath: `${statePath}/${index}` },
|
||||
{
|
||||
key,
|
||||
item: itemValue,
|
||||
index,
|
||||
basePath: resolveRepeatItemStatePath(statePath, index),
|
||||
},
|
||||
{
|
||||
default: () =>
|
||||
props.element.children
|
||||
|
||||
@@ -24,6 +24,8 @@ export const schema = defineSchema(
|
||||
children: s.array(s.string()),
|
||||
/** Visibility condition */
|
||||
visible: { ...s.any(), ...s.optional() },
|
||||
/** Repeat children from a state array */
|
||||
repeat: { ...s.any(), ...s.optional() },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
@@ -85,7 +87,7 @@ export const schema = defineSchema(
|
||||
|
||||
// State and data
|
||||
"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).",
|
||||
'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.',
|
||||
'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"] }. For a nested list stored on the enclosing item, use "repeat": { "statePath": { "$item": "comments" }, "key": "id" }. The $item statePath form is valid only inside another repeat. 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.',
|
||||
|
||||
// Design quality
|
||||
"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.",
|
||||
|
||||
@@ -376,6 +376,9 @@ export function yamlPrompt(
|
||||
lines.push(
|
||||
'Inside repeated children, use { "$item": "field" } for item data and { "$index": true } for the array index.',
|
||||
);
|
||||
lines.push(
|
||||
'For nested lists, an inner repeat can use statePath: { "$item": "field" } to read an array from the enclosing item. This form is valid only inside another repeat.',
|
||||
);
|
||||
lines.push(
|
||||
"ALWAYS use repeat for lists backed by state arrays. NEVER hardcode individual elements per item.",
|
||||
);
|
||||
|
||||
@@ -177,7 +177,7 @@ import { validateSpec, autoFixSpec } from "@json-render/core";
|
||||
|
||||
const { valid, issues } = validateSpec(spec);
|
||||
// issues include: missing_child, invalid_visible (malformed conditions),
|
||||
// repeat_without_children, repeat_state_mismatch (statePath not an array in state)
|
||||
// repeat_without_children, repeat_item_outside_scope, repeat_state_mismatch
|
||||
|
||||
const { spec: fixed, fixDetails } = autoFixSpec(spec);
|
||||
// fixDetails entries are { message, lossy }. Lossless fixes relocate
|
||||
|
||||
@@ -171,6 +171,8 @@ Use the `repeat` field on a container element to render items from a state array
|
||||
|
||||
Inside repeated children, use `{ "$item": "field" }` to read from the current item and `{ "$index": true }` for the current index.
|
||||
|
||||
For nested lists, an inner repeat can use `{ "statePath": { "$item": "children" } }` to iterate an array on the enclosing item.
|
||||
|
||||
## Streaming
|
||||
|
||||
Use `useUIStream` to progressively render specs from JSONL patch streams:
|
||||
|
||||
@@ -95,7 +95,7 @@ const html = await renderToHtml(spec, { registry });
|
||||
|
||||
## Visibility and State
|
||||
|
||||
Supports `visible` conditions, `$state`, `$cond`, repeat (`repeat.statePath`), and the same expression syntax as `@json-render/react`. Use `state` in `RenderOptions` when rendering server-side so expressions resolve.
|
||||
Supports `visible` conditions, `$state`, `$cond`, repeat (`repeat.statePath`), nested repeat paths with `{ "$item": "field" }`, and the same expression syntax as `@json-render/react`. Use `state` in `RenderOptions` when rendering server-side so expressions resolve.
|
||||
|
||||
## Server-Safe Import
|
||||
|
||||
|
||||
@@ -117,6 +117,7 @@ Any prop value can be a data-driven expression resolved at render time:
|
||||
- **`{ "$state": "/state/key" }`** - reads from state model (one-way read)
|
||||
- **`{ "$bindState": "/path" }`** - two-way binding: use on the natural value prop (value, checked, pressed, etc.) of form components.
|
||||
- **`{ "$bindItem": "field" }`** - two-way binding to a repeat item field. Use inside repeat scopes.
|
||||
- Nested lists use `{ "repeat": { "statePath": { "$item": "comments" } } }` inside an enclosing repeat.
|
||||
- **`{ "$cond": <condition>, "$then": <value>, "$else": <value> }`** - conditional value
|
||||
|
||||
```json
|
||||
|
||||
@@ -126,6 +126,8 @@ const buffer = await renderToBuffer(spec, { registry });
|
||||
|
||||
Pass a `StateStore` for full control over state:
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` inside an enclosing repeat.
|
||||
|
||||
```typescript
|
||||
import { createStateStore } from "@json-render/react-pdf";
|
||||
|
||||
|
||||
@@ -119,6 +119,7 @@ Any prop value can be a data-driven expression resolved by the renderer before c
|
||||
- **`{ "$bindState": "/path" }`** - two-way binding: reads from state and enables write-back. Use on the natural value prop (value, checked, pressed, etc.) of form components.
|
||||
- **`{ "$bindItem": "field" }`** - two-way binding to a repeat item field. Use inside repeat scopes.
|
||||
- **Filtered lists**: `repeat` plus an `$item` visible condition on the same container renders only matching items: `{ "repeat": { "statePath": "/tasks", "key": "id" }, "visible": { "$item": "status", "eq": "todo" }, "children": ["task-card"] }`. AND-composed `$state` conjuncts gate the container shell; `$item`/`$index` conjuncts filter items.
|
||||
- **Nested lists**: inside a repeat, use `{ "repeat": { "statePath": { "$item": "comments" }, "key": "id" } }` to iterate an array on the enclosing item.
|
||||
- **`{ "$cond": <condition>, "$then": <value>, "$else": <value> }`** - conditional value
|
||||
- **`{ "$template": "Hello, ${/name}!" }`** - interpolates state values into strings
|
||||
- **`{ "$computed": "fn", "args": { ... } }`** - calls registered functions with resolved args
|
||||
|
||||
@@ -148,6 +148,8 @@ Handled automatically by `ActionProvider`:
|
||||
|
||||
## Dynamic Props and Bindings
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` inside an enclosing repeat.
|
||||
|
||||
Supported expression forms include:
|
||||
|
||||
- `{"$state": "/path"}`
|
||||
|
||||
@@ -205,6 +205,8 @@ Other built-in actions: `pushState`, `removeState`, `push`, `pop`.
|
||||
|
||||
## Dynamic Props and Two-Way Binding
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` inside an enclosing repeat.
|
||||
|
||||
Expression forms resolved before your component receives props:
|
||||
|
||||
- `{"$state": "/state/key"}` - read from state
|
||||
|
||||
@@ -104,6 +104,8 @@ Note: `useStateStore().state` returns a `ShallowRef<StateModel>` — use `state.
|
||||
|
||||
## External Store (StateStore)
|
||||
|
||||
Nested lists can set `repeat.statePath` to `{ "$item": "field" }` inside an enclosing repeat.
|
||||
|
||||
Pass a `StateStore` to `StateProvider` to wire json-render to Pinia, VueUse, or any state management:
|
||||
|
||||
```typescript
|
||||
|
||||
Reference in New Issue
Block a user